cannabinieri website
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49861 lines
1.1 MiB

3 years ago
  1. /**
  2. * @license
  3. * Copyright 2010-2021 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '132';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const FlatShading = 1;
  21. const SmoothShading = 2;
  22. const NoBlending = 0;
  23. const NormalBlending = 1;
  24. const AdditiveBlending = 2;
  25. const SubtractiveBlending = 3;
  26. const MultiplyBlending = 4;
  27. const CustomBlending = 5;
  28. const AddEquation = 100;
  29. const SubtractEquation = 101;
  30. const ReverseSubtractEquation = 102;
  31. const MinEquation = 103;
  32. const MaxEquation = 104;
  33. const ZeroFactor = 200;
  34. const OneFactor = 201;
  35. const SrcColorFactor = 202;
  36. const OneMinusSrcColorFactor = 203;
  37. const SrcAlphaFactor = 204;
  38. const OneMinusSrcAlphaFactor = 205;
  39. const DstAlphaFactor = 206;
  40. const OneMinusDstAlphaFactor = 207;
  41. const DstColorFactor = 208;
  42. const OneMinusDstColorFactor = 209;
  43. const SrcAlphaSaturateFactor = 210;
  44. const NeverDepth = 0;
  45. const AlwaysDepth = 1;
  46. const LessDepth = 2;
  47. const LessEqualDepth = 3;
  48. const EqualDepth = 4;
  49. const GreaterEqualDepth = 5;
  50. const GreaterDepth = 6;
  51. const NotEqualDepth = 7;
  52. const MultiplyOperation = 0;
  53. const MixOperation = 1;
  54. const AddOperation = 2;
  55. const NoToneMapping = 0;
  56. const LinearToneMapping = 1;
  57. const ReinhardToneMapping = 2;
  58. const CineonToneMapping = 3;
  59. const ACESFilmicToneMapping = 4;
  60. const CustomToneMapping = 5;
  61. const UVMapping = 300;
  62. const CubeReflectionMapping = 301;
  63. const CubeRefractionMapping = 302;
  64. const EquirectangularReflectionMapping = 303;
  65. const EquirectangularRefractionMapping = 304;
  66. const CubeUVReflectionMapping = 306;
  67. const CubeUVRefractionMapping = 307;
  68. const RepeatWrapping = 1000;
  69. const ClampToEdgeWrapping = 1001;
  70. const MirroredRepeatWrapping = 1002;
  71. const NearestFilter = 1003;
  72. const NearestMipmapNearestFilter = 1004;
  73. const NearestMipMapNearestFilter = 1004;
  74. const NearestMipmapLinearFilter = 1005;
  75. const NearestMipMapLinearFilter = 1005;
  76. const LinearFilter = 1006;
  77. const LinearMipmapNearestFilter = 1007;
  78. const LinearMipMapNearestFilter = 1007;
  79. const LinearMipmapLinearFilter = 1008;
  80. const LinearMipMapLinearFilter = 1008;
  81. const UnsignedByteType = 1009;
  82. const ByteType = 1010;
  83. const ShortType = 1011;
  84. const UnsignedShortType = 1012;
  85. const IntType = 1013;
  86. const UnsignedIntType = 1014;
  87. const FloatType = 1015;
  88. const HalfFloatType = 1016;
  89. const UnsignedShort4444Type = 1017;
  90. const UnsignedShort5551Type = 1018;
  91. const UnsignedShort565Type = 1019;
  92. const UnsignedInt248Type = 1020;
  93. const AlphaFormat = 1021;
  94. const RGBFormat = 1022;
  95. const RGBAFormat = 1023;
  96. const LuminanceFormat = 1024;
  97. const LuminanceAlphaFormat = 1025;
  98. const RGBEFormat = RGBAFormat;
  99. const DepthFormat = 1026;
  100. const DepthStencilFormat = 1027;
  101. const RedFormat = 1028;
  102. const RedIntegerFormat = 1029;
  103. const RGFormat = 1030;
  104. const RGIntegerFormat = 1031;
  105. const RGBIntegerFormat = 1032;
  106. const RGBAIntegerFormat = 1033;
  107. const RGB_S3TC_DXT1_Format = 33776;
  108. const RGBA_S3TC_DXT1_Format = 33777;
  109. const RGBA_S3TC_DXT3_Format = 33778;
  110. const RGBA_S3TC_DXT5_Format = 33779;
  111. const RGB_PVRTC_4BPPV1_Format = 35840;
  112. const RGB_PVRTC_2BPPV1_Format = 35841;
  113. const RGBA_PVRTC_4BPPV1_Format = 35842;
  114. const RGBA_PVRTC_2BPPV1_Format = 35843;
  115. const RGB_ETC1_Format = 36196;
  116. const RGB_ETC2_Format = 37492;
  117. const RGBA_ETC2_EAC_Format = 37496;
  118. const RGBA_ASTC_4x4_Format = 37808;
  119. const RGBA_ASTC_5x4_Format = 37809;
  120. const RGBA_ASTC_5x5_Format = 37810;
  121. const RGBA_ASTC_6x5_Format = 37811;
  122. const RGBA_ASTC_6x6_Format = 37812;
  123. const RGBA_ASTC_8x5_Format = 37813;
  124. const RGBA_ASTC_8x6_Format = 37814;
  125. const RGBA_ASTC_8x8_Format = 37815;
  126. const RGBA_ASTC_10x5_Format = 37816;
  127. const RGBA_ASTC_10x6_Format = 37817;
  128. const RGBA_ASTC_10x8_Format = 37818;
  129. const RGBA_ASTC_10x10_Format = 37819;
  130. const RGBA_ASTC_12x10_Format = 37820;
  131. const RGBA_ASTC_12x12_Format = 37821;
  132. const RGBA_BPTC_Format = 36492;
  133. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  134. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  135. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  136. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  137. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  138. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  139. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  140. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  141. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  142. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  143. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  144. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  145. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  146. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  147. const LoopOnce = 2200;
  148. const LoopRepeat = 2201;
  149. const LoopPingPong = 2202;
  150. const InterpolateDiscrete = 2300;
  151. const InterpolateLinear = 2301;
  152. const InterpolateSmooth = 2302;
  153. const ZeroCurvatureEnding = 2400;
  154. const ZeroSlopeEnding = 2401;
  155. const WrapAroundEnding = 2402;
  156. const NormalAnimationBlendMode = 2500;
  157. const AdditiveAnimationBlendMode = 2501;
  158. const TrianglesDrawMode = 0;
  159. const TriangleStripDrawMode = 1;
  160. const TriangleFanDrawMode = 2;
  161. const LinearEncoding = 3000;
  162. const sRGBEncoding = 3001;
  163. const GammaEncoding = 3007;
  164. const RGBEEncoding = 3002;
  165. const LogLuvEncoding = 3003;
  166. const RGBM7Encoding = 3004;
  167. const RGBM16Encoding = 3005;
  168. const RGBDEncoding = 3006;
  169. const BasicDepthPacking = 3200;
  170. const RGBADepthPacking = 3201;
  171. const TangentSpaceNormalMap = 0;
  172. const ObjectSpaceNormalMap = 1;
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const StaticDrawUsage = 35044;
  190. const DynamicDrawUsage = 35048;
  191. const StreamDrawUsage = 35040;
  192. const StaticReadUsage = 35045;
  193. const DynamicReadUsage = 35049;
  194. const StreamReadUsage = 35041;
  195. const StaticCopyUsage = 35046;
  196. const DynamicCopyUsage = 35050;
  197. const StreamCopyUsage = 35042;
  198. const GLSL1 = '100';
  199. const GLSL3 = '300 es';
  200. /**
  201. * https://github.com/mrdoob/eventdispatcher.js/
  202. */
  203. class EventDispatcher {
  204. addEventListener( type, listener ) {
  205. if ( this._listeners === undefined ) this._listeners = {};
  206. const listeners = this._listeners;
  207. if ( listeners[ type ] === undefined ) {
  208. listeners[ type ] = [];
  209. }
  210. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  211. listeners[ type ].push( listener );
  212. }
  213. }
  214. hasEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) return false;
  216. const listeners = this._listeners;
  217. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  218. }
  219. removeEventListener( type, listener ) {
  220. if ( this._listeners === undefined ) return;
  221. const listeners = this._listeners;
  222. const listenerArray = listeners[ type ];
  223. if ( listenerArray !== undefined ) {
  224. const index = listenerArray.indexOf( listener );
  225. if ( index !== - 1 ) {
  226. listenerArray.splice( index, 1 );
  227. }
  228. }
  229. }
  230. dispatchEvent( event ) {
  231. if ( this._listeners === undefined ) return;
  232. const listeners = this._listeners;
  233. const listenerArray = listeners[ event.type ];
  234. if ( listenerArray !== undefined ) {
  235. event.target = this;
  236. // Make a copy, in case listeners are removed while iterating.
  237. const array = listenerArray.slice( 0 );
  238. for ( let i = 0, l = array.length; i < l; i ++ ) {
  239. array[ i ].call( this, event );
  240. }
  241. event.target = null;
  242. }
  243. }
  244. }
  245. const _lut = [];
  246. for ( let i = 0; i < 256; i ++ ) {
  247. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  248. }
  249. let _seed = 1234567;
  250. const DEG2RAD = Math.PI / 180;
  251. const RAD2DEG = 180 / Math.PI;
  252. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  253. function generateUUID() {
  254. const d0 = Math.random() * 0xffffffff | 0;
  255. const d1 = Math.random() * 0xffffffff | 0;
  256. const d2 = Math.random() * 0xffffffff | 0;
  257. const d3 = Math.random() * 0xffffffff | 0;
  258. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  259. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  260. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  261. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  262. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  263. return uuid.toUpperCase();
  264. }
  265. function clamp( value, min, max ) {
  266. return Math.max( min, Math.min( max, value ) );
  267. }
  268. // compute euclidian modulo of m % n
  269. // https://en.wikipedia.org/wiki/Modulo_operation
  270. function euclideanModulo( n, m ) {
  271. return ( ( n % m ) + m ) % m;
  272. }
  273. // Linear mapping from range <a1, a2> to range <b1, b2>
  274. function mapLinear( x, a1, a2, b1, b2 ) {
  275. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  276. }
  277. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  278. function inverseLerp( x, y, value ) {
  279. if ( x !== y ) {
  280. return ( value - x ) / ( y - x );
  281. } else {
  282. return 0;
  283. }
  284. }
  285. // https://en.wikipedia.org/wiki/Linear_interpolation
  286. function lerp( x, y, t ) {
  287. return ( 1 - t ) * x + t * y;
  288. }
  289. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  290. function damp( x, y, lambda, dt ) {
  291. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  292. }
  293. // https://www.desmos.com/calculator/vcsjnyz7x4
  294. function pingpong( x, length = 1 ) {
  295. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  296. }
  297. // http://en.wikipedia.org/wiki/Smoothstep
  298. function smoothstep( x, min, max ) {
  299. if ( x <= min ) return 0;
  300. if ( x >= max ) return 1;
  301. x = ( x - min ) / ( max - min );
  302. return x * x * ( 3 - 2 * x );
  303. }
  304. function smootherstep( x, min, max ) {
  305. if ( x <= min ) return 0;
  306. if ( x >= max ) return 1;
  307. x = ( x - min ) / ( max - min );
  308. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  309. }
  310. // Random integer from <low, high> interval
  311. function randInt( low, high ) {
  312. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  313. }
  314. // Random float from <low, high> interval
  315. function randFloat( low, high ) {
  316. return low + Math.random() * ( high - low );
  317. }
  318. // Random float from <-range/2, range/2> interval
  319. function randFloatSpread( range ) {
  320. return range * ( 0.5 - Math.random() );
  321. }
  322. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom( s ) {
  324. if ( s !== undefined ) _seed = s % 2147483647;
  325. // Park-Miller algorithm
  326. _seed = _seed * 16807 % 2147483647;
  327. return ( _seed - 1 ) / 2147483646;
  328. }
  329. function degToRad( degrees ) {
  330. return degrees * DEG2RAD;
  331. }
  332. function radToDeg( radians ) {
  333. return radians * RAD2DEG;
  334. }
  335. function isPowerOfTwo( value ) {
  336. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  337. }
  338. function ceilPowerOfTwo( value ) {
  339. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  340. }
  341. function floorPowerOfTwo( value ) {
  342. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  343. }
  344. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  345. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  346. // rotations are applied to the axes in the order specified by 'order'
  347. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  348. // angles are in radians
  349. const cos = Math.cos;
  350. const sin = Math.sin;
  351. const c2 = cos( b / 2 );
  352. const s2 = sin( b / 2 );
  353. const c13 = cos( ( a + c ) / 2 );
  354. const s13 = sin( ( a + c ) / 2 );
  355. const c1_3 = cos( ( a - c ) / 2 );
  356. const s1_3 = sin( ( a - c ) / 2 );
  357. const c3_1 = cos( ( c - a ) / 2 );
  358. const s3_1 = sin( ( c - a ) / 2 );
  359. switch ( order ) {
  360. case 'XYX':
  361. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  362. break;
  363. case 'YZY':
  364. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  365. break;
  366. case 'ZXZ':
  367. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  368. break;
  369. case 'XZX':
  370. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  371. break;
  372. case 'YXY':
  373. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  374. break;
  375. case 'ZYZ':
  376. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  377. break;
  378. default:
  379. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  380. }
  381. }
  382. var MathUtils = /*#__PURE__*/Object.freeze({
  383. __proto__: null,
  384. DEG2RAD: DEG2RAD,
  385. RAD2DEG: RAD2DEG,
  386. generateUUID: generateUUID,
  387. clamp: clamp,
  388. euclideanModulo: euclideanModulo,
  389. mapLinear: mapLinear,
  390. inverseLerp: inverseLerp,
  391. lerp: lerp,
  392. damp: damp,
  393. pingpong: pingpong,
  394. smoothstep: smoothstep,
  395. smootherstep: smootherstep,
  396. randInt: randInt,
  397. randFloat: randFloat,
  398. randFloatSpread: randFloatSpread,
  399. seededRandom: seededRandom,
  400. degToRad: degToRad,
  401. radToDeg: radToDeg,
  402. isPowerOfTwo: isPowerOfTwo,
  403. ceilPowerOfTwo: ceilPowerOfTwo,
  404. floorPowerOfTwo: floorPowerOfTwo,
  405. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  406. });
  407. class Vector2 {
  408. constructor( x = 0, y = 0 ) {
  409. this.x = x;
  410. this.y = y;
  411. }
  412. get width() {
  413. return this.x;
  414. }
  415. set width( value ) {
  416. this.x = value;
  417. }
  418. get height() {
  419. return this.y;
  420. }
  421. set height( value ) {
  422. this.y = value;
  423. }
  424. set( x, y ) {
  425. this.x = x;
  426. this.y = y;
  427. return this;
  428. }
  429. setScalar( scalar ) {
  430. this.x = scalar;
  431. this.y = scalar;
  432. return this;
  433. }
  434. setX( x ) {
  435. this.x = x;
  436. return this;
  437. }
  438. setY( y ) {
  439. this.y = y;
  440. return this;
  441. }
  442. setComponent( index, value ) {
  443. switch ( index ) {
  444. case 0: this.x = value; break;
  445. case 1: this.y = value; break;
  446. default: throw new Error( 'index is out of range: ' + index );
  447. }
  448. return this;
  449. }
  450. getComponent( index ) {
  451. switch ( index ) {
  452. case 0: return this.x;
  453. case 1: return this.y;
  454. default: throw new Error( 'index is out of range: ' + index );
  455. }
  456. }
  457. clone() {
  458. return new this.constructor( this.x, this.y );
  459. }
  460. copy( v ) {
  461. this.x = v.x;
  462. this.y = v.y;
  463. return this;
  464. }
  465. add( v, w ) {
  466. if ( w !== undefined ) {
  467. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  468. return this.addVectors( v, w );
  469. }
  470. this.x += v.x;
  471. this.y += v.y;
  472. return this;
  473. }
  474. addScalar( s ) {
  475. this.x += s;
  476. this.y += s;
  477. return this;
  478. }
  479. addVectors( a, b ) {
  480. this.x = a.x + b.x;
  481. this.y = a.y + b.y;
  482. return this;
  483. }
  484. addScaledVector( v, s ) {
  485. this.x += v.x * s;
  486. this.y += v.y * s;
  487. return this;
  488. }
  489. sub( v, w ) {
  490. if ( w !== undefined ) {
  491. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  492. return this.subVectors( v, w );
  493. }
  494. this.x -= v.x;
  495. this.y -= v.y;
  496. return this;
  497. }
  498. subScalar( s ) {
  499. this.x -= s;
  500. this.y -= s;
  501. return this;
  502. }
  503. subVectors( a, b ) {
  504. this.x = a.x - b.x;
  505. this.y = a.y - b.y;
  506. return this;
  507. }
  508. multiply( v ) {
  509. this.x *= v.x;
  510. this.y *= v.y;
  511. return this;
  512. }
  513. multiplyScalar( scalar ) {
  514. this.x *= scalar;
  515. this.y *= scalar;
  516. return this;
  517. }
  518. divide( v ) {
  519. this.x /= v.x;
  520. this.y /= v.y;
  521. return this;
  522. }
  523. divideScalar( scalar ) {
  524. return this.multiplyScalar( 1 / scalar );
  525. }
  526. applyMatrix3( m ) {
  527. const x = this.x, y = this.y;
  528. const e = m.elements;
  529. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  530. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  531. return this;
  532. }
  533. min( v ) {
  534. this.x = Math.min( this.x, v.x );
  535. this.y = Math.min( this.y, v.y );
  536. return this;
  537. }
  538. max( v ) {
  539. this.x = Math.max( this.x, v.x );
  540. this.y = Math.max( this.y, v.y );
  541. return this;
  542. }
  543. clamp( min, max ) {
  544. // assumes min < max, componentwise
  545. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  546. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  547. return this;
  548. }
  549. clampScalar( minVal, maxVal ) {
  550. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  551. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  552. return this;
  553. }
  554. clampLength( min, max ) {
  555. const length = this.length();
  556. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  557. }
  558. floor() {
  559. this.x = Math.floor( this.x );
  560. this.y = Math.floor( this.y );
  561. return this;
  562. }
  563. ceil() {
  564. this.x = Math.ceil( this.x );
  565. this.y = Math.ceil( this.y );
  566. return this;
  567. }
  568. round() {
  569. this.x = Math.round( this.x );
  570. this.y = Math.round( this.y );
  571. return this;
  572. }
  573. roundToZero() {
  574. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  575. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  576. return this;
  577. }
  578. negate() {
  579. this.x = - this.x;
  580. this.y = - this.y;
  581. return this;
  582. }
  583. dot( v ) {
  584. return this.x * v.x + this.y * v.y;
  585. }
  586. cross( v ) {
  587. return this.x * v.y - this.y * v.x;
  588. }
  589. lengthSq() {
  590. return this.x * this.x + this.y * this.y;
  591. }
  592. length() {
  593. return Math.sqrt( this.x * this.x + this.y * this.y );
  594. }
  595. manhattanLength() {
  596. return Math.abs( this.x ) + Math.abs( this.y );
  597. }
  598. normalize() {
  599. return this.divideScalar( this.length() || 1 );
  600. }
  601. angle() {
  602. // computes the angle in radians with respect to the positive x-axis
  603. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  604. return angle;
  605. }
  606. distanceTo( v ) {
  607. return Math.sqrt( this.distanceToSquared( v ) );
  608. }
  609. distanceToSquared( v ) {
  610. const dx = this.x - v.x, dy = this.y - v.y;
  611. return dx * dx + dy * dy;
  612. }
  613. manhattanDistanceTo( v ) {
  614. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  615. }
  616. setLength( length ) {
  617. return this.normalize().multiplyScalar( length );
  618. }
  619. lerp( v, alpha ) {
  620. this.x += ( v.x - this.x ) * alpha;
  621. this.y += ( v.y - this.y ) * alpha;
  622. return this;
  623. }
  624. lerpVectors( v1, v2, alpha ) {
  625. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  626. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  627. return this;
  628. }
  629. equals( v ) {
  630. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  631. }
  632. fromArray( array, offset = 0 ) {
  633. this.x = array[ offset ];
  634. this.y = array[ offset + 1 ];
  635. return this;
  636. }
  637. toArray( array = [], offset = 0 ) {
  638. array[ offset ] = this.x;
  639. array[ offset + 1 ] = this.y;
  640. return array;
  641. }
  642. fromBufferAttribute( attribute, index, offset ) {
  643. if ( offset !== undefined ) {
  644. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  645. }
  646. this.x = attribute.getX( index );
  647. this.y = attribute.getY( index );
  648. return this;
  649. }
  650. rotateAround( center, angle ) {
  651. const c = Math.cos( angle ), s = Math.sin( angle );
  652. const x = this.x - center.x;
  653. const y = this.y - center.y;
  654. this.x = x * c - y * s + center.x;
  655. this.y = x * s + y * c + center.y;
  656. return this;
  657. }
  658. random() {
  659. this.x = Math.random();
  660. this.y = Math.random();
  661. return this;
  662. }
  663. }
  664. Vector2.prototype.isVector2 = true;
  665. class Matrix3 {
  666. constructor() {
  667. this.elements = [
  668. 1, 0, 0,
  669. 0, 1, 0,
  670. 0, 0, 1
  671. ];
  672. if ( arguments.length > 0 ) {
  673. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  674. }
  675. }
  676. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  677. const te = this.elements;
  678. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  679. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  680. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  681. return this;
  682. }
  683. identity() {
  684. this.set(
  685. 1, 0, 0,
  686. 0, 1, 0,
  687. 0, 0, 1
  688. );
  689. return this;
  690. }
  691. copy( m ) {
  692. const te = this.elements;
  693. const me = m.elements;
  694. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  695. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  696. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  697. return this;
  698. }
  699. extractBasis( xAxis, yAxis, zAxis ) {
  700. xAxis.setFromMatrix3Column( this, 0 );
  701. yAxis.setFromMatrix3Column( this, 1 );
  702. zAxis.setFromMatrix3Column( this, 2 );
  703. return this;
  704. }
  705. setFromMatrix4( m ) {
  706. const me = m.elements;
  707. this.set(
  708. me[ 0 ], me[ 4 ], me[ 8 ],
  709. me[ 1 ], me[ 5 ], me[ 9 ],
  710. me[ 2 ], me[ 6 ], me[ 10 ]
  711. );
  712. return this;
  713. }
  714. multiply( m ) {
  715. return this.multiplyMatrices( this, m );
  716. }
  717. premultiply( m ) {
  718. return this.multiplyMatrices( m, this );
  719. }
  720. multiplyMatrices( a, b ) {
  721. const ae = a.elements;
  722. const be = b.elements;
  723. const te = this.elements;
  724. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  725. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  726. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  727. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  728. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  729. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  730. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  731. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  732. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  733. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  734. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  735. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  736. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  737. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  738. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  739. return this;
  740. }
  741. multiplyScalar( s ) {
  742. const te = this.elements;
  743. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  744. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  745. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  746. return this;
  747. }
  748. determinant() {
  749. const te = this.elements;
  750. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  751. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  752. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  753. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  754. }
  755. invert() {
  756. const te = this.elements,
  757. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  758. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  759. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  760. t11 = n33 * n22 - n32 * n23,
  761. t12 = n32 * n13 - n33 * n12,
  762. t13 = n23 * n12 - n22 * n13,
  763. det = n11 * t11 + n21 * t12 + n31 * t13;
  764. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  765. const detInv = 1 / det;
  766. te[ 0 ] = t11 * detInv;
  767. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  768. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  769. te[ 3 ] = t12 * detInv;
  770. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  771. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  772. te[ 6 ] = t13 * detInv;
  773. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  774. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  775. return this;
  776. }
  777. transpose() {
  778. let tmp;
  779. const m = this.elements;
  780. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  781. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  782. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  783. return this;
  784. }
  785. getNormalMatrix( matrix4 ) {
  786. return this.setFromMatrix4( matrix4 ).invert().transpose();
  787. }
  788. transposeIntoArray( r ) {
  789. const m = this.elements;
  790. r[ 0 ] = m[ 0 ];
  791. r[ 1 ] = m[ 3 ];
  792. r[ 2 ] = m[ 6 ];
  793. r[ 3 ] = m[ 1 ];
  794. r[ 4 ] = m[ 4 ];
  795. r[ 5 ] = m[ 7 ];
  796. r[ 6 ] = m[ 2 ];
  797. r[ 7 ] = m[ 5 ];
  798. r[ 8 ] = m[ 8 ];
  799. return this;
  800. }
  801. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  802. const c = Math.cos( rotation );
  803. const s = Math.sin( rotation );
  804. this.set(
  805. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  806. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  807. 0, 0, 1
  808. );
  809. return this;
  810. }
  811. scale( sx, sy ) {
  812. const te = this.elements;
  813. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  814. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  815. return this;
  816. }
  817. rotate( theta ) {
  818. const c = Math.cos( theta );
  819. const s = Math.sin( theta );
  820. const te = this.elements;
  821. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  822. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  823. te[ 0 ] = c * a11 + s * a21;
  824. te[ 3 ] = c * a12 + s * a22;
  825. te[ 6 ] = c * a13 + s * a23;
  826. te[ 1 ] = - s * a11 + c * a21;
  827. te[ 4 ] = - s * a12 + c * a22;
  828. te[ 7 ] = - s * a13 + c * a23;
  829. return this;
  830. }
  831. translate( tx, ty ) {
  832. const te = this.elements;
  833. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  834. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  835. return this;
  836. }
  837. equals( matrix ) {
  838. const te = this.elements;
  839. const me = matrix.elements;
  840. for ( let i = 0; i < 9; i ++ ) {
  841. if ( te[ i ] !== me[ i ] ) return false;
  842. }
  843. return true;
  844. }
  845. fromArray( array, offset = 0 ) {
  846. for ( let i = 0; i < 9; i ++ ) {
  847. this.elements[ i ] = array[ i + offset ];
  848. }
  849. return this;
  850. }
  851. toArray( array = [], offset = 0 ) {
  852. const te = this.elements;
  853. array[ offset ] = te[ 0 ];
  854. array[ offset + 1 ] = te[ 1 ];
  855. array[ offset + 2 ] = te[ 2 ];
  856. array[ offset + 3 ] = te[ 3 ];
  857. array[ offset + 4 ] = te[ 4 ];
  858. array[ offset + 5 ] = te[ 5 ];
  859. array[ offset + 6 ] = te[ 6 ];
  860. array[ offset + 7 ] = te[ 7 ];
  861. array[ offset + 8 ] = te[ 8 ];
  862. return array;
  863. }
  864. clone() {
  865. return new this.constructor().fromArray( this.elements );
  866. }
  867. }
  868. Matrix3.prototype.isMatrix3 = true;
  869. let _canvas;
  870. class ImageUtils {
  871. static getDataURL( image ) {
  872. if ( /^data:/i.test( image.src ) ) {
  873. return image.src;
  874. }
  875. if ( typeof HTMLCanvasElement == 'undefined' ) {
  876. return image.src;
  877. }
  878. let canvas;
  879. if ( image instanceof HTMLCanvasElement ) {
  880. canvas = image;
  881. } else {
  882. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  883. _canvas.width = image.width;
  884. _canvas.height = image.height;
  885. const context = _canvas.getContext( '2d' );
  886. if ( image instanceof ImageData ) {
  887. context.putImageData( image, 0, 0 );
  888. } else {
  889. context.drawImage( image, 0, 0, image.width, image.height );
  890. }
  891. canvas = _canvas;
  892. }
  893. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  894. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  895. return canvas.toDataURL( 'image/jpeg', 0.6 );
  896. } else {
  897. return canvas.toDataURL( 'image/png' );
  898. }
  899. }
  900. }
  901. let textureId = 0;
  902. class Texture extends EventDispatcher {
  903. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {
  904. super();
  905. Object.defineProperty( this, 'id', { value: textureId ++ } );
  906. this.uuid = generateUUID();
  907. this.name = '';
  908. this.image = image;
  909. this.mipmaps = [];
  910. this.mapping = mapping;
  911. this.wrapS = wrapS;
  912. this.wrapT = wrapT;
  913. this.magFilter = magFilter;
  914. this.minFilter = minFilter;
  915. this.anisotropy = anisotropy;
  916. this.format = format;
  917. this.internalFormat = null;
  918. this.type = type;
  919. this.offset = new Vector2( 0, 0 );
  920. this.repeat = new Vector2( 1, 1 );
  921. this.center = new Vector2( 0, 0 );
  922. this.rotation = 0;
  923. this.matrixAutoUpdate = true;
  924. this.matrix = new Matrix3();
  925. this.generateMipmaps = true;
  926. this.premultiplyAlpha = false;
  927. this.flipY = true;
  928. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  929. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  930. //
  931. // Also changing the encoding after already used by a Material will not automatically make the Material
  932. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  933. this.encoding = encoding;
  934. this.version = 0;
  935. this.onUpdate = null;
  936. this.isRenderTargetTexture = false;
  937. }
  938. updateMatrix() {
  939. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  940. }
  941. clone() {
  942. return new this.constructor().copy( this );
  943. }
  944. copy( source ) {
  945. this.name = source.name;
  946. this.image = source.image;
  947. this.mipmaps = source.mipmaps.slice( 0 );
  948. this.mapping = source.mapping;
  949. this.wrapS = source.wrapS;
  950. this.wrapT = source.wrapT;
  951. this.magFilter = source.magFilter;
  952. this.minFilter = source.minFilter;
  953. this.anisotropy = source.anisotropy;
  954. this.format = source.format;
  955. this.internalFormat = source.internalFormat;
  956. this.type = source.type;
  957. this.offset.copy( source.offset );
  958. this.repeat.copy( source.repeat );
  959. this.center.copy( source.center );
  960. this.rotation = source.rotation;
  961. this.matrixAutoUpdate = source.matrixAutoUpdate;
  962. this.matrix.copy( source.matrix );
  963. this.generateMipmaps = source.generateMipmaps;
  964. this.premultiplyAlpha = source.premultiplyAlpha;
  965. this.flipY = source.flipY;
  966. this.unpackAlignment = source.unpackAlignment;
  967. this.encoding = source.encoding;
  968. return this;
  969. }
  970. toJSON( meta ) {
  971. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  972. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  973. return meta.textures[ this.uuid ];
  974. }
  975. const output = {
  976. metadata: {
  977. version: 4.5,
  978. type: 'Texture',
  979. generator: 'Texture.toJSON'
  980. },
  981. uuid: this.uuid,
  982. name: this.name,
  983. mapping: this.mapping,
  984. repeat: [ this.repeat.x, this.repeat.y ],
  985. offset: [ this.offset.x, this.offset.y ],
  986. center: [ this.center.x, this.center.y ],
  987. rotation: this.rotation,
  988. wrap: [ this.wrapS, this.wrapT ],
  989. format: this.format,
  990. type: this.type,
  991. encoding: this.encoding,
  992. minFilter: this.minFilter,
  993. magFilter: this.magFilter,
  994. anisotropy: this.anisotropy,
  995. flipY: this.flipY,
  996. premultiplyAlpha: this.premultiplyAlpha,
  997. unpackAlignment: this.unpackAlignment
  998. };
  999. if ( this.image !== undefined ) {
  1000. // TODO: Move to THREE.Image
  1001. const image = this.image;
  1002. if ( image.uuid === undefined ) {
  1003. image.uuid = generateUUID(); // UGH
  1004. }
  1005. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1006. let url;
  1007. if ( Array.isArray( image ) ) {
  1008. // process array of images e.g. CubeTexture
  1009. url = [];
  1010. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1011. // check cube texture with data textures
  1012. if ( image[ i ].isDataTexture ) {
  1013. url.push( serializeImage( image[ i ].image ) );
  1014. } else {
  1015. url.push( serializeImage( image[ i ] ) );
  1016. }
  1017. }
  1018. } else {
  1019. // process single image
  1020. url = serializeImage( image );
  1021. }
  1022. meta.images[ image.uuid ] = {
  1023. uuid: image.uuid,
  1024. url: url
  1025. };
  1026. }
  1027. output.image = image.uuid;
  1028. }
  1029. if ( ! isRootObject ) {
  1030. meta.textures[ this.uuid ] = output;
  1031. }
  1032. return output;
  1033. }
  1034. dispose() {
  1035. this.dispatchEvent( { type: 'dispose' } );
  1036. }
  1037. transformUv( uv ) {
  1038. if ( this.mapping !== UVMapping ) return uv;
  1039. uv.applyMatrix3( this.matrix );
  1040. if ( uv.x < 0 || uv.x > 1 ) {
  1041. switch ( this.wrapS ) {
  1042. case RepeatWrapping:
  1043. uv.x = uv.x - Math.floor( uv.x );
  1044. break;
  1045. case ClampToEdgeWrapping:
  1046. uv.x = uv.x < 0 ? 0 : 1;
  1047. break;
  1048. case MirroredRepeatWrapping:
  1049. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1050. uv.x = Math.ceil( uv.x ) - uv.x;
  1051. } else {
  1052. uv.x = uv.x - Math.floor( uv.x );
  1053. }
  1054. break;
  1055. }
  1056. }
  1057. if ( uv.y < 0 || uv.y > 1 ) {
  1058. switch ( this.wrapT ) {
  1059. case RepeatWrapping:
  1060. uv.y = uv.y - Math.floor( uv.y );
  1061. break;
  1062. case ClampToEdgeWrapping:
  1063. uv.y = uv.y < 0 ? 0 : 1;
  1064. break;
  1065. case MirroredRepeatWrapping:
  1066. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1067. uv.y = Math.ceil( uv.y ) - uv.y;
  1068. } else {
  1069. uv.y = uv.y - Math.floor( uv.y );
  1070. }
  1071. break;
  1072. }
  1073. }
  1074. if ( this.flipY ) {
  1075. uv.y = 1 - uv.y;
  1076. }
  1077. return uv;
  1078. }
  1079. set needsUpdate( value ) {
  1080. if ( value === true ) this.version ++;
  1081. }
  1082. }
  1083. Texture.DEFAULT_IMAGE = undefined;
  1084. Texture.DEFAULT_MAPPING = UVMapping;
  1085. Texture.prototype.isTexture = true;
  1086. function serializeImage( image ) {
  1087. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1088. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1089. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1090. // default images
  1091. return ImageUtils.getDataURL( image );
  1092. } else {
  1093. if ( image.data ) {
  1094. // images of DataTexture
  1095. return {
  1096. data: Array.prototype.slice.call( image.data ),
  1097. width: image.width,
  1098. height: image.height,
  1099. type: image.data.constructor.name
  1100. };
  1101. } else {
  1102. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1103. return {};
  1104. }
  1105. }
  1106. }
  1107. class Vector4 {
  1108. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1109. this.x = x;
  1110. this.y = y;
  1111. this.z = z;
  1112. this.w = w;
  1113. }
  1114. get width() {
  1115. return this.z;
  1116. }
  1117. set width( value ) {
  1118. this.z = value;
  1119. }
  1120. get height() {
  1121. return this.w;
  1122. }
  1123. set height( value ) {
  1124. this.w = value;
  1125. }
  1126. set( x, y, z, w ) {
  1127. this.x = x;
  1128. this.y = y;
  1129. this.z = z;
  1130. this.w = w;
  1131. return this;
  1132. }
  1133. setScalar( scalar ) {
  1134. this.x = scalar;
  1135. this.y = scalar;
  1136. this.z = scalar;
  1137. this.w = scalar;
  1138. return this;
  1139. }
  1140. setX( x ) {
  1141. this.x = x;
  1142. return this;
  1143. }
  1144. setY( y ) {
  1145. this.y = y;
  1146. return this;
  1147. }
  1148. setZ( z ) {
  1149. this.z = z;
  1150. return this;
  1151. }
  1152. setW( w ) {
  1153. this.w = w;
  1154. return this;
  1155. }
  1156. setComponent( index, value ) {
  1157. switch ( index ) {
  1158. case 0: this.x = value; break;
  1159. case 1: this.y = value; break;
  1160. case 2: this.z = value; break;
  1161. case 3: this.w = value; break;
  1162. default: throw new Error( 'index is out of range: ' + index );
  1163. }
  1164. return this;
  1165. }
  1166. getComponent( index ) {
  1167. switch ( index ) {
  1168. case 0: return this.x;
  1169. case 1: return this.y;
  1170. case 2: return this.z;
  1171. case 3: return this.w;
  1172. default: throw new Error( 'index is out of range: ' + index );
  1173. }
  1174. }
  1175. clone() {
  1176. return new this.constructor( this.x, this.y, this.z, this.w );
  1177. }
  1178. copy( v ) {
  1179. this.x = v.x;
  1180. this.y = v.y;
  1181. this.z = v.z;
  1182. this.w = ( v.w !== undefined ) ? v.w : 1;
  1183. return this;
  1184. }
  1185. add( v, w ) {
  1186. if ( w !== undefined ) {
  1187. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1188. return this.addVectors( v, w );
  1189. }
  1190. this.x += v.x;
  1191. this.y += v.y;
  1192. this.z += v.z;
  1193. this.w += v.w;
  1194. return this;
  1195. }
  1196. addScalar( s ) {
  1197. this.x += s;
  1198. this.y += s;
  1199. this.z += s;
  1200. this.w += s;
  1201. return this;
  1202. }
  1203. addVectors( a, b ) {
  1204. this.x = a.x + b.x;
  1205. this.y = a.y + b.y;
  1206. this.z = a.z + b.z;
  1207. this.w = a.w + b.w;
  1208. return this;
  1209. }
  1210. addScaledVector( v, s ) {
  1211. this.x += v.x * s;
  1212. this.y += v.y * s;
  1213. this.z += v.z * s;
  1214. this.w += v.w * s;
  1215. return this;
  1216. }
  1217. sub( v, w ) {
  1218. if ( w !== undefined ) {
  1219. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1220. return this.subVectors( v, w );
  1221. }
  1222. this.x -= v.x;
  1223. this.y -= v.y;
  1224. this.z -= v.z;
  1225. this.w -= v.w;
  1226. return this;
  1227. }
  1228. subScalar( s ) {
  1229. this.x -= s;
  1230. this.y -= s;
  1231. this.z -= s;
  1232. this.w -= s;
  1233. return this;
  1234. }
  1235. subVectors( a, b ) {
  1236. this.x = a.x - b.x;
  1237. this.y = a.y - b.y;
  1238. this.z = a.z - b.z;
  1239. this.w = a.w - b.w;
  1240. return this;
  1241. }
  1242. multiply( v ) {
  1243. this.x *= v.x;
  1244. this.y *= v.y;
  1245. this.z *= v.z;
  1246. this.w *= v.w;
  1247. return this;
  1248. }
  1249. multiplyScalar( scalar ) {
  1250. this.x *= scalar;
  1251. this.y *= scalar;
  1252. this.z *= scalar;
  1253. this.w *= scalar;
  1254. return this;
  1255. }
  1256. applyMatrix4( m ) {
  1257. const x = this.x, y = this.y, z = this.z, w = this.w;
  1258. const e = m.elements;
  1259. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1260. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1261. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1262. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1263. return this;
  1264. }
  1265. divideScalar( scalar ) {
  1266. return this.multiplyScalar( 1 / scalar );
  1267. }
  1268. setAxisAngleFromQuaternion( q ) {
  1269. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1270. // q is assumed to be normalized
  1271. this.w = 2 * Math.acos( q.w );
  1272. const s = Math.sqrt( 1 - q.w * q.w );
  1273. if ( s < 0.0001 ) {
  1274. this.x = 1;
  1275. this.y = 0;
  1276. this.z = 0;
  1277. } else {
  1278. this.x = q.x / s;
  1279. this.y = q.y / s;
  1280. this.z = q.z / s;
  1281. }
  1282. return this;
  1283. }
  1284. setAxisAngleFromRotationMatrix( m ) {
  1285. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1286. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1287. let angle, x, y, z; // variables for result
  1288. const epsilon = 0.01, // margin to allow for rounding errors
  1289. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1290. te = m.elements,
  1291. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1292. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1293. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1294. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1295. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1296. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1297. // singularity found
  1298. // first check for identity matrix which must have +1 for all terms
  1299. // in leading diagonal and zero in other terms
  1300. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1301. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1302. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1303. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1304. // this singularity is identity matrix so angle = 0
  1305. this.set( 1, 0, 0, 0 );
  1306. return this; // zero angle, arbitrary axis
  1307. }
  1308. // otherwise this singularity is angle = 180
  1309. angle = Math.PI;
  1310. const xx = ( m11 + 1 ) / 2;
  1311. const yy = ( m22 + 1 ) / 2;
  1312. const zz = ( m33 + 1 ) / 2;
  1313. const xy = ( m12 + m21 ) / 4;
  1314. const xz = ( m13 + m31 ) / 4;
  1315. const yz = ( m23 + m32 ) / 4;
  1316. if ( ( xx > yy ) && ( xx > zz ) ) {
  1317. // m11 is the largest diagonal term
  1318. if ( xx < epsilon ) {
  1319. x = 0;
  1320. y = 0.707106781;
  1321. z = 0.707106781;
  1322. } else {
  1323. x = Math.sqrt( xx );
  1324. y = xy / x;
  1325. z = xz / x;
  1326. }
  1327. } else if ( yy > zz ) {
  1328. // m22 is the largest diagonal term
  1329. if ( yy < epsilon ) {
  1330. x = 0.707106781;
  1331. y = 0;
  1332. z = 0.707106781;
  1333. } else {
  1334. y = Math.sqrt( yy );
  1335. x = xy / y;
  1336. z = yz / y;
  1337. }
  1338. } else {
  1339. // m33 is the largest diagonal term so base result on this
  1340. if ( zz < epsilon ) {
  1341. x = 0.707106781;
  1342. y = 0.707106781;
  1343. z = 0;
  1344. } else {
  1345. z = Math.sqrt( zz );
  1346. x = xz / z;
  1347. y = yz / z;
  1348. }
  1349. }
  1350. this.set( x, y, z, angle );
  1351. return this; // return 180 deg rotation
  1352. }
  1353. // as we have reached here there are no singularities so we can handle normally
  1354. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1355. ( m13 - m31 ) * ( m13 - m31 ) +
  1356. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1357. if ( Math.abs( s ) < 0.001 ) s = 1;
  1358. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1359. // caught by singularity test above, but I've left it in just in case
  1360. this.x = ( m32 - m23 ) / s;
  1361. this.y = ( m13 - m31 ) / s;
  1362. this.z = ( m21 - m12 ) / s;
  1363. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1364. return this;
  1365. }
  1366. min( v ) {
  1367. this.x = Math.min( this.x, v.x );
  1368. this.y = Math.min( this.y, v.y );
  1369. this.z = Math.min( this.z, v.z );
  1370. this.w = Math.min( this.w, v.w );
  1371. return this;
  1372. }
  1373. max( v ) {
  1374. this.x = Math.max( this.x, v.x );
  1375. this.y = Math.max( this.y, v.y );
  1376. this.z = Math.max( this.z, v.z );
  1377. this.w = Math.max( this.w, v.w );
  1378. return this;
  1379. }
  1380. clamp( min, max ) {
  1381. // assumes min < max, componentwise
  1382. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1383. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1384. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1385. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1386. return this;
  1387. }
  1388. clampScalar( minVal, maxVal ) {
  1389. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1390. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1391. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1392. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1393. return this;
  1394. }
  1395. clampLength( min, max ) {
  1396. const length = this.length();
  1397. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1398. }
  1399. floor() {
  1400. this.x = Math.floor( this.x );
  1401. this.y = Math.floor( this.y );
  1402. this.z = Math.floor( this.z );
  1403. this.w = Math.floor( this.w );
  1404. return this;
  1405. }
  1406. ceil() {
  1407. this.x = Math.ceil( this.x );
  1408. this.y = Math.ceil( this.y );
  1409. this.z = Math.ceil( this.z );
  1410. this.w = Math.ceil( this.w );
  1411. return this;
  1412. }
  1413. round() {
  1414. this.x = Math.round( this.x );
  1415. this.y = Math.round( this.y );
  1416. this.z = Math.round( this.z );
  1417. this.w = Math.round( this.w );
  1418. return this;
  1419. }
  1420. roundToZero() {
  1421. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1422. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1423. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1424. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1425. return this;
  1426. }
  1427. negate() {
  1428. this.x = - this.x;
  1429. this.y = - this.y;
  1430. this.z = - this.z;
  1431. this.w = - this.w;
  1432. return this;
  1433. }
  1434. dot( v ) {
  1435. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1436. }
  1437. lengthSq() {
  1438. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1439. }
  1440. length() {
  1441. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1442. }
  1443. manhattanLength() {
  1444. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1445. }
  1446. normalize() {
  1447. return this.divideScalar( this.length() || 1 );
  1448. }
  1449. setLength( length ) {
  1450. return this.normalize().multiplyScalar( length );
  1451. }
  1452. lerp( v, alpha ) {
  1453. this.x += ( v.x - this.x ) * alpha;
  1454. this.y += ( v.y - this.y ) * alpha;
  1455. this.z += ( v.z - this.z ) * alpha;
  1456. this.w += ( v.w - this.w ) * alpha;
  1457. return this;
  1458. }
  1459. lerpVectors( v1, v2, alpha ) {
  1460. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1461. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1462. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1463. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1464. return this;
  1465. }
  1466. equals( v ) {
  1467. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1468. }
  1469. fromArray( array, offset = 0 ) {
  1470. this.x = array[ offset ];
  1471. this.y = array[ offset + 1 ];
  1472. this.z = array[ offset + 2 ];
  1473. this.w = array[ offset + 3 ];
  1474. return this;
  1475. }
  1476. toArray( array = [], offset = 0 ) {
  1477. array[ offset ] = this.x;
  1478. array[ offset + 1 ] = this.y;
  1479. array[ offset + 2 ] = this.z;
  1480. array[ offset + 3 ] = this.w;
  1481. return array;
  1482. }
  1483. fromBufferAttribute( attribute, index, offset ) {
  1484. if ( offset !== undefined ) {
  1485. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1486. }
  1487. this.x = attribute.getX( index );
  1488. this.y = attribute.getY( index );
  1489. this.z = attribute.getZ( index );
  1490. this.w = attribute.getW( index );
  1491. return this;
  1492. }
  1493. random() {
  1494. this.x = Math.random();
  1495. this.y = Math.random();
  1496. this.z = Math.random();
  1497. this.w = Math.random();
  1498. return this;
  1499. }
  1500. }
  1501. Vector4.prototype.isVector4 = true;
  1502. /*
  1503. In options, we can specify:
  1504. * Texture parameters for an auto-generated target texture
  1505. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1506. */
  1507. class WebGLRenderTarget extends EventDispatcher {
  1508. constructor( width, height, options = {} ) {
  1509. super();
  1510. this.width = width;
  1511. this.height = height;
  1512. this.depth = 1;
  1513. this.scissor = new Vector4( 0, 0, width, height );
  1514. this.scissorTest = false;
  1515. this.viewport = new Vector4( 0, 0, width, height );
  1516. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1517. this.texture.isRenderTargetTexture = true;
  1518. this.texture.image = { width: width, height: height, depth: 1 };
  1519. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1520. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1521. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1522. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1523. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1524. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1525. }
  1526. setTexture( texture ) {
  1527. texture.image = {
  1528. width: this.width,
  1529. height: this.height,
  1530. depth: this.depth
  1531. };
  1532. this.texture = texture;
  1533. }
  1534. setSize( width, height, depth = 1 ) {
  1535. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1536. this.width = width;
  1537. this.height = height;
  1538. this.depth = depth;
  1539. this.texture.image.width = width;
  1540. this.texture.image.height = height;
  1541. this.texture.image.depth = depth;
  1542. this.dispose();
  1543. }
  1544. this.viewport.set( 0, 0, width, height );
  1545. this.scissor.set( 0, 0, width, height );
  1546. }
  1547. clone() {
  1548. return new this.constructor().copy( this );
  1549. }
  1550. copy( source ) {
  1551. this.width = source.width;
  1552. this.height = source.height;
  1553. this.depth = source.depth;
  1554. this.viewport.copy( source.viewport );
  1555. this.texture = source.texture.clone();
  1556. this.texture.image = { ...this.texture.image }; // See #20328.
  1557. this.depthBuffer = source.depthBuffer;
  1558. this.stencilBuffer = source.stencilBuffer;
  1559. this.depthTexture = source.depthTexture;
  1560. return this;
  1561. }
  1562. dispose() {
  1563. this.dispatchEvent( { type: 'dispose' } );
  1564. }
  1565. }
  1566. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1567. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1568. constructor( width, height, count ) {
  1569. super( width, height );
  1570. const texture = this.texture;
  1571. this.texture = [];
  1572. for ( let i = 0; i < count; i ++ ) {
  1573. this.texture[ i ] = texture.clone();
  1574. }
  1575. }
  1576. setSize( width, height, depth = 1 ) {
  1577. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1578. this.width = width;
  1579. this.height = height;
  1580. this.depth = depth;
  1581. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1582. this.texture[ i ].image.width = width;
  1583. this.texture[ i ].image.height = height;
  1584. this.texture[ i ].image.depth = depth;
  1585. }
  1586. this.dispose();
  1587. }
  1588. this.viewport.set( 0, 0, width, height );
  1589. this.scissor.set( 0, 0, width, height );
  1590. return this;
  1591. }
  1592. copy( source ) {
  1593. this.dispose();
  1594. this.width = source.width;
  1595. this.height = source.height;
  1596. this.depth = source.depth;
  1597. this.viewport.set( 0, 0, this.width, this.height );
  1598. this.scissor.set( 0, 0, this.width, this.height );
  1599. this.depthBuffer = source.depthBuffer;
  1600. this.stencilBuffer = source.stencilBuffer;
  1601. this.depthTexture = source.depthTexture;
  1602. this.texture.length = 0;
  1603. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1604. this.texture[ i ] = source.texture[ i ].clone();
  1605. }
  1606. return this;
  1607. }
  1608. }
  1609. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1610. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1611. constructor( width, height, options ) {
  1612. super( width, height, options );
  1613. this.samples = 4;
  1614. }
  1615. copy( source ) {
  1616. super.copy.call( this, source );
  1617. this.samples = source.samples;
  1618. return this;
  1619. }
  1620. }
  1621. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1622. class Quaternion {
  1623. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1624. this._x = x;
  1625. this._y = y;
  1626. this._z = z;
  1627. this._w = w;
  1628. }
  1629. static slerp( qa, qb, qm, t ) {
  1630. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  1631. return qm.slerpQuaternions( qa, qb, t );
  1632. }
  1633. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1634. // fuzz-free, array-based Quaternion SLERP operation
  1635. let x0 = src0[ srcOffset0 + 0 ],
  1636. y0 = src0[ srcOffset0 + 1 ],
  1637. z0 = src0[ srcOffset0 + 2 ],
  1638. w0 = src0[ srcOffset0 + 3 ];
  1639. const x1 = src1[ srcOffset1 + 0 ],
  1640. y1 = src1[ srcOffset1 + 1 ],
  1641. z1 = src1[ srcOffset1 + 2 ],
  1642. w1 = src1[ srcOffset1 + 3 ];
  1643. if ( t === 0 ) {
  1644. dst[ dstOffset + 0 ] = x0;
  1645. dst[ dstOffset + 1 ] = y0;
  1646. dst[ dstOffset + 2 ] = z0;
  1647. dst[ dstOffset + 3 ] = w0;
  1648. return;
  1649. }
  1650. if ( t === 1 ) {
  1651. dst[ dstOffset + 0 ] = x1;
  1652. dst[ dstOffset + 1 ] = y1;
  1653. dst[ dstOffset + 2 ] = z1;
  1654. dst[ dstOffset + 3 ] = w1;
  1655. return;
  1656. }
  1657. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1658. let s = 1 - t;
  1659. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1660. dir = ( cos >= 0 ? 1 : - 1 ),
  1661. sqrSin = 1 - cos * cos;
  1662. // Skip the Slerp for tiny steps to avoid numeric problems:
  1663. if ( sqrSin > Number.EPSILON ) {
  1664. const sin = Math.sqrt( sqrSin ),
  1665. len = Math.atan2( sin, cos * dir );
  1666. s = Math.sin( s * len ) / sin;
  1667. t = Math.sin( t * len ) / sin;
  1668. }
  1669. const tDir = t * dir;
  1670. x0 = x0 * s + x1 * tDir;
  1671. y0 = y0 * s + y1 * tDir;
  1672. z0 = z0 * s + z1 * tDir;
  1673. w0 = w0 * s + w1 * tDir;
  1674. // Normalize in case we just did a lerp:
  1675. if ( s === 1 - t ) {
  1676. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1677. x0 *= f;
  1678. y0 *= f;
  1679. z0 *= f;
  1680. w0 *= f;
  1681. }
  1682. }
  1683. dst[ dstOffset ] = x0;
  1684. dst[ dstOffset + 1 ] = y0;
  1685. dst[ dstOffset + 2 ] = z0;
  1686. dst[ dstOffset + 3 ] = w0;
  1687. }
  1688. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1689. const x0 = src0[ srcOffset0 ];
  1690. const y0 = src0[ srcOffset0 + 1 ];
  1691. const z0 = src0[ srcOffset0 + 2 ];
  1692. const w0 = src0[ srcOffset0 + 3 ];
  1693. const x1 = src1[ srcOffset1 ];
  1694. const y1 = src1[ srcOffset1 + 1 ];
  1695. const z1 = src1[ srcOffset1 + 2 ];
  1696. const w1 = src1[ srcOffset1 + 3 ];
  1697. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1698. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1699. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1700. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1701. return dst;
  1702. }
  1703. get x() {
  1704. return this._x;
  1705. }
  1706. set x( value ) {
  1707. this._x = value;
  1708. this._onChangeCallback();
  1709. }
  1710. get y() {
  1711. return this._y;
  1712. }
  1713. set y( value ) {
  1714. this._y = value;
  1715. this._onChangeCallback();
  1716. }
  1717. get z() {
  1718. return this._z;
  1719. }
  1720. set z( value ) {
  1721. this._z = value;
  1722. this._onChangeCallback();
  1723. }
  1724. get w() {
  1725. return this._w;
  1726. }
  1727. set w( value ) {
  1728. this._w = value;
  1729. this._onChangeCallback();
  1730. }
  1731. set( x, y, z, w ) {
  1732. this._x = x;
  1733. this._y = y;
  1734. this._z = z;
  1735. this._w = w;
  1736. this._onChangeCallback();
  1737. return this;
  1738. }
  1739. clone() {
  1740. return new this.constructor( this._x, this._y, this._z, this._w );
  1741. }
  1742. copy( quaternion ) {
  1743. this._x = quaternion.x;
  1744. this._y = quaternion.y;
  1745. this._z = quaternion.z;
  1746. this._w = quaternion.w;
  1747. this._onChangeCallback();
  1748. return this;
  1749. }
  1750. setFromEuler( euler, update ) {
  1751. if ( ! ( euler && euler.isEuler ) ) {
  1752. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1753. }
  1754. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1755. // http://www.mathworks.com/matlabcentral/fileexchange/
  1756. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1757. // content/SpinCalc.m
  1758. const cos = Math.cos;
  1759. const sin = Math.sin;
  1760. const c1 = cos( x / 2 );
  1761. const c2 = cos( y / 2 );
  1762. const c3 = cos( z / 2 );
  1763. const s1 = sin( x / 2 );
  1764. const s2 = sin( y / 2 );
  1765. const s3 = sin( z / 2 );
  1766. switch ( order ) {
  1767. case 'XYZ':
  1768. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1769. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1770. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1771. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1772. break;
  1773. case 'YXZ':
  1774. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1775. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1776. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1777. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1778. break;
  1779. case 'ZXY':
  1780. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1781. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1782. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1783. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1784. break;
  1785. case 'ZYX':
  1786. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1787. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1788. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1789. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1790. break;
  1791. case 'YZX':
  1792. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1793. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1794. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1795. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1796. break;
  1797. case 'XZY':
  1798. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1799. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1800. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1801. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1802. break;
  1803. default:
  1804. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1805. }
  1806. if ( update !== false ) this._onChangeCallback();
  1807. return this;
  1808. }
  1809. setFromAxisAngle( axis, angle ) {
  1810. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1811. // assumes axis is normalized
  1812. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1813. this._x = axis.x * s;
  1814. this._y = axis.y * s;
  1815. this._z = axis.z * s;
  1816. this._w = Math.cos( halfAngle );
  1817. this._onChangeCallback();
  1818. return this;
  1819. }
  1820. setFromRotationMatrix( m ) {
  1821. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1822. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1823. const te = m.elements,
  1824. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1825. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1826. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1827. trace = m11 + m22 + m33;
  1828. if ( trace > 0 ) {
  1829. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1830. this._w = 0.25 / s;
  1831. this._x = ( m32 - m23 ) * s;
  1832. this._y = ( m13 - m31 ) * s;
  1833. this._z = ( m21 - m12 ) * s;
  1834. } else if ( m11 > m22 && m11 > m33 ) {
  1835. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1836. this._w = ( m32 - m23 ) / s;
  1837. this._x = 0.25 * s;
  1838. this._y = ( m12 + m21 ) / s;
  1839. this._z = ( m13 + m31 ) / s;
  1840. } else if ( m22 > m33 ) {
  1841. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1842. this._w = ( m13 - m31 ) / s;
  1843. this._x = ( m12 + m21 ) / s;
  1844. this._y = 0.25 * s;
  1845. this._z = ( m23 + m32 ) / s;
  1846. } else {
  1847. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1848. this._w = ( m21 - m12 ) / s;
  1849. this._x = ( m13 + m31 ) / s;
  1850. this._y = ( m23 + m32 ) / s;
  1851. this._z = 0.25 * s;
  1852. }
  1853. this._onChangeCallback();
  1854. return this;
  1855. }
  1856. setFromUnitVectors( vFrom, vTo ) {
  1857. // assumes direction vectors vFrom and vTo are normalized
  1858. let r = vFrom.dot( vTo ) + 1;
  1859. if ( r < Number.EPSILON ) {
  1860. // vFrom and vTo point in opposite directions
  1861. r = 0;
  1862. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1863. this._x = - vFrom.y;
  1864. this._y = vFrom.x;
  1865. this._z = 0;
  1866. this._w = r;
  1867. } else {
  1868. this._x = 0;
  1869. this._y = - vFrom.z;
  1870. this._z = vFrom.y;
  1871. this._w = r;
  1872. }
  1873. } else {
  1874. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1875. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1876. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1877. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1878. this._w = r;
  1879. }
  1880. return this.normalize();
  1881. }
  1882. angleTo( q ) {
  1883. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1884. }
  1885. rotateTowards( q, step ) {
  1886. const angle = this.angleTo( q );
  1887. if ( angle === 0 ) return this;
  1888. const t = Math.min( 1, step / angle );
  1889. this.slerp( q, t );
  1890. return this;
  1891. }
  1892. identity() {
  1893. return this.set( 0, 0, 0, 1 );
  1894. }
  1895. invert() {
  1896. // quaternion is assumed to have unit length
  1897. return this.conjugate();
  1898. }
  1899. conjugate() {
  1900. this._x *= - 1;
  1901. this._y *= - 1;
  1902. this._z *= - 1;
  1903. this._onChangeCallback();
  1904. return this;
  1905. }
  1906. dot( v ) {
  1907. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1908. }
  1909. lengthSq() {
  1910. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1911. }
  1912. length() {
  1913. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1914. }
  1915. normalize() {
  1916. let l = this.length();
  1917. if ( l === 0 ) {
  1918. this._x = 0;
  1919. this._y = 0;
  1920. this._z = 0;
  1921. this._w = 1;
  1922. } else {
  1923. l = 1 / l;
  1924. this._x = this._x * l;
  1925. this._y = this._y * l;
  1926. this._z = this._z * l;
  1927. this._w = this._w * l;
  1928. }
  1929. this._onChangeCallback();
  1930. return this;
  1931. }
  1932. multiply( q, p ) {
  1933. if ( p !== undefined ) {
  1934. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1935. return this.multiplyQuaternions( q, p );
  1936. }
  1937. return this.multiplyQuaternions( this, q );
  1938. }
  1939. premultiply( q ) {
  1940. return this.multiplyQuaternions( q, this );
  1941. }
  1942. multiplyQuaternions( a, b ) {
  1943. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1944. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1945. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1946. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1947. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1948. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1949. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1950. this._onChangeCallback();
  1951. return this;
  1952. }
  1953. slerp( qb, t ) {
  1954. if ( t === 0 ) return this;
  1955. if ( t === 1 ) return this.copy( qb );
  1956. const x = this._x, y = this._y, z = this._z, w = this._w;
  1957. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1958. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1959. if ( cosHalfTheta < 0 ) {
  1960. this._w = - qb._w;
  1961. this._x = - qb._x;
  1962. this._y = - qb._y;
  1963. this._z = - qb._z;
  1964. cosHalfTheta = - cosHalfTheta;
  1965. } else {
  1966. this.copy( qb );
  1967. }
  1968. if ( cosHalfTheta >= 1.0 ) {
  1969. this._w = w;
  1970. this._x = x;
  1971. this._y = y;
  1972. this._z = z;
  1973. return this;
  1974. }
  1975. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1976. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1977. const s = 1 - t;
  1978. this._w = s * w + t * this._w;
  1979. this._x = s * x + t * this._x;
  1980. this._y = s * y + t * this._y;
  1981. this._z = s * z + t * this._z;
  1982. this.normalize();
  1983. this._onChangeCallback();
  1984. return this;
  1985. }
  1986. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1987. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1988. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1989. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1990. this._w = ( w * ratioA + this._w * ratioB );
  1991. this._x = ( x * ratioA + this._x * ratioB );
  1992. this._y = ( y * ratioA + this._y * ratioB );
  1993. this._z = ( z * ratioA + this._z * ratioB );
  1994. this._onChangeCallback();
  1995. return this;
  1996. }
  1997. slerpQuaternions( qa, qb, t ) {
  1998. this.copy( qa ).slerp( qb, t );
  1999. }
  2000. equals( quaternion ) {
  2001. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2002. }
  2003. fromArray( array, offset = 0 ) {
  2004. this._x = array[ offset ];
  2005. this._y = array[ offset + 1 ];
  2006. this._z = array[ offset + 2 ];
  2007. this._w = array[ offset + 3 ];
  2008. this._onChangeCallback();
  2009. return this;
  2010. }
  2011. toArray( array = [], offset = 0 ) {
  2012. array[ offset ] = this._x;
  2013. array[ offset + 1 ] = this._y;
  2014. array[ offset + 2 ] = this._z;
  2015. array[ offset + 3 ] = this._w;
  2016. return array;
  2017. }
  2018. fromBufferAttribute( attribute, index ) {
  2019. this._x = attribute.getX( index );
  2020. this._y = attribute.getY( index );
  2021. this._z = attribute.getZ( index );
  2022. this._w = attribute.getW( index );
  2023. return this;
  2024. }
  2025. _onChange( callback ) {
  2026. this._onChangeCallback = callback;
  2027. return this;
  2028. }
  2029. _onChangeCallback() {}
  2030. }
  2031. Quaternion.prototype.isQuaternion = true;
  2032. class Vector3 {
  2033. constructor( x = 0, y = 0, z = 0 ) {
  2034. this.x = x;
  2035. this.y = y;
  2036. this.z = z;
  2037. }
  2038. set( x, y, z ) {
  2039. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2040. this.x = x;
  2041. this.y = y;
  2042. this.z = z;
  2043. return this;
  2044. }
  2045. setScalar( scalar ) {
  2046. this.x = scalar;
  2047. this.y = scalar;
  2048. this.z = scalar;
  2049. return this;
  2050. }
  2051. setX( x ) {
  2052. this.x = x;
  2053. return this;
  2054. }
  2055. setY( y ) {
  2056. this.y = y;
  2057. return this;
  2058. }
  2059. setZ( z ) {
  2060. this.z = z;
  2061. return this;
  2062. }
  2063. setComponent( index, value ) {
  2064. switch ( index ) {
  2065. case 0: this.x = value; break;
  2066. case 1: this.y = value; break;
  2067. case 2: this.z = value; break;
  2068. default: throw new Error( 'index is out of range: ' + index );
  2069. }
  2070. return this;
  2071. }
  2072. getComponent( index ) {
  2073. switch ( index ) {
  2074. case 0: return this.x;
  2075. case 1: return this.y;
  2076. case 2: return this.z;
  2077. default: throw new Error( 'index is out of range: ' + index );
  2078. }
  2079. }
  2080. clone() {
  2081. return new this.constructor( this.x, this.y, this.z );
  2082. }
  2083. copy( v ) {
  2084. this.x = v.x;
  2085. this.y = v.y;
  2086. this.z = v.z;
  2087. return this;
  2088. }
  2089. add( v, w ) {
  2090. if ( w !== undefined ) {
  2091. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2092. return this.addVectors( v, w );
  2093. }
  2094. this.x += v.x;
  2095. this.y += v.y;
  2096. this.z += v.z;
  2097. return this;
  2098. }
  2099. addScalar( s ) {
  2100. this.x += s;
  2101. this.y += s;
  2102. this.z += s;
  2103. return this;
  2104. }
  2105. addVectors( a, b ) {
  2106. this.x = a.x + b.x;
  2107. this.y = a.y + b.y;
  2108. this.z = a.z + b.z;
  2109. return this;
  2110. }
  2111. addScaledVector( v, s ) {
  2112. this.x += v.x * s;
  2113. this.y += v.y * s;
  2114. this.z += v.z * s;
  2115. return this;
  2116. }
  2117. sub( v, w ) {
  2118. if ( w !== undefined ) {
  2119. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2120. return this.subVectors( v, w );
  2121. }
  2122. this.x -= v.x;
  2123. this.y -= v.y;
  2124. this.z -= v.z;
  2125. return this;
  2126. }
  2127. subScalar( s ) {
  2128. this.x -= s;
  2129. this.y -= s;
  2130. this.z -= s;
  2131. return this;
  2132. }
  2133. subVectors( a, b ) {
  2134. this.x = a.x - b.x;
  2135. this.y = a.y - b.y;
  2136. this.z = a.z - b.z;
  2137. return this;
  2138. }
  2139. multiply( v, w ) {
  2140. if ( w !== undefined ) {
  2141. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2142. return this.multiplyVectors( v, w );
  2143. }
  2144. this.x *= v.x;
  2145. this.y *= v.y;
  2146. this.z *= v.z;
  2147. return this;
  2148. }
  2149. multiplyScalar( scalar ) {
  2150. this.x *= scalar;
  2151. this.y *= scalar;
  2152. this.z *= scalar;
  2153. return this;
  2154. }
  2155. multiplyVectors( a, b ) {
  2156. this.x = a.x * b.x;
  2157. this.y = a.y * b.y;
  2158. this.z = a.z * b.z;
  2159. return this;
  2160. }
  2161. applyEuler( euler ) {
  2162. if ( ! ( euler && euler.isEuler ) ) {
  2163. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2164. }
  2165. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2166. }
  2167. applyAxisAngle( axis, angle ) {
  2168. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2169. }
  2170. applyMatrix3( m ) {
  2171. const x = this.x, y = this.y, z = this.z;
  2172. const e = m.elements;
  2173. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2174. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2175. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2176. return this;
  2177. }
  2178. applyNormalMatrix( m ) {
  2179. return this.applyMatrix3( m ).normalize();
  2180. }
  2181. applyMatrix4( m ) {
  2182. const x = this.x, y = this.y, z = this.z;
  2183. const e = m.elements;
  2184. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2185. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2186. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2187. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2188. return this;
  2189. }
  2190. applyQuaternion( q ) {
  2191. const x = this.x, y = this.y, z = this.z;
  2192. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2193. // calculate quat * vector
  2194. const ix = qw * x + qy * z - qz * y;
  2195. const iy = qw * y + qz * x - qx * z;
  2196. const iz = qw * z + qx * y - qy * x;
  2197. const iw = - qx * x - qy * y - qz * z;
  2198. // calculate result * inverse quat
  2199. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2200. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2201. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2202. return this;
  2203. }
  2204. project( camera ) {
  2205. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2206. }
  2207. unproject( camera ) {
  2208. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2209. }
  2210. transformDirection( m ) {
  2211. // input: THREE.Matrix4 affine matrix
  2212. // vector interpreted as a direction
  2213. const x = this.x, y = this.y, z = this.z;
  2214. const e = m.elements;
  2215. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2216. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2217. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2218. return this.normalize();
  2219. }
  2220. divide( v ) {
  2221. this.x /= v.x;
  2222. this.y /= v.y;
  2223. this.z /= v.z;
  2224. return this;
  2225. }
  2226. divideScalar( scalar ) {
  2227. return this.multiplyScalar( 1 / scalar );
  2228. }
  2229. min( v ) {
  2230. this.x = Math.min( this.x, v.x );
  2231. this.y = Math.min( this.y, v.y );
  2232. this.z = Math.min( this.z, v.z );
  2233. return this;
  2234. }
  2235. max( v ) {
  2236. this.x = Math.max( this.x, v.x );
  2237. this.y = Math.max( this.y, v.y );
  2238. this.z = Math.max( this.z, v.z );
  2239. return this;
  2240. }
  2241. clamp( min, max ) {
  2242. // assumes min < max, componentwise
  2243. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2244. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2245. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2246. return this;
  2247. }
  2248. clampScalar( minVal, maxVal ) {
  2249. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2250. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2251. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2252. return this;
  2253. }
  2254. clampLength( min, max ) {
  2255. const length = this.length();
  2256. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2257. }
  2258. floor() {
  2259. this.x = Math.floor( this.x );
  2260. this.y = Math.floor( this.y );
  2261. this.z = Math.floor( this.z );
  2262. return this;
  2263. }
  2264. ceil() {
  2265. this.x = Math.ceil( this.x );
  2266. this.y = Math.ceil( this.y );
  2267. this.z = Math.ceil( this.z );
  2268. return this;
  2269. }
  2270. round() {
  2271. this.x = Math.round( this.x );
  2272. this.y = Math.round( this.y );
  2273. this.z = Math.round( this.z );
  2274. return this;
  2275. }
  2276. roundToZero() {
  2277. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2278. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2279. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2280. return this;
  2281. }
  2282. negate() {
  2283. this.x = - this.x;
  2284. this.y = - this.y;
  2285. this.z = - this.z;
  2286. return this;
  2287. }
  2288. dot( v ) {
  2289. return this.x * v.x + this.y * v.y + this.z * v.z;
  2290. }
  2291. // TODO lengthSquared?
  2292. lengthSq() {
  2293. return this.x * this.x + this.y * this.y + this.z * this.z;
  2294. }
  2295. length() {
  2296. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2297. }
  2298. manhattanLength() {
  2299. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2300. }
  2301. normalize() {
  2302. return this.divideScalar( this.length() || 1 );
  2303. }
  2304. setLength( length ) {
  2305. return this.normalize().multiplyScalar( length );
  2306. }
  2307. lerp( v, alpha ) {
  2308. this.x += ( v.x - this.x ) * alpha;
  2309. this.y += ( v.y - this.y ) * alpha;
  2310. this.z += ( v.z - this.z ) * alpha;
  2311. return this;
  2312. }
  2313. lerpVectors( v1, v2, alpha ) {
  2314. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2315. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2316. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2317. return this;
  2318. }
  2319. cross( v, w ) {
  2320. if ( w !== undefined ) {
  2321. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2322. return this.crossVectors( v, w );
  2323. }
  2324. return this.crossVectors( this, v );
  2325. }
  2326. crossVectors( a, b ) {
  2327. const ax = a.x, ay = a.y, az = a.z;
  2328. const bx = b.x, by = b.y, bz = b.z;
  2329. this.x = ay * bz - az * by;
  2330. this.y = az * bx - ax * bz;
  2331. this.z = ax * by - ay * bx;
  2332. return this;
  2333. }
  2334. projectOnVector( v ) {
  2335. const denominator = v.lengthSq();
  2336. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2337. const scalar = v.dot( this ) / denominator;
  2338. return this.copy( v ).multiplyScalar( scalar );
  2339. }
  2340. projectOnPlane( planeNormal ) {
  2341. _vector$c.copy( this ).projectOnVector( planeNormal );
  2342. return this.sub( _vector$c );
  2343. }
  2344. reflect( normal ) {
  2345. // reflect incident vector off plane orthogonal to normal
  2346. // normal is assumed to have unit length
  2347. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2348. }
  2349. angleTo( v ) {
  2350. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2351. if ( denominator === 0 ) return Math.PI / 2;
  2352. const theta = this.dot( v ) / denominator;
  2353. // clamp, to handle numerical problems
  2354. return Math.acos( clamp( theta, - 1, 1 ) );
  2355. }
  2356. distanceTo( v ) {
  2357. return Math.sqrt( this.distanceToSquared( v ) );
  2358. }
  2359. distanceToSquared( v ) {
  2360. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2361. return dx * dx + dy * dy + dz * dz;
  2362. }
  2363. manhattanDistanceTo( v ) {
  2364. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2365. }
  2366. setFromSpherical( s ) {
  2367. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2368. }
  2369. setFromSphericalCoords( radius, phi, theta ) {
  2370. const sinPhiRadius = Math.sin( phi ) * radius;
  2371. this.x = sinPhiRadius * Math.sin( theta );
  2372. this.y = Math.cos( phi ) * radius;
  2373. this.z = sinPhiRadius * Math.cos( theta );
  2374. return this;
  2375. }
  2376. setFromCylindrical( c ) {
  2377. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2378. }
  2379. setFromCylindricalCoords( radius, theta, y ) {
  2380. this.x = radius * Math.sin( theta );
  2381. this.y = y;
  2382. this.z = radius * Math.cos( theta );
  2383. return this;
  2384. }
  2385. setFromMatrixPosition( m ) {
  2386. const e = m.elements;
  2387. this.x = e[ 12 ];
  2388. this.y = e[ 13 ];
  2389. this.z = e[ 14 ];
  2390. return this;
  2391. }
  2392. setFromMatrixScale( m ) {
  2393. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2394. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2395. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2396. this.x = sx;
  2397. this.y = sy;
  2398. this.z = sz;
  2399. return this;
  2400. }
  2401. setFromMatrixColumn( m, index ) {
  2402. return this.fromArray( m.elements, index * 4 );
  2403. }
  2404. setFromMatrix3Column( m, index ) {
  2405. return this.fromArray( m.elements, index * 3 );
  2406. }
  2407. equals( v ) {
  2408. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2409. }
  2410. fromArray( array, offset = 0 ) {
  2411. this.x = array[ offset ];
  2412. this.y = array[ offset + 1 ];
  2413. this.z = array[ offset + 2 ];
  2414. return this;
  2415. }
  2416. toArray( array = [], offset = 0 ) {
  2417. array[ offset ] = this.x;
  2418. array[ offset + 1 ] = this.y;
  2419. array[ offset + 2 ] = this.z;
  2420. return array;
  2421. }
  2422. fromBufferAttribute( attribute, index, offset ) {
  2423. if ( offset !== undefined ) {
  2424. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2425. }
  2426. this.x = attribute.getX( index );
  2427. this.y = attribute.getY( index );
  2428. this.z = attribute.getZ( index );
  2429. return this;
  2430. }
  2431. random() {
  2432. this.x = Math.random();
  2433. this.y = Math.random();
  2434. this.z = Math.random();
  2435. return this;
  2436. }
  2437. }
  2438. Vector3.prototype.isVector3 = true;
  2439. const _vector$c = /*@__PURE__*/ new Vector3();
  2440. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2441. class Box3 {
  2442. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2443. this.min = min;
  2444. this.max = max;
  2445. }
  2446. set( min, max ) {
  2447. this.min.copy( min );
  2448. this.max.copy( max );
  2449. return this;
  2450. }
  2451. setFromArray( array ) {
  2452. let minX = + Infinity;
  2453. let minY = + Infinity;
  2454. let minZ = + Infinity;
  2455. let maxX = - Infinity;
  2456. let maxY = - Infinity;
  2457. let maxZ = - Infinity;
  2458. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2459. const x = array[ i ];
  2460. const y = array[ i + 1 ];
  2461. const z = array[ i + 2 ];
  2462. if ( x < minX ) minX = x;
  2463. if ( y < minY ) minY = y;
  2464. if ( z < minZ ) minZ = z;
  2465. if ( x > maxX ) maxX = x;
  2466. if ( y > maxY ) maxY = y;
  2467. if ( z > maxZ ) maxZ = z;
  2468. }
  2469. this.min.set( minX, minY, minZ );
  2470. this.max.set( maxX, maxY, maxZ );
  2471. return this;
  2472. }
  2473. setFromBufferAttribute( attribute ) {
  2474. let minX = + Infinity;
  2475. let minY = + Infinity;
  2476. let minZ = + Infinity;
  2477. let maxX = - Infinity;
  2478. let maxY = - Infinity;
  2479. let maxZ = - Infinity;
  2480. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2481. const x = attribute.getX( i );
  2482. const y = attribute.getY( i );
  2483. const z = attribute.getZ( i );
  2484. if ( x < minX ) minX = x;
  2485. if ( y < minY ) minY = y;
  2486. if ( z < minZ ) minZ = z;
  2487. if ( x > maxX ) maxX = x;
  2488. if ( y > maxY ) maxY = y;
  2489. if ( z > maxZ ) maxZ = z;
  2490. }
  2491. this.min.set( minX, minY, minZ );
  2492. this.max.set( maxX, maxY, maxZ );
  2493. return this;
  2494. }
  2495. setFromPoints( points ) {
  2496. this.makeEmpty();
  2497. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2498. this.expandByPoint( points[ i ] );
  2499. }
  2500. return this;
  2501. }
  2502. setFromCenterAndSize( center, size ) {
  2503. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2504. this.min.copy( center ).sub( halfSize );
  2505. this.max.copy( center ).add( halfSize );
  2506. return this;
  2507. }
  2508. setFromObject( object ) {
  2509. this.makeEmpty();
  2510. return this.expandByObject( object );
  2511. }
  2512. clone() {
  2513. return new this.constructor().copy( this );
  2514. }
  2515. copy( box ) {
  2516. this.min.copy( box.min );
  2517. this.max.copy( box.max );
  2518. return this;
  2519. }
  2520. makeEmpty() {
  2521. this.min.x = this.min.y = this.min.z = + Infinity;
  2522. this.max.x = this.max.y = this.max.z = - Infinity;
  2523. return this;
  2524. }
  2525. isEmpty() {
  2526. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2527. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2528. }
  2529. getCenter( target ) {
  2530. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2531. }
  2532. getSize( target ) {
  2533. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2534. }
  2535. expandByPoint( point ) {
  2536. this.min.min( point );
  2537. this.max.max( point );
  2538. return this;
  2539. }
  2540. expandByVector( vector ) {
  2541. this.min.sub( vector );
  2542. this.max.add( vector );
  2543. return this;
  2544. }
  2545. expandByScalar( scalar ) {
  2546. this.min.addScalar( - scalar );
  2547. this.max.addScalar( scalar );
  2548. return this;
  2549. }
  2550. expandByObject( object ) {
  2551. // Computes the world-axis-aligned bounding box of an object (including its children),
  2552. // accounting for both the object's, and children's, world transforms
  2553. object.updateWorldMatrix( false, false );
  2554. const geometry = object.geometry;
  2555. if ( geometry !== undefined ) {
  2556. if ( geometry.boundingBox === null ) {
  2557. geometry.computeBoundingBox();
  2558. }
  2559. _box$3.copy( geometry.boundingBox );
  2560. _box$3.applyMatrix4( object.matrixWorld );
  2561. this.union( _box$3 );
  2562. }
  2563. const children = object.children;
  2564. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2565. this.expandByObject( children[ i ] );
  2566. }
  2567. return this;
  2568. }
  2569. containsPoint( point ) {
  2570. return point.x < this.min.x || point.x > this.max.x ||
  2571. point.y < this.min.y || point.y > this.max.y ||
  2572. point.z < this.min.z || point.z > this.max.z ? false : true;
  2573. }
  2574. containsBox( box ) {
  2575. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2576. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2577. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2578. }
  2579. getParameter( point, target ) {
  2580. // This can potentially have a divide by zero if the box
  2581. // has a size dimension of 0.
  2582. return target.set(
  2583. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2584. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2585. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2586. );
  2587. }
  2588. intersectsBox( box ) {
  2589. // using 6 splitting planes to rule out intersections.
  2590. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2591. box.max.y < this.min.y || box.min.y > this.max.y ||
  2592. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2593. }
  2594. intersectsSphere( sphere ) {
  2595. // Find the point on the AABB closest to the sphere center.
  2596. this.clampPoint( sphere.center, _vector$b );
  2597. // If that point is inside the sphere, the AABB and sphere intersect.
  2598. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2599. }
  2600. intersectsPlane( plane ) {
  2601. // We compute the minimum and maximum dot product values. If those values
  2602. // are on the same side (back or front) of the plane, then there is no intersection.
  2603. let min, max;
  2604. if ( plane.normal.x > 0 ) {
  2605. min = plane.normal.x * this.min.x;
  2606. max = plane.normal.x * this.max.x;
  2607. } else {
  2608. min = plane.normal.x * this.max.x;
  2609. max = plane.normal.x * this.min.x;
  2610. }
  2611. if ( plane.normal.y > 0 ) {
  2612. min += plane.normal.y * this.min.y;
  2613. max += plane.normal.y * this.max.y;
  2614. } else {
  2615. min += plane.normal.y * this.max.y;
  2616. max += plane.normal.y * this.min.y;
  2617. }
  2618. if ( plane.normal.z > 0 ) {
  2619. min += plane.normal.z * this.min.z;
  2620. max += plane.normal.z * this.max.z;
  2621. } else {
  2622. min += plane.normal.z * this.max.z;
  2623. max += plane.normal.z * this.min.z;
  2624. }
  2625. return ( min <= - plane.constant && max >= - plane.constant );
  2626. }
  2627. intersectsTriangle( triangle ) {
  2628. if ( this.isEmpty() ) {
  2629. return false;
  2630. }
  2631. // compute box center and extents
  2632. this.getCenter( _center );
  2633. _extents.subVectors( this.max, _center );
  2634. // translate triangle to aabb origin
  2635. _v0$2.subVectors( triangle.a, _center );
  2636. _v1$7.subVectors( triangle.b, _center );
  2637. _v2$3.subVectors( triangle.c, _center );
  2638. // compute edge vectors for triangle
  2639. _f0.subVectors( _v1$7, _v0$2 );
  2640. _f1.subVectors( _v2$3, _v1$7 );
  2641. _f2.subVectors( _v0$2, _v2$3 );
  2642. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2643. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  2644. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2645. let axes = [
  2646. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2647. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2648. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2649. ];
  2650. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2651. return false;
  2652. }
  2653. // test 3 face normals from the aabb
  2654. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2655. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2656. return false;
  2657. }
  2658. // finally testing the face normal of the triangle
  2659. // use already existing triangle edge vectors here
  2660. _triangleNormal.crossVectors( _f0, _f1 );
  2661. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2662. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  2663. }
  2664. clampPoint( point, target ) {
  2665. return target.copy( point ).clamp( this.min, this.max );
  2666. }
  2667. distanceToPoint( point ) {
  2668. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  2669. return clampedPoint.sub( point ).length();
  2670. }
  2671. getBoundingSphere( target ) {
  2672. this.getCenter( target.center );
  2673. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2674. return target;
  2675. }
  2676. intersect( box ) {
  2677. this.min.max( box.min );
  2678. this.max.min( box.max );
  2679. // 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.
  2680. if ( this.isEmpty() ) this.makeEmpty();
  2681. return this;
  2682. }
  2683. union( box ) {
  2684. this.min.min( box.min );
  2685. this.max.max( box.max );
  2686. return this;
  2687. }
  2688. applyMatrix4( matrix ) {
  2689. // transform of empty box is an empty box.
  2690. if ( this.isEmpty() ) return this;
  2691. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2692. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2693. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2694. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2695. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2696. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2697. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2698. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2699. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2700. this.setFromPoints( _points );
  2701. return this;
  2702. }
  2703. translate( offset ) {
  2704. this.min.add( offset );
  2705. this.max.add( offset );
  2706. return this;
  2707. }
  2708. equals( box ) {
  2709. return box.min.equals( this.min ) && box.max.equals( this.max );
  2710. }
  2711. }
  2712. Box3.prototype.isBox3 = true;
  2713. const _points = [
  2714. /*@__PURE__*/ new Vector3(),
  2715. /*@__PURE__*/ new Vector3(),
  2716. /*@__PURE__*/ new Vector3(),
  2717. /*@__PURE__*/ new Vector3(),
  2718. /*@__PURE__*/ new Vector3(),
  2719. /*@__PURE__*/ new Vector3(),
  2720. /*@__PURE__*/ new Vector3(),
  2721. /*@__PURE__*/ new Vector3()
  2722. ];
  2723. const _vector$b = /*@__PURE__*/ new Vector3();
  2724. const _box$3 = /*@__PURE__*/ new Box3();
  2725. // triangle centered vertices
  2726. const _v0$2 = /*@__PURE__*/ new Vector3();
  2727. const _v1$7 = /*@__PURE__*/ new Vector3();
  2728. const _v2$3 = /*@__PURE__*/ new Vector3();
  2729. // triangle edge vectors
  2730. const _f0 = /*@__PURE__*/ new Vector3();
  2731. const _f1 = /*@__PURE__*/ new Vector3();
  2732. const _f2 = /*@__PURE__*/ new Vector3();
  2733. const _center = /*@__PURE__*/ new Vector3();
  2734. const _extents = /*@__PURE__*/ new Vector3();
  2735. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2736. const _testAxis = /*@__PURE__*/ new Vector3();
  2737. function satForAxes( axes, v0, v1, v2, extents ) {
  2738. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2739. _testAxis.fromArray( axes, i );
  2740. // project the aabb onto the seperating axis
  2741. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2742. // project all 3 vertices of the triangle onto the seperating axis
  2743. const p0 = v0.dot( _testAxis );
  2744. const p1 = v1.dot( _testAxis );
  2745. const p2 = v2.dot( _testAxis );
  2746. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2747. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2748. // points of the projected triangle are outside the projected half-length of the aabb
  2749. // the axis is seperating and we can exit
  2750. return false;
  2751. }
  2752. }
  2753. return true;
  2754. }
  2755. const _box$2 = /*@__PURE__*/ new Box3();
  2756. const _v1$6 = /*@__PURE__*/ new Vector3();
  2757. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  2758. const _toPoint = /*@__PURE__*/ new Vector3();
  2759. class Sphere {
  2760. constructor( center = new Vector3(), radius = - 1 ) {
  2761. this.center = center;
  2762. this.radius = radius;
  2763. }
  2764. set( center, radius ) {
  2765. this.center.copy( center );
  2766. this.radius = radius;
  2767. return this;
  2768. }
  2769. setFromPoints( points, optionalCenter ) {
  2770. const center = this.center;
  2771. if ( optionalCenter !== undefined ) {
  2772. center.copy( optionalCenter );
  2773. } else {
  2774. _box$2.setFromPoints( points ).getCenter( center );
  2775. }
  2776. let maxRadiusSq = 0;
  2777. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2778. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2779. }
  2780. this.radius = Math.sqrt( maxRadiusSq );
  2781. return this;
  2782. }
  2783. copy( sphere ) {
  2784. this.center.copy( sphere.center );
  2785. this.radius = sphere.radius;
  2786. return this;
  2787. }
  2788. isEmpty() {
  2789. return ( this.radius < 0 );
  2790. }
  2791. makeEmpty() {
  2792. this.center.set( 0, 0, 0 );
  2793. this.radius = - 1;
  2794. return this;
  2795. }
  2796. containsPoint( point ) {
  2797. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2798. }
  2799. distanceToPoint( point ) {
  2800. return ( point.distanceTo( this.center ) - this.radius );
  2801. }
  2802. intersectsSphere( sphere ) {
  2803. const radiusSum = this.radius + sphere.radius;
  2804. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2805. }
  2806. intersectsBox( box ) {
  2807. return box.intersectsSphere( this );
  2808. }
  2809. intersectsPlane( plane ) {
  2810. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2811. }
  2812. clampPoint( point, target ) {
  2813. const deltaLengthSq = this.center.distanceToSquared( point );
  2814. target.copy( point );
  2815. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2816. target.sub( this.center ).normalize();
  2817. target.multiplyScalar( this.radius ).add( this.center );
  2818. }
  2819. return target;
  2820. }
  2821. getBoundingBox( target ) {
  2822. if ( this.isEmpty() ) {
  2823. // Empty sphere produces empty bounding box
  2824. target.makeEmpty();
  2825. return target;
  2826. }
  2827. target.set( this.center, this.center );
  2828. target.expandByScalar( this.radius );
  2829. return target;
  2830. }
  2831. applyMatrix4( matrix ) {
  2832. this.center.applyMatrix4( matrix );
  2833. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2834. return this;
  2835. }
  2836. translate( offset ) {
  2837. this.center.add( offset );
  2838. return this;
  2839. }
  2840. expandByPoint( point ) {
  2841. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2842. _toPoint.subVectors( point, this.center );
  2843. const lengthSq = _toPoint.lengthSq();
  2844. if ( lengthSq > ( this.radius * this.radius ) ) {
  2845. const length = Math.sqrt( lengthSq );
  2846. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  2847. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2848. // and the other half to position. This gives a tighter enclosure, instead of if
  2849. // the whole missing distance were just added to radius.
  2850. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  2851. this.radius += missingRadiusHalf;
  2852. }
  2853. return this;
  2854. }
  2855. union( sphere ) {
  2856. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2857. // To enclose another sphere into this sphere, we only need to enclose two points:
  2858. // 1) Enclose the farthest point on the other sphere into this sphere.
  2859. // 2) Enclose the opposite point of the farthest point into this sphere.
  2860. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  2861. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  2862. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  2863. return this;
  2864. }
  2865. equals( sphere ) {
  2866. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2867. }
  2868. clone() {
  2869. return new this.constructor().copy( this );
  2870. }
  2871. }
  2872. const _vector$a = /*@__PURE__*/ new Vector3();
  2873. const _segCenter = /*@__PURE__*/ new Vector3();
  2874. const _segDir = /*@__PURE__*/ new Vector3();
  2875. const _diff = /*@__PURE__*/ new Vector3();
  2876. const _edge1 = /*@__PURE__*/ new Vector3();
  2877. const _edge2 = /*@__PURE__*/ new Vector3();
  2878. const _normal$1 = /*@__PURE__*/ new Vector3();
  2879. class Ray {
  2880. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  2881. this.origin = origin;
  2882. this.direction = direction;
  2883. }
  2884. set( origin, direction ) {
  2885. this.origin.copy( origin );
  2886. this.direction.copy( direction );
  2887. return this;
  2888. }
  2889. copy( ray ) {
  2890. this.origin.copy( ray.origin );
  2891. this.direction.copy( ray.direction );
  2892. return this;
  2893. }
  2894. at( t, target ) {
  2895. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2896. }
  2897. lookAt( v ) {
  2898. this.direction.copy( v ).sub( this.origin ).normalize();
  2899. return this;
  2900. }
  2901. recast( t ) {
  2902. this.origin.copy( this.at( t, _vector$a ) );
  2903. return this;
  2904. }
  2905. closestPointToPoint( point, target ) {
  2906. target.subVectors( point, this.origin );
  2907. const directionDistance = target.dot( this.direction );
  2908. if ( directionDistance < 0 ) {
  2909. return target.copy( this.origin );
  2910. }
  2911. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2912. }
  2913. distanceToPoint( point ) {
  2914. return Math.sqrt( this.distanceSqToPoint( point ) );
  2915. }
  2916. distanceSqToPoint( point ) {
  2917. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  2918. // point behind the ray
  2919. if ( directionDistance < 0 ) {
  2920. return this.origin.distanceToSquared( point );
  2921. }
  2922. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2923. return _vector$a.distanceToSquared( point );
  2924. }
  2925. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  2926. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2927. // It returns the min distance between the ray and the segment
  2928. // defined by v0 and v1
  2929. // It can also set two optional targets :
  2930. // - The closest point on the ray
  2931. // - The closest point on the segment
  2932. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  2933. _segDir.copy( v1 ).sub( v0 ).normalize();
  2934. _diff.copy( this.origin ).sub( _segCenter );
  2935. const segExtent = v0.distanceTo( v1 ) * 0.5;
  2936. const a01 = - this.direction.dot( _segDir );
  2937. const b0 = _diff.dot( this.direction );
  2938. const b1 = - _diff.dot( _segDir );
  2939. const c = _diff.lengthSq();
  2940. const det = Math.abs( 1 - a01 * a01 );
  2941. let s0, s1, sqrDist, extDet;
  2942. if ( det > 0 ) {
  2943. // The ray and segment are not parallel.
  2944. s0 = a01 * b1 - b0;
  2945. s1 = a01 * b0 - b1;
  2946. extDet = segExtent * det;
  2947. if ( s0 >= 0 ) {
  2948. if ( s1 >= - extDet ) {
  2949. if ( s1 <= extDet ) {
  2950. // region 0
  2951. // Minimum at interior points of ray and segment.
  2952. const invDet = 1 / det;
  2953. s0 *= invDet;
  2954. s1 *= invDet;
  2955. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  2956. } else {
  2957. // region 1
  2958. s1 = segExtent;
  2959. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2960. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2961. }
  2962. } else {
  2963. // region 5
  2964. s1 = - segExtent;
  2965. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2966. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2967. }
  2968. } else {
  2969. if ( s1 <= - extDet ) {
  2970. // region 4
  2971. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  2972. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2973. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2974. } else if ( s1 <= extDet ) {
  2975. // region 3
  2976. s0 = 0;
  2977. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2978. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  2979. } else {
  2980. // region 2
  2981. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  2982. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2983. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2984. }
  2985. }
  2986. } else {
  2987. // Ray and segment are parallel.
  2988. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  2989. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2990. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2991. }
  2992. if ( optionalPointOnRay ) {
  2993. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  2994. }
  2995. if ( optionalPointOnSegment ) {
  2996. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  2997. }
  2998. return sqrDist;
  2999. }
  3000. intersectSphere( sphere, target ) {
  3001. _vector$a.subVectors( sphere.center, this.origin );
  3002. const tca = _vector$a.dot( this.direction );
  3003. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3004. const radius2 = sphere.radius * sphere.radius;
  3005. if ( d2 > radius2 ) return null;
  3006. const thc = Math.sqrt( radius2 - d2 );
  3007. // t0 = first intersect point - entrance on front of sphere
  3008. const t0 = tca - thc;
  3009. // t1 = second intersect point - exit point on back of sphere
  3010. const t1 = tca + thc;
  3011. // test to see if both t0 and t1 are behind the ray - if so, return null
  3012. if ( t0 < 0 && t1 < 0 ) return null;
  3013. // test to see if t0 is behind the ray:
  3014. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3015. // in order to always return an intersect point that is in front of the ray.
  3016. if ( t0 < 0 ) return this.at( t1, target );
  3017. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3018. return this.at( t0, target );
  3019. }
  3020. intersectsSphere( sphere ) {
  3021. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3022. }
  3023. distanceToPlane( plane ) {
  3024. const denominator = plane.normal.dot( this.direction );
  3025. if ( denominator === 0 ) {
  3026. // line is coplanar, return origin
  3027. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3028. return 0;
  3029. }
  3030. // Null is preferable to undefined since undefined means.... it is undefined
  3031. return null;
  3032. }
  3033. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3034. // Return if the ray never intersects the plane
  3035. return t >= 0 ? t : null;
  3036. }
  3037. intersectPlane( plane, target ) {
  3038. const t = this.distanceToPlane( plane );
  3039. if ( t === null ) {
  3040. return null;
  3041. }
  3042. return this.at( t, target );
  3043. }
  3044. intersectsPlane( plane ) {
  3045. // check if the ray lies on the plane first
  3046. const distToPoint = plane.distanceToPoint( this.origin );
  3047. if ( distToPoint === 0 ) {
  3048. return true;
  3049. }
  3050. const denominator = plane.normal.dot( this.direction );
  3051. if ( denominator * distToPoint < 0 ) {
  3052. return true;
  3053. }
  3054. // ray origin is behind the plane (and is pointing behind it)
  3055. return false;
  3056. }
  3057. intersectBox( box, target ) {
  3058. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3059. const invdirx = 1 / this.direction.x,
  3060. invdiry = 1 / this.direction.y,
  3061. invdirz = 1 / this.direction.z;
  3062. const origin = this.origin;
  3063. if ( invdirx >= 0 ) {
  3064. tmin = ( box.min.x - origin.x ) * invdirx;
  3065. tmax = ( box.max.x - origin.x ) * invdirx;
  3066. } else {
  3067. tmin = ( box.max.x - origin.x ) * invdirx;
  3068. tmax = ( box.min.x - origin.x ) * invdirx;
  3069. }
  3070. if ( invdiry >= 0 ) {
  3071. tymin = ( box.min.y - origin.y ) * invdiry;
  3072. tymax = ( box.max.y - origin.y ) * invdiry;
  3073. } else {
  3074. tymin = ( box.max.y - origin.y ) * invdiry;
  3075. tymax = ( box.min.y - origin.y ) * invdiry;
  3076. }
  3077. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3078. // These lines also handle the case where tmin or tmax is NaN
  3079. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3080. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3081. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3082. if ( invdirz >= 0 ) {
  3083. tzmin = ( box.min.z - origin.z ) * invdirz;
  3084. tzmax = ( box.max.z - origin.z ) * invdirz;
  3085. } else {
  3086. tzmin = ( box.max.z - origin.z ) * invdirz;
  3087. tzmax = ( box.min.z - origin.z ) * invdirz;
  3088. }
  3089. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3090. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3091. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3092. //return point closest to the ray (positive side)
  3093. if ( tmax < 0 ) return null;
  3094. return this.at( tmin >= 0 ? tmin : tmax, target );
  3095. }
  3096. intersectsBox( box ) {
  3097. return this.intersectBox( box, _vector$a ) !== null;
  3098. }
  3099. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3100. // Compute the offset origin, edges, and normal.
  3101. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3102. _edge1.subVectors( b, a );
  3103. _edge2.subVectors( c, a );
  3104. _normal$1.crossVectors( _edge1, _edge2 );
  3105. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3106. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3107. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3108. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3109. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3110. let DdN = this.direction.dot( _normal$1 );
  3111. let sign;
  3112. if ( DdN > 0 ) {
  3113. if ( backfaceCulling ) return null;
  3114. sign = 1;
  3115. } else if ( DdN < 0 ) {
  3116. sign = - 1;
  3117. DdN = - DdN;
  3118. } else {
  3119. return null;
  3120. }
  3121. _diff.subVectors( this.origin, a );
  3122. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3123. // b1 < 0, no intersection
  3124. if ( DdQxE2 < 0 ) {
  3125. return null;
  3126. }
  3127. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3128. // b2 < 0, no intersection
  3129. if ( DdE1xQ < 0 ) {
  3130. return null;
  3131. }
  3132. // b1+b2 > 1, no intersection
  3133. if ( DdQxE2 + DdE1xQ > DdN ) {
  3134. return null;
  3135. }
  3136. // Line intersects triangle, check if ray does.
  3137. const QdN = - sign * _diff.dot( _normal$1 );
  3138. // t < 0, no intersection
  3139. if ( QdN < 0 ) {
  3140. return null;
  3141. }
  3142. // Ray intersects triangle.
  3143. return this.at( QdN / DdN, target );
  3144. }
  3145. applyMatrix4( matrix4 ) {
  3146. this.origin.applyMatrix4( matrix4 );
  3147. this.direction.transformDirection( matrix4 );
  3148. return this;
  3149. }
  3150. equals( ray ) {
  3151. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3152. }
  3153. clone() {
  3154. return new this.constructor().copy( this );
  3155. }
  3156. }
  3157. class Matrix4 {
  3158. constructor() {
  3159. this.elements = [
  3160. 1, 0, 0, 0,
  3161. 0, 1, 0, 0,
  3162. 0, 0, 1, 0,
  3163. 0, 0, 0, 1
  3164. ];
  3165. if ( arguments.length > 0 ) {
  3166. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3167. }
  3168. }
  3169. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3170. const te = this.elements;
  3171. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3172. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3173. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3174. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3175. return this;
  3176. }
  3177. identity() {
  3178. this.set(
  3179. 1, 0, 0, 0,
  3180. 0, 1, 0, 0,
  3181. 0, 0, 1, 0,
  3182. 0, 0, 0, 1
  3183. );
  3184. return this;
  3185. }
  3186. clone() {
  3187. return new Matrix4().fromArray( this.elements );
  3188. }
  3189. copy( m ) {
  3190. const te = this.elements;
  3191. const me = m.elements;
  3192. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3193. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3194. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3195. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3196. return this;
  3197. }
  3198. copyPosition( m ) {
  3199. const te = this.elements, me = m.elements;
  3200. te[ 12 ] = me[ 12 ];
  3201. te[ 13 ] = me[ 13 ];
  3202. te[ 14 ] = me[ 14 ];
  3203. return this;
  3204. }
  3205. setFromMatrix3( m ) {
  3206. const me = m.elements;
  3207. this.set(
  3208. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3209. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3210. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3211. 0, 0, 0, 1
  3212. );
  3213. return this;
  3214. }
  3215. extractBasis( xAxis, yAxis, zAxis ) {
  3216. xAxis.setFromMatrixColumn( this, 0 );
  3217. yAxis.setFromMatrixColumn( this, 1 );
  3218. zAxis.setFromMatrixColumn( this, 2 );
  3219. return this;
  3220. }
  3221. makeBasis( xAxis, yAxis, zAxis ) {
  3222. this.set(
  3223. xAxis.x, yAxis.x, zAxis.x, 0,
  3224. xAxis.y, yAxis.y, zAxis.y, 0,
  3225. xAxis.z, yAxis.z, zAxis.z, 0,
  3226. 0, 0, 0, 1
  3227. );
  3228. return this;
  3229. }
  3230. extractRotation( m ) {
  3231. // this method does not support reflection matrices
  3232. const te = this.elements;
  3233. const me = m.elements;
  3234. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3235. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3236. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3237. te[ 0 ] = me[ 0 ] * scaleX;
  3238. te[ 1 ] = me[ 1 ] * scaleX;
  3239. te[ 2 ] = me[ 2 ] * scaleX;
  3240. te[ 3 ] = 0;
  3241. te[ 4 ] = me[ 4 ] * scaleY;
  3242. te[ 5 ] = me[ 5 ] * scaleY;
  3243. te[ 6 ] = me[ 6 ] * scaleY;
  3244. te[ 7 ] = 0;
  3245. te[ 8 ] = me[ 8 ] * scaleZ;
  3246. te[ 9 ] = me[ 9 ] * scaleZ;
  3247. te[ 10 ] = me[ 10 ] * scaleZ;
  3248. te[ 11 ] = 0;
  3249. te[ 12 ] = 0;
  3250. te[ 13 ] = 0;
  3251. te[ 14 ] = 0;
  3252. te[ 15 ] = 1;
  3253. return this;
  3254. }
  3255. makeRotationFromEuler( euler ) {
  3256. if ( ! ( euler && euler.isEuler ) ) {
  3257. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3258. }
  3259. const te = this.elements;
  3260. const x = euler.x, y = euler.y, z = euler.z;
  3261. const a = Math.cos( x ), b = Math.sin( x );
  3262. const c = Math.cos( y ), d = Math.sin( y );
  3263. const e = Math.cos( z ), f = Math.sin( z );
  3264. if ( euler.order === 'XYZ' ) {
  3265. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3266. te[ 0 ] = c * e;
  3267. te[ 4 ] = - c * f;
  3268. te[ 8 ] = d;
  3269. te[ 1 ] = af + be * d;
  3270. te[ 5 ] = ae - bf * d;
  3271. te[ 9 ] = - b * c;
  3272. te[ 2 ] = bf - ae * d;
  3273. te[ 6 ] = be + af * d;
  3274. te[ 10 ] = a * c;
  3275. } else if ( euler.order === 'YXZ' ) {
  3276. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3277. te[ 0 ] = ce + df * b;
  3278. te[ 4 ] = de * b - cf;
  3279. te[ 8 ] = a * d;
  3280. te[ 1 ] = a * f;
  3281. te[ 5 ] = a * e;
  3282. te[ 9 ] = - b;
  3283. te[ 2 ] = cf * b - de;
  3284. te[ 6 ] = df + ce * b;
  3285. te[ 10 ] = a * c;
  3286. } else if ( euler.order === 'ZXY' ) {
  3287. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3288. te[ 0 ] = ce - df * b;
  3289. te[ 4 ] = - a * f;
  3290. te[ 8 ] = de + cf * b;
  3291. te[ 1 ] = cf + de * b;
  3292. te[ 5 ] = a * e;
  3293. te[ 9 ] = df - ce * b;
  3294. te[ 2 ] = - a * d;
  3295. te[ 6 ] = b;
  3296. te[ 10 ] = a * c;
  3297. } else if ( euler.order === 'ZYX' ) {
  3298. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3299. te[ 0 ] = c * e;
  3300. te[ 4 ] = be * d - af;
  3301. te[ 8 ] = ae * d + bf;
  3302. te[ 1 ] = c * f;
  3303. te[ 5 ] = bf * d + ae;
  3304. te[ 9 ] = af * d - be;
  3305. te[ 2 ] = - d;
  3306. te[ 6 ] = b * c;
  3307. te[ 10 ] = a * c;
  3308. } else if ( euler.order === 'YZX' ) {
  3309. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3310. te[ 0 ] = c * e;
  3311. te[ 4 ] = bd - ac * f;
  3312. te[ 8 ] = bc * f + ad;
  3313. te[ 1 ] = f;
  3314. te[ 5 ] = a * e;
  3315. te[ 9 ] = - b * e;
  3316. te[ 2 ] = - d * e;
  3317. te[ 6 ] = ad * f + bc;
  3318. te[ 10 ] = ac - bd * f;
  3319. } else if ( euler.order === 'XZY' ) {
  3320. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3321. te[ 0 ] = c * e;
  3322. te[ 4 ] = - f;
  3323. te[ 8 ] = d * e;
  3324. te[ 1 ] = ac * f + bd;
  3325. te[ 5 ] = a * e;
  3326. te[ 9 ] = ad * f - bc;
  3327. te[ 2 ] = bc * f - ad;
  3328. te[ 6 ] = b * e;
  3329. te[ 10 ] = bd * f + ac;
  3330. }
  3331. // bottom row
  3332. te[ 3 ] = 0;
  3333. te[ 7 ] = 0;
  3334. te[ 11 ] = 0;
  3335. // last column
  3336. te[ 12 ] = 0;
  3337. te[ 13 ] = 0;
  3338. te[ 14 ] = 0;
  3339. te[ 15 ] = 1;
  3340. return this;
  3341. }
  3342. makeRotationFromQuaternion( q ) {
  3343. return this.compose( _zero, q, _one );
  3344. }
  3345. lookAt( eye, target, up ) {
  3346. const te = this.elements;
  3347. _z.subVectors( eye, target );
  3348. if ( _z.lengthSq() === 0 ) {
  3349. // eye and target are in the same position
  3350. _z.z = 1;
  3351. }
  3352. _z.normalize();
  3353. _x.crossVectors( up, _z );
  3354. if ( _x.lengthSq() === 0 ) {
  3355. // up and z are parallel
  3356. if ( Math.abs( up.z ) === 1 ) {
  3357. _z.x += 0.0001;
  3358. } else {
  3359. _z.z += 0.0001;
  3360. }
  3361. _z.normalize();
  3362. _x.crossVectors( up, _z );
  3363. }
  3364. _x.normalize();
  3365. _y.crossVectors( _z, _x );
  3366. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3367. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3368. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3369. return this;
  3370. }
  3371. multiply( m, n ) {
  3372. if ( n !== undefined ) {
  3373. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3374. return this.multiplyMatrices( m, n );
  3375. }
  3376. return this.multiplyMatrices( this, m );
  3377. }
  3378. premultiply( m ) {
  3379. return this.multiplyMatrices( m, this );
  3380. }
  3381. multiplyMatrices( a, b ) {
  3382. const ae = a.elements;
  3383. const be = b.elements;
  3384. const te = this.elements;
  3385. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3386. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3387. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3388. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3389. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3390. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3391. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3392. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3393. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3394. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3395. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3396. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3397. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3398. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3399. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3400. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3401. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3402. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3403. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3404. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3405. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3406. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3407. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3408. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3409. return this;
  3410. }
  3411. multiplyScalar( s ) {
  3412. const te = this.elements;
  3413. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3414. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3415. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3416. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3417. return this;
  3418. }
  3419. determinant() {
  3420. const te = this.elements;
  3421. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3422. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3423. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3424. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3425. //TODO: make this more efficient
  3426. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3427. return (
  3428. n41 * (
  3429. + n14 * n23 * n32
  3430. - n13 * n24 * n32
  3431. - n14 * n22 * n33
  3432. + n12 * n24 * n33
  3433. + n13 * n22 * n34
  3434. - n12 * n23 * n34
  3435. ) +
  3436. n42 * (
  3437. + n11 * n23 * n34
  3438. - n11 * n24 * n33
  3439. + n14 * n21 * n33
  3440. - n13 * n21 * n34
  3441. + n13 * n24 * n31
  3442. - n14 * n23 * n31
  3443. ) +
  3444. n43 * (
  3445. + n11 * n24 * n32
  3446. - n11 * n22 * n34
  3447. - n14 * n21 * n32
  3448. + n12 * n21 * n34
  3449. + n14 * n22 * n31
  3450. - n12 * n24 * n31
  3451. ) +
  3452. n44 * (
  3453. - n13 * n22 * n31
  3454. - n11 * n23 * n32
  3455. + n11 * n22 * n33
  3456. + n13 * n21 * n32
  3457. - n12 * n21 * n33
  3458. + n12 * n23 * n31
  3459. )
  3460. );
  3461. }
  3462. transpose() {
  3463. const te = this.elements;
  3464. let tmp;
  3465. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3466. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3467. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3468. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3469. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3470. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3471. return this;
  3472. }
  3473. setPosition( x, y, z ) {
  3474. const te = this.elements;
  3475. if ( x.isVector3 ) {
  3476. te[ 12 ] = x.x;
  3477. te[ 13 ] = x.y;
  3478. te[ 14 ] = x.z;
  3479. } else {
  3480. te[ 12 ] = x;
  3481. te[ 13 ] = y;
  3482. te[ 14 ] = z;
  3483. }
  3484. return this;
  3485. }
  3486. invert() {
  3487. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3488. const te = this.elements,
  3489. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3490. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3491. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3492. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3493. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3494. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3495. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3496. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3497. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3498. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3499. const detInv = 1 / det;
  3500. te[ 0 ] = t11 * detInv;
  3501. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3502. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3503. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3504. te[ 4 ] = t12 * detInv;
  3505. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3506. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3507. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3508. te[ 8 ] = t13 * detInv;
  3509. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3510. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3511. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3512. te[ 12 ] = t14 * detInv;
  3513. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3514. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3515. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3516. return this;
  3517. }
  3518. scale( v ) {
  3519. const te = this.elements;
  3520. const x = v.x, y = v.y, z = v.z;
  3521. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3522. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3523. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3524. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3525. return this;
  3526. }
  3527. getMaxScaleOnAxis() {
  3528. const te = this.elements;
  3529. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3530. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3531. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3532. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3533. }
  3534. makeTranslation( x, y, z ) {
  3535. this.set(
  3536. 1, 0, 0, x,
  3537. 0, 1, 0, y,
  3538. 0, 0, 1, z,
  3539. 0, 0, 0, 1
  3540. );
  3541. return this;
  3542. }
  3543. makeRotationX( theta ) {
  3544. const c = Math.cos( theta ), s = Math.sin( theta );
  3545. this.set(
  3546. 1, 0, 0, 0,
  3547. 0, c, - s, 0,
  3548. 0, s, c, 0,
  3549. 0, 0, 0, 1
  3550. );
  3551. return this;
  3552. }
  3553. makeRotationY( theta ) {
  3554. const c = Math.cos( theta ), s = Math.sin( theta );
  3555. this.set(
  3556. c, 0, s, 0,
  3557. 0, 1, 0, 0,
  3558. - s, 0, c, 0,
  3559. 0, 0, 0, 1
  3560. );
  3561. return this;
  3562. }
  3563. makeRotationZ( theta ) {
  3564. const c = Math.cos( theta ), s = Math.sin( theta );
  3565. this.set(
  3566. c, - s, 0, 0,
  3567. s, c, 0, 0,
  3568. 0, 0, 1, 0,
  3569. 0, 0, 0, 1
  3570. );
  3571. return this;
  3572. }
  3573. makeRotationAxis( axis, angle ) {
  3574. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3575. const c = Math.cos( angle );
  3576. const s = Math.sin( angle );
  3577. const t = 1 - c;
  3578. const x = axis.x, y = axis.y, z = axis.z;
  3579. const tx = t * x, ty = t * y;
  3580. this.set(
  3581. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3582. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3583. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3584. 0, 0, 0, 1
  3585. );
  3586. return this;
  3587. }
  3588. makeScale( x, y, z ) {
  3589. this.set(
  3590. x, 0, 0, 0,
  3591. 0, y, 0, 0,
  3592. 0, 0, z, 0,
  3593. 0, 0, 0, 1
  3594. );
  3595. return this;
  3596. }
  3597. makeShear( xy, xz, yx, yz, zx, zy ) {
  3598. this.set(
  3599. 1, yx, zx, 0,
  3600. xy, 1, zy, 0,
  3601. xz, yz, 1, 0,
  3602. 0, 0, 0, 1
  3603. );
  3604. return this;
  3605. }
  3606. compose( position, quaternion, scale ) {
  3607. const te = this.elements;
  3608. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3609. const x2 = x + x, y2 = y + y, z2 = z + z;
  3610. const xx = x * x2, xy = x * y2, xz = x * z2;
  3611. const yy = y * y2, yz = y * z2, zz = z * z2;
  3612. const wx = w * x2, wy = w * y2, wz = w * z2;
  3613. const sx = scale.x, sy = scale.y, sz = scale.z;
  3614. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3615. te[ 1 ] = ( xy + wz ) * sx;
  3616. te[ 2 ] = ( xz - wy ) * sx;
  3617. te[ 3 ] = 0;
  3618. te[ 4 ] = ( xy - wz ) * sy;
  3619. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3620. te[ 6 ] = ( yz + wx ) * sy;
  3621. te[ 7 ] = 0;
  3622. te[ 8 ] = ( xz + wy ) * sz;
  3623. te[ 9 ] = ( yz - wx ) * sz;
  3624. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3625. te[ 11 ] = 0;
  3626. te[ 12 ] = position.x;
  3627. te[ 13 ] = position.y;
  3628. te[ 14 ] = position.z;
  3629. te[ 15 ] = 1;
  3630. return this;
  3631. }
  3632. decompose( position, quaternion, scale ) {
  3633. const te = this.elements;
  3634. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3635. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3636. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3637. // if determine is negative, we need to invert one scale
  3638. const det = this.determinant();
  3639. if ( det < 0 ) sx = - sx;
  3640. position.x = te[ 12 ];
  3641. position.y = te[ 13 ];
  3642. position.z = te[ 14 ];
  3643. // scale the rotation part
  3644. _m1$2.copy( this );
  3645. const invSX = 1 / sx;
  3646. const invSY = 1 / sy;
  3647. const invSZ = 1 / sz;
  3648. _m1$2.elements[ 0 ] *= invSX;
  3649. _m1$2.elements[ 1 ] *= invSX;
  3650. _m1$2.elements[ 2 ] *= invSX;
  3651. _m1$2.elements[ 4 ] *= invSY;
  3652. _m1$2.elements[ 5 ] *= invSY;
  3653. _m1$2.elements[ 6 ] *= invSY;
  3654. _m1$2.elements[ 8 ] *= invSZ;
  3655. _m1$2.elements[ 9 ] *= invSZ;
  3656. _m1$2.elements[ 10 ] *= invSZ;
  3657. quaternion.setFromRotationMatrix( _m1$2 );
  3658. scale.x = sx;
  3659. scale.y = sy;
  3660. scale.z = sz;
  3661. return this;
  3662. }
  3663. makePerspective( left, right, top, bottom, near, far ) {
  3664. if ( far === undefined ) {
  3665. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3666. }
  3667. const te = this.elements;
  3668. const x = 2 * near / ( right - left );
  3669. const y = 2 * near / ( top - bottom );
  3670. const a = ( right + left ) / ( right - left );
  3671. const b = ( top + bottom ) / ( top - bottom );
  3672. const c = - ( far + near ) / ( far - near );
  3673. const d = - 2 * far * near / ( far - near );
  3674. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3675. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3676. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3677. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3678. return this;
  3679. }
  3680. makeOrthographic( left, right, top, bottom, near, far ) {
  3681. const te = this.elements;
  3682. const w = 1.0 / ( right - left );
  3683. const h = 1.0 / ( top - bottom );
  3684. const p = 1.0 / ( far - near );
  3685. const x = ( right + left ) * w;
  3686. const y = ( top + bottom ) * h;
  3687. const z = ( far + near ) * p;
  3688. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3689. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3690. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3691. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3692. return this;
  3693. }
  3694. equals( matrix ) {
  3695. const te = this.elements;
  3696. const me = matrix.elements;
  3697. for ( let i = 0; i < 16; i ++ ) {
  3698. if ( te[ i ] !== me[ i ] ) return false;
  3699. }
  3700. return true;
  3701. }
  3702. fromArray( array, offset = 0 ) {
  3703. for ( let i = 0; i < 16; i ++ ) {
  3704. this.elements[ i ] = array[ i + offset ];
  3705. }
  3706. return this;
  3707. }
  3708. toArray( array = [], offset = 0 ) {
  3709. const te = this.elements;
  3710. array[ offset ] = te[ 0 ];
  3711. array[ offset + 1 ] = te[ 1 ];
  3712. array[ offset + 2 ] = te[ 2 ];
  3713. array[ offset + 3 ] = te[ 3 ];
  3714. array[ offset + 4 ] = te[ 4 ];
  3715. array[ offset + 5 ] = te[ 5 ];
  3716. array[ offset + 6 ] = te[ 6 ];
  3717. array[ offset + 7 ] = te[ 7 ];
  3718. array[ offset + 8 ] = te[ 8 ];
  3719. array[ offset + 9 ] = te[ 9 ];
  3720. array[ offset + 10 ] = te[ 10 ];
  3721. array[ offset + 11 ] = te[ 11 ];
  3722. array[ offset + 12 ] = te[ 12 ];
  3723. array[ offset + 13 ] = te[ 13 ];
  3724. array[ offset + 14 ] = te[ 14 ];
  3725. array[ offset + 15 ] = te[ 15 ];
  3726. return array;
  3727. }
  3728. }
  3729. Matrix4.prototype.isMatrix4 = true;
  3730. const _v1$5 = /*@__PURE__*/ new Vector3();
  3731. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3732. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3733. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3734. const _x = /*@__PURE__*/ new Vector3();
  3735. const _y = /*@__PURE__*/ new Vector3();
  3736. const _z = /*@__PURE__*/ new Vector3();
  3737. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  3738. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3739. class Euler {
  3740. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3741. this._x = x;
  3742. this._y = y;
  3743. this._z = z;
  3744. this._order = order;
  3745. }
  3746. get x() {
  3747. return this._x;
  3748. }
  3749. set x( value ) {
  3750. this._x = value;
  3751. this._onChangeCallback();
  3752. }
  3753. get y() {
  3754. return this._y;
  3755. }
  3756. set y( value ) {
  3757. this._y = value;
  3758. this._onChangeCallback();
  3759. }
  3760. get z() {
  3761. return this._z;
  3762. }
  3763. set z( value ) {
  3764. this._z = value;
  3765. this._onChangeCallback();
  3766. }
  3767. get order() {
  3768. return this._order;
  3769. }
  3770. set order( value ) {
  3771. this._order = value;
  3772. this._onChangeCallback();
  3773. }
  3774. set( x, y, z, order = this._order ) {
  3775. this._x = x;
  3776. this._y = y;
  3777. this._z = z;
  3778. this._order = order;
  3779. this._onChangeCallback();
  3780. return this;
  3781. }
  3782. clone() {
  3783. return new this.constructor( this._x, this._y, this._z, this._order );
  3784. }
  3785. copy( euler ) {
  3786. this._x = euler._x;
  3787. this._y = euler._y;
  3788. this._z = euler._z;
  3789. this._order = euler._order;
  3790. this._onChangeCallback();
  3791. return this;
  3792. }
  3793. setFromRotationMatrix( m, order = this._order, update = true ) {
  3794. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3795. const te = m.elements;
  3796. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3797. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3798. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3799. switch ( order ) {
  3800. case 'XYZ':
  3801. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3802. if ( Math.abs( m13 ) < 0.9999999 ) {
  3803. this._x = Math.atan2( - m23, m33 );
  3804. this._z = Math.atan2( - m12, m11 );
  3805. } else {
  3806. this._x = Math.atan2( m32, m22 );
  3807. this._z = 0;
  3808. }
  3809. break;
  3810. case 'YXZ':
  3811. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3812. if ( Math.abs( m23 ) < 0.9999999 ) {
  3813. this._y = Math.atan2( m13, m33 );
  3814. this._z = Math.atan2( m21, m22 );
  3815. } else {
  3816. this._y = Math.atan2( - m31, m11 );
  3817. this._z = 0;
  3818. }
  3819. break;
  3820. case 'ZXY':
  3821. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3822. if ( Math.abs( m32 ) < 0.9999999 ) {
  3823. this._y = Math.atan2( - m31, m33 );
  3824. this._z = Math.atan2( - m12, m22 );
  3825. } else {
  3826. this._y = 0;
  3827. this._z = Math.atan2( m21, m11 );
  3828. }
  3829. break;
  3830. case 'ZYX':
  3831. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3832. if ( Math.abs( m31 ) < 0.9999999 ) {
  3833. this._x = Math.atan2( m32, m33 );
  3834. this._z = Math.atan2( m21, m11 );
  3835. } else {
  3836. this._x = 0;
  3837. this._z = Math.atan2( - m12, m22 );
  3838. }
  3839. break;
  3840. case 'YZX':
  3841. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3842. if ( Math.abs( m21 ) < 0.9999999 ) {
  3843. this._x = Math.atan2( - m23, m22 );
  3844. this._y = Math.atan2( - m31, m11 );
  3845. } else {
  3846. this._x = 0;
  3847. this._y = Math.atan2( m13, m33 );
  3848. }
  3849. break;
  3850. case 'XZY':
  3851. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3852. if ( Math.abs( m12 ) < 0.9999999 ) {
  3853. this._x = Math.atan2( m32, m22 );
  3854. this._y = Math.atan2( m13, m11 );
  3855. } else {
  3856. this._x = Math.atan2( - m23, m33 );
  3857. this._y = 0;
  3858. }
  3859. break;
  3860. default:
  3861. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3862. }
  3863. this._order = order;
  3864. if ( update === true ) this._onChangeCallback();
  3865. return this;
  3866. }
  3867. setFromQuaternion( q, order, update ) {
  3868. _matrix$1.makeRotationFromQuaternion( q );
  3869. return this.setFromRotationMatrix( _matrix$1, order, update );
  3870. }
  3871. setFromVector3( v, order = this._order ) {
  3872. return this.set( v.x, v.y, v.z, order );
  3873. }
  3874. reorder( newOrder ) {
  3875. // WARNING: this discards revolution information -bhouston
  3876. _quaternion$3.setFromEuler( this );
  3877. return this.setFromQuaternion( _quaternion$3, newOrder );
  3878. }
  3879. equals( euler ) {
  3880. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3881. }
  3882. fromArray( array ) {
  3883. this._x = array[ 0 ];
  3884. this._y = array[ 1 ];
  3885. this._z = array[ 2 ];
  3886. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3887. this._onChangeCallback();
  3888. return this;
  3889. }
  3890. toArray( array = [], offset = 0 ) {
  3891. array[ offset ] = this._x;
  3892. array[ offset + 1 ] = this._y;
  3893. array[ offset + 2 ] = this._z;
  3894. array[ offset + 3 ] = this._order;
  3895. return array;
  3896. }
  3897. toVector3( optionalResult ) {
  3898. if ( optionalResult ) {
  3899. return optionalResult.set( this._x, this._y, this._z );
  3900. } else {
  3901. return new Vector3( this._x, this._y, this._z );
  3902. }
  3903. }
  3904. _onChange( callback ) {
  3905. this._onChangeCallback = callback;
  3906. return this;
  3907. }
  3908. _onChangeCallback() {}
  3909. }
  3910. Euler.prototype.isEuler = true;
  3911. Euler.DefaultOrder = 'XYZ';
  3912. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  3913. class Layers {
  3914. constructor() {
  3915. this.mask = 1 | 0;
  3916. }
  3917. set( channel ) {
  3918. this.mask = 1 << channel | 0;
  3919. }
  3920. enable( channel ) {
  3921. this.mask |= 1 << channel | 0;
  3922. }
  3923. enableAll() {
  3924. this.mask = 0xffffffff | 0;
  3925. }
  3926. toggle( channel ) {
  3927. this.mask ^= 1 << channel | 0;
  3928. }
  3929. disable( channel ) {
  3930. this.mask &= ~ ( 1 << channel | 0 );
  3931. }
  3932. disableAll() {
  3933. this.mask = 0;
  3934. }
  3935. test( layers ) {
  3936. return ( this.mask & layers.mask ) !== 0;
  3937. }
  3938. }
  3939. let _object3DId = 0;
  3940. const _v1$4 = /*@__PURE__*/ new Vector3();
  3941. const _q1 = /*@__PURE__*/ new Quaternion();
  3942. const _m1$1 = /*@__PURE__*/ new Matrix4();
  3943. const _target = /*@__PURE__*/ new Vector3();
  3944. const _position$3 = /*@__PURE__*/ new Vector3();
  3945. const _scale$2 = /*@__PURE__*/ new Vector3();
  3946. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  3947. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  3948. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  3949. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  3950. const _addedEvent = { type: 'added' };
  3951. const _removedEvent = { type: 'removed' };
  3952. class Object3D extends EventDispatcher {
  3953. constructor() {
  3954. super();
  3955. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  3956. this.uuid = generateUUID();
  3957. this.name = '';
  3958. this.type = 'Object3D';
  3959. this.parent = null;
  3960. this.children = [];
  3961. this.up = Object3D.DefaultUp.clone();
  3962. const position = new Vector3();
  3963. const rotation = new Euler();
  3964. const quaternion = new Quaternion();
  3965. const scale = new Vector3( 1, 1, 1 );
  3966. function onRotationChange() {
  3967. quaternion.setFromEuler( rotation, false );
  3968. }
  3969. function onQuaternionChange() {
  3970. rotation.setFromQuaternion( quaternion, undefined, false );
  3971. }
  3972. rotation._onChange( onRotationChange );
  3973. quaternion._onChange( onQuaternionChange );
  3974. Object.defineProperties( this, {
  3975. position: {
  3976. configurable: true,
  3977. enumerable: true,
  3978. value: position
  3979. },
  3980. rotation: {
  3981. configurable: true,
  3982. enumerable: true,
  3983. value: rotation
  3984. },
  3985. quaternion: {
  3986. configurable: true,
  3987. enumerable: true,
  3988. value: quaternion
  3989. },
  3990. scale: {
  3991. configurable: true,
  3992. enumerable: true,
  3993. value: scale
  3994. },
  3995. modelViewMatrix: {
  3996. value: new Matrix4()
  3997. },
  3998. normalMatrix: {
  3999. value: new Matrix3()
  4000. }
  4001. } );
  4002. this.matrix = new Matrix4();
  4003. this.matrixWorld = new Matrix4();
  4004. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4005. this.matrixWorldNeedsUpdate = false;
  4006. this.layers = new Layers();
  4007. this.visible = true;
  4008. this.castShadow = false;
  4009. this.receiveShadow = false;
  4010. this.frustumCulled = true;
  4011. this.renderOrder = 0;
  4012. this.animations = [];
  4013. this.userData = {};
  4014. }
  4015. onBeforeRender() {}
  4016. onAfterRender() {}
  4017. applyMatrix4( matrix ) {
  4018. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4019. this.matrix.premultiply( matrix );
  4020. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4021. }
  4022. applyQuaternion( q ) {
  4023. this.quaternion.premultiply( q );
  4024. return this;
  4025. }
  4026. setRotationFromAxisAngle( axis, angle ) {
  4027. // assumes axis is normalized
  4028. this.quaternion.setFromAxisAngle( axis, angle );
  4029. }
  4030. setRotationFromEuler( euler ) {
  4031. this.quaternion.setFromEuler( euler, true );
  4032. }
  4033. setRotationFromMatrix( m ) {
  4034. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4035. this.quaternion.setFromRotationMatrix( m );
  4036. }
  4037. setRotationFromQuaternion( q ) {
  4038. // assumes q is normalized
  4039. this.quaternion.copy( q );
  4040. }
  4041. rotateOnAxis( axis, angle ) {
  4042. // rotate object on axis in object space
  4043. // axis is assumed to be normalized
  4044. _q1.setFromAxisAngle( axis, angle );
  4045. this.quaternion.multiply( _q1 );
  4046. return this;
  4047. }
  4048. rotateOnWorldAxis( axis, angle ) {
  4049. // rotate object on axis in world space
  4050. // axis is assumed to be normalized
  4051. // method assumes no rotated parent
  4052. _q1.setFromAxisAngle( axis, angle );
  4053. this.quaternion.premultiply( _q1 );
  4054. return this;
  4055. }
  4056. rotateX( angle ) {
  4057. return this.rotateOnAxis( _xAxis, angle );
  4058. }
  4059. rotateY( angle ) {
  4060. return this.rotateOnAxis( _yAxis, angle );
  4061. }
  4062. rotateZ( angle ) {
  4063. return this.rotateOnAxis( _zAxis, angle );
  4064. }
  4065. translateOnAxis( axis, distance ) {
  4066. // translate object by distance along axis in object space
  4067. // axis is assumed to be normalized
  4068. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4069. this.position.add( _v1$4.multiplyScalar( distance ) );
  4070. return this;
  4071. }
  4072. translateX( distance ) {
  4073. return this.translateOnAxis( _xAxis, distance );
  4074. }
  4075. translateY( distance ) {
  4076. return this.translateOnAxis( _yAxis, distance );
  4077. }
  4078. translateZ( distance ) {
  4079. return this.translateOnAxis( _zAxis, distance );
  4080. }
  4081. localToWorld( vector ) {
  4082. return vector.applyMatrix4( this.matrixWorld );
  4083. }
  4084. worldToLocal( vector ) {
  4085. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4086. }
  4087. lookAt( x, y, z ) {
  4088. // This method does not support objects having non-uniformly-scaled parent(s)
  4089. if ( x.isVector3 ) {
  4090. _target.copy( x );
  4091. } else {
  4092. _target.set( x, y, z );
  4093. }
  4094. const parent = this.parent;
  4095. this.updateWorldMatrix( true, false );
  4096. _position$3.setFromMatrixPosition( this.matrixWorld );
  4097. if ( this.isCamera || this.isLight ) {
  4098. _m1$1.lookAt( _position$3, _target, this.up );
  4099. } else {
  4100. _m1$1.lookAt( _target, _position$3, this.up );
  4101. }
  4102. this.quaternion.setFromRotationMatrix( _m1$1 );
  4103. if ( parent ) {
  4104. _m1$1.extractRotation( parent.matrixWorld );
  4105. _q1.setFromRotationMatrix( _m1$1 );
  4106. this.quaternion.premultiply( _q1.invert() );
  4107. }
  4108. }
  4109. add( object ) {
  4110. if ( arguments.length > 1 ) {
  4111. for ( let i = 0; i < arguments.length; i ++ ) {
  4112. this.add( arguments[ i ] );
  4113. }
  4114. return this;
  4115. }
  4116. if ( object === this ) {
  4117. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4118. return this;
  4119. }
  4120. if ( object && object.isObject3D ) {
  4121. if ( object.parent !== null ) {
  4122. object.parent.remove( object );
  4123. }
  4124. object.parent = this;
  4125. this.children.push( object );
  4126. object.dispatchEvent( _addedEvent );
  4127. } else {
  4128. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4129. }
  4130. return this;
  4131. }
  4132. remove( object ) {
  4133. if ( arguments.length > 1 ) {
  4134. for ( let i = 0; i < arguments.length; i ++ ) {
  4135. this.remove( arguments[ i ] );
  4136. }
  4137. return this;
  4138. }
  4139. const index = this.children.indexOf( object );
  4140. if ( index !== - 1 ) {
  4141. object.parent = null;
  4142. this.children.splice( index, 1 );
  4143. object.dispatchEvent( _removedEvent );
  4144. }
  4145. return this;
  4146. }
  4147. removeFromParent() {
  4148. const parent = this.parent;
  4149. if ( parent !== null ) {
  4150. parent.remove( this );
  4151. }
  4152. return this;
  4153. }
  4154. clear() {
  4155. for ( let i = 0; i < this.children.length; i ++ ) {
  4156. const object = this.children[ i ];
  4157. object.parent = null;
  4158. object.dispatchEvent( _removedEvent );
  4159. }
  4160. this.children.length = 0;
  4161. return this;
  4162. }
  4163. attach( object ) {
  4164. // adds object as a child of this, while maintaining the object's world transform
  4165. this.updateWorldMatrix( true, false );
  4166. _m1$1.copy( this.matrixWorld ).invert();
  4167. if ( object.parent !== null ) {
  4168. object.parent.updateWorldMatrix( true, false );
  4169. _m1$1.multiply( object.parent.matrixWorld );
  4170. }
  4171. object.applyMatrix4( _m1$1 );
  4172. this.add( object );
  4173. object.updateWorldMatrix( false, true );
  4174. return this;
  4175. }
  4176. getObjectById( id ) {
  4177. return this.getObjectByProperty( 'id', id );
  4178. }
  4179. getObjectByName( name ) {
  4180. return this.getObjectByProperty( 'name', name );
  4181. }
  4182. getObjectByProperty( name, value ) {
  4183. if ( this[ name ] === value ) return this;
  4184. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4185. const child = this.children[ i ];
  4186. const object = child.getObjectByProperty( name, value );
  4187. if ( object !== undefined ) {
  4188. return object;
  4189. }
  4190. }
  4191. return undefined;
  4192. }
  4193. getWorldPosition( target ) {
  4194. this.updateWorldMatrix( true, false );
  4195. return target.setFromMatrixPosition( this.matrixWorld );
  4196. }
  4197. getWorldQuaternion( target ) {
  4198. this.updateWorldMatrix( true, false );
  4199. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4200. return target;
  4201. }
  4202. getWorldScale( target ) {
  4203. this.updateWorldMatrix( true, false );
  4204. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4205. return target;
  4206. }
  4207. getWorldDirection( target ) {
  4208. this.updateWorldMatrix( true, false );
  4209. const e = this.matrixWorld.elements;
  4210. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4211. }
  4212. raycast() {}
  4213. traverse( callback ) {
  4214. callback( this );
  4215. const children = this.children;
  4216. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4217. children[ i ].traverse( callback );
  4218. }
  4219. }
  4220. traverseVisible( callback ) {
  4221. if ( this.visible === false ) return;
  4222. callback( this );
  4223. const children = this.children;
  4224. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4225. children[ i ].traverseVisible( callback );
  4226. }
  4227. }
  4228. traverseAncestors( callback ) {
  4229. const parent = this.parent;
  4230. if ( parent !== null ) {
  4231. callback( parent );
  4232. parent.traverseAncestors( callback );
  4233. }
  4234. }
  4235. updateMatrix() {
  4236. this.matrix.compose( this.position, this.quaternion, this.scale );
  4237. this.matrixWorldNeedsUpdate = true;
  4238. }
  4239. updateMatrixWorld( force ) {
  4240. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4241. if ( this.matrixWorldNeedsUpdate || force ) {
  4242. if ( this.parent === null ) {
  4243. this.matrixWorld.copy( this.matrix );
  4244. } else {
  4245. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4246. }
  4247. this.matrixWorldNeedsUpdate = false;
  4248. force = true;
  4249. }
  4250. // update children
  4251. const children = this.children;
  4252. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4253. children[ i ].updateMatrixWorld( force );
  4254. }
  4255. }
  4256. updateWorldMatrix( updateParents, updateChildren ) {
  4257. const parent = this.parent;
  4258. if ( updateParents === true && parent !== null ) {
  4259. parent.updateWorldMatrix( true, false );
  4260. }
  4261. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4262. if ( this.parent === null ) {
  4263. this.matrixWorld.copy( this.matrix );
  4264. } else {
  4265. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4266. }
  4267. // update children
  4268. if ( updateChildren === true ) {
  4269. const children = this.children;
  4270. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4271. children[ i ].updateWorldMatrix( false, true );
  4272. }
  4273. }
  4274. }
  4275. toJSON( meta ) {
  4276. // meta is a string when called from JSON.stringify
  4277. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4278. const output = {};
  4279. // meta is a hash used to collect geometries, materials.
  4280. // not providing it implies that this is the root object
  4281. // being serialized.
  4282. if ( isRootObject ) {
  4283. // initialize meta obj
  4284. meta = {
  4285. geometries: {},
  4286. materials: {},
  4287. textures: {},
  4288. images: {},
  4289. shapes: {},
  4290. skeletons: {},
  4291. animations: {}
  4292. };
  4293. output.metadata = {
  4294. version: 4.5,
  4295. type: 'Object',
  4296. generator: 'Object3D.toJSON'
  4297. };
  4298. }
  4299. // standard Object3D serialization
  4300. const object = {};
  4301. object.uuid = this.uuid;
  4302. object.type = this.type;
  4303. if ( this.name !== '' ) object.name = this.name;
  4304. if ( this.castShadow === true ) object.castShadow = true;
  4305. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4306. if ( this.visible === false ) object.visible = false;
  4307. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4308. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4309. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4310. object.layers = this.layers.mask;
  4311. object.matrix = this.matrix.toArray();
  4312. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4313. // object specific properties
  4314. if ( this.isInstancedMesh ) {
  4315. object.type = 'InstancedMesh';
  4316. object.count = this.count;
  4317. object.instanceMatrix = this.instanceMatrix.toJSON();
  4318. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4319. }
  4320. //
  4321. function serialize( library, element ) {
  4322. if ( library[ element.uuid ] === undefined ) {
  4323. library[ element.uuid ] = element.toJSON( meta );
  4324. }
  4325. return element.uuid;
  4326. }
  4327. if ( this.isScene ) {
  4328. if ( this.background ) {
  4329. if ( this.background.isColor ) {
  4330. object.background = this.background.toJSON();
  4331. } else if ( this.background.isTexture ) {
  4332. object.background = this.background.toJSON( meta ).uuid;
  4333. }
  4334. }
  4335. if ( this.environment && this.environment.isTexture ) {
  4336. object.environment = this.environment.toJSON( meta ).uuid;
  4337. }
  4338. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4339. object.geometry = serialize( meta.geometries, this.geometry );
  4340. const parameters = this.geometry.parameters;
  4341. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4342. const shapes = parameters.shapes;
  4343. if ( Array.isArray( shapes ) ) {
  4344. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4345. const shape = shapes[ i ];
  4346. serialize( meta.shapes, shape );
  4347. }
  4348. } else {
  4349. serialize( meta.shapes, shapes );
  4350. }
  4351. }
  4352. }
  4353. if ( this.isSkinnedMesh ) {
  4354. object.bindMode = this.bindMode;
  4355. object.bindMatrix = this.bindMatrix.toArray();
  4356. if ( this.skeleton !== undefined ) {
  4357. serialize( meta.skeletons, this.skeleton );
  4358. object.skeleton = this.skeleton.uuid;
  4359. }
  4360. }
  4361. if ( this.material !== undefined ) {
  4362. if ( Array.isArray( this.material ) ) {
  4363. const uuids = [];
  4364. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4365. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4366. }
  4367. object.material = uuids;
  4368. } else {
  4369. object.material = serialize( meta.materials, this.material );
  4370. }
  4371. }
  4372. //
  4373. if ( this.children.length > 0 ) {
  4374. object.children = [];
  4375. for ( let i = 0; i < this.children.length; i ++ ) {
  4376. object.children.push( this.children[ i ].toJSON( meta ).object );
  4377. }
  4378. }
  4379. //
  4380. if ( this.animations.length > 0 ) {
  4381. object.animations = [];
  4382. for ( let i = 0; i < this.animations.length; i ++ ) {
  4383. const animation = this.animations[ i ];
  4384. object.animations.push( serialize( meta.animations, animation ) );
  4385. }
  4386. }
  4387. if ( isRootObject ) {
  4388. const geometries = extractFromCache( meta.geometries );
  4389. const materials = extractFromCache( meta.materials );
  4390. const textures = extractFromCache( meta.textures );
  4391. const images = extractFromCache( meta.images );
  4392. const shapes = extractFromCache( meta.shapes );
  4393. const skeletons = extractFromCache( meta.skeletons );
  4394. const animations = extractFromCache( meta.animations );
  4395. if ( geometries.length > 0 ) output.geometries = geometries;
  4396. if ( materials.length > 0 ) output.materials = materials;
  4397. if ( textures.length > 0 ) output.textures = textures;
  4398. if ( images.length > 0 ) output.images = images;
  4399. if ( shapes.length > 0 ) output.shapes = shapes;
  4400. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4401. if ( animations.length > 0 ) output.animations = animations;
  4402. }
  4403. output.object = object;
  4404. return output;
  4405. // extract data from the cache hash
  4406. // remove metadata on each item
  4407. // and return as array
  4408. function extractFromCache( cache ) {
  4409. const values = [];
  4410. for ( const key in cache ) {
  4411. const data = cache[ key ];
  4412. delete data.metadata;
  4413. values.push( data );
  4414. }
  4415. return values;
  4416. }
  4417. }
  4418. clone( recursive ) {
  4419. return new this.constructor().copy( this, recursive );
  4420. }
  4421. copy( source, recursive = true ) {
  4422. this.name = source.name;
  4423. this.up.copy( source.up );
  4424. this.position.copy( source.position );
  4425. this.rotation.order = source.rotation.order;
  4426. this.quaternion.copy( source.quaternion );
  4427. this.scale.copy( source.scale );
  4428. this.matrix.copy( source.matrix );
  4429. this.matrixWorld.copy( source.matrixWorld );
  4430. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4431. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4432. this.layers.mask = source.layers.mask;
  4433. this.visible = source.visible;
  4434. this.castShadow = source.castShadow;
  4435. this.receiveShadow = source.receiveShadow;
  4436. this.frustumCulled = source.frustumCulled;
  4437. this.renderOrder = source.renderOrder;
  4438. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4439. if ( recursive === true ) {
  4440. for ( let i = 0; i < source.children.length; i ++ ) {
  4441. const child = source.children[ i ];
  4442. this.add( child.clone() );
  4443. }
  4444. }
  4445. return this;
  4446. }
  4447. }
  4448. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4449. Object3D.DefaultMatrixAutoUpdate = true;
  4450. Object3D.prototype.isObject3D = true;
  4451. const _v0$1 = /*@__PURE__*/ new Vector3();
  4452. const _v1$3 = /*@__PURE__*/ new Vector3();
  4453. const _v2$2 = /*@__PURE__*/ new Vector3();
  4454. const _v3$1 = /*@__PURE__*/ new Vector3();
  4455. const _vab = /*@__PURE__*/ new Vector3();
  4456. const _vac = /*@__PURE__*/ new Vector3();
  4457. const _vbc = /*@__PURE__*/ new Vector3();
  4458. const _vap = /*@__PURE__*/ new Vector3();
  4459. const _vbp = /*@__PURE__*/ new Vector3();
  4460. const _vcp = /*@__PURE__*/ new Vector3();
  4461. class Triangle {
  4462. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4463. this.a = a;
  4464. this.b = b;
  4465. this.c = c;
  4466. }
  4467. static getNormal( a, b, c, target ) {
  4468. target.subVectors( c, b );
  4469. _v0$1.subVectors( a, b );
  4470. target.cross( _v0$1 );
  4471. const targetLengthSq = target.lengthSq();
  4472. if ( targetLengthSq > 0 ) {
  4473. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4474. }
  4475. return target.set( 0, 0, 0 );
  4476. }
  4477. // static/instance method to calculate barycentric coordinates
  4478. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4479. static getBarycoord( point, a, b, c, target ) {
  4480. _v0$1.subVectors( c, a );
  4481. _v1$3.subVectors( b, a );
  4482. _v2$2.subVectors( point, a );
  4483. const dot00 = _v0$1.dot( _v0$1 );
  4484. const dot01 = _v0$1.dot( _v1$3 );
  4485. const dot02 = _v0$1.dot( _v2$2 );
  4486. const dot11 = _v1$3.dot( _v1$3 );
  4487. const dot12 = _v1$3.dot( _v2$2 );
  4488. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4489. // collinear or singular triangle
  4490. if ( denom === 0 ) {
  4491. // arbitrary location outside of triangle?
  4492. // not sure if this is the best idea, maybe should be returning undefined
  4493. return target.set( - 2, - 1, - 1 );
  4494. }
  4495. const invDenom = 1 / denom;
  4496. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4497. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4498. // barycentric coordinates must always sum to 1
  4499. return target.set( 1 - u - v, v, u );
  4500. }
  4501. static containsPoint( point, a, b, c ) {
  4502. this.getBarycoord( point, a, b, c, _v3$1 );
  4503. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4504. }
  4505. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4506. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4507. target.set( 0, 0 );
  4508. target.addScaledVector( uv1, _v3$1.x );
  4509. target.addScaledVector( uv2, _v3$1.y );
  4510. target.addScaledVector( uv3, _v3$1.z );
  4511. return target;
  4512. }
  4513. static isFrontFacing( a, b, c, direction ) {
  4514. _v0$1.subVectors( c, b );
  4515. _v1$3.subVectors( a, b );
  4516. // strictly front facing
  4517. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4518. }
  4519. set( a, b, c ) {
  4520. this.a.copy( a );
  4521. this.b.copy( b );
  4522. this.c.copy( c );
  4523. return this;
  4524. }
  4525. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4526. this.a.copy( points[ i0 ] );
  4527. this.b.copy( points[ i1 ] );
  4528. this.c.copy( points[ i2 ] );
  4529. return this;
  4530. }
  4531. clone() {
  4532. return new this.constructor().copy( this );
  4533. }
  4534. copy( triangle ) {
  4535. this.a.copy( triangle.a );
  4536. this.b.copy( triangle.b );
  4537. this.c.copy( triangle.c );
  4538. return this;
  4539. }
  4540. getArea() {
  4541. _v0$1.subVectors( this.c, this.b );
  4542. _v1$3.subVectors( this.a, this.b );
  4543. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4544. }
  4545. getMidpoint( target ) {
  4546. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4547. }
  4548. getNormal( target ) {
  4549. return Triangle.getNormal( this.a, this.b, this.c, target );
  4550. }
  4551. getPlane( target ) {
  4552. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4553. }
  4554. getBarycoord( point, target ) {
  4555. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4556. }
  4557. getUV( point, uv1, uv2, uv3, target ) {
  4558. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4559. }
  4560. containsPoint( point ) {
  4561. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4562. }
  4563. isFrontFacing( direction ) {
  4564. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4565. }
  4566. intersectsBox( box ) {
  4567. return box.intersectsTriangle( this );
  4568. }
  4569. closestPointToPoint( p, target ) {
  4570. const a = this.a, b = this.b, c = this.c;
  4571. let v, w;
  4572. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4573. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4574. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4575. // basically, we're distinguishing which of the voronoi regions of the triangle
  4576. // the point lies in with the minimum amount of redundant computation.
  4577. _vab.subVectors( b, a );
  4578. _vac.subVectors( c, a );
  4579. _vap.subVectors( p, a );
  4580. const d1 = _vab.dot( _vap );
  4581. const d2 = _vac.dot( _vap );
  4582. if ( d1 <= 0 && d2 <= 0 ) {
  4583. // vertex region of A; barycentric coords (1, 0, 0)
  4584. return target.copy( a );
  4585. }
  4586. _vbp.subVectors( p, b );
  4587. const d3 = _vab.dot( _vbp );
  4588. const d4 = _vac.dot( _vbp );
  4589. if ( d3 >= 0 && d4 <= d3 ) {
  4590. // vertex region of B; barycentric coords (0, 1, 0)
  4591. return target.copy( b );
  4592. }
  4593. const vc = d1 * d4 - d3 * d2;
  4594. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4595. v = d1 / ( d1 - d3 );
  4596. // edge region of AB; barycentric coords (1-v, v, 0)
  4597. return target.copy( a ).addScaledVector( _vab, v );
  4598. }
  4599. _vcp.subVectors( p, c );
  4600. const d5 = _vab.dot( _vcp );
  4601. const d6 = _vac.dot( _vcp );
  4602. if ( d6 >= 0 && d5 <= d6 ) {
  4603. // vertex region of C; barycentric coords (0, 0, 1)
  4604. return target.copy( c );
  4605. }
  4606. const vb = d5 * d2 - d1 * d6;
  4607. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4608. w = d2 / ( d2 - d6 );
  4609. // edge region of AC; barycentric coords (1-w, 0, w)
  4610. return target.copy( a ).addScaledVector( _vac, w );
  4611. }
  4612. const va = d3 * d6 - d5 * d4;
  4613. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4614. _vbc.subVectors( c, b );
  4615. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4616. // edge region of BC; barycentric coords (0, 1-w, w)
  4617. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4618. }
  4619. // face region
  4620. const denom = 1 / ( va + vb + vc );
  4621. // u = va * denom
  4622. v = vb * denom;
  4623. w = vc * denom;
  4624. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4625. }
  4626. equals( triangle ) {
  4627. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4628. }
  4629. }
  4630. let materialId = 0;
  4631. class Material extends EventDispatcher {
  4632. constructor() {
  4633. super();
  4634. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4635. this.uuid = generateUUID();
  4636. this.name = '';
  4637. this.type = 'Material';
  4638. this.fog = true;
  4639. this.blending = NormalBlending;
  4640. this.side = FrontSide;
  4641. this.vertexColors = false;
  4642. this.opacity = 1;
  4643. this.format = RGBAFormat;
  4644. this.transparent = false;
  4645. this.blendSrc = SrcAlphaFactor;
  4646. this.blendDst = OneMinusSrcAlphaFactor;
  4647. this.blendEquation = AddEquation;
  4648. this.blendSrcAlpha = null;
  4649. this.blendDstAlpha = null;
  4650. this.blendEquationAlpha = null;
  4651. this.depthFunc = LessEqualDepth;
  4652. this.depthTest = true;
  4653. this.depthWrite = true;
  4654. this.stencilWriteMask = 0xff;
  4655. this.stencilFunc = AlwaysStencilFunc;
  4656. this.stencilRef = 0;
  4657. this.stencilFuncMask = 0xff;
  4658. this.stencilFail = KeepStencilOp;
  4659. this.stencilZFail = KeepStencilOp;
  4660. this.stencilZPass = KeepStencilOp;
  4661. this.stencilWrite = false;
  4662. this.clippingPlanes = null;
  4663. this.clipIntersection = false;
  4664. this.clipShadows = false;
  4665. this.shadowSide = null;
  4666. this.colorWrite = true;
  4667. this.precision = null; // override the renderer's default precision for this material
  4668. this.polygonOffset = false;
  4669. this.polygonOffsetFactor = 0;
  4670. this.polygonOffsetUnits = 0;
  4671. this.dithering = false;
  4672. this.alphaToCoverage = false;
  4673. this.premultipliedAlpha = false;
  4674. this.visible = true;
  4675. this.toneMapped = true;
  4676. this.userData = {};
  4677. this.version = 0;
  4678. this._alphaTest = 0;
  4679. }
  4680. get alphaTest() {
  4681. return this._alphaTest;
  4682. }
  4683. set alphaTest( value ) {
  4684. if ( this._alphaTest > 0 !== value > 0 ) {
  4685. this.version ++;
  4686. }
  4687. this._alphaTest = value;
  4688. }
  4689. onBuild( /* shaderobject, renderer */ ) {}
  4690. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4691. customProgramCacheKey() {
  4692. return this.onBeforeCompile.toString();
  4693. }
  4694. setValues( values ) {
  4695. if ( values === undefined ) return;
  4696. for ( const key in values ) {
  4697. const newValue = values[ key ];
  4698. if ( newValue === undefined ) {
  4699. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4700. continue;
  4701. }
  4702. // for backward compatability if shading is set in the constructor
  4703. if ( key === 'shading' ) {
  4704. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4705. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4706. continue;
  4707. }
  4708. const currentValue = this[ key ];
  4709. if ( currentValue === undefined ) {
  4710. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4711. continue;
  4712. }
  4713. if ( currentValue && currentValue.isColor ) {
  4714. currentValue.set( newValue );
  4715. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4716. currentValue.copy( newValue );
  4717. } else {
  4718. this[ key ] = newValue;
  4719. }
  4720. }
  4721. }
  4722. toJSON( meta ) {
  4723. const isRoot = ( meta === undefined || typeof meta === 'string' );
  4724. if ( isRoot ) {
  4725. meta = {
  4726. textures: {},
  4727. images: {}
  4728. };
  4729. }
  4730. const data = {
  4731. metadata: {
  4732. version: 4.5,
  4733. type: 'Material',
  4734. generator: 'Material.toJSON'
  4735. }
  4736. };
  4737. // standard Material serialization
  4738. data.uuid = this.uuid;
  4739. data.type = this.type;
  4740. if ( this.name !== '' ) data.name = this.name;
  4741. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4742. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4743. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4744. if ( this.sheenTint && this.sheenTint.isColor ) data.sheenTint = this.sheenTint.getHex();
  4745. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4746. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  4747. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4748. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  4749. if ( this.specularTint && this.specularTint.isColor ) data.specularTint = this.specularTint.getHex();
  4750. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4751. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  4752. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  4753. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  4754. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  4755. }
  4756. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  4757. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  4758. }
  4759. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  4760. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  4761. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4762. }
  4763. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4764. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  4765. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4766. if ( this.lightMap && this.lightMap.isTexture ) {
  4767. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4768. data.lightMapIntensity = this.lightMapIntensity;
  4769. }
  4770. if ( this.aoMap && this.aoMap.isTexture ) {
  4771. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  4772. data.aoMapIntensity = this.aoMapIntensity;
  4773. }
  4774. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4775. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4776. data.bumpScale = this.bumpScale;
  4777. }
  4778. if ( this.normalMap && this.normalMap.isTexture ) {
  4779. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4780. data.normalMapType = this.normalMapType;
  4781. data.normalScale = this.normalScale.toArray();
  4782. }
  4783. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4784. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4785. data.displacementScale = this.displacementScale;
  4786. data.displacementBias = this.displacementBias;
  4787. }
  4788. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4789. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4790. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4791. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4792. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  4793. if ( this.specularTintMap && this.specularTintMap.isTexture ) data.specularTintMap = this.specularTintMap.toJSON( meta ).uuid;
  4794. if ( this.envMap && this.envMap.isTexture ) {
  4795. data.envMap = this.envMap.toJSON( meta ).uuid;
  4796. if ( this.combine !== undefined ) data.combine = this.combine;
  4797. }
  4798. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  4799. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  4800. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  4801. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4802. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4803. }
  4804. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  4805. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  4806. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  4807. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  4808. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  4809. if ( this.attenuationTint !== undefined ) data.attenuationTint = this.attenuationTint.getHex();
  4810. if ( this.size !== undefined ) data.size = this.size;
  4811. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  4812. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4813. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4814. if ( this.side !== FrontSide ) data.side = this.side;
  4815. if ( this.vertexColors ) data.vertexColors = true;
  4816. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4817. if ( this.format !== RGBAFormat ) data.format = this.format;
  4818. if ( this.transparent === true ) data.transparent = this.transparent;
  4819. data.depthFunc = this.depthFunc;
  4820. data.depthTest = this.depthTest;
  4821. data.depthWrite = this.depthWrite;
  4822. data.colorWrite = this.colorWrite;
  4823. data.stencilWrite = this.stencilWrite;
  4824. data.stencilWriteMask = this.stencilWriteMask;
  4825. data.stencilFunc = this.stencilFunc;
  4826. data.stencilRef = this.stencilRef;
  4827. data.stencilFuncMask = this.stencilFuncMask;
  4828. data.stencilFail = this.stencilFail;
  4829. data.stencilZFail = this.stencilZFail;
  4830. data.stencilZPass = this.stencilZPass;
  4831. // rotation (SpriteMaterial)
  4832. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  4833. if ( this.polygonOffset === true ) data.polygonOffset = true;
  4834. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4835. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4836. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  4837. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  4838. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  4839. if ( this.scale !== undefined ) data.scale = this.scale;
  4840. if ( this.dithering === true ) data.dithering = true;
  4841. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4842. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  4843. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4844. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4845. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4846. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4847. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4848. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4849. if ( this.visible === false ) data.visible = false;
  4850. if ( this.toneMapped === false ) data.toneMapped = false;
  4851. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4852. // TODO: Copied from Object3D.toJSON
  4853. function extractFromCache( cache ) {
  4854. const values = [];
  4855. for ( const key in cache ) {
  4856. const data = cache[ key ];
  4857. delete data.metadata;
  4858. values.push( data );
  4859. }
  4860. return values;
  4861. }
  4862. if ( isRoot ) {
  4863. const textures = extractFromCache( meta.textures );
  4864. const images = extractFromCache( meta.images );
  4865. if ( textures.length > 0 ) data.textures = textures;
  4866. if ( images.length > 0 ) data.images = images;
  4867. }
  4868. return data;
  4869. }
  4870. clone() {
  4871. return new this.constructor().copy( this );
  4872. }
  4873. copy( source ) {
  4874. this.name = source.name;
  4875. this.fog = source.fog;
  4876. this.blending = source.blending;
  4877. this.side = source.side;
  4878. this.vertexColors = source.vertexColors;
  4879. this.opacity = source.opacity;
  4880. this.format = source.format;
  4881. this.transparent = source.transparent;
  4882. this.blendSrc = source.blendSrc;
  4883. this.blendDst = source.blendDst;
  4884. this.blendEquation = source.blendEquation;
  4885. this.blendSrcAlpha = source.blendSrcAlpha;
  4886. this.blendDstAlpha = source.blendDstAlpha;
  4887. this.blendEquationAlpha = source.blendEquationAlpha;
  4888. this.depthFunc = source.depthFunc;
  4889. this.depthTest = source.depthTest;
  4890. this.depthWrite = source.depthWrite;
  4891. this.stencilWriteMask = source.stencilWriteMask;
  4892. this.stencilFunc = source.stencilFunc;
  4893. this.stencilRef = source.stencilRef;
  4894. this.stencilFuncMask = source.stencilFuncMask;
  4895. this.stencilFail = source.stencilFail;
  4896. this.stencilZFail = source.stencilZFail;
  4897. this.stencilZPass = source.stencilZPass;
  4898. this.stencilWrite = source.stencilWrite;
  4899. const srcPlanes = source.clippingPlanes;
  4900. let dstPlanes = null;
  4901. if ( srcPlanes !== null ) {
  4902. const n = srcPlanes.length;
  4903. dstPlanes = new Array( n );
  4904. for ( let i = 0; i !== n; ++ i ) {
  4905. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4906. }
  4907. }
  4908. this.clippingPlanes = dstPlanes;
  4909. this.clipIntersection = source.clipIntersection;
  4910. this.clipShadows = source.clipShadows;
  4911. this.shadowSide = source.shadowSide;
  4912. this.colorWrite = source.colorWrite;
  4913. this.precision = source.precision;
  4914. this.polygonOffset = source.polygonOffset;
  4915. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4916. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4917. this.dithering = source.dithering;
  4918. this.alphaTest = source.alphaTest;
  4919. this.alphaToCoverage = source.alphaToCoverage;
  4920. this.premultipliedAlpha = source.premultipliedAlpha;
  4921. this.visible = source.visible;
  4922. this.toneMapped = source.toneMapped;
  4923. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4924. return this;
  4925. }
  4926. dispose() {
  4927. this.dispatchEvent( { type: 'dispose' } );
  4928. }
  4929. set needsUpdate( value ) {
  4930. if ( value === true ) this.version ++;
  4931. }
  4932. }
  4933. Material.prototype.isMaterial = true;
  4934. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  4935. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  4936. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  4937. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  4938. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  4939. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  4940. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  4941. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  4942. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  4943. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  4944. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  4945. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  4946. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  4947. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  4948. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  4949. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  4950. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  4951. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  4952. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  4953. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  4954. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  4955. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  4956. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  4957. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  4958. const _hslA = { h: 0, s: 0, l: 0 };
  4959. const _hslB = { h: 0, s: 0, l: 0 };
  4960. function hue2rgb( p, q, t ) {
  4961. if ( t < 0 ) t += 1;
  4962. if ( t > 1 ) t -= 1;
  4963. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  4964. if ( t < 1 / 2 ) return q;
  4965. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  4966. return p;
  4967. }
  4968. function SRGBToLinear( c ) {
  4969. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  4970. }
  4971. function LinearToSRGB( c ) {
  4972. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  4973. }
  4974. class Color {
  4975. constructor( r, g, b ) {
  4976. if ( g === undefined && b === undefined ) {
  4977. // r is THREE.Color, hex or string
  4978. return this.set( r );
  4979. }
  4980. return this.setRGB( r, g, b );
  4981. }
  4982. set( value ) {
  4983. if ( value && value.isColor ) {
  4984. this.copy( value );
  4985. } else if ( typeof value === 'number' ) {
  4986. this.setHex( value );
  4987. } else if ( typeof value === 'string' ) {
  4988. this.setStyle( value );
  4989. }
  4990. return this;
  4991. }
  4992. setScalar( scalar ) {
  4993. this.r = scalar;
  4994. this.g = scalar;
  4995. this.b = scalar;
  4996. return this;
  4997. }
  4998. setHex( hex ) {
  4999. hex = Math.floor( hex );
  5000. this.r = ( hex >> 16 & 255 ) / 255;
  5001. this.g = ( hex >> 8 & 255 ) / 255;
  5002. this.b = ( hex & 255 ) / 255;
  5003. return this;
  5004. }
  5005. setRGB( r, g, b ) {
  5006. this.r = r;
  5007. this.g = g;
  5008. this.b = b;
  5009. return this;
  5010. }
  5011. setHSL( h, s, l ) {
  5012. // h,s,l ranges are in 0.0 - 1.0
  5013. h = euclideanModulo( h, 1 );
  5014. s = clamp( s, 0, 1 );
  5015. l = clamp( l, 0, 1 );
  5016. if ( s === 0 ) {
  5017. this.r = this.g = this.b = l;
  5018. } else {
  5019. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5020. const q = ( 2 * l ) - p;
  5021. this.r = hue2rgb( q, p, h + 1 / 3 );
  5022. this.g = hue2rgb( q, p, h );
  5023. this.b = hue2rgb( q, p, h - 1 / 3 );
  5024. }
  5025. return this;
  5026. }
  5027. setStyle( style ) {
  5028. function handleAlpha( string ) {
  5029. if ( string === undefined ) return;
  5030. if ( parseFloat( string ) < 1 ) {
  5031. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5032. }
  5033. }
  5034. let m;
  5035. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  5036. // rgb / hsl
  5037. let color;
  5038. const name = m[ 1 ];
  5039. const components = m[ 2 ];
  5040. switch ( name ) {
  5041. case 'rgb':
  5042. case 'rgba':
  5043. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5044. // rgb(255,0,0) rgba(255,0,0,0.5)
  5045. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5046. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5047. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5048. handleAlpha( color[ 4 ] );
  5049. return this;
  5050. }
  5051. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5052. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5053. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5054. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5055. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5056. handleAlpha( color[ 4 ] );
  5057. return this;
  5058. }
  5059. break;
  5060. case 'hsl':
  5061. case 'hsla':
  5062. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5063. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5064. const h = parseFloat( color[ 1 ] ) / 360;
  5065. const s = parseInt( color[ 2 ], 10 ) / 100;
  5066. const l = parseInt( color[ 3 ], 10 ) / 100;
  5067. handleAlpha( color[ 4 ] );
  5068. return this.setHSL( h, s, l );
  5069. }
  5070. break;
  5071. }
  5072. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5073. // hex color
  5074. const hex = m[ 1 ];
  5075. const size = hex.length;
  5076. if ( size === 3 ) {
  5077. // #ff0
  5078. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5079. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5080. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5081. return this;
  5082. } else if ( size === 6 ) {
  5083. // #ff0000
  5084. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5085. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5086. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5087. return this;
  5088. }
  5089. }
  5090. if ( style && style.length > 0 ) {
  5091. return this.setColorName( style );
  5092. }
  5093. return this;
  5094. }
  5095. setColorName( style ) {
  5096. // color keywords
  5097. const hex = _colorKeywords[ style.toLowerCase() ];
  5098. if ( hex !== undefined ) {
  5099. // red
  5100. this.setHex( hex );
  5101. } else {
  5102. // unknown color
  5103. console.warn( 'THREE.Color: Unknown color ' + style );
  5104. }
  5105. return this;
  5106. }
  5107. clone() {
  5108. return new this.constructor( this.r, this.g, this.b );
  5109. }
  5110. copy( color ) {
  5111. this.r = color.r;
  5112. this.g = color.g;
  5113. this.b = color.b;
  5114. return this;
  5115. }
  5116. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5117. this.r = Math.pow( color.r, gammaFactor );
  5118. this.g = Math.pow( color.g, gammaFactor );
  5119. this.b = Math.pow( color.b, gammaFactor );
  5120. return this;
  5121. }
  5122. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5123. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5124. this.r = Math.pow( color.r, safeInverse );
  5125. this.g = Math.pow( color.g, safeInverse );
  5126. this.b = Math.pow( color.b, safeInverse );
  5127. return this;
  5128. }
  5129. convertGammaToLinear( gammaFactor ) {
  5130. this.copyGammaToLinear( this, gammaFactor );
  5131. return this;
  5132. }
  5133. convertLinearToGamma( gammaFactor ) {
  5134. this.copyLinearToGamma( this, gammaFactor );
  5135. return this;
  5136. }
  5137. copySRGBToLinear( color ) {
  5138. this.r = SRGBToLinear( color.r );
  5139. this.g = SRGBToLinear( color.g );
  5140. this.b = SRGBToLinear( color.b );
  5141. return this;
  5142. }
  5143. copyLinearToSRGB( color ) {
  5144. this.r = LinearToSRGB( color.r );
  5145. this.g = LinearToSRGB( color.g );
  5146. this.b = LinearToSRGB( color.b );
  5147. return this;
  5148. }
  5149. convertSRGBToLinear() {
  5150. this.copySRGBToLinear( this );
  5151. return this;
  5152. }
  5153. convertLinearToSRGB() {
  5154. this.copyLinearToSRGB( this );
  5155. return this;
  5156. }
  5157. getHex() {
  5158. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5159. }
  5160. getHexString() {
  5161. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5162. }
  5163. getHSL( target ) {
  5164. // h,s,l ranges are in 0.0 - 1.0
  5165. const r = this.r, g = this.g, b = this.b;
  5166. const max = Math.max( r, g, b );
  5167. const min = Math.min( r, g, b );
  5168. let hue, saturation;
  5169. const lightness = ( min + max ) / 2.0;
  5170. if ( min === max ) {
  5171. hue = 0;
  5172. saturation = 0;
  5173. } else {
  5174. const delta = max - min;
  5175. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5176. switch ( max ) {
  5177. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5178. case g: hue = ( b - r ) / delta + 2; break;
  5179. case b: hue = ( r - g ) / delta + 4; break;
  5180. }
  5181. hue /= 6;
  5182. }
  5183. target.h = hue;
  5184. target.s = saturation;
  5185. target.l = lightness;
  5186. return target;
  5187. }
  5188. getStyle() {
  5189. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5190. }
  5191. offsetHSL( h, s, l ) {
  5192. this.getHSL( _hslA );
  5193. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5194. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5195. return this;
  5196. }
  5197. add( color ) {
  5198. this.r += color.r;
  5199. this.g += color.g;
  5200. this.b += color.b;
  5201. return this;
  5202. }
  5203. addColors( color1, color2 ) {
  5204. this.r = color1.r + color2.r;
  5205. this.g = color1.g + color2.g;
  5206. this.b = color1.b + color2.b;
  5207. return this;
  5208. }
  5209. addScalar( s ) {
  5210. this.r += s;
  5211. this.g += s;
  5212. this.b += s;
  5213. return this;
  5214. }
  5215. sub( color ) {
  5216. this.r = Math.max( 0, this.r - color.r );
  5217. this.g = Math.max( 0, this.g - color.g );
  5218. this.b = Math.max( 0, this.b - color.b );
  5219. return this;
  5220. }
  5221. multiply( color ) {
  5222. this.r *= color.r;
  5223. this.g *= color.g;
  5224. this.b *= color.b;
  5225. return this;
  5226. }
  5227. multiplyScalar( s ) {
  5228. this.r *= s;
  5229. this.g *= s;
  5230. this.b *= s;
  5231. return this;
  5232. }
  5233. lerp( color, alpha ) {
  5234. this.r += ( color.r - this.r ) * alpha;
  5235. this.g += ( color.g - this.g ) * alpha;
  5236. this.b += ( color.b - this.b ) * alpha;
  5237. return this;
  5238. }
  5239. lerpColors( color1, color2, alpha ) {
  5240. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5241. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5242. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5243. return this;
  5244. }
  5245. lerpHSL( color, alpha ) {
  5246. this.getHSL( _hslA );
  5247. color.getHSL( _hslB );
  5248. const h = lerp( _hslA.h, _hslB.h, alpha );
  5249. const s = lerp( _hslA.s, _hslB.s, alpha );
  5250. const l = lerp( _hslA.l, _hslB.l, alpha );
  5251. this.setHSL( h, s, l );
  5252. return this;
  5253. }
  5254. equals( c ) {
  5255. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5256. }
  5257. fromArray( array, offset = 0 ) {
  5258. this.r = array[ offset ];
  5259. this.g = array[ offset + 1 ];
  5260. this.b = array[ offset + 2 ];
  5261. return this;
  5262. }
  5263. toArray( array = [], offset = 0 ) {
  5264. array[ offset ] = this.r;
  5265. array[ offset + 1 ] = this.g;
  5266. array[ offset + 2 ] = this.b;
  5267. return array;
  5268. }
  5269. fromBufferAttribute( attribute, index ) {
  5270. this.r = attribute.getX( index );
  5271. this.g = attribute.getY( index );
  5272. this.b = attribute.getZ( index );
  5273. if ( attribute.normalized === true ) {
  5274. // assuming Uint8Array
  5275. this.r /= 255;
  5276. this.g /= 255;
  5277. this.b /= 255;
  5278. }
  5279. return this;
  5280. }
  5281. toJSON() {
  5282. return this.getHex();
  5283. }
  5284. }
  5285. Color.NAMES = _colorKeywords;
  5286. Color.prototype.isColor = true;
  5287. Color.prototype.r = 1;
  5288. Color.prototype.g = 1;
  5289. Color.prototype.b = 1;
  5290. /**
  5291. * parameters = {
  5292. * color: <hex>,
  5293. * opacity: <float>,
  5294. * map: new THREE.Texture( <Image> ),
  5295. *
  5296. * lightMap: new THREE.Texture( <Image> ),
  5297. * lightMapIntensity: <float>
  5298. *
  5299. * aoMap: new THREE.Texture( <Image> ),
  5300. * aoMapIntensity: <float>
  5301. *
  5302. * specularMap: new THREE.Texture( <Image> ),
  5303. *
  5304. * alphaMap: new THREE.Texture( <Image> ),
  5305. *
  5306. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5307. * combine: THREE.Multiply,
  5308. * reflectivity: <float>,
  5309. * refractionRatio: <float>,
  5310. *
  5311. * depthTest: <bool>,
  5312. * depthWrite: <bool>,
  5313. *
  5314. * wireframe: <boolean>,
  5315. * wireframeLinewidth: <float>,
  5316. * }
  5317. */
  5318. class MeshBasicMaterial extends Material {
  5319. constructor( parameters ) {
  5320. super();
  5321. this.type = 'MeshBasicMaterial';
  5322. this.color = new Color( 0xffffff ); // emissive
  5323. this.map = null;
  5324. this.lightMap = null;
  5325. this.lightMapIntensity = 1.0;
  5326. this.aoMap = null;
  5327. this.aoMapIntensity = 1.0;
  5328. this.specularMap = null;
  5329. this.alphaMap = null;
  5330. this.envMap = null;
  5331. this.combine = MultiplyOperation;
  5332. this.reflectivity = 1;
  5333. this.refractionRatio = 0.98;
  5334. this.wireframe = false;
  5335. this.wireframeLinewidth = 1;
  5336. this.wireframeLinecap = 'round';
  5337. this.wireframeLinejoin = 'round';
  5338. this.setValues( parameters );
  5339. }
  5340. copy( source ) {
  5341. super.copy( source );
  5342. this.color.copy( source.color );
  5343. this.map = source.map;
  5344. this.lightMap = source.lightMap;
  5345. this.lightMapIntensity = source.lightMapIntensity;
  5346. this.aoMap = source.aoMap;
  5347. this.aoMapIntensity = source.aoMapIntensity;
  5348. this.specularMap = source.specularMap;
  5349. this.alphaMap = source.alphaMap;
  5350. this.envMap = source.envMap;
  5351. this.combine = source.combine;
  5352. this.reflectivity = source.reflectivity;
  5353. this.refractionRatio = source.refractionRatio;
  5354. this.wireframe = source.wireframe;
  5355. this.wireframeLinewidth = source.wireframeLinewidth;
  5356. this.wireframeLinecap = source.wireframeLinecap;
  5357. this.wireframeLinejoin = source.wireframeLinejoin;
  5358. return this;
  5359. }
  5360. }
  5361. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5362. const _vector$9 = /*@__PURE__*/ new Vector3();
  5363. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5364. class BufferAttribute {
  5365. constructor( array, itemSize, normalized ) {
  5366. if ( Array.isArray( array ) ) {
  5367. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5368. }
  5369. this.name = '';
  5370. this.array = array;
  5371. this.itemSize = itemSize;
  5372. this.count = array !== undefined ? array.length / itemSize : 0;
  5373. this.normalized = normalized === true;
  5374. this.usage = StaticDrawUsage;
  5375. this.updateRange = { offset: 0, count: - 1 };
  5376. this.version = 0;
  5377. }
  5378. onUploadCallback() {}
  5379. set needsUpdate( value ) {
  5380. if ( value === true ) this.version ++;
  5381. }
  5382. setUsage( value ) {
  5383. this.usage = value;
  5384. return this;
  5385. }
  5386. copy( source ) {
  5387. this.name = source.name;
  5388. this.array = new source.array.constructor( source.array );
  5389. this.itemSize = source.itemSize;
  5390. this.count = source.count;
  5391. this.normalized = source.normalized;
  5392. this.usage = source.usage;
  5393. return this;
  5394. }
  5395. copyAt( index1, attribute, index2 ) {
  5396. index1 *= this.itemSize;
  5397. index2 *= attribute.itemSize;
  5398. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5399. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5400. }
  5401. return this;
  5402. }
  5403. copyArray( array ) {
  5404. this.array.set( array );
  5405. return this;
  5406. }
  5407. copyColorsArray( colors ) {
  5408. const array = this.array;
  5409. let offset = 0;
  5410. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5411. let color = colors[ i ];
  5412. if ( color === undefined ) {
  5413. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5414. color = new Color();
  5415. }
  5416. array[ offset ++ ] = color.r;
  5417. array[ offset ++ ] = color.g;
  5418. array[ offset ++ ] = color.b;
  5419. }
  5420. return this;
  5421. }
  5422. copyVector2sArray( vectors ) {
  5423. const array = this.array;
  5424. let offset = 0;
  5425. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5426. let vector = vectors[ i ];
  5427. if ( vector === undefined ) {
  5428. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5429. vector = new Vector2();
  5430. }
  5431. array[ offset ++ ] = vector.x;
  5432. array[ offset ++ ] = vector.y;
  5433. }
  5434. return this;
  5435. }
  5436. copyVector3sArray( vectors ) {
  5437. const array = this.array;
  5438. let offset = 0;
  5439. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5440. let vector = vectors[ i ];
  5441. if ( vector === undefined ) {
  5442. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5443. vector = new Vector3();
  5444. }
  5445. array[ offset ++ ] = vector.x;
  5446. array[ offset ++ ] = vector.y;
  5447. array[ offset ++ ] = vector.z;
  5448. }
  5449. return this;
  5450. }
  5451. copyVector4sArray( vectors ) {
  5452. const array = this.array;
  5453. let offset = 0;
  5454. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5455. let vector = vectors[ i ];
  5456. if ( vector === undefined ) {
  5457. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5458. vector = new Vector4();
  5459. }
  5460. array[ offset ++ ] = vector.x;
  5461. array[ offset ++ ] = vector.y;
  5462. array[ offset ++ ] = vector.z;
  5463. array[ offset ++ ] = vector.w;
  5464. }
  5465. return this;
  5466. }
  5467. applyMatrix3( m ) {
  5468. if ( this.itemSize === 2 ) {
  5469. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5470. _vector2$1.fromBufferAttribute( this, i );
  5471. _vector2$1.applyMatrix3( m );
  5472. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5473. }
  5474. } else if ( this.itemSize === 3 ) {
  5475. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5476. _vector$9.fromBufferAttribute( this, i );
  5477. _vector$9.applyMatrix3( m );
  5478. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5479. }
  5480. }
  5481. return this;
  5482. }
  5483. applyMatrix4( m ) {
  5484. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5485. _vector$9.x = this.getX( i );
  5486. _vector$9.y = this.getY( i );
  5487. _vector$9.z = this.getZ( i );
  5488. _vector$9.applyMatrix4( m );
  5489. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5490. }
  5491. return this;
  5492. }
  5493. applyNormalMatrix( m ) {
  5494. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5495. _vector$9.x = this.getX( i );
  5496. _vector$9.y = this.getY( i );
  5497. _vector$9.z = this.getZ( i );
  5498. _vector$9.applyNormalMatrix( m );
  5499. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5500. }
  5501. return this;
  5502. }
  5503. transformDirection( m ) {
  5504. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5505. _vector$9.x = this.getX( i );
  5506. _vector$9.y = this.getY( i );
  5507. _vector$9.z = this.getZ( i );
  5508. _vector$9.transformDirection( m );
  5509. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5510. }
  5511. return this;
  5512. }
  5513. set( value, offset = 0 ) {
  5514. this.array.set( value, offset );
  5515. return this;
  5516. }
  5517. getX( index ) {
  5518. return this.array[ index * this.itemSize ];
  5519. }
  5520. setX( index, x ) {
  5521. this.array[ index * this.itemSize ] = x;
  5522. return this;
  5523. }
  5524. getY( index ) {
  5525. return this.array[ index * this.itemSize + 1 ];
  5526. }
  5527. setY( index, y ) {
  5528. this.array[ index * this.itemSize + 1 ] = y;
  5529. return this;
  5530. }
  5531. getZ( index ) {
  5532. return this.array[ index * this.itemSize + 2 ];
  5533. }
  5534. setZ( index, z ) {
  5535. this.array[ index * this.itemSize + 2 ] = z;
  5536. return this;
  5537. }
  5538. getW( index ) {
  5539. return this.array[ index * this.itemSize + 3 ];
  5540. }
  5541. setW( index, w ) {
  5542. this.array[ index * this.itemSize + 3 ] = w;
  5543. return this;
  5544. }
  5545. setXY( index, x, y ) {
  5546. index *= this.itemSize;
  5547. this.array[ index + 0 ] = x;
  5548. this.array[ index + 1 ] = y;
  5549. return this;
  5550. }
  5551. setXYZ( index, x, y, z ) {
  5552. index *= this.itemSize;
  5553. this.array[ index + 0 ] = x;
  5554. this.array[ index + 1 ] = y;
  5555. this.array[ index + 2 ] = z;
  5556. return this;
  5557. }
  5558. setXYZW( index, x, y, z, w ) {
  5559. index *= this.itemSize;
  5560. this.array[ index + 0 ] = x;
  5561. this.array[ index + 1 ] = y;
  5562. this.array[ index + 2 ] = z;
  5563. this.array[ index + 3 ] = w;
  5564. return this;
  5565. }
  5566. onUpload( callback ) {
  5567. this.onUploadCallback = callback;
  5568. return this;
  5569. }
  5570. clone() {
  5571. return new this.constructor( this.array, this.itemSize ).copy( this );
  5572. }
  5573. toJSON() {
  5574. const data = {
  5575. itemSize: this.itemSize,
  5576. type: this.array.constructor.name,
  5577. array: Array.prototype.slice.call( this.array ),
  5578. normalized: this.normalized
  5579. };
  5580. if ( this.name !== '' ) data.name = this.name;
  5581. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5582. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5583. return data;
  5584. }
  5585. }
  5586. BufferAttribute.prototype.isBufferAttribute = true;
  5587. //
  5588. class Int8BufferAttribute extends BufferAttribute {
  5589. constructor( array, itemSize, normalized ) {
  5590. super( new Int8Array( array ), itemSize, normalized );
  5591. }
  5592. }
  5593. class Uint8BufferAttribute extends BufferAttribute {
  5594. constructor( array, itemSize, normalized ) {
  5595. super( new Uint8Array( array ), itemSize, normalized );
  5596. }
  5597. }
  5598. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5599. constructor( array, itemSize, normalized ) {
  5600. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5601. }
  5602. }
  5603. class Int16BufferAttribute extends BufferAttribute {
  5604. constructor( array, itemSize, normalized ) {
  5605. super( new Int16Array( array ), itemSize, normalized );
  5606. }
  5607. }
  5608. class Uint16BufferAttribute extends BufferAttribute {
  5609. constructor( array, itemSize, normalized ) {
  5610. super( new Uint16Array( array ), itemSize, normalized );
  5611. }
  5612. }
  5613. class Int32BufferAttribute extends BufferAttribute {
  5614. constructor( array, itemSize, normalized ) {
  5615. super( new Int32Array( array ), itemSize, normalized );
  5616. }
  5617. }
  5618. class Uint32BufferAttribute extends BufferAttribute {
  5619. constructor( array, itemSize, normalized ) {
  5620. super( new Uint32Array( array ), itemSize, normalized );
  5621. }
  5622. }
  5623. class Float16BufferAttribute extends BufferAttribute {
  5624. constructor( array, itemSize, normalized ) {
  5625. super( new Uint16Array( array ), itemSize, normalized );
  5626. }
  5627. }
  5628. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5629. class Float32BufferAttribute extends BufferAttribute {
  5630. constructor( array, itemSize, normalized ) {
  5631. super( new Float32Array( array ), itemSize, normalized );
  5632. }
  5633. }
  5634. class Float64BufferAttribute extends BufferAttribute {
  5635. constructor( array, itemSize, normalized ) {
  5636. super( new Float64Array( array ), itemSize, normalized );
  5637. }
  5638. }
  5639. function arrayMax( array ) {
  5640. if ( array.length === 0 ) return - Infinity;
  5641. let max = array[ 0 ];
  5642. for ( let i = 1, l = array.length; i < l; ++ i ) {
  5643. if ( array[ i ] > max ) max = array[ i ];
  5644. }
  5645. return max;
  5646. }
  5647. const TYPED_ARRAYS = {
  5648. Int8Array: Int8Array,
  5649. Uint8Array: Uint8Array,
  5650. Uint8ClampedArray: Uint8ClampedArray,
  5651. Int16Array: Int16Array,
  5652. Uint16Array: Uint16Array,
  5653. Int32Array: Int32Array,
  5654. Uint32Array: Uint32Array,
  5655. Float32Array: Float32Array,
  5656. Float64Array: Float64Array
  5657. };
  5658. function getTypedArray( type, buffer ) {
  5659. return new TYPED_ARRAYS[ type ]( buffer );
  5660. }
  5661. let _id = 0;
  5662. const _m1 = /*@__PURE__*/ new Matrix4();
  5663. const _obj = /*@__PURE__*/ new Object3D();
  5664. const _offset = /*@__PURE__*/ new Vector3();
  5665. const _box$1 = /*@__PURE__*/ new Box3();
  5666. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5667. const _vector$8 = /*@__PURE__*/ new Vector3();
  5668. class BufferGeometry extends EventDispatcher {
  5669. constructor() {
  5670. super();
  5671. Object.defineProperty( this, 'id', { value: _id ++ } );
  5672. this.uuid = generateUUID();
  5673. this.name = '';
  5674. this.type = 'BufferGeometry';
  5675. this.index = null;
  5676. this.attributes = {};
  5677. this.morphAttributes = {};
  5678. this.morphTargetsRelative = false;
  5679. this.groups = [];
  5680. this.boundingBox = null;
  5681. this.boundingSphere = null;
  5682. this.drawRange = { start: 0, count: Infinity };
  5683. this.userData = {};
  5684. }
  5685. getIndex() {
  5686. return this.index;
  5687. }
  5688. setIndex( index ) {
  5689. if ( Array.isArray( index ) ) {
  5690. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5691. } else {
  5692. this.index = index;
  5693. }
  5694. return this;
  5695. }
  5696. getAttribute( name ) {
  5697. return this.attributes[ name ];
  5698. }
  5699. setAttribute( name, attribute ) {
  5700. this.attributes[ name ] = attribute;
  5701. return this;
  5702. }
  5703. deleteAttribute( name ) {
  5704. delete this.attributes[ name ];
  5705. return this;
  5706. }
  5707. hasAttribute( name ) {
  5708. return this.attributes[ name ] !== undefined;
  5709. }
  5710. addGroup( start, count, materialIndex = 0 ) {
  5711. this.groups.push( {
  5712. start: start,
  5713. count: count,
  5714. materialIndex: materialIndex
  5715. } );
  5716. }
  5717. clearGroups() {
  5718. this.groups = [];
  5719. }
  5720. setDrawRange( start, count ) {
  5721. this.drawRange.start = start;
  5722. this.drawRange.count = count;
  5723. }
  5724. applyMatrix4( matrix ) {
  5725. const position = this.attributes.position;
  5726. if ( position !== undefined ) {
  5727. position.applyMatrix4( matrix );
  5728. position.needsUpdate = true;
  5729. }
  5730. const normal = this.attributes.normal;
  5731. if ( normal !== undefined ) {
  5732. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5733. normal.applyNormalMatrix( normalMatrix );
  5734. normal.needsUpdate = true;
  5735. }
  5736. const tangent = this.attributes.tangent;
  5737. if ( tangent !== undefined ) {
  5738. tangent.transformDirection( matrix );
  5739. tangent.needsUpdate = true;
  5740. }
  5741. if ( this.boundingBox !== null ) {
  5742. this.computeBoundingBox();
  5743. }
  5744. if ( this.boundingSphere !== null ) {
  5745. this.computeBoundingSphere();
  5746. }
  5747. return this;
  5748. }
  5749. applyQuaternion( q ) {
  5750. _m1.makeRotationFromQuaternion( q );
  5751. this.applyMatrix4( _m1 );
  5752. return this;
  5753. }
  5754. rotateX( angle ) {
  5755. // rotate geometry around world x-axis
  5756. _m1.makeRotationX( angle );
  5757. this.applyMatrix4( _m1 );
  5758. return this;
  5759. }
  5760. rotateY( angle ) {
  5761. // rotate geometry around world y-axis
  5762. _m1.makeRotationY( angle );
  5763. this.applyMatrix4( _m1 );
  5764. return this;
  5765. }
  5766. rotateZ( angle ) {
  5767. // rotate geometry around world z-axis
  5768. _m1.makeRotationZ( angle );
  5769. this.applyMatrix4( _m1 );
  5770. return this;
  5771. }
  5772. translate( x, y, z ) {
  5773. // translate geometry
  5774. _m1.makeTranslation( x, y, z );
  5775. this.applyMatrix4( _m1 );
  5776. return this;
  5777. }
  5778. scale( x, y, z ) {
  5779. // scale geometry
  5780. _m1.makeScale( x, y, z );
  5781. this.applyMatrix4( _m1 );
  5782. return this;
  5783. }
  5784. lookAt( vector ) {
  5785. _obj.lookAt( vector );
  5786. _obj.updateMatrix();
  5787. this.applyMatrix4( _obj.matrix );
  5788. return this;
  5789. }
  5790. center() {
  5791. this.computeBoundingBox();
  5792. this.boundingBox.getCenter( _offset ).negate();
  5793. this.translate( _offset.x, _offset.y, _offset.z );
  5794. return this;
  5795. }
  5796. setFromPoints( points ) {
  5797. const position = [];
  5798. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5799. const point = points[ i ];
  5800. position.push( point.x, point.y, point.z || 0 );
  5801. }
  5802. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5803. return this;
  5804. }
  5805. computeBoundingBox() {
  5806. if ( this.boundingBox === null ) {
  5807. this.boundingBox = new Box3();
  5808. }
  5809. const position = this.attributes.position;
  5810. const morphAttributesPosition = this.morphAttributes.position;
  5811. if ( position && position.isGLBufferAttribute ) {
  5812. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5813. this.boundingBox.set(
  5814. new Vector3( - Infinity, - Infinity, - Infinity ),
  5815. new Vector3( + Infinity, + Infinity, + Infinity )
  5816. );
  5817. return;
  5818. }
  5819. if ( position !== undefined ) {
  5820. this.boundingBox.setFromBufferAttribute( position );
  5821. // process morph attributes if present
  5822. if ( morphAttributesPosition ) {
  5823. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5824. const morphAttribute = morphAttributesPosition[ i ];
  5825. _box$1.setFromBufferAttribute( morphAttribute );
  5826. if ( this.morphTargetsRelative ) {
  5827. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5828. this.boundingBox.expandByPoint( _vector$8 );
  5829. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5830. this.boundingBox.expandByPoint( _vector$8 );
  5831. } else {
  5832. this.boundingBox.expandByPoint( _box$1.min );
  5833. this.boundingBox.expandByPoint( _box$1.max );
  5834. }
  5835. }
  5836. }
  5837. } else {
  5838. this.boundingBox.makeEmpty();
  5839. }
  5840. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5841. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5842. }
  5843. }
  5844. computeBoundingSphere() {
  5845. if ( this.boundingSphere === null ) {
  5846. this.boundingSphere = new Sphere();
  5847. }
  5848. const position = this.attributes.position;
  5849. const morphAttributesPosition = this.morphAttributes.position;
  5850. if ( position && position.isGLBufferAttribute ) {
  5851. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5852. this.boundingSphere.set( new Vector3(), Infinity );
  5853. return;
  5854. }
  5855. if ( position ) {
  5856. // first, find the center of the bounding sphere
  5857. const center = this.boundingSphere.center;
  5858. _box$1.setFromBufferAttribute( position );
  5859. // process morph attributes if present
  5860. if ( morphAttributesPosition ) {
  5861. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5862. const morphAttribute = morphAttributesPosition[ i ];
  5863. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  5864. if ( this.morphTargetsRelative ) {
  5865. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  5866. _box$1.expandByPoint( _vector$8 );
  5867. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  5868. _box$1.expandByPoint( _vector$8 );
  5869. } else {
  5870. _box$1.expandByPoint( _boxMorphTargets.min );
  5871. _box$1.expandByPoint( _boxMorphTargets.max );
  5872. }
  5873. }
  5874. }
  5875. _box$1.getCenter( center );
  5876. // second, try to find a boundingSphere with a radius smaller than the
  5877. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5878. let maxRadiusSq = 0;
  5879. for ( let i = 0, il = position.count; i < il; i ++ ) {
  5880. _vector$8.fromBufferAttribute( position, i );
  5881. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5882. }
  5883. // process morph attributes if present
  5884. if ( morphAttributesPosition ) {
  5885. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5886. const morphAttribute = morphAttributesPosition[ i ];
  5887. const morphTargetsRelative = this.morphTargetsRelative;
  5888. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  5889. _vector$8.fromBufferAttribute( morphAttribute, j );
  5890. if ( morphTargetsRelative ) {
  5891. _offset.fromBufferAttribute( position, j );
  5892. _vector$8.add( _offset );
  5893. }
  5894. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5895. }
  5896. }
  5897. }
  5898. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5899. if ( isNaN( this.boundingSphere.radius ) ) {
  5900. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  5901. }
  5902. }
  5903. }
  5904. computeTangents() {
  5905. const index = this.index;
  5906. const attributes = this.attributes;
  5907. // based on http://www.terathon.com/code/tangent.html
  5908. // (per vertex tangents)
  5909. if ( index === null ||
  5910. attributes.position === undefined ||
  5911. attributes.normal === undefined ||
  5912. attributes.uv === undefined ) {
  5913. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  5914. return;
  5915. }
  5916. const indices = index.array;
  5917. const positions = attributes.position.array;
  5918. const normals = attributes.normal.array;
  5919. const uvs = attributes.uv.array;
  5920. const nVertices = positions.length / 3;
  5921. if ( attributes.tangent === undefined ) {
  5922. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  5923. }
  5924. const tangents = attributes.tangent.array;
  5925. const tan1 = [], tan2 = [];
  5926. for ( let i = 0; i < nVertices; i ++ ) {
  5927. tan1[ i ] = new Vector3();
  5928. tan2[ i ] = new Vector3();
  5929. }
  5930. const vA = new Vector3(),
  5931. vB = new Vector3(),
  5932. vC = new Vector3(),
  5933. uvA = new Vector2(),
  5934. uvB = new Vector2(),
  5935. uvC = new Vector2(),
  5936. sdir = new Vector3(),
  5937. tdir = new Vector3();
  5938. function handleTriangle( a, b, c ) {
  5939. vA.fromArray( positions, a * 3 );
  5940. vB.fromArray( positions, b * 3 );
  5941. vC.fromArray( positions, c * 3 );
  5942. uvA.fromArray( uvs, a * 2 );
  5943. uvB.fromArray( uvs, b * 2 );
  5944. uvC.fromArray( uvs, c * 2 );
  5945. vB.sub( vA );
  5946. vC.sub( vA );
  5947. uvB.sub( uvA );
  5948. uvC.sub( uvA );
  5949. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  5950. // silently ignore degenerate uv triangles having coincident or colinear vertices
  5951. if ( ! isFinite( r ) ) return;
  5952. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  5953. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  5954. tan1[ a ].add( sdir );
  5955. tan1[ b ].add( sdir );
  5956. tan1[ c ].add( sdir );
  5957. tan2[ a ].add( tdir );
  5958. tan2[ b ].add( tdir );
  5959. tan2[ c ].add( tdir );
  5960. }
  5961. let groups = this.groups;
  5962. if ( groups.length === 0 ) {
  5963. groups = [ {
  5964. start: 0,
  5965. count: indices.length
  5966. } ];
  5967. }
  5968. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  5969. const group = groups[ i ];
  5970. const start = group.start;
  5971. const count = group.count;
  5972. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  5973. handleTriangle(
  5974. indices[ j + 0 ],
  5975. indices[ j + 1 ],
  5976. indices[ j + 2 ]
  5977. );
  5978. }
  5979. }
  5980. const tmp = new Vector3(), tmp2 = new Vector3();
  5981. const n = new Vector3(), n2 = new Vector3();
  5982. function handleVertex( v ) {
  5983. n.fromArray( normals, v * 3 );
  5984. n2.copy( n );
  5985. const t = tan1[ v ];
  5986. // Gram-Schmidt orthogonalize
  5987. tmp.copy( t );
  5988. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5989. // Calculate handedness
  5990. tmp2.crossVectors( n2, t );
  5991. const test = tmp2.dot( tan2[ v ] );
  5992. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5993. tangents[ v * 4 ] = tmp.x;
  5994. tangents[ v * 4 + 1 ] = tmp.y;
  5995. tangents[ v * 4 + 2 ] = tmp.z;
  5996. tangents[ v * 4 + 3 ] = w;
  5997. }
  5998. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  5999. const group = groups[ i ];
  6000. const start = group.start;
  6001. const count = group.count;
  6002. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6003. handleVertex( indices[ j + 0 ] );
  6004. handleVertex( indices[ j + 1 ] );
  6005. handleVertex( indices[ j + 2 ] );
  6006. }
  6007. }
  6008. }
  6009. computeVertexNormals() {
  6010. const index = this.index;
  6011. const positionAttribute = this.getAttribute( 'position' );
  6012. if ( positionAttribute !== undefined ) {
  6013. let normalAttribute = this.getAttribute( 'normal' );
  6014. if ( normalAttribute === undefined ) {
  6015. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6016. this.setAttribute( 'normal', normalAttribute );
  6017. } else {
  6018. // reset existing normals to zero
  6019. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6020. normalAttribute.setXYZ( i, 0, 0, 0 );
  6021. }
  6022. }
  6023. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6024. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6025. const cb = new Vector3(), ab = new Vector3();
  6026. // indexed elements
  6027. if ( index ) {
  6028. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6029. const vA = index.getX( i + 0 );
  6030. const vB = index.getX( i + 1 );
  6031. const vC = index.getX( i + 2 );
  6032. pA.fromBufferAttribute( positionAttribute, vA );
  6033. pB.fromBufferAttribute( positionAttribute, vB );
  6034. pC.fromBufferAttribute( positionAttribute, vC );
  6035. cb.subVectors( pC, pB );
  6036. ab.subVectors( pA, pB );
  6037. cb.cross( ab );
  6038. nA.fromBufferAttribute( normalAttribute, vA );
  6039. nB.fromBufferAttribute( normalAttribute, vB );
  6040. nC.fromBufferAttribute( normalAttribute, vC );
  6041. nA.add( cb );
  6042. nB.add( cb );
  6043. nC.add( cb );
  6044. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6045. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6046. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6047. }
  6048. } else {
  6049. // non-indexed elements (unconnected triangle soup)
  6050. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6051. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6052. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6053. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6054. cb.subVectors( pC, pB );
  6055. ab.subVectors( pA, pB );
  6056. cb.cross( ab );
  6057. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6058. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6059. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6060. }
  6061. }
  6062. this.normalizeNormals();
  6063. normalAttribute.needsUpdate = true;
  6064. }
  6065. }
  6066. merge( geometry, offset ) {
  6067. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6068. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6069. return;
  6070. }
  6071. if ( offset === undefined ) {
  6072. offset = 0;
  6073. console.warn(
  6074. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6075. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6076. );
  6077. }
  6078. const attributes = this.attributes;
  6079. for ( const key in attributes ) {
  6080. if ( geometry.attributes[ key ] === undefined ) continue;
  6081. const attribute1 = attributes[ key ];
  6082. const attributeArray1 = attribute1.array;
  6083. const attribute2 = geometry.attributes[ key ];
  6084. const attributeArray2 = attribute2.array;
  6085. const attributeOffset = attribute2.itemSize * offset;
  6086. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6087. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6088. attributeArray1[ j ] = attributeArray2[ i ];
  6089. }
  6090. }
  6091. return this;
  6092. }
  6093. normalizeNormals() {
  6094. const normals = this.attributes.normal;
  6095. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6096. _vector$8.fromBufferAttribute( normals, i );
  6097. _vector$8.normalize();
  6098. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6099. }
  6100. }
  6101. toNonIndexed() {
  6102. function convertBufferAttribute( attribute, indices ) {
  6103. const array = attribute.array;
  6104. const itemSize = attribute.itemSize;
  6105. const normalized = attribute.normalized;
  6106. const array2 = new array.constructor( indices.length * itemSize );
  6107. let index = 0, index2 = 0;
  6108. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6109. if ( attribute.isInterleavedBufferAttribute ) {
  6110. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6111. } else {
  6112. index = indices[ i ] * itemSize;
  6113. }
  6114. for ( let j = 0; j < itemSize; j ++ ) {
  6115. array2[ index2 ++ ] = array[ index ++ ];
  6116. }
  6117. }
  6118. return new BufferAttribute( array2, itemSize, normalized );
  6119. }
  6120. //
  6121. if ( this.index === null ) {
  6122. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6123. return this;
  6124. }
  6125. const geometry2 = new BufferGeometry();
  6126. const indices = this.index.array;
  6127. const attributes = this.attributes;
  6128. // attributes
  6129. for ( const name in attributes ) {
  6130. const attribute = attributes[ name ];
  6131. const newAttribute = convertBufferAttribute( attribute, indices );
  6132. geometry2.setAttribute( name, newAttribute );
  6133. }
  6134. // morph attributes
  6135. const morphAttributes = this.morphAttributes;
  6136. for ( const name in morphAttributes ) {
  6137. const morphArray = [];
  6138. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6139. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6140. const attribute = morphAttribute[ i ];
  6141. const newAttribute = convertBufferAttribute( attribute, indices );
  6142. morphArray.push( newAttribute );
  6143. }
  6144. geometry2.morphAttributes[ name ] = morphArray;
  6145. }
  6146. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6147. // groups
  6148. const groups = this.groups;
  6149. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6150. const group = groups[ i ];
  6151. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6152. }
  6153. return geometry2;
  6154. }
  6155. toJSON() {
  6156. const data = {
  6157. metadata: {
  6158. version: 4.5,
  6159. type: 'BufferGeometry',
  6160. generator: 'BufferGeometry.toJSON'
  6161. }
  6162. };
  6163. // standard BufferGeometry serialization
  6164. data.uuid = this.uuid;
  6165. data.type = this.type;
  6166. if ( this.name !== '' ) data.name = this.name;
  6167. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6168. if ( this.parameters !== undefined ) {
  6169. const parameters = this.parameters;
  6170. for ( const key in parameters ) {
  6171. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6172. }
  6173. return data;
  6174. }
  6175. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6176. data.data = { attributes: {} };
  6177. const index = this.index;
  6178. if ( index !== null ) {
  6179. data.data.index = {
  6180. type: index.array.constructor.name,
  6181. array: Array.prototype.slice.call( index.array )
  6182. };
  6183. }
  6184. const attributes = this.attributes;
  6185. for ( const key in attributes ) {
  6186. const attribute = attributes[ key ];
  6187. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6188. }
  6189. const morphAttributes = {};
  6190. let hasMorphAttributes = false;
  6191. for ( const key in this.morphAttributes ) {
  6192. const attributeArray = this.morphAttributes[ key ];
  6193. const array = [];
  6194. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6195. const attribute = attributeArray[ i ];
  6196. array.push( attribute.toJSON( data.data ) );
  6197. }
  6198. if ( array.length > 0 ) {
  6199. morphAttributes[ key ] = array;
  6200. hasMorphAttributes = true;
  6201. }
  6202. }
  6203. if ( hasMorphAttributes ) {
  6204. data.data.morphAttributes = morphAttributes;
  6205. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6206. }
  6207. const groups = this.groups;
  6208. if ( groups.length > 0 ) {
  6209. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6210. }
  6211. const boundingSphere = this.boundingSphere;
  6212. if ( boundingSphere !== null ) {
  6213. data.data.boundingSphere = {
  6214. center: boundingSphere.center.toArray(),
  6215. radius: boundingSphere.radius
  6216. };
  6217. }
  6218. return data;
  6219. }
  6220. clone() {
  6221. /*
  6222. // Handle primitives
  6223. const parameters = this.parameters;
  6224. if ( parameters !== undefined ) {
  6225. const values = [];
  6226. for ( const key in parameters ) {
  6227. values.push( parameters[ key ] );
  6228. }
  6229. const geometry = Object.create( this.constructor.prototype );
  6230. this.constructor.apply( geometry, values );
  6231. return geometry;
  6232. }
  6233. return new this.constructor().copy( this );
  6234. */
  6235. return new BufferGeometry().copy( this );
  6236. }
  6237. copy( source ) {
  6238. // reset
  6239. this.index = null;
  6240. this.attributes = {};
  6241. this.morphAttributes = {};
  6242. this.groups = [];
  6243. this.boundingBox = null;
  6244. this.boundingSphere = null;
  6245. // used for storing cloned, shared data
  6246. const data = {};
  6247. // name
  6248. this.name = source.name;
  6249. // index
  6250. const index = source.index;
  6251. if ( index !== null ) {
  6252. this.setIndex( index.clone( data ) );
  6253. }
  6254. // attributes
  6255. const attributes = source.attributes;
  6256. for ( const name in attributes ) {
  6257. const attribute = attributes[ name ];
  6258. this.setAttribute( name, attribute.clone( data ) );
  6259. }
  6260. // morph attributes
  6261. const morphAttributes = source.morphAttributes;
  6262. for ( const name in morphAttributes ) {
  6263. const array = [];
  6264. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6265. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6266. array.push( morphAttribute[ i ].clone( data ) );
  6267. }
  6268. this.morphAttributes[ name ] = array;
  6269. }
  6270. this.morphTargetsRelative = source.morphTargetsRelative;
  6271. // groups
  6272. const groups = source.groups;
  6273. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6274. const group = groups[ i ];
  6275. this.addGroup( group.start, group.count, group.materialIndex );
  6276. }
  6277. // bounding box
  6278. const boundingBox = source.boundingBox;
  6279. if ( boundingBox !== null ) {
  6280. this.boundingBox = boundingBox.clone();
  6281. }
  6282. // bounding sphere
  6283. const boundingSphere = source.boundingSphere;
  6284. if ( boundingSphere !== null ) {
  6285. this.boundingSphere = boundingSphere.clone();
  6286. }
  6287. // draw range
  6288. this.drawRange.start = source.drawRange.start;
  6289. this.drawRange.count = source.drawRange.count;
  6290. // user data
  6291. this.userData = source.userData;
  6292. return this;
  6293. }
  6294. dispose() {
  6295. this.dispatchEvent( { type: 'dispose' } );
  6296. }
  6297. }
  6298. BufferGeometry.prototype.isBufferGeometry = true;
  6299. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6300. const _ray$2 = /*@__PURE__*/ new Ray();
  6301. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6302. const _vA$1 = /*@__PURE__*/ new Vector3();
  6303. const _vB$1 = /*@__PURE__*/ new Vector3();
  6304. const _vC$1 = /*@__PURE__*/ new Vector3();
  6305. const _tempA = /*@__PURE__*/ new Vector3();
  6306. const _tempB = /*@__PURE__*/ new Vector3();
  6307. const _tempC = /*@__PURE__*/ new Vector3();
  6308. const _morphA = /*@__PURE__*/ new Vector3();
  6309. const _morphB = /*@__PURE__*/ new Vector3();
  6310. const _morphC = /*@__PURE__*/ new Vector3();
  6311. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6312. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6313. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6314. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6315. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6316. class Mesh extends Object3D {
  6317. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6318. super();
  6319. this.type = 'Mesh';
  6320. this.geometry = geometry;
  6321. this.material = material;
  6322. this.updateMorphTargets();
  6323. }
  6324. copy( source ) {
  6325. super.copy( source );
  6326. if ( source.morphTargetInfluences !== undefined ) {
  6327. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6328. }
  6329. if ( source.morphTargetDictionary !== undefined ) {
  6330. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6331. }
  6332. this.material = source.material;
  6333. this.geometry = source.geometry;
  6334. return this;
  6335. }
  6336. updateMorphTargets() {
  6337. const geometry = this.geometry;
  6338. if ( geometry.isBufferGeometry ) {
  6339. const morphAttributes = geometry.morphAttributes;
  6340. const keys = Object.keys( morphAttributes );
  6341. if ( keys.length > 0 ) {
  6342. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6343. if ( morphAttribute !== undefined ) {
  6344. this.morphTargetInfluences = [];
  6345. this.morphTargetDictionary = {};
  6346. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6347. const name = morphAttribute[ m ].name || String( m );
  6348. this.morphTargetInfluences.push( 0 );
  6349. this.morphTargetDictionary[ name ] = m;
  6350. }
  6351. }
  6352. }
  6353. } else {
  6354. const morphTargets = geometry.morphTargets;
  6355. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6356. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6357. }
  6358. }
  6359. }
  6360. raycast( raycaster, intersects ) {
  6361. const geometry = this.geometry;
  6362. const material = this.material;
  6363. const matrixWorld = this.matrixWorld;
  6364. if ( material === undefined ) return;
  6365. // Checking boundingSphere distance to ray
  6366. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6367. _sphere$3.copy( geometry.boundingSphere );
  6368. _sphere$3.applyMatrix4( matrixWorld );
  6369. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6370. //
  6371. _inverseMatrix$2.copy( matrixWorld ).invert();
  6372. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6373. // Check boundingBox before continuing
  6374. if ( geometry.boundingBox !== null ) {
  6375. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6376. }
  6377. let intersection;
  6378. if ( geometry.isBufferGeometry ) {
  6379. const index = geometry.index;
  6380. const position = geometry.attributes.position;
  6381. const morphPosition = geometry.morphAttributes.position;
  6382. const morphTargetsRelative = geometry.morphTargetsRelative;
  6383. const uv = geometry.attributes.uv;
  6384. const uv2 = geometry.attributes.uv2;
  6385. const groups = geometry.groups;
  6386. const drawRange = geometry.drawRange;
  6387. if ( index !== null ) {
  6388. // indexed buffer geometry
  6389. if ( Array.isArray( material ) ) {
  6390. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6391. const group = groups[ i ];
  6392. const groupMaterial = material[ group.materialIndex ];
  6393. const start = Math.max( group.start, drawRange.start );
  6394. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6395. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6396. const a = index.getX( j );
  6397. const b = index.getX( j + 1 );
  6398. const c = index.getX( j + 2 );
  6399. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6400. if ( intersection ) {
  6401. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6402. intersection.face.materialIndex = group.materialIndex;
  6403. intersects.push( intersection );
  6404. }
  6405. }
  6406. }
  6407. } else {
  6408. const start = Math.max( 0, drawRange.start );
  6409. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6410. for ( let i = start, il = end; i < il; i += 3 ) {
  6411. const a = index.getX( i );
  6412. const b = index.getX( i + 1 );
  6413. const c = index.getX( i + 2 );
  6414. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6415. if ( intersection ) {
  6416. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6417. intersects.push( intersection );
  6418. }
  6419. }
  6420. }
  6421. } else if ( position !== undefined ) {
  6422. // non-indexed buffer geometry
  6423. if ( Array.isArray( material ) ) {
  6424. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6425. const group = groups[ i ];
  6426. const groupMaterial = material[ group.materialIndex ];
  6427. const start = Math.max( group.start, drawRange.start );
  6428. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6429. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6430. const a = j;
  6431. const b = j + 1;
  6432. const c = j + 2;
  6433. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6434. if ( intersection ) {
  6435. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6436. intersection.face.materialIndex = group.materialIndex;
  6437. intersects.push( intersection );
  6438. }
  6439. }
  6440. }
  6441. } else {
  6442. const start = Math.max( 0, drawRange.start );
  6443. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6444. for ( let i = start, il = end; i < il; i += 3 ) {
  6445. const a = i;
  6446. const b = i + 1;
  6447. const c = i + 2;
  6448. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6449. if ( intersection ) {
  6450. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6451. intersects.push( intersection );
  6452. }
  6453. }
  6454. }
  6455. }
  6456. } else if ( geometry.isGeometry ) {
  6457. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6458. }
  6459. }
  6460. }
  6461. Mesh.prototype.isMesh = true;
  6462. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6463. let intersect;
  6464. if ( material.side === BackSide ) {
  6465. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6466. } else {
  6467. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6468. }
  6469. if ( intersect === null ) return null;
  6470. _intersectionPointWorld.copy( point );
  6471. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6472. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6473. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6474. return {
  6475. distance: distance,
  6476. point: _intersectionPointWorld.clone(),
  6477. object: object
  6478. };
  6479. }
  6480. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6481. _vA$1.fromBufferAttribute( position, a );
  6482. _vB$1.fromBufferAttribute( position, b );
  6483. _vC$1.fromBufferAttribute( position, c );
  6484. const morphInfluences = object.morphTargetInfluences;
  6485. if ( morphPosition && morphInfluences ) {
  6486. _morphA.set( 0, 0, 0 );
  6487. _morphB.set( 0, 0, 0 );
  6488. _morphC.set( 0, 0, 0 );
  6489. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6490. const influence = morphInfluences[ i ];
  6491. const morphAttribute = morphPosition[ i ];
  6492. if ( influence === 0 ) continue;
  6493. _tempA.fromBufferAttribute( morphAttribute, a );
  6494. _tempB.fromBufferAttribute( morphAttribute, b );
  6495. _tempC.fromBufferAttribute( morphAttribute, c );
  6496. if ( morphTargetsRelative ) {
  6497. _morphA.addScaledVector( _tempA, influence );
  6498. _morphB.addScaledVector( _tempB, influence );
  6499. _morphC.addScaledVector( _tempC, influence );
  6500. } else {
  6501. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6502. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6503. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6504. }
  6505. }
  6506. _vA$1.add( _morphA );
  6507. _vB$1.add( _morphB );
  6508. _vC$1.add( _morphC );
  6509. }
  6510. if ( object.isSkinnedMesh ) {
  6511. object.boneTransform( a, _vA$1 );
  6512. object.boneTransform( b, _vB$1 );
  6513. object.boneTransform( c, _vC$1 );
  6514. }
  6515. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6516. if ( intersection ) {
  6517. if ( uv ) {
  6518. _uvA$1.fromBufferAttribute( uv, a );
  6519. _uvB$1.fromBufferAttribute( uv, b );
  6520. _uvC$1.fromBufferAttribute( uv, c );
  6521. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6522. }
  6523. if ( uv2 ) {
  6524. _uvA$1.fromBufferAttribute( uv2, a );
  6525. _uvB$1.fromBufferAttribute( uv2, b );
  6526. _uvC$1.fromBufferAttribute( uv2, c );
  6527. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6528. }
  6529. const face = {
  6530. a: a,
  6531. b: b,
  6532. c: c,
  6533. normal: new Vector3(),
  6534. materialIndex: 0
  6535. };
  6536. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6537. intersection.face = face;
  6538. }
  6539. return intersection;
  6540. }
  6541. class BoxGeometry extends BufferGeometry {
  6542. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6543. super();
  6544. this.type = 'BoxGeometry';
  6545. this.parameters = {
  6546. width: width,
  6547. height: height,
  6548. depth: depth,
  6549. widthSegments: widthSegments,
  6550. heightSegments: heightSegments,
  6551. depthSegments: depthSegments
  6552. };
  6553. const scope = this;
  6554. // segments
  6555. widthSegments = Math.floor( widthSegments );
  6556. heightSegments = Math.floor( heightSegments );
  6557. depthSegments = Math.floor( depthSegments );
  6558. // buffers
  6559. const indices = [];
  6560. const vertices = [];
  6561. const normals = [];
  6562. const uvs = [];
  6563. // helper variables
  6564. let numberOfVertices = 0;
  6565. let groupStart = 0;
  6566. // build each side of the box geometry
  6567. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6568. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6569. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6570. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6571. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6572. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6573. // build geometry
  6574. this.setIndex( indices );
  6575. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6576. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6577. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6578. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6579. const segmentWidth = width / gridX;
  6580. const segmentHeight = height / gridY;
  6581. const widthHalf = width / 2;
  6582. const heightHalf = height / 2;
  6583. const depthHalf = depth / 2;
  6584. const gridX1 = gridX + 1;
  6585. const gridY1 = gridY + 1;
  6586. let vertexCounter = 0;
  6587. let groupCount = 0;
  6588. const vector = new Vector3();
  6589. // generate vertices, normals and uvs
  6590. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6591. const y = iy * segmentHeight - heightHalf;
  6592. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6593. const x = ix * segmentWidth - widthHalf;
  6594. // set values to correct vector component
  6595. vector[ u ] = x * udir;
  6596. vector[ v ] = y * vdir;
  6597. vector[ w ] = depthHalf;
  6598. // now apply vector to vertex buffer
  6599. vertices.push( vector.x, vector.y, vector.z );
  6600. // set values to correct vector component
  6601. vector[ u ] = 0;
  6602. vector[ v ] = 0;
  6603. vector[ w ] = depth > 0 ? 1 : - 1;
  6604. // now apply vector to normal buffer
  6605. normals.push( vector.x, vector.y, vector.z );
  6606. // uvs
  6607. uvs.push( ix / gridX );
  6608. uvs.push( 1 - ( iy / gridY ) );
  6609. // counters
  6610. vertexCounter += 1;
  6611. }
  6612. }
  6613. // indices
  6614. // 1. you need three indices to draw a single face
  6615. // 2. a single segment consists of two faces
  6616. // 3. so we need to generate six (2*3) indices per segment
  6617. for ( let iy = 0; iy < gridY; iy ++ ) {
  6618. for ( let ix = 0; ix < gridX; ix ++ ) {
  6619. const a = numberOfVertices + ix + gridX1 * iy;
  6620. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6621. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6622. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6623. // faces
  6624. indices.push( a, b, d );
  6625. indices.push( b, c, d );
  6626. // increase counter
  6627. groupCount += 6;
  6628. }
  6629. }
  6630. // add a group to the geometry. this will ensure multi material support
  6631. scope.addGroup( groupStart, groupCount, materialIndex );
  6632. // calculate new start value for groups
  6633. groupStart += groupCount;
  6634. // update total number of vertices
  6635. numberOfVertices += vertexCounter;
  6636. }
  6637. }
  6638. static fromJSON( data ) {
  6639. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6640. }
  6641. }
  6642. /**
  6643. * Uniform Utilities
  6644. */
  6645. function cloneUniforms( src ) {
  6646. const dst = {};
  6647. for ( const u in src ) {
  6648. dst[ u ] = {};
  6649. for ( const p in src[ u ] ) {
  6650. const property = src[ u ][ p ];
  6651. if ( property && ( property.isColor ||
  6652. property.isMatrix3 || property.isMatrix4 ||
  6653. property.isVector2 || property.isVector3 || property.isVector4 ||
  6654. property.isTexture || property.isQuaternion ) ) {
  6655. dst[ u ][ p ] = property.clone();
  6656. } else if ( Array.isArray( property ) ) {
  6657. dst[ u ][ p ] = property.slice();
  6658. } else {
  6659. dst[ u ][ p ] = property;
  6660. }
  6661. }
  6662. }
  6663. return dst;
  6664. }
  6665. function mergeUniforms( uniforms ) {
  6666. const merged = {};
  6667. for ( let u = 0; u < uniforms.length; u ++ ) {
  6668. const tmp = cloneUniforms( uniforms[ u ] );
  6669. for ( const p in tmp ) {
  6670. merged[ p ] = tmp[ p ];
  6671. }
  6672. }
  6673. return merged;
  6674. }
  6675. // Legacy
  6676. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6677. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6678. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6679. /**
  6680. * parameters = {
  6681. * defines: { "label" : "value" },
  6682. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6683. *
  6684. * fragmentShader: <string>,
  6685. * vertexShader: <string>,
  6686. *
  6687. * wireframe: <boolean>,
  6688. * wireframeLinewidth: <float>,
  6689. *
  6690. * lights: <bool>
  6691. * }
  6692. */
  6693. class ShaderMaterial extends Material {
  6694. constructor( parameters ) {
  6695. super();
  6696. this.type = 'ShaderMaterial';
  6697. this.defines = {};
  6698. this.uniforms = {};
  6699. this.vertexShader = default_vertex;
  6700. this.fragmentShader = default_fragment;
  6701. this.linewidth = 1;
  6702. this.wireframe = false;
  6703. this.wireframeLinewidth = 1;
  6704. this.fog = false; // set to use scene fog
  6705. this.lights = false; // set to use scene lights
  6706. this.clipping = false; // set to use user-defined clipping planes
  6707. this.extensions = {
  6708. derivatives: false, // set to use derivatives
  6709. fragDepth: false, // set to use fragment depth values
  6710. drawBuffers: false, // set to use draw buffers
  6711. shaderTextureLOD: false // set to use shader texture LOD
  6712. };
  6713. // When rendered geometry doesn't include these attributes but the material does,
  6714. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6715. this.defaultAttributeValues = {
  6716. 'color': [ 1, 1, 1 ],
  6717. 'uv': [ 0, 0 ],
  6718. 'uv2': [ 0, 0 ]
  6719. };
  6720. this.index0AttributeName = undefined;
  6721. this.uniformsNeedUpdate = false;
  6722. this.glslVersion = null;
  6723. if ( parameters !== undefined ) {
  6724. if ( parameters.attributes !== undefined ) {
  6725. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6726. }
  6727. this.setValues( parameters );
  6728. }
  6729. }
  6730. copy( source ) {
  6731. super.copy( source );
  6732. this.fragmentShader = source.fragmentShader;
  6733. this.vertexShader = source.vertexShader;
  6734. this.uniforms = cloneUniforms( source.uniforms );
  6735. this.defines = Object.assign( {}, source.defines );
  6736. this.wireframe = source.wireframe;
  6737. this.wireframeLinewidth = source.wireframeLinewidth;
  6738. this.lights = source.lights;
  6739. this.clipping = source.clipping;
  6740. this.extensions = Object.assign( {}, source.extensions );
  6741. this.glslVersion = source.glslVersion;
  6742. return this;
  6743. }
  6744. toJSON( meta ) {
  6745. const data = super.toJSON( meta );
  6746. data.glslVersion = this.glslVersion;
  6747. data.uniforms = {};
  6748. for ( const name in this.uniforms ) {
  6749. const uniform = this.uniforms[ name ];
  6750. const value = uniform.value;
  6751. if ( value && value.isTexture ) {
  6752. data.uniforms[ name ] = {
  6753. type: 't',
  6754. value: value.toJSON( meta ).uuid
  6755. };
  6756. } else if ( value && value.isColor ) {
  6757. data.uniforms[ name ] = {
  6758. type: 'c',
  6759. value: value.getHex()
  6760. };
  6761. } else if ( value && value.isVector2 ) {
  6762. data.uniforms[ name ] = {
  6763. type: 'v2',
  6764. value: value.toArray()
  6765. };
  6766. } else if ( value && value.isVector3 ) {
  6767. data.uniforms[ name ] = {
  6768. type: 'v3',
  6769. value: value.toArray()
  6770. };
  6771. } else if ( value && value.isVector4 ) {
  6772. data.uniforms[ name ] = {
  6773. type: 'v4',
  6774. value: value.toArray()
  6775. };
  6776. } else if ( value && value.isMatrix3 ) {
  6777. data.uniforms[ name ] = {
  6778. type: 'm3',
  6779. value: value.toArray()
  6780. };
  6781. } else if ( value && value.isMatrix4 ) {
  6782. data.uniforms[ name ] = {
  6783. type: 'm4',
  6784. value: value.toArray()
  6785. };
  6786. } else {
  6787. data.uniforms[ name ] = {
  6788. value: value
  6789. };
  6790. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6791. }
  6792. }
  6793. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6794. data.vertexShader = this.vertexShader;
  6795. data.fragmentShader = this.fragmentShader;
  6796. const extensions = {};
  6797. for ( const key in this.extensions ) {
  6798. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6799. }
  6800. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6801. return data;
  6802. }
  6803. }
  6804. ShaderMaterial.prototype.isShaderMaterial = true;
  6805. class Camera extends Object3D {
  6806. constructor() {
  6807. super();
  6808. this.type = 'Camera';
  6809. this.matrixWorldInverse = new Matrix4();
  6810. this.projectionMatrix = new Matrix4();
  6811. this.projectionMatrixInverse = new Matrix4();
  6812. }
  6813. copy( source, recursive ) {
  6814. super.copy( source, recursive );
  6815. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6816. this.projectionMatrix.copy( source.projectionMatrix );
  6817. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6818. return this;
  6819. }
  6820. getWorldDirection( target ) {
  6821. this.updateWorldMatrix( true, false );
  6822. const e = this.matrixWorld.elements;
  6823. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6824. }
  6825. updateMatrixWorld( force ) {
  6826. super.updateMatrixWorld( force );
  6827. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6828. }
  6829. updateWorldMatrix( updateParents, updateChildren ) {
  6830. super.updateWorldMatrix( updateParents, updateChildren );
  6831. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6832. }
  6833. clone() {
  6834. return new this.constructor().copy( this );
  6835. }
  6836. }
  6837. Camera.prototype.isCamera = true;
  6838. class PerspectiveCamera extends Camera {
  6839. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6840. super();
  6841. this.type = 'PerspectiveCamera';
  6842. this.fov = fov;
  6843. this.zoom = 1;
  6844. this.near = near;
  6845. this.far = far;
  6846. this.focus = 10;
  6847. this.aspect = aspect;
  6848. this.view = null;
  6849. this.filmGauge = 35; // width of the film (default in millimeters)
  6850. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6851. this.updateProjectionMatrix();
  6852. }
  6853. copy( source, recursive ) {
  6854. super.copy( source, recursive );
  6855. this.fov = source.fov;
  6856. this.zoom = source.zoom;
  6857. this.near = source.near;
  6858. this.far = source.far;
  6859. this.focus = source.focus;
  6860. this.aspect = source.aspect;
  6861. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6862. this.filmGauge = source.filmGauge;
  6863. this.filmOffset = source.filmOffset;
  6864. return this;
  6865. }
  6866. /**
  6867. * Sets the FOV by focal length in respect to the current .filmGauge.
  6868. *
  6869. * The default film gauge is 35, so that the focal length can be specified for
  6870. * a 35mm (full frame) camera.
  6871. *
  6872. * Values for focal length and film gauge must have the same unit.
  6873. */
  6874. setFocalLength( focalLength ) {
  6875. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6876. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6877. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6878. this.updateProjectionMatrix();
  6879. }
  6880. /**
  6881. * Calculates the focal length from the current .fov and .filmGauge.
  6882. */
  6883. getFocalLength() {
  6884. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6885. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6886. }
  6887. getEffectiveFOV() {
  6888. return RAD2DEG * 2 * Math.atan(
  6889. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6890. }
  6891. getFilmWidth() {
  6892. // film not completely covered in portrait format (aspect < 1)
  6893. return this.filmGauge * Math.min( this.aspect, 1 );
  6894. }
  6895. getFilmHeight() {
  6896. // film not completely covered in landscape format (aspect > 1)
  6897. return this.filmGauge / Math.max( this.aspect, 1 );
  6898. }
  6899. /**
  6900. * Sets an offset in a larger frustum. This is useful for multi-window or
  6901. * multi-monitor/multi-machine setups.
  6902. *
  6903. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6904. * the monitors are in grid like this
  6905. *
  6906. * +---+---+---+
  6907. * | A | B | C |
  6908. * +---+---+---+
  6909. * | D | E | F |
  6910. * +---+---+---+
  6911. *
  6912. * then for each monitor you would call it like this
  6913. *
  6914. * const w = 1920;
  6915. * const h = 1080;
  6916. * const fullWidth = w * 3;
  6917. * const fullHeight = h * 2;
  6918. *
  6919. * --A--
  6920. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6921. * --B--
  6922. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6923. * --C--
  6924. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6925. * --D--
  6926. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6927. * --E--
  6928. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6929. * --F--
  6930. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6931. *
  6932. * Note there is no reason monitors have to be the same size or in a grid.
  6933. */
  6934. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  6935. this.aspect = fullWidth / fullHeight;
  6936. if ( this.view === null ) {
  6937. this.view = {
  6938. enabled: true,
  6939. fullWidth: 1,
  6940. fullHeight: 1,
  6941. offsetX: 0,
  6942. offsetY: 0,
  6943. width: 1,
  6944. height: 1
  6945. };
  6946. }
  6947. this.view.enabled = true;
  6948. this.view.fullWidth = fullWidth;
  6949. this.view.fullHeight = fullHeight;
  6950. this.view.offsetX = x;
  6951. this.view.offsetY = y;
  6952. this.view.width = width;
  6953. this.view.height = height;
  6954. this.updateProjectionMatrix();
  6955. }
  6956. clearViewOffset() {
  6957. if ( this.view !== null ) {
  6958. this.view.enabled = false;
  6959. }
  6960. this.updateProjectionMatrix();
  6961. }
  6962. updateProjectionMatrix() {
  6963. const near = this.near;
  6964. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  6965. let height = 2 * top;
  6966. let width = this.aspect * height;
  6967. let left = - 0.5 * width;
  6968. const view = this.view;
  6969. if ( this.view !== null && this.view.enabled ) {
  6970. const fullWidth = view.fullWidth,
  6971. fullHeight = view.fullHeight;
  6972. left += view.offsetX * width / fullWidth;
  6973. top -= view.offsetY * height / fullHeight;
  6974. width *= view.width / fullWidth;
  6975. height *= view.height / fullHeight;
  6976. }
  6977. const skew = this.filmOffset;
  6978. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  6979. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  6980. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  6981. }
  6982. toJSON( meta ) {
  6983. const data = super.toJSON( meta );
  6984. data.object.fov = this.fov;
  6985. data.object.zoom = this.zoom;
  6986. data.object.near = this.near;
  6987. data.object.far = this.far;
  6988. data.object.focus = this.focus;
  6989. data.object.aspect = this.aspect;
  6990. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6991. data.object.filmGauge = this.filmGauge;
  6992. data.object.filmOffset = this.filmOffset;
  6993. return data;
  6994. }
  6995. }
  6996. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  6997. const fov = 90, aspect = 1;
  6998. class CubeCamera extends Object3D {
  6999. constructor( near, far, renderTarget ) {
  7000. super();
  7001. this.type = 'CubeCamera';
  7002. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7003. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7004. return;
  7005. }
  7006. this.renderTarget = renderTarget;
  7007. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7008. cameraPX.layers = this.layers;
  7009. cameraPX.up.set( 0, - 1, 0 );
  7010. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7011. this.add( cameraPX );
  7012. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7013. cameraNX.layers = this.layers;
  7014. cameraNX.up.set( 0, - 1, 0 );
  7015. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7016. this.add( cameraNX );
  7017. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7018. cameraPY.layers = this.layers;
  7019. cameraPY.up.set( 0, 0, 1 );
  7020. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7021. this.add( cameraPY );
  7022. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7023. cameraNY.layers = this.layers;
  7024. cameraNY.up.set( 0, 0, - 1 );
  7025. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7026. this.add( cameraNY );
  7027. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7028. cameraPZ.layers = this.layers;
  7029. cameraPZ.up.set( 0, - 1, 0 );
  7030. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7031. this.add( cameraPZ );
  7032. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7033. cameraNZ.layers = this.layers;
  7034. cameraNZ.up.set( 0, - 1, 0 );
  7035. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7036. this.add( cameraNZ );
  7037. }
  7038. update( renderer, scene ) {
  7039. if ( this.parent === null ) this.updateMatrixWorld();
  7040. const renderTarget = this.renderTarget;
  7041. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7042. const currentXrEnabled = renderer.xr.enabled;
  7043. const currentRenderTarget = renderer.getRenderTarget();
  7044. renderer.xr.enabled = false;
  7045. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7046. renderTarget.texture.generateMipmaps = false;
  7047. renderer.setRenderTarget( renderTarget, 0 );
  7048. renderer.render( scene, cameraPX );
  7049. renderer.setRenderTarget( renderTarget, 1 );
  7050. renderer.render( scene, cameraNX );
  7051. renderer.setRenderTarget( renderTarget, 2 );
  7052. renderer.render( scene, cameraPY );
  7053. renderer.setRenderTarget( renderTarget, 3 );
  7054. renderer.render( scene, cameraNY );
  7055. renderer.setRenderTarget( renderTarget, 4 );
  7056. renderer.render( scene, cameraPZ );
  7057. renderTarget.texture.generateMipmaps = generateMipmaps;
  7058. renderer.setRenderTarget( renderTarget, 5 );
  7059. renderer.render( scene, cameraNZ );
  7060. renderer.setRenderTarget( currentRenderTarget );
  7061. renderer.xr.enabled = currentXrEnabled;
  7062. }
  7063. }
  7064. class CubeTexture extends Texture {
  7065. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7066. images = images !== undefined ? images : [];
  7067. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7068. format = format !== undefined ? format : RGBFormat;
  7069. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7070. this.flipY = false;
  7071. }
  7072. get images() {
  7073. return this.image;
  7074. }
  7075. set images( value ) {
  7076. this.image = value;
  7077. }
  7078. }
  7079. CubeTexture.prototype.isCubeTexture = true;
  7080. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7081. constructor( size, options, dummy ) {
  7082. if ( Number.isInteger( options ) ) {
  7083. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  7084. options = dummy;
  7085. }
  7086. super( size, size, options );
  7087. options = options || {};
  7088. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7089. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7090. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7091. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7092. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7093. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7094. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7095. this.texture.isRenderTargetTexture = true;
  7096. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7097. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7098. this.texture._needsFlipEnvMap = false;
  7099. }
  7100. fromEquirectangularTexture( renderer, texture ) {
  7101. this.texture.type = texture.type;
  7102. this.texture.format = RGBAFormat; // see #18859
  7103. this.texture.encoding = texture.encoding;
  7104. this.texture.generateMipmaps = texture.generateMipmaps;
  7105. this.texture.minFilter = texture.minFilter;
  7106. this.texture.magFilter = texture.magFilter;
  7107. const shader = {
  7108. uniforms: {
  7109. tEquirect: { value: null },
  7110. },
  7111. vertexShader: /* glsl */`
  7112. varying vec3 vWorldDirection;
  7113. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7114. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7115. }
  7116. void main() {
  7117. vWorldDirection = transformDirection( position, modelMatrix );
  7118. #include <begin_vertex>
  7119. #include <project_vertex>
  7120. }
  7121. `,
  7122. fragmentShader: /* glsl */`
  7123. uniform sampler2D tEquirect;
  7124. varying vec3 vWorldDirection;
  7125. #include <common>
  7126. void main() {
  7127. vec3 direction = normalize( vWorldDirection );
  7128. vec2 sampleUV = equirectUv( direction );
  7129. gl_FragColor = texture2D( tEquirect, sampleUV );
  7130. }
  7131. `
  7132. };
  7133. const geometry = new BoxGeometry( 5, 5, 5 );
  7134. const material = new ShaderMaterial( {
  7135. name: 'CubemapFromEquirect',
  7136. uniforms: cloneUniforms( shader.uniforms ),
  7137. vertexShader: shader.vertexShader,
  7138. fragmentShader: shader.fragmentShader,
  7139. side: BackSide,
  7140. blending: NoBlending
  7141. } );
  7142. material.uniforms.tEquirect.value = texture;
  7143. const mesh = new Mesh( geometry, material );
  7144. const currentMinFilter = texture.minFilter;
  7145. // Avoid blurred poles
  7146. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7147. const camera = new CubeCamera( 1, 10, this );
  7148. camera.update( renderer, mesh );
  7149. texture.minFilter = currentMinFilter;
  7150. mesh.geometry.dispose();
  7151. mesh.material.dispose();
  7152. return this;
  7153. }
  7154. clear( renderer, color, depth, stencil ) {
  7155. const currentRenderTarget = renderer.getRenderTarget();
  7156. for ( let i = 0; i < 6; i ++ ) {
  7157. renderer.setRenderTarget( this, i );
  7158. renderer.clear( color, depth, stencil );
  7159. }
  7160. renderer.setRenderTarget( currentRenderTarget );
  7161. }
  7162. }
  7163. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7164. const _vector1 = /*@__PURE__*/ new Vector3();
  7165. const _vector2 = /*@__PURE__*/ new Vector3();
  7166. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7167. class Plane {
  7168. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7169. // normal is assumed to be normalized
  7170. this.normal = normal;
  7171. this.constant = constant;
  7172. }
  7173. set( normal, constant ) {
  7174. this.normal.copy( normal );
  7175. this.constant = constant;
  7176. return this;
  7177. }
  7178. setComponents( x, y, z, w ) {
  7179. this.normal.set( x, y, z );
  7180. this.constant = w;
  7181. return this;
  7182. }
  7183. setFromNormalAndCoplanarPoint( normal, point ) {
  7184. this.normal.copy( normal );
  7185. this.constant = - point.dot( this.normal );
  7186. return this;
  7187. }
  7188. setFromCoplanarPoints( a, b, c ) {
  7189. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7190. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7191. this.setFromNormalAndCoplanarPoint( normal, a );
  7192. return this;
  7193. }
  7194. copy( plane ) {
  7195. this.normal.copy( plane.normal );
  7196. this.constant = plane.constant;
  7197. return this;
  7198. }
  7199. normalize() {
  7200. // Note: will lead to a divide by zero if the plane is invalid.
  7201. const inverseNormalLength = 1.0 / this.normal.length();
  7202. this.normal.multiplyScalar( inverseNormalLength );
  7203. this.constant *= inverseNormalLength;
  7204. return this;
  7205. }
  7206. negate() {
  7207. this.constant *= - 1;
  7208. this.normal.negate();
  7209. return this;
  7210. }
  7211. distanceToPoint( point ) {
  7212. return this.normal.dot( point ) + this.constant;
  7213. }
  7214. distanceToSphere( sphere ) {
  7215. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7216. }
  7217. projectPoint( point, target ) {
  7218. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7219. }
  7220. intersectLine( line, target ) {
  7221. const direction = line.delta( _vector1 );
  7222. const denominator = this.normal.dot( direction );
  7223. if ( denominator === 0 ) {
  7224. // line is coplanar, return origin
  7225. if ( this.distanceToPoint( line.start ) === 0 ) {
  7226. return target.copy( line.start );
  7227. }
  7228. // Unsure if this is the correct method to handle this case.
  7229. return null;
  7230. }
  7231. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7232. if ( t < 0 || t > 1 ) {
  7233. return null;
  7234. }
  7235. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7236. }
  7237. intersectsLine( line ) {
  7238. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7239. const startSign = this.distanceToPoint( line.start );
  7240. const endSign = this.distanceToPoint( line.end );
  7241. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7242. }
  7243. intersectsBox( box ) {
  7244. return box.intersectsPlane( this );
  7245. }
  7246. intersectsSphere( sphere ) {
  7247. return sphere.intersectsPlane( this );
  7248. }
  7249. coplanarPoint( target ) {
  7250. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7251. }
  7252. applyMatrix4( matrix, optionalNormalMatrix ) {
  7253. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7254. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7255. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7256. this.constant = - referencePoint.dot( normal );
  7257. return this;
  7258. }
  7259. translate( offset ) {
  7260. this.constant -= offset.dot( this.normal );
  7261. return this;
  7262. }
  7263. equals( plane ) {
  7264. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7265. }
  7266. clone() {
  7267. return new this.constructor().copy( this );
  7268. }
  7269. }
  7270. Plane.prototype.isPlane = true;
  7271. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7272. const _vector$7 = /*@__PURE__*/ new Vector3();
  7273. class Frustum {
  7274. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7275. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7276. }
  7277. set( p0, p1, p2, p3, p4, p5 ) {
  7278. const planes = this.planes;
  7279. planes[ 0 ].copy( p0 );
  7280. planes[ 1 ].copy( p1 );
  7281. planes[ 2 ].copy( p2 );
  7282. planes[ 3 ].copy( p3 );
  7283. planes[ 4 ].copy( p4 );
  7284. planes[ 5 ].copy( p5 );
  7285. return this;
  7286. }
  7287. copy( frustum ) {
  7288. const planes = this.planes;
  7289. for ( let i = 0; i < 6; i ++ ) {
  7290. planes[ i ].copy( frustum.planes[ i ] );
  7291. }
  7292. return this;
  7293. }
  7294. setFromProjectionMatrix( m ) {
  7295. const planes = this.planes;
  7296. const me = m.elements;
  7297. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7298. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7299. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7300. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7301. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7302. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7303. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7304. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7305. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7306. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7307. return this;
  7308. }
  7309. intersectsObject( object ) {
  7310. const geometry = object.geometry;
  7311. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7312. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7313. return this.intersectsSphere( _sphere$2 );
  7314. }
  7315. intersectsSprite( sprite ) {
  7316. _sphere$2.center.set( 0, 0, 0 );
  7317. _sphere$2.radius = 0.7071067811865476;
  7318. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7319. return this.intersectsSphere( _sphere$2 );
  7320. }
  7321. intersectsSphere( sphere ) {
  7322. const planes = this.planes;
  7323. const center = sphere.center;
  7324. const negRadius = - sphere.radius;
  7325. for ( let i = 0; i < 6; i ++ ) {
  7326. const distance = planes[ i ].distanceToPoint( center );
  7327. if ( distance < negRadius ) {
  7328. return false;
  7329. }
  7330. }
  7331. return true;
  7332. }
  7333. intersectsBox( box ) {
  7334. const planes = this.planes;
  7335. for ( let i = 0; i < 6; i ++ ) {
  7336. const plane = planes[ i ];
  7337. // corner at max distance
  7338. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7339. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7340. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7341. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7342. return false;
  7343. }
  7344. }
  7345. return true;
  7346. }
  7347. containsPoint( point ) {
  7348. const planes = this.planes;
  7349. for ( let i = 0; i < 6; i ++ ) {
  7350. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7351. return false;
  7352. }
  7353. }
  7354. return true;
  7355. }
  7356. clone() {
  7357. return new this.constructor().copy( this );
  7358. }
  7359. }
  7360. function WebGLAnimation() {
  7361. let context = null;
  7362. let isAnimating = false;
  7363. let animationLoop = null;
  7364. let requestId = null;
  7365. function onAnimationFrame( time, frame ) {
  7366. animationLoop( time, frame );
  7367. requestId = context.requestAnimationFrame( onAnimationFrame );
  7368. }
  7369. return {
  7370. start: function () {
  7371. if ( isAnimating === true ) return;
  7372. if ( animationLoop === null ) return;
  7373. requestId = context.requestAnimationFrame( onAnimationFrame );
  7374. isAnimating = true;
  7375. },
  7376. stop: function () {
  7377. context.cancelAnimationFrame( requestId );
  7378. isAnimating = false;
  7379. },
  7380. setAnimationLoop: function ( callback ) {
  7381. animationLoop = callback;
  7382. },
  7383. setContext: function ( value ) {
  7384. context = value;
  7385. }
  7386. };
  7387. }
  7388. function WebGLAttributes( gl, capabilities ) {
  7389. const isWebGL2 = capabilities.isWebGL2;
  7390. const buffers = new WeakMap();
  7391. function createBuffer( attribute, bufferType ) {
  7392. const array = attribute.array;
  7393. const usage = attribute.usage;
  7394. const buffer = gl.createBuffer();
  7395. gl.bindBuffer( bufferType, buffer );
  7396. gl.bufferData( bufferType, array, usage );
  7397. attribute.onUploadCallback();
  7398. let type = 5126;
  7399. if ( array instanceof Float32Array ) {
  7400. type = 5126;
  7401. } else if ( array instanceof Float64Array ) {
  7402. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7403. } else if ( array instanceof Uint16Array ) {
  7404. if ( attribute.isFloat16BufferAttribute ) {
  7405. if ( isWebGL2 ) {
  7406. type = 5131;
  7407. } else {
  7408. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7409. }
  7410. } else {
  7411. type = 5123;
  7412. }
  7413. } else if ( array instanceof Int16Array ) {
  7414. type = 5122;
  7415. } else if ( array instanceof Uint32Array ) {
  7416. type = 5125;
  7417. } else if ( array instanceof Int32Array ) {
  7418. type = 5124;
  7419. } else if ( array instanceof Int8Array ) {
  7420. type = 5120;
  7421. } else if ( array instanceof Uint8Array ) {
  7422. type = 5121;
  7423. } else if ( array instanceof Uint8ClampedArray ) {
  7424. type = 5121;
  7425. }
  7426. return {
  7427. buffer: buffer,
  7428. type: type,
  7429. bytesPerElement: array.BYTES_PER_ELEMENT,
  7430. version: attribute.version
  7431. };
  7432. }
  7433. function updateBuffer( buffer, attribute, bufferType ) {
  7434. const array = attribute.array;
  7435. const updateRange = attribute.updateRange;
  7436. gl.bindBuffer( bufferType, buffer );
  7437. if ( updateRange.count === - 1 ) {
  7438. // Not using update ranges
  7439. gl.bufferSubData( bufferType, 0, array );
  7440. } else {
  7441. if ( isWebGL2 ) {
  7442. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7443. array, updateRange.offset, updateRange.count );
  7444. } else {
  7445. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7446. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7447. }
  7448. updateRange.count = - 1; // reset range
  7449. }
  7450. }
  7451. //
  7452. function get( attribute ) {
  7453. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7454. return buffers.get( attribute );
  7455. }
  7456. function remove( attribute ) {
  7457. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7458. const data = buffers.get( attribute );
  7459. if ( data ) {
  7460. gl.deleteBuffer( data.buffer );
  7461. buffers.delete( attribute );
  7462. }
  7463. }
  7464. function update( attribute, bufferType ) {
  7465. if ( attribute.isGLBufferAttribute ) {
  7466. const cached = buffers.get( attribute );
  7467. if ( ! cached || cached.version < attribute.version ) {
  7468. buffers.set( attribute, {
  7469. buffer: attribute.buffer,
  7470. type: attribute.type,
  7471. bytesPerElement: attribute.elementSize,
  7472. version: attribute.version
  7473. } );
  7474. }
  7475. return;
  7476. }
  7477. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7478. const data = buffers.get( attribute );
  7479. if ( data === undefined ) {
  7480. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7481. } else if ( data.version < attribute.version ) {
  7482. updateBuffer( data.buffer, attribute, bufferType );
  7483. data.version = attribute.version;
  7484. }
  7485. }
  7486. return {
  7487. get: get,
  7488. remove: remove,
  7489. update: update
  7490. };
  7491. }
  7492. class PlaneGeometry extends BufferGeometry {
  7493. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7494. super();
  7495. this.type = 'PlaneGeometry';
  7496. this.parameters = {
  7497. width: width,
  7498. height: height,
  7499. widthSegments: widthSegments,
  7500. heightSegments: heightSegments
  7501. };
  7502. const width_half = width / 2;
  7503. const height_half = height / 2;
  7504. const gridX = Math.floor( widthSegments );
  7505. const gridY = Math.floor( heightSegments );
  7506. const gridX1 = gridX + 1;
  7507. const gridY1 = gridY + 1;
  7508. const segment_width = width / gridX;
  7509. const segment_height = height / gridY;
  7510. //
  7511. const indices = [];
  7512. const vertices = [];
  7513. const normals = [];
  7514. const uvs = [];
  7515. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7516. const y = iy * segment_height - height_half;
  7517. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7518. const x = ix * segment_width - width_half;
  7519. vertices.push( x, - y, 0 );
  7520. normals.push( 0, 0, 1 );
  7521. uvs.push( ix / gridX );
  7522. uvs.push( 1 - ( iy / gridY ) );
  7523. }
  7524. }
  7525. for ( let iy = 0; iy < gridY; iy ++ ) {
  7526. for ( let ix = 0; ix < gridX; ix ++ ) {
  7527. const a = ix + gridX1 * iy;
  7528. const b = ix + gridX1 * ( iy + 1 );
  7529. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7530. const d = ( ix + 1 ) + gridX1 * iy;
  7531. indices.push( a, b, d );
  7532. indices.push( b, c, d );
  7533. }
  7534. }
  7535. this.setIndex( indices );
  7536. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7537. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7538. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7539. }
  7540. static fromJSON( data ) {
  7541. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7542. }
  7543. }
  7544. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7545. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7546. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7547. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7548. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7549. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7550. var begin_vertex = "vec3 transformed = vec3( position );";
  7551. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7552. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( 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 dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n
  7553. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7554. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7555. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7556. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7557. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7558. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7559. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7560. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7561. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7562. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\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 precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7563. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7564. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7565. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7566. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7567. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7568. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7569. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7570. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  7571. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7572. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7573. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  7574. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  7575. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  7576. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7577. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7578. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7579. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7580. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7581. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7582. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7583. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7584. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible =
  7585. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in GeometricContext geometry ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7586. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7587. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7588. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7589. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight, 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_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)";
  7590. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenTint = sheenTint;\n#endif";
  7591. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenTint;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.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}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( material.roughness, directLight.direction, geometry, material.sheenTint );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif
  7592. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7593. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7594. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  7595. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7596. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  7597. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  7598. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  7599. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7600. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7601. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7602. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7603. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7604. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7605. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  7606. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7607. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  7608. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7609. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7610. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7611. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7612. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7613. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7614. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7615. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7616. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7617. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7618. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7619. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7620. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  7621. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7622. var 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";
  7623. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7624. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7625. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadow
  7626. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  7627. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7628. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  7629. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  7630. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  7631. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  7632. var 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";
  7633. var 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";
  7634. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7635. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7636. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  7637. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = transmission.a;\n#endif";
  7638. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7639. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7640. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7641. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7642. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7643. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7644. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7645. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7646. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7647. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7648. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7649. var 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}";
  7650. var 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 <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\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\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7651. var 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>\nvarying vec2 vHighPrecisionZW;\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\tvHighPrecisionZW = gl_Position.zw;\n}";
  7652. var 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 <alphatest_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}";
  7653. var 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}";
  7654. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7655. var 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}";
  7656. var 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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7657. var 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 <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7658. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\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 <alphatest_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 <cube_uv_reflection_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\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\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}";
  7659. var 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#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\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 <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7660. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <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 <alphatest_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 <cube_uv_reflection_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\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_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_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\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}";
  7661. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <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}";
  7662. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_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 <color_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\t#include <output_fragment>\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}";
  7663. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_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 <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 <normal_vertex>\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}";
  7664. var meshnormal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_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}";
  7665. var meshnormal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_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#include <normal_vertex>\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}";
  7666. var 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 <alphatest_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 <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\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\t#include <output_fragment>\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}";
  7667. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\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 <normal_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 <normal_vertex>\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}";
  7668. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularTint;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARTINTMAP\n\t\tuniform sampler2D specularTintMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenTint;\n#endif\nvarying vec3 vViewPosition;\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 <alphatest_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 <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_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 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat;\n\t#endif\n\t#include <output_fragment>\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}";
  7669. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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 <normal_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 <normal_vertex>\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#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7670. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_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\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 <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_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 + totalEmissiveRadiance;\n\t#include <output_fragment>\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}";
  7671. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\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 <normal_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 <normal_vertex>\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}";
  7672. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7673. var 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 = isPerspectiveMatrix( projectionMatrix );\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}";
  7674. var 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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7675. var shadow_vert = "#include <common>\n#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 <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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7676. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_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 <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7677. var 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 = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7678. const ShaderChunk = {
  7679. alphamap_fragment: alphamap_fragment,
  7680. alphamap_pars_fragment: alphamap_pars_fragment,
  7681. alphatest_fragment: alphatest_fragment,
  7682. alphatest_pars_fragment: alphatest_pars_fragment,
  7683. aomap_fragment: aomap_fragment,
  7684. aomap_pars_fragment: aomap_pars_fragment,
  7685. begin_vertex: begin_vertex,
  7686. beginnormal_vertex: beginnormal_vertex,
  7687. bsdfs: bsdfs,
  7688. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7689. clipping_planes_fragment: clipping_planes_fragment,
  7690. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7691. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7692. clipping_planes_vertex: clipping_planes_vertex,
  7693. color_fragment: color_fragment,
  7694. color_pars_fragment: color_pars_fragment,
  7695. color_pars_vertex: color_pars_vertex,
  7696. color_vertex: color_vertex,
  7697. common: common,
  7698. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7699. defaultnormal_vertex: defaultnormal_vertex,
  7700. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7701. displacementmap_vertex: displacementmap_vertex,
  7702. emissivemap_fragment: emissivemap_fragment,
  7703. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7704. encodings_fragment: encodings_fragment,
  7705. encodings_pars_fragment: encodings_pars_fragment,
  7706. envmap_fragment: envmap_fragment,
  7707. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7708. envmap_pars_fragment: envmap_pars_fragment,
  7709. envmap_pars_vertex: envmap_pars_vertex,
  7710. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7711. envmap_vertex: envmap_vertex,
  7712. fog_vertex: fog_vertex,
  7713. fog_pars_vertex: fog_pars_vertex,
  7714. fog_fragment: fog_fragment,
  7715. fog_pars_fragment: fog_pars_fragment,
  7716. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7717. lightmap_fragment: lightmap_fragment,
  7718. lightmap_pars_fragment: lightmap_pars_fragment,
  7719. lights_lambert_vertex: lights_lambert_vertex,
  7720. lights_pars_begin: lights_pars_begin,
  7721. lights_toon_fragment: lights_toon_fragment,
  7722. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7723. lights_phong_fragment: lights_phong_fragment,
  7724. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7725. lights_physical_fragment: lights_physical_fragment,
  7726. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7727. lights_fragment_begin: lights_fragment_begin,
  7728. lights_fragment_maps: lights_fragment_maps,
  7729. lights_fragment_end: lights_fragment_end,
  7730. logdepthbuf_fragment: logdepthbuf_fragment,
  7731. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7732. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7733. logdepthbuf_vertex: logdepthbuf_vertex,
  7734. map_fragment: map_fragment,
  7735. map_pars_fragment: map_pars_fragment,
  7736. map_particle_fragment: map_particle_fragment,
  7737. map_particle_pars_fragment: map_particle_pars_fragment,
  7738. metalnessmap_fragment: metalnessmap_fragment,
  7739. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7740. morphnormal_vertex: morphnormal_vertex,
  7741. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7742. morphtarget_vertex: morphtarget_vertex,
  7743. normal_fragment_begin: normal_fragment_begin,
  7744. normal_fragment_maps: normal_fragment_maps,
  7745. normal_pars_fragment: normal_pars_fragment,
  7746. normal_pars_vertex: normal_pars_vertex,
  7747. normal_vertex: normal_vertex,
  7748. normalmap_pars_fragment: normalmap_pars_fragment,
  7749. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7750. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7751. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7752. output_fragment: output_fragment,
  7753. packing: packing,
  7754. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7755. project_vertex: project_vertex,
  7756. dithering_fragment: dithering_fragment,
  7757. dithering_pars_fragment: dithering_pars_fragment,
  7758. roughnessmap_fragment: roughnessmap_fragment,
  7759. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7760. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7761. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7762. shadowmap_vertex: shadowmap_vertex,
  7763. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7764. skinbase_vertex: skinbase_vertex,
  7765. skinning_pars_vertex: skinning_pars_vertex,
  7766. skinning_vertex: skinning_vertex,
  7767. skinnormal_vertex: skinnormal_vertex,
  7768. specularmap_fragment: specularmap_fragment,
  7769. specularmap_pars_fragment: specularmap_pars_fragment,
  7770. tonemapping_fragment: tonemapping_fragment,
  7771. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7772. transmission_fragment: transmission_fragment,
  7773. transmission_pars_fragment: transmission_pars_fragment,
  7774. uv_pars_fragment: uv_pars_fragment,
  7775. uv_pars_vertex: uv_pars_vertex,
  7776. uv_vertex: uv_vertex,
  7777. uv2_pars_fragment: uv2_pars_fragment,
  7778. uv2_pars_vertex: uv2_pars_vertex,
  7779. uv2_vertex: uv2_vertex,
  7780. worldpos_vertex: worldpos_vertex,
  7781. background_frag: background_frag,
  7782. background_vert: background_vert,
  7783. cube_frag: cube_frag,
  7784. cube_vert: cube_vert,
  7785. depth_frag: depth_frag,
  7786. depth_vert: depth_vert,
  7787. distanceRGBA_frag: distanceRGBA_frag,
  7788. distanceRGBA_vert: distanceRGBA_vert,
  7789. equirect_frag: equirect_frag,
  7790. equirect_vert: equirect_vert,
  7791. linedashed_frag: linedashed_frag,
  7792. linedashed_vert: linedashed_vert,
  7793. meshbasic_frag: meshbasic_frag,
  7794. meshbasic_vert: meshbasic_vert,
  7795. meshlambert_frag: meshlambert_frag,
  7796. meshlambert_vert: meshlambert_vert,
  7797. meshmatcap_frag: meshmatcap_frag,
  7798. meshmatcap_vert: meshmatcap_vert,
  7799. meshnormal_frag: meshnormal_frag,
  7800. meshnormal_vert: meshnormal_vert,
  7801. meshphong_frag: meshphong_frag,
  7802. meshphong_vert: meshphong_vert,
  7803. meshphysical_frag: meshphysical_frag,
  7804. meshphysical_vert: meshphysical_vert,
  7805. meshtoon_frag: meshtoon_frag,
  7806. meshtoon_vert: meshtoon_vert,
  7807. points_frag: points_frag,
  7808. points_vert: points_vert,
  7809. shadow_frag: shadow_frag,
  7810. shadow_vert: shadow_vert,
  7811. sprite_frag: sprite_frag,
  7812. sprite_vert: sprite_vert
  7813. };
  7814. /**
  7815. * Uniforms library for shared webgl shaders
  7816. */
  7817. const UniformsLib = {
  7818. common: {
  7819. diffuse: { value: new Color( 0xffffff ) },
  7820. opacity: { value: 1.0 },
  7821. map: { value: null },
  7822. uvTransform: { value: new Matrix3() },
  7823. uv2Transform: { value: new Matrix3() },
  7824. alphaMap: { value: null },
  7825. alphaTest: { value: 0 }
  7826. },
  7827. specularmap: {
  7828. specularMap: { value: null },
  7829. },
  7830. envmap: {
  7831. envMap: { value: null },
  7832. flipEnvMap: { value: - 1 },
  7833. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7834. ior: { value: 1.5 }, // standard, physical
  7835. refractionRatio: { value: 0.98 },
  7836. maxMipLevel: { value: 0 }
  7837. },
  7838. aomap: {
  7839. aoMap: { value: null },
  7840. aoMapIntensity: { value: 1 }
  7841. },
  7842. lightmap: {
  7843. lightMap: { value: null },
  7844. lightMapIntensity: { value: 1 }
  7845. },
  7846. emissivemap: {
  7847. emissiveMap: { value: null }
  7848. },
  7849. bumpmap: {
  7850. bumpMap: { value: null },
  7851. bumpScale: { value: 1 }
  7852. },
  7853. normalmap: {
  7854. normalMap: { value: null },
  7855. normalScale: { value: new Vector2( 1, 1 ) }
  7856. },
  7857. displacementmap: {
  7858. displacementMap: { value: null },
  7859. displacementScale: { value: 1 },
  7860. displacementBias: { value: 0 }
  7861. },
  7862. roughnessmap: {
  7863. roughnessMap: { value: null }
  7864. },
  7865. metalnessmap: {
  7866. metalnessMap: { value: null }
  7867. },
  7868. gradientmap: {
  7869. gradientMap: { value: null }
  7870. },
  7871. fog: {
  7872. fogDensity: { value: 0.00025 },
  7873. fogNear: { value: 1 },
  7874. fogFar: { value: 2000 },
  7875. fogColor: { value: new Color( 0xffffff ) }
  7876. },
  7877. lights: {
  7878. ambientLightColor: { value: [] },
  7879. lightProbe: { value: [] },
  7880. directionalLights: { value: [], properties: {
  7881. direction: {},
  7882. color: {}
  7883. } },
  7884. directionalLightShadows: { value: [], properties: {
  7885. shadowBias: {},
  7886. shadowNormalBias: {},
  7887. shadowRadius: {},
  7888. shadowMapSize: {}
  7889. } },
  7890. directionalShadowMap: { value: [] },
  7891. directionalShadowMatrix: { value: [] },
  7892. spotLights: { value: [], properties: {
  7893. color: {},
  7894. position: {},
  7895. direction: {},
  7896. distance: {},
  7897. coneCos: {},
  7898. penumbraCos: {},
  7899. decay: {}
  7900. } },
  7901. spotLightShadows: { value: [], properties: {
  7902. shadowBias: {},
  7903. shadowNormalBias: {},
  7904. shadowRadius: {},
  7905. shadowMapSize: {}
  7906. } },
  7907. spotShadowMap: { value: [] },
  7908. spotShadowMatrix: { value: [] },
  7909. pointLights: { value: [], properties: {
  7910. color: {},
  7911. position: {},
  7912. decay: {},
  7913. distance: {}
  7914. } },
  7915. pointLightShadows: { value: [], properties: {
  7916. shadowBias: {},
  7917. shadowNormalBias: {},
  7918. shadowRadius: {},
  7919. shadowMapSize: {},
  7920. shadowCameraNear: {},
  7921. shadowCameraFar: {}
  7922. } },
  7923. pointShadowMap: { value: [] },
  7924. pointShadowMatrix: { value: [] },
  7925. hemisphereLights: { value: [], properties: {
  7926. direction: {},
  7927. skyColor: {},
  7928. groundColor: {}
  7929. } },
  7930. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7931. rectAreaLights: { value: [], properties: {
  7932. color: {},
  7933. position: {},
  7934. width: {},
  7935. height: {}
  7936. } },
  7937. ltc_1: { value: null },
  7938. ltc_2: { value: null }
  7939. },
  7940. points: {
  7941. diffuse: { value: new Color( 0xffffff ) },
  7942. opacity: { value: 1.0 },
  7943. size: { value: 1.0 },
  7944. scale: { value: 1.0 },
  7945. map: { value: null },
  7946. alphaMap: { value: null },
  7947. alphaTest: { value: 0 },
  7948. uvTransform: { value: new Matrix3() }
  7949. },
  7950. sprite: {
  7951. diffuse: { value: new Color( 0xffffff ) },
  7952. opacity: { value: 1.0 },
  7953. center: { value: new Vector2( 0.5, 0.5 ) },
  7954. rotation: { value: 0.0 },
  7955. map: { value: null },
  7956. alphaMap: { value: null },
  7957. alphaTest: { value: 0 },
  7958. uvTransform: { value: new Matrix3() }
  7959. }
  7960. };
  7961. const ShaderLib = {
  7962. basic: {
  7963. uniforms: mergeUniforms( [
  7964. UniformsLib.common,
  7965. UniformsLib.specularmap,
  7966. UniformsLib.envmap,
  7967. UniformsLib.aomap,
  7968. UniformsLib.lightmap,
  7969. UniformsLib.fog
  7970. ] ),
  7971. vertexShader: ShaderChunk.meshbasic_vert,
  7972. fragmentShader: ShaderChunk.meshbasic_frag
  7973. },
  7974. lambert: {
  7975. uniforms: mergeUniforms( [
  7976. UniformsLib.common,
  7977. UniformsLib.specularmap,
  7978. UniformsLib.envmap,
  7979. UniformsLib.aomap,
  7980. UniformsLib.lightmap,
  7981. UniformsLib.emissivemap,
  7982. UniformsLib.fog,
  7983. UniformsLib.lights,
  7984. {
  7985. emissive: { value: new Color( 0x000000 ) }
  7986. }
  7987. ] ),
  7988. vertexShader: ShaderChunk.meshlambert_vert,
  7989. fragmentShader: ShaderChunk.meshlambert_frag
  7990. },
  7991. phong: {
  7992. uniforms: mergeUniforms( [
  7993. UniformsLib.common,
  7994. UniformsLib.specularmap,
  7995. UniformsLib.envmap,
  7996. UniformsLib.aomap,
  7997. UniformsLib.lightmap,
  7998. UniformsLib.emissivemap,
  7999. UniformsLib.bumpmap,
  8000. UniformsLib.normalmap,
  8001. UniformsLib.displacementmap,
  8002. UniformsLib.fog,
  8003. UniformsLib.lights,
  8004. {
  8005. emissive: { value: new Color( 0x000000 ) },
  8006. specular: { value: new Color( 0x111111 ) },
  8007. shininess: { value: 30 }
  8008. }
  8009. ] ),
  8010. vertexShader: ShaderChunk.meshphong_vert,
  8011. fragmentShader: ShaderChunk.meshphong_frag
  8012. },
  8013. standard: {
  8014. uniforms: mergeUniforms( [
  8015. UniformsLib.common,
  8016. UniformsLib.envmap,
  8017. UniformsLib.aomap,
  8018. UniformsLib.lightmap,
  8019. UniformsLib.emissivemap,
  8020. UniformsLib.bumpmap,
  8021. UniformsLib.normalmap,
  8022. UniformsLib.displacementmap,
  8023. UniformsLib.roughnessmap,
  8024. UniformsLib.metalnessmap,
  8025. UniformsLib.fog,
  8026. UniformsLib.lights,
  8027. {
  8028. emissive: { value: new Color( 0x000000 ) },
  8029. roughness: { value: 1.0 },
  8030. metalness: { value: 0.0 },
  8031. envMapIntensity: { value: 1 } // temporary
  8032. }
  8033. ] ),
  8034. vertexShader: ShaderChunk.meshphysical_vert,
  8035. fragmentShader: ShaderChunk.meshphysical_frag
  8036. },
  8037. toon: {
  8038. uniforms: mergeUniforms( [
  8039. UniformsLib.common,
  8040. UniformsLib.aomap,
  8041. UniformsLib.lightmap,
  8042. UniformsLib.emissivemap,
  8043. UniformsLib.bumpmap,
  8044. UniformsLib.normalmap,
  8045. UniformsLib.displacementmap,
  8046. UniformsLib.gradientmap,
  8047. UniformsLib.fog,
  8048. UniformsLib.lights,
  8049. {
  8050. emissive: { value: new Color( 0x000000 ) }
  8051. }
  8052. ] ),
  8053. vertexShader: ShaderChunk.meshtoon_vert,
  8054. fragmentShader: ShaderChunk.meshtoon_frag
  8055. },
  8056. matcap: {
  8057. uniforms: mergeUniforms( [
  8058. UniformsLib.common,
  8059. UniformsLib.bumpmap,
  8060. UniformsLib.normalmap,
  8061. UniformsLib.displacementmap,
  8062. UniformsLib.fog,
  8063. {
  8064. matcap: { value: null }
  8065. }
  8066. ] ),
  8067. vertexShader: ShaderChunk.meshmatcap_vert,
  8068. fragmentShader: ShaderChunk.meshmatcap_frag
  8069. },
  8070. points: {
  8071. uniforms: mergeUniforms( [
  8072. UniformsLib.points,
  8073. UniformsLib.fog
  8074. ] ),
  8075. vertexShader: ShaderChunk.points_vert,
  8076. fragmentShader: ShaderChunk.points_frag
  8077. },
  8078. dashed: {
  8079. uniforms: mergeUniforms( [
  8080. UniformsLib.common,
  8081. UniformsLib.fog,
  8082. {
  8083. scale: { value: 1 },
  8084. dashSize: { value: 1 },
  8085. totalSize: { value: 2 }
  8086. }
  8087. ] ),
  8088. vertexShader: ShaderChunk.linedashed_vert,
  8089. fragmentShader: ShaderChunk.linedashed_frag
  8090. },
  8091. depth: {
  8092. uniforms: mergeUniforms( [
  8093. UniformsLib.common,
  8094. UniformsLib.displacementmap
  8095. ] ),
  8096. vertexShader: ShaderChunk.depth_vert,
  8097. fragmentShader: ShaderChunk.depth_frag
  8098. },
  8099. normal: {
  8100. uniforms: mergeUniforms( [
  8101. UniformsLib.common,
  8102. UniformsLib.bumpmap,
  8103. UniformsLib.normalmap,
  8104. UniformsLib.displacementmap,
  8105. {
  8106. opacity: { value: 1.0 }
  8107. }
  8108. ] ),
  8109. vertexShader: ShaderChunk.meshnormal_vert,
  8110. fragmentShader: ShaderChunk.meshnormal_frag
  8111. },
  8112. sprite: {
  8113. uniforms: mergeUniforms( [
  8114. UniformsLib.sprite,
  8115. UniformsLib.fog
  8116. ] ),
  8117. vertexShader: ShaderChunk.sprite_vert,
  8118. fragmentShader: ShaderChunk.sprite_frag
  8119. },
  8120. background: {
  8121. uniforms: {
  8122. uvTransform: { value: new Matrix3() },
  8123. t2D: { value: null },
  8124. },
  8125. vertexShader: ShaderChunk.background_vert,
  8126. fragmentShader: ShaderChunk.background_frag
  8127. },
  8128. /* -------------------------------------------------------------------------
  8129. // Cube map shader
  8130. ------------------------------------------------------------------------- */
  8131. cube: {
  8132. uniforms: mergeUniforms( [
  8133. UniformsLib.envmap,
  8134. {
  8135. opacity: { value: 1.0 }
  8136. }
  8137. ] ),
  8138. vertexShader: ShaderChunk.cube_vert,
  8139. fragmentShader: ShaderChunk.cube_frag
  8140. },
  8141. equirect: {
  8142. uniforms: {
  8143. tEquirect: { value: null },
  8144. },
  8145. vertexShader: ShaderChunk.equirect_vert,
  8146. fragmentShader: ShaderChunk.equirect_frag
  8147. },
  8148. distanceRGBA: {
  8149. uniforms: mergeUniforms( [
  8150. UniformsLib.common,
  8151. UniformsLib.displacementmap,
  8152. {
  8153. referencePosition: { value: new Vector3() },
  8154. nearDistance: { value: 1 },
  8155. farDistance: { value: 1000 }
  8156. }
  8157. ] ),
  8158. vertexShader: ShaderChunk.distanceRGBA_vert,
  8159. fragmentShader: ShaderChunk.distanceRGBA_frag
  8160. },
  8161. shadow: {
  8162. uniforms: mergeUniforms( [
  8163. UniformsLib.lights,
  8164. UniformsLib.fog,
  8165. {
  8166. color: { value: new Color( 0x00000 ) },
  8167. opacity: { value: 1.0 }
  8168. },
  8169. ] ),
  8170. vertexShader: ShaderChunk.shadow_vert,
  8171. fragmentShader: ShaderChunk.shadow_frag
  8172. }
  8173. };
  8174. ShaderLib.physical = {
  8175. uniforms: mergeUniforms( [
  8176. ShaderLib.standard.uniforms,
  8177. {
  8178. clearcoat: { value: 0 },
  8179. clearcoatMap: { value: null },
  8180. clearcoatRoughness: { value: 0 },
  8181. clearcoatRoughnessMap: { value: null },
  8182. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8183. clearcoatNormalMap: { value: null },
  8184. sheenTint: { value: new Color( 0x000000 ) },
  8185. transmission: { value: 0 },
  8186. transmissionMap: { value: null },
  8187. transmissionSamplerSize: { value: new Vector2() },
  8188. transmissionSamplerMap: { value: null },
  8189. thickness: { value: 0 },
  8190. thicknessMap: { value: null },
  8191. attenuationDistance: { value: 0 },
  8192. attenuationTint: { value: new Color( 0x000000 ) },
  8193. specularIntensity: { value: 0 },
  8194. specularIntensityMap: { value: null },
  8195. specularTint: { value: new Color( 1, 1, 1 ) },
  8196. specularTintMap: { value: null },
  8197. }
  8198. ] ),
  8199. vertexShader: ShaderChunk.meshphysical_vert,
  8200. fragmentShader: ShaderChunk.meshphysical_frag
  8201. };
  8202. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  8203. const clearColor = new Color( 0x000000 );
  8204. let clearAlpha = 0;
  8205. let planeMesh;
  8206. let boxMesh;
  8207. let currentBackground = null;
  8208. let currentBackgroundVersion = 0;
  8209. let currentTonemapping = null;
  8210. function render( renderList, scene ) {
  8211. let forceClear = false;
  8212. let background = scene.isScene === true ? scene.background : null;
  8213. if ( background && background.isTexture ) {
  8214. background = cubemaps.get( background );
  8215. }
  8216. // Ignore background in AR
  8217. // TODO: Reconsider this.
  8218. const xr = renderer.xr;
  8219. const session = xr.getSession && xr.getSession();
  8220. if ( session && session.environmentBlendMode === 'additive' ) {
  8221. background = null;
  8222. }
  8223. if ( background === null ) {
  8224. setClear( clearColor, clearAlpha );
  8225. } else if ( background && background.isColor ) {
  8226. setClear( background, 1 );
  8227. forceClear = true;
  8228. }
  8229. if ( renderer.autoClear || forceClear ) {
  8230. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8231. }
  8232. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8233. if ( boxMesh === undefined ) {
  8234. boxMesh = new Mesh(
  8235. new BoxGeometry( 1, 1, 1 ),
  8236. new ShaderMaterial( {
  8237. name: 'BackgroundCubeMaterial',
  8238. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8239. vertexShader: ShaderLib.cube.vertexShader,
  8240. fragmentShader: ShaderLib.cube.fragmentShader,
  8241. side: BackSide,
  8242. depthTest: false,
  8243. depthWrite: false,
  8244. fog: false
  8245. } )
  8246. );
  8247. boxMesh.geometry.deleteAttribute( 'normal' );
  8248. boxMesh.geometry.deleteAttribute( 'uv' );
  8249. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8250. this.matrixWorld.copyPosition( camera.matrixWorld );
  8251. };
  8252. // enable code injection for non-built-in material
  8253. Object.defineProperty( boxMesh.material, 'envMap', {
  8254. get: function () {
  8255. return this.uniforms.envMap.value;
  8256. }
  8257. } );
  8258. objects.update( boxMesh );
  8259. }
  8260. boxMesh.material.uniforms.envMap.value = background;
  8261. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8262. if ( currentBackground !== background ||
  8263. currentBackgroundVersion !== background.version ||
  8264. currentTonemapping !== renderer.toneMapping ) {
  8265. boxMesh.material.needsUpdate = true;
  8266. currentBackground = background;
  8267. currentBackgroundVersion = background.version;
  8268. currentTonemapping = renderer.toneMapping;
  8269. }
  8270. // push to the pre-sorted opaque render list
  8271. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8272. } else if ( background && background.isTexture ) {
  8273. if ( planeMesh === undefined ) {
  8274. planeMesh = new Mesh(
  8275. new PlaneGeometry( 2, 2 ),
  8276. new ShaderMaterial( {
  8277. name: 'BackgroundMaterial',
  8278. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8279. vertexShader: ShaderLib.background.vertexShader,
  8280. fragmentShader: ShaderLib.background.fragmentShader,
  8281. side: FrontSide,
  8282. depthTest: false,
  8283. depthWrite: false,
  8284. fog: false
  8285. } )
  8286. );
  8287. planeMesh.geometry.deleteAttribute( 'normal' );
  8288. // enable code injection for non-built-in material
  8289. Object.defineProperty( planeMesh.material, 'map', {
  8290. get: function () {
  8291. return this.uniforms.t2D.value;
  8292. }
  8293. } );
  8294. objects.update( planeMesh );
  8295. }
  8296. planeMesh.material.uniforms.t2D.value = background;
  8297. if ( background.matrixAutoUpdate === true ) {
  8298. background.updateMatrix();
  8299. }
  8300. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8301. if ( currentBackground !== background ||
  8302. currentBackgroundVersion !== background.version ||
  8303. currentTonemapping !== renderer.toneMapping ) {
  8304. planeMesh.material.needsUpdate = true;
  8305. currentBackground = background;
  8306. currentBackgroundVersion = background.version;
  8307. currentTonemapping = renderer.toneMapping;
  8308. }
  8309. // push to the pre-sorted opaque render list
  8310. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8311. }
  8312. }
  8313. function setClear( color, alpha ) {
  8314. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8315. }
  8316. return {
  8317. getClearColor: function () {
  8318. return clearColor;
  8319. },
  8320. setClearColor: function ( color, alpha = 1 ) {
  8321. clearColor.set( color );
  8322. clearAlpha = alpha;
  8323. setClear( clearColor, clearAlpha );
  8324. },
  8325. getClearAlpha: function () {
  8326. return clearAlpha;
  8327. },
  8328. setClearAlpha: function ( alpha ) {
  8329. clearAlpha = alpha;
  8330. setClear( clearColor, clearAlpha );
  8331. },
  8332. render: render
  8333. };
  8334. }
  8335. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8336. const maxVertexAttributes = gl.getParameter( 34921 );
  8337. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8338. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8339. const bindingStates = {};
  8340. const defaultState = createBindingState( null );
  8341. let currentState = defaultState;
  8342. function setup( object, material, program, geometry, index ) {
  8343. let updateBuffers = false;
  8344. if ( vaoAvailable ) {
  8345. const state = getBindingState( geometry, program, material );
  8346. if ( currentState !== state ) {
  8347. currentState = state;
  8348. bindVertexArrayObject( currentState.object );
  8349. }
  8350. updateBuffers = needsUpdate( geometry, index );
  8351. if ( updateBuffers ) saveCache( geometry, index );
  8352. } else {
  8353. const wireframe = ( material.wireframe === true );
  8354. if ( currentState.geometry !== geometry.id ||
  8355. currentState.program !== program.id ||
  8356. currentState.wireframe !== wireframe ) {
  8357. currentState.geometry = geometry.id;
  8358. currentState.program = program.id;
  8359. currentState.wireframe = wireframe;
  8360. updateBuffers = true;
  8361. }
  8362. }
  8363. if ( object.isInstancedMesh === true ) {
  8364. updateBuffers = true;
  8365. }
  8366. if ( index !== null ) {
  8367. attributes.update( index, 34963 );
  8368. }
  8369. if ( updateBuffers ) {
  8370. setupVertexAttributes( object, material, program, geometry );
  8371. if ( index !== null ) {
  8372. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8373. }
  8374. }
  8375. }
  8376. function createVertexArrayObject() {
  8377. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8378. return extension.createVertexArrayOES();
  8379. }
  8380. function bindVertexArrayObject( vao ) {
  8381. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8382. return extension.bindVertexArrayOES( vao );
  8383. }
  8384. function deleteVertexArrayObject( vao ) {
  8385. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8386. return extension.deleteVertexArrayOES( vao );
  8387. }
  8388. function getBindingState( geometry, program, material ) {
  8389. const wireframe = ( material.wireframe === true );
  8390. let programMap = bindingStates[ geometry.id ];
  8391. if ( programMap === undefined ) {
  8392. programMap = {};
  8393. bindingStates[ geometry.id ] = programMap;
  8394. }
  8395. let stateMap = programMap[ program.id ];
  8396. if ( stateMap === undefined ) {
  8397. stateMap = {};
  8398. programMap[ program.id ] = stateMap;
  8399. }
  8400. let state = stateMap[ wireframe ];
  8401. if ( state === undefined ) {
  8402. state = createBindingState( createVertexArrayObject() );
  8403. stateMap[ wireframe ] = state;
  8404. }
  8405. return state;
  8406. }
  8407. function createBindingState( vao ) {
  8408. const newAttributes = [];
  8409. const enabledAttributes = [];
  8410. const attributeDivisors = [];
  8411. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8412. newAttributes[ i ] = 0;
  8413. enabledAttributes[ i ] = 0;
  8414. attributeDivisors[ i ] = 0;
  8415. }
  8416. return {
  8417. // for backward compatibility on non-VAO support browser
  8418. geometry: null,
  8419. program: null,
  8420. wireframe: false,
  8421. newAttributes: newAttributes,
  8422. enabledAttributes: enabledAttributes,
  8423. attributeDivisors: attributeDivisors,
  8424. object: vao,
  8425. attributes: {},
  8426. index: null
  8427. };
  8428. }
  8429. function needsUpdate( geometry, index ) {
  8430. const cachedAttributes = currentState.attributes;
  8431. const geometryAttributes = geometry.attributes;
  8432. let attributesNum = 0;
  8433. for ( const key in geometryAttributes ) {
  8434. const cachedAttribute = cachedAttributes[ key ];
  8435. const geometryAttribute = geometryAttributes[ key ];
  8436. if ( cachedAttribute === undefined ) return true;
  8437. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8438. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8439. attributesNum ++;
  8440. }
  8441. if ( currentState.attributesNum !== attributesNum ) return true;
  8442. if ( currentState.index !== index ) return true;
  8443. return false;
  8444. }
  8445. function saveCache( geometry, index ) {
  8446. const cache = {};
  8447. const attributes = geometry.attributes;
  8448. let attributesNum = 0;
  8449. for ( const key in attributes ) {
  8450. const attribute = attributes[ key ];
  8451. const data = {};
  8452. data.attribute = attribute;
  8453. if ( attribute.data ) {
  8454. data.data = attribute.data;
  8455. }
  8456. cache[ key ] = data;
  8457. attributesNum ++;
  8458. }
  8459. currentState.attributes = cache;
  8460. currentState.attributesNum = attributesNum;
  8461. currentState.index = index;
  8462. }
  8463. function initAttributes() {
  8464. const newAttributes = currentState.newAttributes;
  8465. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8466. newAttributes[ i ] = 0;
  8467. }
  8468. }
  8469. function enableAttribute( attribute ) {
  8470. enableAttributeAndDivisor( attribute, 0 );
  8471. }
  8472. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8473. const newAttributes = currentState.newAttributes;
  8474. const enabledAttributes = currentState.enabledAttributes;
  8475. const attributeDivisors = currentState.attributeDivisors;
  8476. newAttributes[ attribute ] = 1;
  8477. if ( enabledAttributes[ attribute ] === 0 ) {
  8478. gl.enableVertexAttribArray( attribute );
  8479. enabledAttributes[ attribute ] = 1;
  8480. }
  8481. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8482. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8483. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8484. attributeDivisors[ attribute ] = meshPerAttribute;
  8485. }
  8486. }
  8487. function disableUnusedAttributes() {
  8488. const newAttributes = currentState.newAttributes;
  8489. const enabledAttributes = currentState.enabledAttributes;
  8490. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8491. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8492. gl.disableVertexAttribArray( i );
  8493. enabledAttributes[ i ] = 0;
  8494. }
  8495. }
  8496. }
  8497. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8498. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8499. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8500. } else {
  8501. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8502. }
  8503. }
  8504. function setupVertexAttributes( object, material, program, geometry ) {
  8505. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8506. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8507. }
  8508. initAttributes();
  8509. const geometryAttributes = geometry.attributes;
  8510. const programAttributes = program.getAttributes();
  8511. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8512. for ( const name in programAttributes ) {
  8513. const programAttribute = programAttributes[ name ];
  8514. if ( programAttribute.location >= 0 ) {
  8515. let geometryAttribute = geometryAttributes[ name ];
  8516. if ( geometryAttribute === undefined ) {
  8517. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8518. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8519. }
  8520. if ( geometryAttribute !== undefined ) {
  8521. const normalized = geometryAttribute.normalized;
  8522. const size = geometryAttribute.itemSize;
  8523. const attribute = attributes.get( geometryAttribute );
  8524. // TODO Attribute may not be available on context restore
  8525. if ( attribute === undefined ) continue;
  8526. const buffer = attribute.buffer;
  8527. const type = attribute.type;
  8528. const bytesPerElement = attribute.bytesPerElement;
  8529. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8530. const data = geometryAttribute.data;
  8531. const stride = data.stride;
  8532. const offset = geometryAttribute.offset;
  8533. if ( data && data.isInstancedInterleavedBuffer ) {
  8534. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8535. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8536. }
  8537. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8538. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8539. }
  8540. } else {
  8541. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8542. enableAttribute( programAttribute.location + i );
  8543. }
  8544. }
  8545. gl.bindBuffer( 34962, buffer );
  8546. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8547. vertexAttribPointer(
  8548. programAttribute.location + i,
  8549. size / programAttribute.locationSize,
  8550. type,
  8551. normalized,
  8552. stride * bytesPerElement,
  8553. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8554. );
  8555. }
  8556. } else {
  8557. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8558. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8559. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8560. }
  8561. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8562. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8563. }
  8564. } else {
  8565. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8566. enableAttribute( programAttribute.location + i );
  8567. }
  8568. }
  8569. gl.bindBuffer( 34962, buffer );
  8570. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8571. vertexAttribPointer(
  8572. programAttribute.location + i,
  8573. size / programAttribute.locationSize,
  8574. type,
  8575. normalized,
  8576. size * bytesPerElement,
  8577. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8578. );
  8579. }
  8580. }
  8581. } else if ( materialDefaultAttributeValues !== undefined ) {
  8582. const value = materialDefaultAttributeValues[ name ];
  8583. if ( value !== undefined ) {
  8584. switch ( value.length ) {
  8585. case 2:
  8586. gl.vertexAttrib2fv( programAttribute.location, value );
  8587. break;
  8588. case 3:
  8589. gl.vertexAttrib3fv( programAttribute.location, value );
  8590. break;
  8591. case 4:
  8592. gl.vertexAttrib4fv( programAttribute.location, value );
  8593. break;
  8594. default:
  8595. gl.vertexAttrib1fv( programAttribute.location, value );
  8596. }
  8597. }
  8598. }
  8599. }
  8600. }
  8601. disableUnusedAttributes();
  8602. }
  8603. function dispose() {
  8604. reset();
  8605. for ( const geometryId in bindingStates ) {
  8606. const programMap = bindingStates[ geometryId ];
  8607. for ( const programId in programMap ) {
  8608. const stateMap = programMap[ programId ];
  8609. for ( const wireframe in stateMap ) {
  8610. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8611. delete stateMap[ wireframe ];
  8612. }
  8613. delete programMap[ programId ];
  8614. }
  8615. delete bindingStates[ geometryId ];
  8616. }
  8617. }
  8618. function releaseStatesOfGeometry( geometry ) {
  8619. if ( bindingStates[ geometry.id ] === undefined ) return;
  8620. const programMap = bindingStates[ geometry.id ];
  8621. for ( const programId in programMap ) {
  8622. const stateMap = programMap[ programId ];
  8623. for ( const wireframe in stateMap ) {
  8624. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8625. delete stateMap[ wireframe ];
  8626. }
  8627. delete programMap[ programId ];
  8628. }
  8629. delete bindingStates[ geometry.id ];
  8630. }
  8631. function releaseStatesOfProgram( program ) {
  8632. for ( const geometryId in bindingStates ) {
  8633. const programMap = bindingStates[ geometryId ];
  8634. if ( programMap[ program.id ] === undefined ) continue;
  8635. const stateMap = programMap[ program.id ];
  8636. for ( const wireframe in stateMap ) {
  8637. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8638. delete stateMap[ wireframe ];
  8639. }
  8640. delete programMap[ program.id ];
  8641. }
  8642. }
  8643. function reset() {
  8644. resetDefaultState();
  8645. if ( currentState === defaultState ) return;
  8646. currentState = defaultState;
  8647. bindVertexArrayObject( currentState.object );
  8648. }
  8649. // for backward-compatilibity
  8650. function resetDefaultState() {
  8651. defaultState.geometry = null;
  8652. defaultState.program = null;
  8653. defaultState.wireframe = false;
  8654. }
  8655. return {
  8656. setup: setup,
  8657. reset: reset,
  8658. resetDefaultState: resetDefaultState,
  8659. dispose: dispose,
  8660. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8661. releaseStatesOfProgram: releaseStatesOfProgram,
  8662. initAttributes: initAttributes,
  8663. enableAttribute: enableAttribute,
  8664. disableUnusedAttributes: disableUnusedAttributes
  8665. };
  8666. }
  8667. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8668. const isWebGL2 = capabilities.isWebGL2;
  8669. let mode;
  8670. function setMode( value ) {
  8671. mode = value;
  8672. }
  8673. function render( start, count ) {
  8674. gl.drawArrays( mode, start, count );
  8675. info.update( count, mode, 1 );
  8676. }
  8677. function renderInstances( start, count, primcount ) {
  8678. if ( primcount === 0 ) return;
  8679. let extension, methodName;
  8680. if ( isWebGL2 ) {
  8681. extension = gl;
  8682. methodName = 'drawArraysInstanced';
  8683. } else {
  8684. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8685. methodName = 'drawArraysInstancedANGLE';
  8686. if ( extension === null ) {
  8687. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8688. return;
  8689. }
  8690. }
  8691. extension[ methodName ]( mode, start, count, primcount );
  8692. info.update( count, mode, primcount );
  8693. }
  8694. //
  8695. this.setMode = setMode;
  8696. this.render = render;
  8697. this.renderInstances = renderInstances;
  8698. }
  8699. function WebGLCapabilities( gl, extensions, parameters ) {
  8700. let maxAnisotropy;
  8701. function getMaxAnisotropy() {
  8702. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8703. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8704. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8705. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8706. } else {
  8707. maxAnisotropy = 0;
  8708. }
  8709. return maxAnisotropy;
  8710. }
  8711. function getMaxPrecision( precision ) {
  8712. if ( precision === 'highp' ) {
  8713. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8714. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8715. return 'highp';
  8716. }
  8717. precision = 'mediump';
  8718. }
  8719. if ( precision === 'mediump' ) {
  8720. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8721. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8722. return 'mediump';
  8723. }
  8724. }
  8725. return 'lowp';
  8726. }
  8727. /* eslint-disable no-undef */
  8728. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8729. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8730. /* eslint-enable no-undef */
  8731. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8732. const maxPrecision = getMaxPrecision( precision );
  8733. if ( maxPrecision !== precision ) {
  8734. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8735. precision = maxPrecision;
  8736. }
  8737. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8738. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8739. const maxTextures = gl.getParameter( 34930 );
  8740. const maxVertexTextures = gl.getParameter( 35660 );
  8741. const maxTextureSize = gl.getParameter( 3379 );
  8742. const maxCubemapSize = gl.getParameter( 34076 );
  8743. const maxAttributes = gl.getParameter( 34921 );
  8744. const maxVertexUniforms = gl.getParameter( 36347 );
  8745. const maxVaryings = gl.getParameter( 36348 );
  8746. const maxFragmentUniforms = gl.getParameter( 36349 );
  8747. const vertexTextures = maxVertexTextures > 0;
  8748. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8749. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8750. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8751. return {
  8752. isWebGL2: isWebGL2,
  8753. drawBuffers: drawBuffers,
  8754. getMaxAnisotropy: getMaxAnisotropy,
  8755. getMaxPrecision: getMaxPrecision,
  8756. precision: precision,
  8757. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8758. maxTextures: maxTextures,
  8759. maxVertexTextures: maxVertexTextures,
  8760. maxTextureSize: maxTextureSize,
  8761. maxCubemapSize: maxCubemapSize,
  8762. maxAttributes: maxAttributes,
  8763. maxVertexUniforms: maxVertexUniforms,
  8764. maxVaryings: maxVaryings,
  8765. maxFragmentUniforms: maxFragmentUniforms,
  8766. vertexTextures: vertexTextures,
  8767. floatFragmentTextures: floatFragmentTextures,
  8768. floatVertexTextures: floatVertexTextures,
  8769. maxSamples: maxSamples
  8770. };
  8771. }
  8772. function WebGLClipping( properties ) {
  8773. const scope = this;
  8774. let globalState = null,
  8775. numGlobalPlanes = 0,
  8776. localClippingEnabled = false,
  8777. renderingShadows = false;
  8778. const plane = new Plane(),
  8779. viewNormalMatrix = new Matrix3(),
  8780. uniform = { value: null, needsUpdate: false };
  8781. this.uniform = uniform;
  8782. this.numPlanes = 0;
  8783. this.numIntersection = 0;
  8784. this.init = function ( planes, enableLocalClipping, camera ) {
  8785. const enabled =
  8786. planes.length !== 0 ||
  8787. enableLocalClipping ||
  8788. // enable state of previous frame - the clipping code has to
  8789. // run another frame in order to reset the state:
  8790. numGlobalPlanes !== 0 ||
  8791. localClippingEnabled;
  8792. localClippingEnabled = enableLocalClipping;
  8793. globalState = projectPlanes( planes, camera, 0 );
  8794. numGlobalPlanes = planes.length;
  8795. return enabled;
  8796. };
  8797. this.beginShadows = function () {
  8798. renderingShadows = true;
  8799. projectPlanes( null );
  8800. };
  8801. this.endShadows = function () {
  8802. renderingShadows = false;
  8803. resetGlobalState();
  8804. };
  8805. this.setState = function ( material, camera, useCache ) {
  8806. const planes = material.clippingPlanes,
  8807. clipIntersection = material.clipIntersection,
  8808. clipShadows = material.clipShadows;
  8809. const materialProperties = properties.get( material );
  8810. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8811. // there's no local clipping
  8812. if ( renderingShadows ) {
  8813. // there's no global clipping
  8814. projectPlanes( null );
  8815. } else {
  8816. resetGlobalState();
  8817. }
  8818. } else {
  8819. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8820. lGlobal = nGlobal * 4;
  8821. let dstArray = materialProperties.clippingState || null;
  8822. uniform.value = dstArray; // ensure unique state
  8823. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8824. for ( let i = 0; i !== lGlobal; ++ i ) {
  8825. dstArray[ i ] = globalState[ i ];
  8826. }
  8827. materialProperties.clippingState = dstArray;
  8828. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8829. this.numPlanes += nGlobal;
  8830. }
  8831. };
  8832. function resetGlobalState() {
  8833. if ( uniform.value !== globalState ) {
  8834. uniform.value = globalState;
  8835. uniform.needsUpdate = numGlobalPlanes > 0;
  8836. }
  8837. scope.numPlanes = numGlobalPlanes;
  8838. scope.numIntersection = 0;
  8839. }
  8840. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8841. const nPlanes = planes !== null ? planes.length : 0;
  8842. let dstArray = null;
  8843. if ( nPlanes !== 0 ) {
  8844. dstArray = uniform.value;
  8845. if ( skipTransform !== true || dstArray === null ) {
  8846. const flatSize = dstOffset + nPlanes * 4,
  8847. viewMatrix = camera.matrixWorldInverse;
  8848. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8849. if ( dstArray === null || dstArray.length < flatSize ) {
  8850. dstArray = new Float32Array( flatSize );
  8851. }
  8852. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8853. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8854. plane.normal.toArray( dstArray, i4 );
  8855. dstArray[ i4 + 3 ] = plane.constant;
  8856. }
  8857. }
  8858. uniform.value = dstArray;
  8859. uniform.needsUpdate = true;
  8860. }
  8861. scope.numPlanes = nPlanes;
  8862. scope.numIntersection = 0;
  8863. return dstArray;
  8864. }
  8865. }
  8866. function WebGLCubeMaps( renderer ) {
  8867. let cubemaps = new WeakMap();
  8868. function mapTextureMapping( texture, mapping ) {
  8869. if ( mapping === EquirectangularReflectionMapping ) {
  8870. texture.mapping = CubeReflectionMapping;
  8871. } else if ( mapping === EquirectangularRefractionMapping ) {
  8872. texture.mapping = CubeRefractionMapping;
  8873. }
  8874. return texture;
  8875. }
  8876. function get( texture ) {
  8877. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  8878. const mapping = texture.mapping;
  8879. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8880. if ( cubemaps.has( texture ) ) {
  8881. const cubemap = cubemaps.get( texture ).texture;
  8882. return mapTextureMapping( cubemap, texture.mapping );
  8883. } else {
  8884. const image = texture.image;
  8885. if ( image && image.height > 0 ) {
  8886. const currentRenderTarget = renderer.getRenderTarget();
  8887. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  8888. renderTarget.fromEquirectangularTexture( renderer, texture );
  8889. cubemaps.set( texture, renderTarget );
  8890. renderer.setRenderTarget( currentRenderTarget );
  8891. texture.addEventListener( 'dispose', onTextureDispose );
  8892. return mapTextureMapping( renderTarget.texture, texture.mapping );
  8893. } else {
  8894. // image not yet ready. try the conversion next frame
  8895. return null;
  8896. }
  8897. }
  8898. }
  8899. }
  8900. return texture;
  8901. }
  8902. function onTextureDispose( event ) {
  8903. const texture = event.target;
  8904. texture.removeEventListener( 'dispose', onTextureDispose );
  8905. const cubemap = cubemaps.get( texture );
  8906. if ( cubemap !== undefined ) {
  8907. cubemaps.delete( texture );
  8908. cubemap.dispose();
  8909. }
  8910. }
  8911. function dispose() {
  8912. cubemaps = new WeakMap();
  8913. }
  8914. return {
  8915. get: get,
  8916. dispose: dispose
  8917. };
  8918. }
  8919. class OrthographicCamera extends Camera {
  8920. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  8921. super();
  8922. this.type = 'OrthographicCamera';
  8923. this.zoom = 1;
  8924. this.view = null;
  8925. this.left = left;
  8926. this.right = right;
  8927. this.top = top;
  8928. this.bottom = bottom;
  8929. this.near = near;
  8930. this.far = far;
  8931. this.updateProjectionMatrix();
  8932. }
  8933. copy( source, recursive ) {
  8934. super.copy( source, recursive );
  8935. this.left = source.left;
  8936. this.right = source.right;
  8937. this.top = source.top;
  8938. this.bottom = source.bottom;
  8939. this.near = source.near;
  8940. this.far = source.far;
  8941. this.zoom = source.zoom;
  8942. this.view = source.view === null ? null : Object.assign( {}, source.view );
  8943. return this;
  8944. }
  8945. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  8946. if ( this.view === null ) {
  8947. this.view = {
  8948. enabled: true,
  8949. fullWidth: 1,
  8950. fullHeight: 1,
  8951. offsetX: 0,
  8952. offsetY: 0,
  8953. width: 1,
  8954. height: 1
  8955. };
  8956. }
  8957. this.view.enabled = true;
  8958. this.view.fullWidth = fullWidth;
  8959. this.view.fullHeight = fullHeight;
  8960. this.view.offsetX = x;
  8961. this.view.offsetY = y;
  8962. this.view.width = width;
  8963. this.view.height = height;
  8964. this.updateProjectionMatrix();
  8965. }
  8966. clearViewOffset() {
  8967. if ( this.view !== null ) {
  8968. this.view.enabled = false;
  8969. }
  8970. this.updateProjectionMatrix();
  8971. }
  8972. updateProjectionMatrix() {
  8973. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  8974. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  8975. const cx = ( this.right + this.left ) / 2;
  8976. const cy = ( this.top + this.bottom ) / 2;
  8977. let left = cx - dx;
  8978. let right = cx + dx;
  8979. let top = cy + dy;
  8980. let bottom = cy - dy;
  8981. if ( this.view !== null && this.view.enabled ) {
  8982. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  8983. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  8984. left += scaleW * this.view.offsetX;
  8985. right = left + scaleW * this.view.width;
  8986. top -= scaleH * this.view.offsetY;
  8987. bottom = top - scaleH * this.view.height;
  8988. }
  8989. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  8990. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  8991. }
  8992. toJSON( meta ) {
  8993. const data = super.toJSON( meta );
  8994. data.object.zoom = this.zoom;
  8995. data.object.left = this.left;
  8996. data.object.right = this.right;
  8997. data.object.top = this.top;
  8998. data.object.bottom = this.bottom;
  8999. data.object.near = this.near;
  9000. data.object.far = this.far;
  9001. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9002. return data;
  9003. }
  9004. }
  9005. OrthographicCamera.prototype.isOrthographicCamera = true;
  9006. class RawShaderMaterial extends ShaderMaterial {
  9007. constructor( parameters ) {
  9008. super( parameters );
  9009. this.type = 'RawShaderMaterial';
  9010. }
  9011. }
  9012. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9013. const LOD_MIN = 4;
  9014. const LOD_MAX = 8;
  9015. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  9016. // The standard deviations (radians) associated with the extra mips. These are
  9017. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9018. // geometric shadowing function. These sigma values squared must match the
  9019. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9020. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9021. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9022. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9023. // samples and exit early, but not recompile the shader.
  9024. const MAX_SAMPLES = 20;
  9025. const ENCODINGS = {
  9026. [ LinearEncoding ]: 0,
  9027. [ sRGBEncoding ]: 1,
  9028. [ RGBEEncoding ]: 2,
  9029. [ RGBM7Encoding ]: 3,
  9030. [ RGBM16Encoding ]: 4,
  9031. [ RGBDEncoding ]: 5,
  9032. [ GammaEncoding ]: 6
  9033. };
  9034. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9035. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  9036. const _clearColor = /*@__PURE__*/ new Color();
  9037. let _oldTarget = null;
  9038. // Golden Ratio
  9039. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9040. const INV_PHI = 1 / PHI;
  9041. // Vertices of a dodecahedron (except the opposites, which represent the
  9042. // same axis), used as axis directions evenly spread on a sphere.
  9043. const _axisDirections = [
  9044. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9045. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9046. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9047. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9048. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9049. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9050. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9051. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9052. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9053. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9054. /**
  9055. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9056. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9057. * blur to be quickly accessed based on material roughness. It is packed into a
  9058. * special CubeUV format that allows us to perform custom interpolation so that
  9059. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9060. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9061. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9062. * higher roughness levels. In this way we maintain resolution to smoothly
  9063. * interpolate diffuse lighting while limiting sampling computation.
  9064. *
  9065. * Paper: Fast, Accurate Image-Based Lighting
  9066. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9067. */
  9068. class PMREMGenerator {
  9069. constructor( renderer ) {
  9070. this._renderer = renderer;
  9071. this._pingPongRenderTarget = null;
  9072. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  9073. this._equirectShader = null;
  9074. this._cubemapShader = null;
  9075. this._compileMaterial( this._blurMaterial );
  9076. }
  9077. /**
  9078. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9079. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9080. * in radians to be applied to the scene before PMREM generation. Optional near
  9081. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9082. * is placed at the origin).
  9083. */
  9084. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9085. _oldTarget = this._renderer.getRenderTarget();
  9086. const cubeUVRenderTarget = this._allocateTargets();
  9087. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9088. if ( sigma > 0 ) {
  9089. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9090. }
  9091. this._applyPMREM( cubeUVRenderTarget );
  9092. this._cleanup( cubeUVRenderTarget );
  9093. return cubeUVRenderTarget;
  9094. }
  9095. /**
  9096. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9097. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9098. * as this matches best with the 256 x 256 cubemap output.
  9099. */
  9100. fromEquirectangular( equirectangular ) {
  9101. return this._fromTexture( equirectangular );
  9102. }
  9103. /**
  9104. * Generates a PMREM from an cubemap texture, which can be either LDR
  9105. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9106. * as this matches best with the 256 x 256 cubemap output.
  9107. */
  9108. fromCubemap( cubemap ) {
  9109. return this._fromTexture( cubemap );
  9110. }
  9111. /**
  9112. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9113. * your texture's network fetch for increased concurrency.
  9114. */
  9115. compileCubemapShader() {
  9116. if ( this._cubemapShader === null ) {
  9117. this._cubemapShader = _getCubemapShader();
  9118. this._compileMaterial( this._cubemapShader );
  9119. }
  9120. }
  9121. /**
  9122. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9123. * your texture's network fetch for increased concurrency.
  9124. */
  9125. compileEquirectangularShader() {
  9126. if ( this._equirectShader === null ) {
  9127. this._equirectShader = _getEquirectShader();
  9128. this._compileMaterial( this._equirectShader );
  9129. }
  9130. }
  9131. /**
  9132. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9133. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9134. * one of them will cause any others to also become unusable.
  9135. */
  9136. dispose() {
  9137. this._blurMaterial.dispose();
  9138. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  9139. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  9140. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  9141. _lodPlanes[ i ].dispose();
  9142. }
  9143. }
  9144. // private interface
  9145. _cleanup( outputTarget ) {
  9146. this._pingPongRenderTarget.dispose();
  9147. this._renderer.setRenderTarget( _oldTarget );
  9148. outputTarget.scissorTest = false;
  9149. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9150. }
  9151. _fromTexture( texture ) {
  9152. _oldTarget = this._renderer.getRenderTarget();
  9153. const cubeUVRenderTarget = this._allocateTargets( texture );
  9154. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9155. this._applyPMREM( cubeUVRenderTarget );
  9156. this._cleanup( cubeUVRenderTarget );
  9157. return cubeUVRenderTarget;
  9158. }
  9159. _allocateTargets( texture ) { // warning: null texture is valid
  9160. const params = {
  9161. magFilter: NearestFilter,
  9162. minFilter: NearestFilter,
  9163. generateMipmaps: false,
  9164. type: UnsignedByteType,
  9165. format: RGBEFormat,
  9166. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  9167. depthBuffer: false
  9168. };
  9169. const cubeUVRenderTarget = _createRenderTarget( params );
  9170. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9171. this._pingPongRenderTarget = _createRenderTarget( params );
  9172. return cubeUVRenderTarget;
  9173. }
  9174. _compileMaterial( material ) {
  9175. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  9176. this._renderer.compile( tmpMesh, _flatCamera );
  9177. }
  9178. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9179. const fov = 90;
  9180. const aspect = 1;
  9181. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9182. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9183. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9184. const renderer = this._renderer;
  9185. const originalAutoClear = renderer.autoClear;
  9186. const outputEncoding = renderer.outputEncoding;
  9187. const toneMapping = renderer.toneMapping;
  9188. renderer.getClearColor( _clearColor );
  9189. renderer.toneMapping = NoToneMapping;
  9190. renderer.outputEncoding = LinearEncoding;
  9191. renderer.autoClear = false;
  9192. const backgroundMaterial = new MeshBasicMaterial( {
  9193. name: 'PMREM.Background',
  9194. side: BackSide,
  9195. depthWrite: false,
  9196. depthTest: false,
  9197. } );
  9198. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9199. let useSolidColor = false;
  9200. const background = scene.background;
  9201. if ( background ) {
  9202. if ( background.isColor ) {
  9203. backgroundMaterial.color.copy( background );
  9204. scene.background = null;
  9205. useSolidColor = true;
  9206. }
  9207. } else {
  9208. backgroundMaterial.color.copy( _clearColor );
  9209. useSolidColor = true;
  9210. }
  9211. for ( let i = 0; i < 6; i ++ ) {
  9212. const col = i % 3;
  9213. if ( col == 0 ) {
  9214. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9215. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9216. } else if ( col == 1 ) {
  9217. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9218. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9219. } else {
  9220. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9221. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9222. }
  9223. _setViewport( cubeUVRenderTarget,
  9224. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  9225. renderer.setRenderTarget( cubeUVRenderTarget );
  9226. if ( useSolidColor ) {
  9227. renderer.render( backgroundBox, cubeCamera );
  9228. }
  9229. renderer.render( scene, cubeCamera );
  9230. }
  9231. backgroundBox.geometry.dispose();
  9232. backgroundBox.material.dispose();
  9233. renderer.toneMapping = toneMapping;
  9234. renderer.outputEncoding = outputEncoding;
  9235. renderer.autoClear = originalAutoClear;
  9236. scene.background = background;
  9237. }
  9238. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9239. const renderer = this._renderer;
  9240. if ( texture.isCubeTexture ) {
  9241. if ( this._cubemapShader == null ) {
  9242. this._cubemapShader = _getCubemapShader();
  9243. }
  9244. } else {
  9245. if ( this._equirectShader == null ) {
  9246. this._equirectShader = _getEquirectShader();
  9247. }
  9248. }
  9249. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  9250. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  9251. const uniforms = material.uniforms;
  9252. uniforms[ 'envMap' ].value = texture;
  9253. if ( ! texture.isCubeTexture ) {
  9254. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  9255. }
  9256. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  9257. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  9258. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  9259. renderer.setRenderTarget( cubeUVRenderTarget );
  9260. renderer.render( mesh, _flatCamera );
  9261. }
  9262. _applyPMREM( cubeUVRenderTarget ) {
  9263. const renderer = this._renderer;
  9264. const autoClear = renderer.autoClear;
  9265. renderer.autoClear = false;
  9266. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  9267. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  9268. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9269. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9270. }
  9271. renderer.autoClear = autoClear;
  9272. }
  9273. /**
  9274. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9275. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9276. * the blur latitudinally (around the poles), and then longitudinally (towards
  9277. * the poles) to approximate the orthogonally-separable blur. It is least
  9278. * accurate at the poles, but still does a decent job.
  9279. */
  9280. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9281. const pingPongRenderTarget = this._pingPongRenderTarget;
  9282. this._halfBlur(
  9283. cubeUVRenderTarget,
  9284. pingPongRenderTarget,
  9285. lodIn,
  9286. lodOut,
  9287. sigma,
  9288. 'latitudinal',
  9289. poleAxis );
  9290. this._halfBlur(
  9291. pingPongRenderTarget,
  9292. cubeUVRenderTarget,
  9293. lodOut,
  9294. lodOut,
  9295. sigma,
  9296. 'longitudinal',
  9297. poleAxis );
  9298. }
  9299. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9300. const renderer = this._renderer;
  9301. const blurMaterial = this._blurMaterial;
  9302. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9303. console.error(
  9304. 'blur direction must be either latitudinal or longitudinal!' );
  9305. }
  9306. // Number of standard deviations at which to cut off the discrete approximation.
  9307. const STANDARD_DEVIATIONS = 3;
  9308. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  9309. const blurUniforms = blurMaterial.uniforms;
  9310. const pixels = _sizeLods[ lodIn ] - 1;
  9311. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9312. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9313. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9314. if ( samples > MAX_SAMPLES ) {
  9315. console.warn( `sigmaRadians, ${
  9316. sigmaRadians}, is too large and will clip, as it requested ${
  9317. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9318. }
  9319. const weights = [];
  9320. let sum = 0;
  9321. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9322. const x = i / sigmaPixels;
  9323. const weight = Math.exp( - x * x / 2 );
  9324. weights.push( weight );
  9325. if ( i == 0 ) {
  9326. sum += weight;
  9327. } else if ( i < samples ) {
  9328. sum += 2 * weight;
  9329. }
  9330. }
  9331. for ( let i = 0; i < weights.length; i ++ ) {
  9332. weights[ i ] = weights[ i ] / sum;
  9333. }
  9334. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9335. blurUniforms[ 'samples' ].value = samples;
  9336. blurUniforms[ 'weights' ].value = weights;
  9337. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9338. if ( poleAxis ) {
  9339. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9340. }
  9341. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9342. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  9343. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  9344. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  9345. const outputSize = _sizeLods[ lodOut ];
  9346. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  9347. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  9348. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9349. renderer.setRenderTarget( targetOut );
  9350. renderer.render( blurMesh, _flatCamera );
  9351. }
  9352. }
  9353. function _isLDR( texture ) {
  9354. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  9355. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9356. }
  9357. function _createPlanes() {
  9358. const _lodPlanes = [];
  9359. const _sizeLods = [];
  9360. const _sigmas = [];
  9361. let lod = LOD_MAX;
  9362. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  9363. const sizeLod = Math.pow( 2, lod );
  9364. _sizeLods.push( sizeLod );
  9365. let sigma = 1.0 / sizeLod;
  9366. if ( i > LOD_MAX - LOD_MIN ) {
  9367. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  9368. } else if ( i == 0 ) {
  9369. sigma = 0;
  9370. }
  9371. _sigmas.push( sigma );
  9372. const texelSize = 1.0 / ( sizeLod - 1 );
  9373. const min = - texelSize / 2;
  9374. const max = 1 + texelSize / 2;
  9375. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9376. const cubeFaces = 6;
  9377. const vertices = 6;
  9378. const positionSize = 3;
  9379. const uvSize = 2;
  9380. const faceIndexSize = 1;
  9381. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9382. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9383. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9384. for ( let face = 0; face < cubeFaces; face ++ ) {
  9385. const x = ( face % 3 ) * 2 / 3 - 1;
  9386. const y = face > 2 ? 0 : - 1;
  9387. const coordinates = [
  9388. x, y, 0,
  9389. x + 2 / 3, y, 0,
  9390. x + 2 / 3, y + 1, 0,
  9391. x, y, 0,
  9392. x + 2 / 3, y + 1, 0,
  9393. x, y + 1, 0
  9394. ];
  9395. position.set( coordinates, positionSize * vertices * face );
  9396. uv.set( uv1, uvSize * vertices * face );
  9397. const fill = [ face, face, face, face, face, face ];
  9398. faceIndex.set( fill, faceIndexSize * vertices * face );
  9399. }
  9400. const planes = new BufferGeometry();
  9401. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9402. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9403. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9404. _lodPlanes.push( planes );
  9405. if ( lod > LOD_MIN ) {
  9406. lod --;
  9407. }
  9408. }
  9409. return { _lodPlanes, _sizeLods, _sigmas };
  9410. }
  9411. function _createRenderTarget( params ) {
  9412. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  9413. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9414. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9415. cubeUVRenderTarget.scissorTest = true;
  9416. return cubeUVRenderTarget;
  9417. }
  9418. function _setViewport( target, x, y, width, height ) {
  9419. target.viewport.set( x, y, width, height );
  9420. target.scissor.set( x, y, width, height );
  9421. }
  9422. function _getBlurShader( maxSamples ) {
  9423. const weights = new Float32Array( maxSamples );
  9424. const poleAxis = new Vector3( 0, 1, 0 );
  9425. const shaderMaterial = new RawShaderMaterial( {
  9426. name: 'SphericalGaussianBlur',
  9427. defines: { 'n': maxSamples },
  9428. uniforms: {
  9429. 'envMap': { value: null },
  9430. 'samples': { value: 1 },
  9431. 'weights': { value: weights },
  9432. 'latitudinal': { value: false },
  9433. 'dTheta': { value: 0 },
  9434. 'mipInt': { value: 0 },
  9435. 'poleAxis': { value: poleAxis },
  9436. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9437. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9438. },
  9439. vertexShader: _getCommonVertexShader(),
  9440. fragmentShader: /* glsl */`
  9441. precision mediump float;
  9442. precision mediump int;
  9443. varying vec3 vOutputDirection;
  9444. uniform sampler2D envMap;
  9445. uniform int samples;
  9446. uniform float weights[ n ];
  9447. uniform bool latitudinal;
  9448. uniform float dTheta;
  9449. uniform float mipInt;
  9450. uniform vec3 poleAxis;
  9451. ${ _getEncodings() }
  9452. #define ENVMAP_TYPE_CUBE_UV
  9453. #include <cube_uv_reflection_fragment>
  9454. vec3 getSample( float theta, vec3 axis ) {
  9455. float cosTheta = cos( theta );
  9456. // Rodrigues' axis-angle rotation
  9457. vec3 sampleDirection = vOutputDirection * cosTheta
  9458. + cross( axis, vOutputDirection ) * sin( theta )
  9459. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9460. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9461. }
  9462. void main() {
  9463. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9464. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9465. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9466. }
  9467. axis = normalize( axis );
  9468. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9469. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9470. for ( int i = 1; i < n; i++ ) {
  9471. if ( i >= samples ) {
  9472. break;
  9473. }
  9474. float theta = dTheta * float( i );
  9475. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9476. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9477. }
  9478. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9479. }
  9480. `,
  9481. blending: NoBlending,
  9482. depthTest: false,
  9483. depthWrite: false
  9484. } );
  9485. return shaderMaterial;
  9486. }
  9487. function _getEquirectShader() {
  9488. const texelSize = new Vector2( 1, 1 );
  9489. const shaderMaterial = new RawShaderMaterial( {
  9490. name: 'EquirectangularToCubeUV',
  9491. uniforms: {
  9492. 'envMap': { value: null },
  9493. 'texelSize': { value: texelSize },
  9494. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9495. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9496. },
  9497. vertexShader: _getCommonVertexShader(),
  9498. fragmentShader: /* glsl */`
  9499. precision mediump float;
  9500. precision mediump int;
  9501. varying vec3 vOutputDirection;
  9502. uniform sampler2D envMap;
  9503. uniform vec2 texelSize;
  9504. ${ _getEncodings() }
  9505. #include <common>
  9506. void main() {
  9507. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9508. vec3 outputDirection = normalize( vOutputDirection );
  9509. vec2 uv = equirectUv( outputDirection );
  9510. vec2 f = fract( uv / texelSize - 0.5 );
  9511. uv -= f * texelSize;
  9512. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9513. uv.x += texelSize.x;
  9514. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9515. uv.y += texelSize.y;
  9516. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9517. uv.x -= texelSize.x;
  9518. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9519. vec3 tm = mix( tl, tr, f.x );
  9520. vec3 bm = mix( bl, br, f.x );
  9521. gl_FragColor.rgb = mix( tm, bm, f.y );
  9522. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9523. }
  9524. `,
  9525. blending: NoBlending,
  9526. depthTest: false,
  9527. depthWrite: false
  9528. } );
  9529. return shaderMaterial;
  9530. }
  9531. function _getCubemapShader() {
  9532. const shaderMaterial = new RawShaderMaterial( {
  9533. name: 'CubemapToCubeUV',
  9534. uniforms: {
  9535. 'envMap': { value: null },
  9536. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9537. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9538. },
  9539. vertexShader: _getCommonVertexShader(),
  9540. fragmentShader: /* glsl */`
  9541. precision mediump float;
  9542. precision mediump int;
  9543. varying vec3 vOutputDirection;
  9544. uniform samplerCube envMap;
  9545. ${ _getEncodings() }
  9546. void main() {
  9547. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9548. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9549. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9550. }
  9551. `,
  9552. blending: NoBlending,
  9553. depthTest: false,
  9554. depthWrite: false
  9555. } );
  9556. return shaderMaterial;
  9557. }
  9558. function _getCommonVertexShader() {
  9559. return /* glsl */`
  9560. precision mediump float;
  9561. precision mediump int;
  9562. attribute vec3 position;
  9563. attribute vec2 uv;
  9564. attribute float faceIndex;
  9565. varying vec3 vOutputDirection;
  9566. // RH coordinate system; PMREM face-indexing convention
  9567. vec3 getDirection( vec2 uv, float face ) {
  9568. uv = 2.0 * uv - 1.0;
  9569. vec3 direction = vec3( uv, 1.0 );
  9570. if ( face == 0.0 ) {
  9571. direction = direction.zyx; // ( 1, v, u ) pos x
  9572. } else if ( face == 1.0 ) {
  9573. direction = direction.xzy;
  9574. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9575. } else if ( face == 2.0 ) {
  9576. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9577. } else if ( face == 3.0 ) {
  9578. direction = direction.zyx;
  9579. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9580. } else if ( face == 4.0 ) {
  9581. direction = direction.xzy;
  9582. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9583. } else if ( face == 5.0 ) {
  9584. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9585. }
  9586. return direction;
  9587. }
  9588. void main() {
  9589. vOutputDirection = getDirection( uv, faceIndex );
  9590. gl_Position = vec4( position, 1.0 );
  9591. }
  9592. `;
  9593. }
  9594. function _getEncodings() {
  9595. return /* glsl */`
  9596. uniform int inputEncoding;
  9597. uniform int outputEncoding;
  9598. #include <encodings_pars_fragment>
  9599. vec4 inputTexelToLinear( vec4 value ) {
  9600. if ( inputEncoding == 0 ) {
  9601. return value;
  9602. } else if ( inputEncoding == 1 ) {
  9603. return sRGBToLinear( value );
  9604. } else if ( inputEncoding == 2 ) {
  9605. return RGBEToLinear( value );
  9606. } else if ( inputEncoding == 3 ) {
  9607. return RGBMToLinear( value, 7.0 );
  9608. } else if ( inputEncoding == 4 ) {
  9609. return RGBMToLinear( value, 16.0 );
  9610. } else if ( inputEncoding == 5 ) {
  9611. return RGBDToLinear( value, 256.0 );
  9612. } else {
  9613. return GammaToLinear( value, 2.2 );
  9614. }
  9615. }
  9616. vec4 linearToOutputTexel( vec4 value ) {
  9617. if ( outputEncoding == 0 ) {
  9618. return value;
  9619. } else if ( outputEncoding == 1 ) {
  9620. return LinearTosRGB( value );
  9621. } else if ( outputEncoding == 2 ) {
  9622. return LinearToRGBE( value );
  9623. } else if ( outputEncoding == 3 ) {
  9624. return LinearToRGBM( value, 7.0 );
  9625. } else if ( outputEncoding == 4 ) {
  9626. return LinearToRGBM( value, 16.0 );
  9627. } else if ( outputEncoding == 5 ) {
  9628. return LinearToRGBD( value, 256.0 );
  9629. } else {
  9630. return LinearToGamma( value, 2.2 );
  9631. }
  9632. }
  9633. vec4 envMapTexelToLinear( vec4 color ) {
  9634. return inputTexelToLinear( color );
  9635. }
  9636. `;
  9637. }
  9638. function WebGLCubeUVMaps( renderer ) {
  9639. let cubeUVmaps = new WeakMap();
  9640. let pmremGenerator = null;
  9641. function get( texture ) {
  9642. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9643. const mapping = texture.mapping;
  9644. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9645. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9646. if ( isEquirectMap || isCubeMap ) {
  9647. // equirect/cube map to cubeUV conversion
  9648. if ( cubeUVmaps.has( texture ) ) {
  9649. return cubeUVmaps.get( texture ).texture;
  9650. } else {
  9651. const image = texture.image;
  9652. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9653. const currentRenderTarget = renderer.getRenderTarget();
  9654. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9655. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9656. cubeUVmaps.set( texture, renderTarget );
  9657. renderer.setRenderTarget( currentRenderTarget );
  9658. texture.addEventListener( 'dispose', onTextureDispose );
  9659. return renderTarget.texture;
  9660. } else {
  9661. // image not yet ready. try the conversion next frame
  9662. return null;
  9663. }
  9664. }
  9665. }
  9666. }
  9667. return texture;
  9668. }
  9669. function isCubeTextureComplete( image ) {
  9670. let count = 0;
  9671. const length = 6;
  9672. for ( let i = 0; i < length; i ++ ) {
  9673. if ( image[ i ] !== undefined ) count ++;
  9674. }
  9675. return count === length;
  9676. }
  9677. function onTextureDispose( event ) {
  9678. const texture = event.target;
  9679. texture.removeEventListener( 'dispose', onTextureDispose );
  9680. const cubemapUV = cubeUVmaps.get( texture );
  9681. if ( cubemapUV !== undefined ) {
  9682. cubeUVmaps.delete( texture );
  9683. cubemapUV.dispose();
  9684. }
  9685. }
  9686. function dispose() {
  9687. cubeUVmaps = new WeakMap();
  9688. if ( pmremGenerator !== null ) {
  9689. pmremGenerator.dispose();
  9690. pmremGenerator = null;
  9691. }
  9692. }
  9693. return {
  9694. get: get,
  9695. dispose: dispose
  9696. };
  9697. }
  9698. function WebGLExtensions( gl ) {
  9699. const extensions = {};
  9700. function getExtension( name ) {
  9701. if ( extensions[ name ] !== undefined ) {
  9702. return extensions[ name ];
  9703. }
  9704. let extension;
  9705. switch ( name ) {
  9706. case 'WEBGL_depth_texture':
  9707. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9708. break;
  9709. case 'EXT_texture_filter_anisotropic':
  9710. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9711. break;
  9712. case 'WEBGL_compressed_texture_s3tc':
  9713. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9714. break;
  9715. case 'WEBGL_compressed_texture_pvrtc':
  9716. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9717. break;
  9718. default:
  9719. extension = gl.getExtension( name );
  9720. }
  9721. extensions[ name ] = extension;
  9722. return extension;
  9723. }
  9724. return {
  9725. has: function ( name ) {
  9726. return getExtension( name ) !== null;
  9727. },
  9728. init: function ( capabilities ) {
  9729. if ( capabilities.isWebGL2 ) {
  9730. getExtension( 'EXT_color_buffer_float' );
  9731. } else {
  9732. getExtension( 'WEBGL_depth_texture' );
  9733. getExtension( 'OES_texture_float' );
  9734. getExtension( 'OES_texture_half_float' );
  9735. getExtension( 'OES_texture_half_float_linear' );
  9736. getExtension( 'OES_standard_derivatives' );
  9737. getExtension( 'OES_element_index_uint' );
  9738. getExtension( 'OES_vertex_array_object' );
  9739. getExtension( 'ANGLE_instanced_arrays' );
  9740. }
  9741. getExtension( 'OES_texture_float_linear' );
  9742. getExtension( 'EXT_color_buffer_half_float' );
  9743. },
  9744. get: function ( name ) {
  9745. const extension = getExtension( name );
  9746. if ( extension === null ) {
  9747. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9748. }
  9749. return extension;
  9750. }
  9751. };
  9752. }
  9753. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9754. const geometries = {};
  9755. const wireframeAttributes = new WeakMap();
  9756. function onGeometryDispose( event ) {
  9757. const geometry = event.target;
  9758. if ( geometry.index !== null ) {
  9759. attributes.remove( geometry.index );
  9760. }
  9761. for ( const name in geometry.attributes ) {
  9762. attributes.remove( geometry.attributes[ name ] );
  9763. }
  9764. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9765. delete geometries[ geometry.id ];
  9766. const attribute = wireframeAttributes.get( geometry );
  9767. if ( attribute ) {
  9768. attributes.remove( attribute );
  9769. wireframeAttributes.delete( geometry );
  9770. }
  9771. bindingStates.releaseStatesOfGeometry( geometry );
  9772. if ( geometry.isInstancedBufferGeometry === true ) {
  9773. delete geometry._maxInstanceCount;
  9774. }
  9775. //
  9776. info.memory.geometries --;
  9777. }
  9778. function get( object, geometry ) {
  9779. if ( geometries[ geometry.id ] === true ) return geometry;
  9780. geometry.addEventListener( 'dispose', onGeometryDispose );
  9781. geometries[ geometry.id ] = true;
  9782. info.memory.geometries ++;
  9783. return geometry;
  9784. }
  9785. function update( geometry ) {
  9786. const geometryAttributes = geometry.attributes;
  9787. // Updating index buffer in VAO now. See WebGLBindingStates.
  9788. for ( const name in geometryAttributes ) {
  9789. attributes.update( geometryAttributes[ name ], 34962 );
  9790. }
  9791. // morph targets
  9792. const morphAttributes = geometry.morphAttributes;
  9793. for ( const name in morphAttributes ) {
  9794. const array = morphAttributes[ name ];
  9795. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9796. attributes.update( array[ i ], 34962 );
  9797. }
  9798. }
  9799. }
  9800. function updateWireframeAttribute( geometry ) {
  9801. const indices = [];
  9802. const geometryIndex = geometry.index;
  9803. const geometryPosition = geometry.attributes.position;
  9804. let version = 0;
  9805. if ( geometryIndex !== null ) {
  9806. const array = geometryIndex.array;
  9807. version = geometryIndex.version;
  9808. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9809. const a = array[ i + 0 ];
  9810. const b = array[ i + 1 ];
  9811. const c = array[ i + 2 ];
  9812. indices.push( a, b, b, c, c, a );
  9813. }
  9814. } else {
  9815. const array = geometryPosition.array;
  9816. version = geometryPosition.version;
  9817. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9818. const a = i + 0;
  9819. const b = i + 1;
  9820. const c = i + 2;
  9821. indices.push( a, b, b, c, c, a );
  9822. }
  9823. }
  9824. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9825. attribute.version = version;
  9826. // Updating index buffer in VAO now. See WebGLBindingStates
  9827. //
  9828. const previousAttribute = wireframeAttributes.get( geometry );
  9829. if ( previousAttribute ) attributes.remove( previousAttribute );
  9830. //
  9831. wireframeAttributes.set( geometry, attribute );
  9832. }
  9833. function getWireframeAttribute( geometry ) {
  9834. const currentAttribute = wireframeAttributes.get( geometry );
  9835. if ( currentAttribute ) {
  9836. const geometryIndex = geometry.index;
  9837. if ( geometryIndex !== null ) {
  9838. // if the attribute is obsolete, create a new one
  9839. if ( currentAttribute.version < geometryIndex.version ) {
  9840. updateWireframeAttribute( geometry );
  9841. }
  9842. }
  9843. } else {
  9844. updateWireframeAttribute( geometry );
  9845. }
  9846. return wireframeAttributes.get( geometry );
  9847. }
  9848. return {
  9849. get: get,
  9850. update: update,
  9851. getWireframeAttribute: getWireframeAttribute
  9852. };
  9853. }
  9854. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9855. const isWebGL2 = capabilities.isWebGL2;
  9856. let mode;
  9857. function setMode( value ) {
  9858. mode = value;
  9859. }
  9860. let type, bytesPerElement;
  9861. function setIndex( value ) {
  9862. type = value.type;
  9863. bytesPerElement = value.bytesPerElement;
  9864. }
  9865. function render( start, count ) {
  9866. gl.drawElements( mode, count, type, start * bytesPerElement );
  9867. info.update( count, mode, 1 );
  9868. }
  9869. function renderInstances( start, count, primcount ) {
  9870. if ( primcount === 0 ) return;
  9871. let extension, methodName;
  9872. if ( isWebGL2 ) {
  9873. extension = gl;
  9874. methodName = 'drawElementsInstanced';
  9875. } else {
  9876. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9877. methodName = 'drawElementsInstancedANGLE';
  9878. if ( extension === null ) {
  9879. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9880. return;
  9881. }
  9882. }
  9883. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9884. info.update( count, mode, primcount );
  9885. }
  9886. //
  9887. this.setMode = setMode;
  9888. this.setIndex = setIndex;
  9889. this.render = render;
  9890. this.renderInstances = renderInstances;
  9891. }
  9892. function WebGLInfo( gl ) {
  9893. const memory = {
  9894. geometries: 0,
  9895. textures: 0
  9896. };
  9897. const render = {
  9898. frame: 0,
  9899. calls: 0,
  9900. triangles: 0,
  9901. points: 0,
  9902. lines: 0
  9903. };
  9904. function update( count, mode, instanceCount ) {
  9905. render.calls ++;
  9906. switch ( mode ) {
  9907. case 4:
  9908. render.triangles += instanceCount * ( count / 3 );
  9909. break;
  9910. case 1:
  9911. render.lines += instanceCount * ( count / 2 );
  9912. break;
  9913. case 3:
  9914. render.lines += instanceCount * ( count - 1 );
  9915. break;
  9916. case 2:
  9917. render.lines += instanceCount * count;
  9918. break;
  9919. case 0:
  9920. render.points += instanceCount * count;
  9921. break;
  9922. default:
  9923. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9924. break;
  9925. }
  9926. }
  9927. function reset() {
  9928. render.frame ++;
  9929. render.calls = 0;
  9930. render.triangles = 0;
  9931. render.points = 0;
  9932. render.lines = 0;
  9933. }
  9934. return {
  9935. memory: memory,
  9936. render: render,
  9937. programs: null,
  9938. autoReset: true,
  9939. reset: reset,
  9940. update: update
  9941. };
  9942. }
  9943. function numericalSort( a, b ) {
  9944. return a[ 0 ] - b[ 0 ];
  9945. }
  9946. function absNumericalSort( a, b ) {
  9947. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9948. }
  9949. function WebGLMorphtargets( gl ) {
  9950. const influencesList = {};
  9951. const morphInfluences = new Float32Array( 8 );
  9952. const workInfluences = [];
  9953. for ( let i = 0; i < 8; i ++ ) {
  9954. workInfluences[ i ] = [ i, 0 ];
  9955. }
  9956. function update( object, geometry, material, program ) {
  9957. const objectInfluences = object.morphTargetInfluences;
  9958. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9959. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9960. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9961. let influences = influencesList[ geometry.id ];
  9962. if ( influences === undefined || influences.length !== length ) {
  9963. // initialise list
  9964. influences = [];
  9965. for ( let i = 0; i < length; i ++ ) {
  9966. influences[ i ] = [ i, 0 ];
  9967. }
  9968. influencesList[ geometry.id ] = influences;
  9969. }
  9970. // Collect influences
  9971. for ( let i = 0; i < length; i ++ ) {
  9972. const influence = influences[ i ];
  9973. influence[ 0 ] = i;
  9974. influence[ 1 ] = objectInfluences[ i ];
  9975. }
  9976. influences.sort( absNumericalSort );
  9977. for ( let i = 0; i < 8; i ++ ) {
  9978. if ( i < length && influences[ i ][ 1 ] ) {
  9979. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  9980. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  9981. } else {
  9982. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  9983. workInfluences[ i ][ 1 ] = 0;
  9984. }
  9985. }
  9986. workInfluences.sort( numericalSort );
  9987. const morphTargets = geometry.morphAttributes.position;
  9988. const morphNormals = geometry.morphAttributes.normal;
  9989. let morphInfluencesSum = 0;
  9990. for ( let i = 0; i < 8; i ++ ) {
  9991. const influence = workInfluences[ i ];
  9992. const index = influence[ 0 ];
  9993. const value = influence[ 1 ];
  9994. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  9995. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  9996. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  9997. }
  9998. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  9999. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10000. }
  10001. morphInfluences[ i ] = value;
  10002. morphInfluencesSum += value;
  10003. } else {
  10004. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10005. geometry.deleteAttribute( 'morphTarget' + i );
  10006. }
  10007. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10008. geometry.deleteAttribute( 'morphNormal' + i );
  10009. }
  10010. morphInfluences[ i ] = 0;
  10011. }
  10012. }
  10013. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10014. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10015. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10016. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10017. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10018. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10019. }
  10020. return {
  10021. update: update
  10022. };
  10023. }
  10024. function WebGLObjects( gl, geometries, attributes, info ) {
  10025. let updateMap = new WeakMap();
  10026. function update( object ) {
  10027. const frame = info.render.frame;
  10028. const geometry = object.geometry;
  10029. const buffergeometry = geometries.get( object, geometry );
  10030. // Update once per frame
  10031. if ( updateMap.get( buffergeometry ) !== frame ) {
  10032. geometries.update( buffergeometry );
  10033. updateMap.set( buffergeometry, frame );
  10034. }
  10035. if ( object.isInstancedMesh ) {
  10036. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10037. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10038. }
  10039. attributes.update( object.instanceMatrix, 34962 );
  10040. if ( object.instanceColor !== null ) {
  10041. attributes.update( object.instanceColor, 34962 );
  10042. }
  10043. }
  10044. return buffergeometry;
  10045. }
  10046. function dispose() {
  10047. updateMap = new WeakMap();
  10048. }
  10049. function onInstancedMeshDispose( event ) {
  10050. const instancedMesh = event.target;
  10051. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10052. attributes.remove( instancedMesh.instanceMatrix );
  10053. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10054. }
  10055. return {
  10056. update: update,
  10057. dispose: dispose
  10058. };
  10059. }
  10060. class DataTexture2DArray extends Texture {
  10061. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  10062. super( null );
  10063. this.image = { data, width, height, depth };
  10064. this.magFilter = NearestFilter;
  10065. this.minFilter = NearestFilter;
  10066. this.wrapR = ClampToEdgeWrapping;
  10067. this.generateMipmaps = false;
  10068. this.flipY = false;
  10069. this.unpackAlignment = 1;
  10070. this.needsUpdate = true;
  10071. }
  10072. }
  10073. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10074. class DataTexture3D extends Texture {
  10075. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  10076. // We're going to add .setXXX() methods for setting properties later.
  10077. // Users can still set in DataTexture3D directly.
  10078. //
  10079. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10080. // texture.anisotropy = 16;
  10081. //
  10082. // See #14839
  10083. super( null );
  10084. this.image = { data, width, height, depth };
  10085. this.magFilter = NearestFilter;
  10086. this.minFilter = NearestFilter;
  10087. this.wrapR = ClampToEdgeWrapping;
  10088. this.generateMipmaps = false;
  10089. this.flipY = false;
  10090. this.unpackAlignment = 1;
  10091. this.needsUpdate = true;
  10092. }
  10093. }
  10094. DataTexture3D.prototype.isDataTexture3D = true;
  10095. /**
  10096. * Uniforms of a program.
  10097. * Those form a tree structure with a special top-level container for the root,
  10098. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10099. *
  10100. *
  10101. * Properties of inner nodes including the top-level container:
  10102. *
  10103. * .seq - array of nested uniforms
  10104. * .map - nested uniforms by name
  10105. *
  10106. *
  10107. * Methods of all nodes except the top-level container:
  10108. *
  10109. * .setValue( gl, value, [textures] )
  10110. *
  10111. * uploads a uniform value(s)
  10112. * the 'textures' parameter is needed for sampler uniforms
  10113. *
  10114. *
  10115. * Static methods of the top-level container (textures factorizations):
  10116. *
  10117. * .upload( gl, seq, values, textures )
  10118. *
  10119. * sets uniforms in 'seq' to 'values[id].value'
  10120. *
  10121. * .seqWithValue( seq, values ) : filteredSeq
  10122. *
  10123. * filters 'seq' entries with corresponding entry in values
  10124. *
  10125. *
  10126. * Methods of the top-level container (textures factorizations):
  10127. *
  10128. * .setValue( gl, name, value, textures )
  10129. *
  10130. * sets uniform with name 'name' to 'value'
  10131. *
  10132. * .setOptional( gl, obj, prop )
  10133. *
  10134. * like .set for an optional property of the object
  10135. *
  10136. */
  10137. const emptyTexture = new Texture();
  10138. const emptyTexture2dArray = new DataTexture2DArray();
  10139. const emptyTexture3d = new DataTexture3D();
  10140. const emptyCubeTexture = new CubeTexture();
  10141. // --- Utilities ---
  10142. // Array Caches (provide typed arrays for temporary by size)
  10143. const arrayCacheF32 = [];
  10144. const arrayCacheI32 = [];
  10145. // Float32Array caches used for uploading Matrix uniforms
  10146. const mat4array = new Float32Array( 16 );
  10147. const mat3array = new Float32Array( 9 );
  10148. const mat2array = new Float32Array( 4 );
  10149. // Flattening for arrays of vectors and matrices
  10150. function flatten( array, nBlocks, blockSize ) {
  10151. const firstElem = array[ 0 ];
  10152. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10153. // unoptimized: ! isNaN( firstElem )
  10154. // see http://jacksondunstan.com/articles/983
  10155. const n = nBlocks * blockSize;
  10156. let r = arrayCacheF32[ n ];
  10157. if ( r === undefined ) {
  10158. r = new Float32Array( n );
  10159. arrayCacheF32[ n ] = r;
  10160. }
  10161. if ( nBlocks !== 0 ) {
  10162. firstElem.toArray( r, 0 );
  10163. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10164. offset += blockSize;
  10165. array[ i ].toArray( r, offset );
  10166. }
  10167. }
  10168. return r;
  10169. }
  10170. function arraysEqual( a, b ) {
  10171. if ( a.length !== b.length ) return false;
  10172. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10173. if ( a[ i ] !== b[ i ] ) return false;
  10174. }
  10175. return true;
  10176. }
  10177. function copyArray( a, b ) {
  10178. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10179. a[ i ] = b[ i ];
  10180. }
  10181. }
  10182. // Texture unit allocation
  10183. function allocTexUnits( textures, n ) {
  10184. let r = arrayCacheI32[ n ];
  10185. if ( r === undefined ) {
  10186. r = new Int32Array( n );
  10187. arrayCacheI32[ n ] = r;
  10188. }
  10189. for ( let i = 0; i !== n; ++ i ) {
  10190. r[ i ] = textures.allocateTextureUnit();
  10191. }
  10192. return r;
  10193. }
  10194. // --- Setters ---
  10195. // Note: Defining these methods externally, because they come in a bunch
  10196. // and this way their names minify.
  10197. // Single scalar
  10198. function setValueV1f( gl, v ) {
  10199. const cache = this.cache;
  10200. if ( cache[ 0 ] === v ) return;
  10201. gl.uniform1f( this.addr, v );
  10202. cache[ 0 ] = v;
  10203. }
  10204. // Single float vector (from flat array or THREE.VectorN)
  10205. function setValueV2f( gl, v ) {
  10206. const cache = this.cache;
  10207. if ( v.x !== undefined ) {
  10208. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10209. gl.uniform2f( this.addr, v.x, v.y );
  10210. cache[ 0 ] = v.x;
  10211. cache[ 1 ] = v.y;
  10212. }
  10213. } else {
  10214. if ( arraysEqual( cache, v ) ) return;
  10215. gl.uniform2fv( this.addr, v );
  10216. copyArray( cache, v );
  10217. }
  10218. }
  10219. function setValueV3f( gl, v ) {
  10220. const cache = this.cache;
  10221. if ( v.x !== undefined ) {
  10222. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10223. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10224. cache[ 0 ] = v.x;
  10225. cache[ 1 ] = v.y;
  10226. cache[ 2 ] = v.z;
  10227. }
  10228. } else if ( v.r !== undefined ) {
  10229. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10230. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10231. cache[ 0 ] = v.r;
  10232. cache[ 1 ] = v.g;
  10233. cache[ 2 ] = v.b;
  10234. }
  10235. } else {
  10236. if ( arraysEqual( cache, v ) ) return;
  10237. gl.uniform3fv( this.addr, v );
  10238. copyArray( cache, v );
  10239. }
  10240. }
  10241. function setValueV4f( gl, v ) {
  10242. const cache = this.cache;
  10243. if ( v.x !== undefined ) {
  10244. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10245. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10246. cache[ 0 ] = v.x;
  10247. cache[ 1 ] = v.y;
  10248. cache[ 2 ] = v.z;
  10249. cache[ 3 ] = v.w;
  10250. }
  10251. } else {
  10252. if ( arraysEqual( cache, v ) ) return;
  10253. gl.uniform4fv( this.addr, v );
  10254. copyArray( cache, v );
  10255. }
  10256. }
  10257. // Single matrix (from flat array or THREE.MatrixN)
  10258. function setValueM2( gl, v ) {
  10259. const cache = this.cache;
  10260. const elements = v.elements;
  10261. if ( elements === undefined ) {
  10262. if ( arraysEqual( cache, v ) ) return;
  10263. gl.uniformMatrix2fv( this.addr, false, v );
  10264. copyArray( cache, v );
  10265. } else {
  10266. if ( arraysEqual( cache, elements ) ) return;
  10267. mat2array.set( elements );
  10268. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10269. copyArray( cache, elements );
  10270. }
  10271. }
  10272. function setValueM3( gl, v ) {
  10273. const cache = this.cache;
  10274. const elements = v.elements;
  10275. if ( elements === undefined ) {
  10276. if ( arraysEqual( cache, v ) ) return;
  10277. gl.uniformMatrix3fv( this.addr, false, v );
  10278. copyArray( cache, v );
  10279. } else {
  10280. if ( arraysEqual( cache, elements ) ) return;
  10281. mat3array.set( elements );
  10282. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10283. copyArray( cache, elements );
  10284. }
  10285. }
  10286. function setValueM4( gl, v ) {
  10287. const cache = this.cache;
  10288. const elements = v.elements;
  10289. if ( elements === undefined ) {
  10290. if ( arraysEqual( cache, v ) ) return;
  10291. gl.uniformMatrix4fv( this.addr, false, v );
  10292. copyArray( cache, v );
  10293. } else {
  10294. if ( arraysEqual( cache, elements ) ) return;
  10295. mat4array.set( elements );
  10296. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10297. copyArray( cache, elements );
  10298. }
  10299. }
  10300. // Single integer / boolean
  10301. function setValueV1i( gl, v ) {
  10302. const cache = this.cache;
  10303. if ( cache[ 0 ] === v ) return;
  10304. gl.uniform1i( this.addr, v );
  10305. cache[ 0 ] = v;
  10306. }
  10307. // Single integer / boolean vector (from flat array)
  10308. function setValueV2i( gl, v ) {
  10309. const cache = this.cache;
  10310. if ( arraysEqual( cache, v ) ) return;
  10311. gl.uniform2iv( this.addr, v );
  10312. copyArray( cache, v );
  10313. }
  10314. function setValueV3i( gl, v ) {
  10315. const cache = this.cache;
  10316. if ( arraysEqual( cache, v ) ) return;
  10317. gl.uniform3iv( this.addr, v );
  10318. copyArray( cache, v );
  10319. }
  10320. function setValueV4i( gl, v ) {
  10321. const cache = this.cache;
  10322. if ( arraysEqual( cache, v ) ) return;
  10323. gl.uniform4iv( this.addr, v );
  10324. copyArray( cache, v );
  10325. }
  10326. // Single unsigned integer
  10327. function setValueV1ui( gl, v ) {
  10328. const cache = this.cache;
  10329. if ( cache[ 0 ] === v ) return;
  10330. gl.uniform1ui( this.addr, v );
  10331. cache[ 0 ] = v;
  10332. }
  10333. // Single unsigned integer vector (from flat array)
  10334. function setValueV2ui( gl, v ) {
  10335. const cache = this.cache;
  10336. if ( arraysEqual( cache, v ) ) return;
  10337. gl.uniform2uiv( this.addr, v );
  10338. copyArray( cache, v );
  10339. }
  10340. function setValueV3ui( gl, v ) {
  10341. const cache = this.cache;
  10342. if ( arraysEqual( cache, v ) ) return;
  10343. gl.uniform3uiv( this.addr, v );
  10344. copyArray( cache, v );
  10345. }
  10346. function setValueV4ui( gl, v ) {
  10347. const cache = this.cache;
  10348. if ( arraysEqual( cache, v ) ) return;
  10349. gl.uniform4uiv( this.addr, v );
  10350. copyArray( cache, v );
  10351. }
  10352. // Single texture (2D / Cube)
  10353. function setValueT1( gl, v, textures ) {
  10354. const cache = this.cache;
  10355. const unit = textures.allocateTextureUnit();
  10356. if ( cache[ 0 ] !== unit ) {
  10357. gl.uniform1i( this.addr, unit );
  10358. cache[ 0 ] = unit;
  10359. }
  10360. textures.safeSetTexture2D( v || emptyTexture, unit );
  10361. }
  10362. function setValueT3D1( gl, v, textures ) {
  10363. const cache = this.cache;
  10364. const unit = textures.allocateTextureUnit();
  10365. if ( cache[ 0 ] !== unit ) {
  10366. gl.uniform1i( this.addr, unit );
  10367. cache[ 0 ] = unit;
  10368. }
  10369. textures.setTexture3D( v || emptyTexture3d, unit );
  10370. }
  10371. function setValueT6( gl, v, textures ) {
  10372. const cache = this.cache;
  10373. const unit = textures.allocateTextureUnit();
  10374. if ( cache[ 0 ] !== unit ) {
  10375. gl.uniform1i( this.addr, unit );
  10376. cache[ 0 ] = unit;
  10377. }
  10378. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10379. }
  10380. function setValueT2DArray1( gl, v, textures ) {
  10381. const cache = this.cache;
  10382. const unit = textures.allocateTextureUnit();
  10383. if ( cache[ 0 ] !== unit ) {
  10384. gl.uniform1i( this.addr, unit );
  10385. cache[ 0 ] = unit;
  10386. }
  10387. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10388. }
  10389. // Helper to pick the right setter for the singular case
  10390. function getSingularSetter( type ) {
  10391. switch ( type ) {
  10392. case 0x1406: return setValueV1f; // FLOAT
  10393. case 0x8b50: return setValueV2f; // _VEC2
  10394. case 0x8b51: return setValueV3f; // _VEC3
  10395. case 0x8b52: return setValueV4f; // _VEC4
  10396. case 0x8b5a: return setValueM2; // _MAT2
  10397. case 0x8b5b: return setValueM3; // _MAT3
  10398. case 0x8b5c: return setValueM4; // _MAT4
  10399. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10400. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10401. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10402. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10403. case 0x1405: return setValueV1ui; // UINT
  10404. case 0x8dc6: return setValueV2ui; // _VEC2
  10405. case 0x8dc7: return setValueV3ui; // _VEC3
  10406. case 0x8dc8: return setValueV4ui; // _VEC4
  10407. case 0x8b5e: // SAMPLER_2D
  10408. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10409. case 0x8dca: // INT_SAMPLER_2D
  10410. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10411. case 0x8b62: // SAMPLER_2D_SHADOW
  10412. return setValueT1;
  10413. case 0x8b5f: // SAMPLER_3D
  10414. case 0x8dcb: // INT_SAMPLER_3D
  10415. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10416. return setValueT3D1;
  10417. case 0x8b60: // SAMPLER_CUBE
  10418. case 0x8dcc: // INT_SAMPLER_CUBE
  10419. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10420. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10421. return setValueT6;
  10422. case 0x8dc1: // SAMPLER_2D_ARRAY
  10423. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10424. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10425. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10426. return setValueT2DArray1;
  10427. }
  10428. }
  10429. // Array of scalars
  10430. function setValueV1fArray( gl, v ) {
  10431. gl.uniform1fv( this.addr, v );
  10432. }
  10433. // Array of vectors (from flat array or array of THREE.VectorN)
  10434. function setValueV2fArray( gl, v ) {
  10435. const data = flatten( v, this.size, 2 );
  10436. gl.uniform2fv( this.addr, data );
  10437. }
  10438. function setValueV3fArray( gl, v ) {
  10439. const data = flatten( v, this.size, 3 );
  10440. gl.uniform3fv( this.addr, data );
  10441. }
  10442. function setValueV4fArray( gl, v ) {
  10443. const data = flatten( v, this.size, 4 );
  10444. gl.uniform4fv( this.addr, data );
  10445. }
  10446. // Array of matrices (from flat array or array of THREE.MatrixN)
  10447. function setValueM2Array( gl, v ) {
  10448. const data = flatten( v, this.size, 4 );
  10449. gl.uniformMatrix2fv( this.addr, false, data );
  10450. }
  10451. function setValueM3Array( gl, v ) {
  10452. const data = flatten( v, this.size, 9 );
  10453. gl.uniformMatrix3fv( this.addr, false, data );
  10454. }
  10455. function setValueM4Array( gl, v ) {
  10456. const data = flatten( v, this.size, 16 );
  10457. gl.uniformMatrix4fv( this.addr, false, data );
  10458. }
  10459. // Array of integer / boolean
  10460. function setValueV1iArray( gl, v ) {
  10461. gl.uniform1iv( this.addr, v );
  10462. }
  10463. // Array of integer / boolean vectors (from flat array)
  10464. function setValueV2iArray( gl, v ) {
  10465. gl.uniform2iv( this.addr, v );
  10466. }
  10467. function setValueV3iArray( gl, v ) {
  10468. gl.uniform3iv( this.addr, v );
  10469. }
  10470. function setValueV4iArray( gl, v ) {
  10471. gl.uniform4iv( this.addr, v );
  10472. }
  10473. // Array of unsigned integer
  10474. function setValueV1uiArray( gl, v ) {
  10475. gl.uniform1uiv( this.addr, v );
  10476. }
  10477. // Array of unsigned integer vectors (from flat array)
  10478. function setValueV2uiArray( gl, v ) {
  10479. gl.uniform2uiv( this.addr, v );
  10480. }
  10481. function setValueV3uiArray( gl, v ) {
  10482. gl.uniform3uiv( this.addr, v );
  10483. }
  10484. function setValueV4uiArray( gl, v ) {
  10485. gl.uniform4uiv( this.addr, v );
  10486. }
  10487. // Array of textures (2D / Cube)
  10488. function setValueT1Array( gl, v, textures ) {
  10489. const n = v.length;
  10490. const units = allocTexUnits( textures, n );
  10491. gl.uniform1iv( this.addr, units );
  10492. for ( let i = 0; i !== n; ++ i ) {
  10493. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10494. }
  10495. }
  10496. function setValueT6Array( gl, v, textures ) {
  10497. const n = v.length;
  10498. const units = allocTexUnits( textures, n );
  10499. gl.uniform1iv( this.addr, units );
  10500. for ( let i = 0; i !== n; ++ i ) {
  10501. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10502. }
  10503. }
  10504. // Helper to pick the right setter for a pure (bottom-level) array
  10505. function getPureArraySetter( type ) {
  10506. switch ( type ) {
  10507. case 0x1406: return setValueV1fArray; // FLOAT
  10508. case 0x8b50: return setValueV2fArray; // _VEC2
  10509. case 0x8b51: return setValueV3fArray; // _VEC3
  10510. case 0x8b52: return setValueV4fArray; // _VEC4
  10511. case 0x8b5a: return setValueM2Array; // _MAT2
  10512. case 0x8b5b: return setValueM3Array; // _MAT3
  10513. case 0x8b5c: return setValueM4Array; // _MAT4
  10514. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10515. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10516. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10517. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10518. case 0x1405: return setValueV1uiArray; // UINT
  10519. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10520. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10521. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10522. case 0x8b5e: // SAMPLER_2D
  10523. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10524. case 0x8dca: // INT_SAMPLER_2D
  10525. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10526. case 0x8b62: // SAMPLER_2D_SHADOW
  10527. return setValueT1Array;
  10528. case 0x8b60: // SAMPLER_CUBE
  10529. case 0x8dcc: // INT_SAMPLER_CUBE
  10530. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10531. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10532. return setValueT6Array;
  10533. }
  10534. }
  10535. // --- Uniform Classes ---
  10536. function SingleUniform( id, activeInfo, addr ) {
  10537. this.id = id;
  10538. this.addr = addr;
  10539. this.cache = [];
  10540. this.setValue = getSingularSetter( activeInfo.type );
  10541. // this.path = activeInfo.name; // DEBUG
  10542. }
  10543. function PureArrayUniform( id, activeInfo, addr ) {
  10544. this.id = id;
  10545. this.addr = addr;
  10546. this.cache = [];
  10547. this.size = activeInfo.size;
  10548. this.setValue = getPureArraySetter( activeInfo.type );
  10549. // this.path = activeInfo.name; // DEBUG
  10550. }
  10551. PureArrayUniform.prototype.updateCache = function ( data ) {
  10552. const cache = this.cache;
  10553. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10554. this.cache = new Float32Array( data.length );
  10555. }
  10556. copyArray( cache, data );
  10557. };
  10558. function StructuredUniform( id ) {
  10559. this.id = id;
  10560. this.seq = [];
  10561. this.map = {};
  10562. }
  10563. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10564. const seq = this.seq;
  10565. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10566. const u = seq[ i ];
  10567. u.setValue( gl, value[ u.id ], textures );
  10568. }
  10569. };
  10570. // --- Top-level ---
  10571. // Parser - builds up the property tree from the path strings
  10572. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10573. // extracts
  10574. // - the identifier (member name or array index)
  10575. // - followed by an optional right bracket (found when array index)
  10576. // - followed by an optional left bracket or dot (type of subscript)
  10577. //
  10578. // Note: These portions can be read in a non-overlapping fashion and
  10579. // allow straightforward parsing of the hierarchy that WebGL encodes
  10580. // in the uniform names.
  10581. function addUniform( container, uniformObject ) {
  10582. container.seq.push( uniformObject );
  10583. container.map[ uniformObject.id ] = uniformObject;
  10584. }
  10585. function parseUniform( activeInfo, addr, container ) {
  10586. const path = activeInfo.name,
  10587. pathLength = path.length;
  10588. // reset RegExp object, because of the early exit of a previous run
  10589. RePathPart.lastIndex = 0;
  10590. while ( true ) {
  10591. const match = RePathPart.exec( path ),
  10592. matchEnd = RePathPart.lastIndex;
  10593. let id = match[ 1 ];
  10594. const idIsIndex = match[ 2 ] === ']',
  10595. subscript = match[ 3 ];
  10596. if ( idIsIndex ) id = id | 0; // convert to integer
  10597. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10598. // bare name or "pure" bottom-level array "[0]" suffix
  10599. addUniform( container, subscript === undefined ?
  10600. new SingleUniform( id, activeInfo, addr ) :
  10601. new PureArrayUniform( id, activeInfo, addr ) );
  10602. break;
  10603. } else {
  10604. // step into inner node / create it in case it doesn't exist
  10605. const map = container.map;
  10606. let next = map[ id ];
  10607. if ( next === undefined ) {
  10608. next = new StructuredUniform( id );
  10609. addUniform( container, next );
  10610. }
  10611. container = next;
  10612. }
  10613. }
  10614. }
  10615. // Root Container
  10616. function WebGLUniforms( gl, program ) {
  10617. this.seq = [];
  10618. this.map = {};
  10619. const n = gl.getProgramParameter( program, 35718 );
  10620. for ( let i = 0; i < n; ++ i ) {
  10621. const info = gl.getActiveUniform( program, i ),
  10622. addr = gl.getUniformLocation( program, info.name );
  10623. parseUniform( info, addr, this );
  10624. }
  10625. }
  10626. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10627. const u = this.map[ name ];
  10628. if ( u !== undefined ) u.setValue( gl, value, textures );
  10629. };
  10630. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10631. const v = object[ name ];
  10632. if ( v !== undefined ) this.setValue( gl, name, v );
  10633. };
  10634. // Static interface
  10635. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10636. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10637. const u = seq[ i ],
  10638. v = values[ u.id ];
  10639. if ( v.needsUpdate !== false ) {
  10640. // note: always updating when .needsUpdate is undefined
  10641. u.setValue( gl, v.value, textures );
  10642. }
  10643. }
  10644. };
  10645. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10646. const r = [];
  10647. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10648. const u = seq[ i ];
  10649. if ( u.id in values ) r.push( u );
  10650. }
  10651. return r;
  10652. };
  10653. function WebGLShader( gl, type, string ) {
  10654. const shader = gl.createShader( type );
  10655. gl.shaderSource( shader, string );
  10656. gl.compileShader( shader );
  10657. return shader;
  10658. }
  10659. let programIdCount = 0;
  10660. function addLineNumbers( string ) {
  10661. const lines = string.split( '\n' );
  10662. for ( let i = 0; i < lines.length; i ++ ) {
  10663. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10664. }
  10665. return lines.join( '\n' );
  10666. }
  10667. function getEncodingComponents( encoding ) {
  10668. switch ( encoding ) {
  10669. case LinearEncoding:
  10670. return [ 'Linear', '( value )' ];
  10671. case sRGBEncoding:
  10672. return [ 'sRGB', '( value )' ];
  10673. case RGBEEncoding:
  10674. return [ 'RGBE', '( value )' ];
  10675. case RGBM7Encoding:
  10676. return [ 'RGBM', '( value, 7.0 )' ];
  10677. case RGBM16Encoding:
  10678. return [ 'RGBM', '( value, 16.0 )' ];
  10679. case RGBDEncoding:
  10680. return [ 'RGBD', '( value, 256.0 )' ];
  10681. case GammaEncoding:
  10682. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  10683. case LogLuvEncoding:
  10684. return [ 'LogLuv', '( value )' ];
  10685. default:
  10686. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10687. return [ 'Linear', '( value )' ];
  10688. }
  10689. }
  10690. function getShaderErrors( gl, shader, type ) {
  10691. const status = gl.getShaderParameter( shader, 35713 );
  10692. const errors = gl.getShaderInfoLog( shader ).trim();
  10693. if ( status && errors === '' ) return '';
  10694. // --enable-privileged-webgl-extension
  10695. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10696. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers( gl.getShaderSource( shader ) );
  10697. }
  10698. function getTexelDecodingFunction( functionName, encoding ) {
  10699. const components = getEncodingComponents( encoding );
  10700. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10701. }
  10702. function getTexelEncodingFunction( functionName, encoding ) {
  10703. const components = getEncodingComponents( encoding );
  10704. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10705. }
  10706. function getToneMappingFunction( functionName, toneMapping ) {
  10707. let toneMappingName;
  10708. switch ( toneMapping ) {
  10709. case LinearToneMapping:
  10710. toneMappingName = 'Linear';
  10711. break;
  10712. case ReinhardToneMapping:
  10713. toneMappingName = 'Reinhard';
  10714. break;
  10715. case CineonToneMapping:
  10716. toneMappingName = 'OptimizedCineon';
  10717. break;
  10718. case ACESFilmicToneMapping:
  10719. toneMappingName = 'ACESFilmic';
  10720. break;
  10721. case CustomToneMapping:
  10722. toneMappingName = 'Custom';
  10723. break;
  10724. default:
  10725. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10726. toneMappingName = 'Linear';
  10727. }
  10728. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10729. }
  10730. function generateExtensions( parameters ) {
  10731. const chunks = [
  10732. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10733. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10734. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10735. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10736. ];
  10737. return chunks.filter( filterEmptyLine ).join( '\n' );
  10738. }
  10739. function generateDefines( defines ) {
  10740. const chunks = [];
  10741. for ( const name in defines ) {
  10742. const value = defines[ name ];
  10743. if ( value === false ) continue;
  10744. chunks.push( '#define ' + name + ' ' + value );
  10745. }
  10746. return chunks.join( '\n' );
  10747. }
  10748. function fetchAttributeLocations( gl, program ) {
  10749. const attributes = {};
  10750. const n = gl.getProgramParameter( program, 35721 );
  10751. for ( let i = 0; i < n; i ++ ) {
  10752. const info = gl.getActiveAttrib( program, i );
  10753. const name = info.name;
  10754. let locationSize = 1;
  10755. if ( info.type === 35674 ) locationSize = 2;
  10756. if ( info.type === 35675 ) locationSize = 3;
  10757. if ( info.type === 35676 ) locationSize = 4;
  10758. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10759. attributes[ name ] = {
  10760. type: info.type,
  10761. location: gl.getAttribLocation( program, name ),
  10762. locationSize: locationSize
  10763. };
  10764. }
  10765. return attributes;
  10766. }
  10767. function filterEmptyLine( string ) {
  10768. return string !== '';
  10769. }
  10770. function replaceLightNums( string, parameters ) {
  10771. return string
  10772. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10773. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10774. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10775. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10776. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10777. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10778. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10779. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10780. }
  10781. function replaceClippingPlaneNums( string, parameters ) {
  10782. return string
  10783. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10784. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10785. }
  10786. // Resolve Includes
  10787. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10788. function resolveIncludes( string ) {
  10789. return string.replace( includePattern, includeReplacer );
  10790. }
  10791. function includeReplacer( match, include ) {
  10792. const string = ShaderChunk[ include ];
  10793. if ( string === undefined ) {
  10794. throw new Error( 'Can not resolve #include <' + include + '>' );
  10795. }
  10796. return resolveIncludes( string );
  10797. }
  10798. // Unroll Loops
  10799. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10800. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  10801. function unrollLoops( string ) {
  10802. return string
  10803. .replace( unrollLoopPattern, loopReplacer )
  10804. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10805. }
  10806. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10807. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10808. return loopReplacer( match, start, end, snippet );
  10809. }
  10810. function loopReplacer( match, start, end, snippet ) {
  10811. let string = '';
  10812. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10813. string += snippet
  10814. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10815. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10816. }
  10817. return string;
  10818. }
  10819. //
  10820. function generatePrecision( parameters ) {
  10821. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10822. if ( parameters.precision === 'highp' ) {
  10823. precisionstring += '\n#define HIGH_PRECISION';
  10824. } else if ( parameters.precision === 'mediump' ) {
  10825. precisionstring += '\n#define MEDIUM_PRECISION';
  10826. } else if ( parameters.precision === 'lowp' ) {
  10827. precisionstring += '\n#define LOW_PRECISION';
  10828. }
  10829. return precisionstring;
  10830. }
  10831. function generateShadowMapTypeDefine( parameters ) {
  10832. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10833. if ( parameters.shadowMapType === PCFShadowMap ) {
  10834. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10835. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10836. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10837. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10838. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10839. }
  10840. return shadowMapTypeDefine;
  10841. }
  10842. function generateEnvMapTypeDefine( parameters ) {
  10843. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10844. if ( parameters.envMap ) {
  10845. switch ( parameters.envMapMode ) {
  10846. case CubeReflectionMapping:
  10847. case CubeRefractionMapping:
  10848. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10849. break;
  10850. case CubeUVReflectionMapping:
  10851. case CubeUVRefractionMapping:
  10852. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10853. break;
  10854. }
  10855. }
  10856. return envMapTypeDefine;
  10857. }
  10858. function generateEnvMapModeDefine( parameters ) {
  10859. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10860. if ( parameters.envMap ) {
  10861. switch ( parameters.envMapMode ) {
  10862. case CubeRefractionMapping:
  10863. case CubeUVRefractionMapping:
  10864. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10865. break;
  10866. }
  10867. }
  10868. return envMapModeDefine;
  10869. }
  10870. function generateEnvMapBlendingDefine( parameters ) {
  10871. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10872. if ( parameters.envMap ) {
  10873. switch ( parameters.combine ) {
  10874. case MultiplyOperation:
  10875. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10876. break;
  10877. case MixOperation:
  10878. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10879. break;
  10880. case AddOperation:
  10881. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10882. break;
  10883. }
  10884. }
  10885. return envMapBlendingDefine;
  10886. }
  10887. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10888. // TODO Send this event to Three.js DevTools
  10889. // console.log( 'WebGLProgram', cacheKey );
  10890. const gl = renderer.getContext();
  10891. const defines = parameters.defines;
  10892. let vertexShader = parameters.vertexShader;
  10893. let fragmentShader = parameters.fragmentShader;
  10894. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10895. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10896. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10897. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10898. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10899. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10900. const customDefines = generateDefines( defines );
  10901. const program = gl.createProgram();
  10902. let prefixVertex, prefixFragment;
  10903. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10904. if ( parameters.isRawShaderMaterial ) {
  10905. prefixVertex = [
  10906. customDefines
  10907. ].filter( filterEmptyLine ).join( '\n' );
  10908. if ( prefixVertex.length > 0 ) {
  10909. prefixVertex += '\n';
  10910. }
  10911. prefixFragment = [
  10912. customExtensions,
  10913. customDefines
  10914. ].filter( filterEmptyLine ).join( '\n' );
  10915. if ( prefixFragment.length > 0 ) {
  10916. prefixFragment += '\n';
  10917. }
  10918. } else {
  10919. prefixVertex = [
  10920. generatePrecision( parameters ),
  10921. '#define SHADER_NAME ' + parameters.shaderName,
  10922. customDefines,
  10923. parameters.instancing ? '#define USE_INSTANCING' : '',
  10924. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10925. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10926. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10927. '#define MAX_BONES ' + parameters.maxBones,
  10928. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10929. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10930. parameters.map ? '#define USE_MAP' : '',
  10931. parameters.envMap ? '#define USE_ENVMAP' : '',
  10932. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10933. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10934. parameters.aoMap ? '#define USE_AOMAP' : '',
  10935. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10936. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10937. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10938. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10939. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10940. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10941. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10942. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10943. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10944. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10945. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  10946. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  10947. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10948. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10949. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10950. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  10951. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10952. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  10953. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10954. parameters.vertexColors ? '#define USE_COLOR' : '',
  10955. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  10956. parameters.vertexUvs ? '#define USE_UV' : '',
  10957. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10958. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10959. parameters.skinning ? '#define USE_SKINNING' : '',
  10960. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10961. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10962. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10963. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10964. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10965. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10966. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10967. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10968. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10969. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10970. 'uniform mat4 modelMatrix;',
  10971. 'uniform mat4 modelViewMatrix;',
  10972. 'uniform mat4 projectionMatrix;',
  10973. 'uniform mat4 viewMatrix;',
  10974. 'uniform mat3 normalMatrix;',
  10975. 'uniform vec3 cameraPosition;',
  10976. 'uniform bool isOrthographic;',
  10977. '#ifdef USE_INSTANCING',
  10978. ' attribute mat4 instanceMatrix;',
  10979. '#endif',
  10980. '#ifdef USE_INSTANCING_COLOR',
  10981. ' attribute vec3 instanceColor;',
  10982. '#endif',
  10983. 'attribute vec3 position;',
  10984. 'attribute vec3 normal;',
  10985. 'attribute vec2 uv;',
  10986. '#ifdef USE_TANGENT',
  10987. ' attribute vec4 tangent;',
  10988. '#endif',
  10989. '#if defined( USE_COLOR_ALPHA )',
  10990. ' attribute vec4 color;',
  10991. '#elif defined( USE_COLOR )',
  10992. ' attribute vec3 color;',
  10993. '#endif',
  10994. '#ifdef USE_MORPHTARGETS',
  10995. ' attribute vec3 morphTarget0;',
  10996. ' attribute vec3 morphTarget1;',
  10997. ' attribute vec3 morphTarget2;',
  10998. ' attribute vec3 morphTarget3;',
  10999. ' #ifdef USE_MORPHNORMALS',
  11000. ' attribute vec3 morphNormal0;',
  11001. ' attribute vec3 morphNormal1;',
  11002. ' attribute vec3 morphNormal2;',
  11003. ' attribute vec3 morphNormal3;',
  11004. ' #else',
  11005. ' attribute vec3 morphTarget4;',
  11006. ' attribute vec3 morphTarget5;',
  11007. ' attribute vec3 morphTarget6;',
  11008. ' attribute vec3 morphTarget7;',
  11009. ' #endif',
  11010. '#endif',
  11011. '#ifdef USE_SKINNING',
  11012. ' attribute vec4 skinIndex;',
  11013. ' attribute vec4 skinWeight;',
  11014. '#endif',
  11015. '\n'
  11016. ].filter( filterEmptyLine ).join( '\n' );
  11017. prefixFragment = [
  11018. customExtensions,
  11019. generatePrecision( parameters ),
  11020. '#define SHADER_NAME ' + parameters.shaderName,
  11021. customDefines,
  11022. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11023. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11024. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11025. parameters.map ? '#define USE_MAP' : '',
  11026. parameters.matcap ? '#define USE_MATCAP' : '',
  11027. parameters.envMap ? '#define USE_ENVMAP' : '',
  11028. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11029. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11030. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11031. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11032. parameters.aoMap ? '#define USE_AOMAP' : '',
  11033. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11034. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11035. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11036. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11037. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11038. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11039. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11040. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11041. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11042. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11043. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11044. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  11045. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11046. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11047. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11048. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11049. parameters.sheenTint ? '#define USE_SHEEN' : '',
  11050. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11051. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11052. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11053. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11054. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11055. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11056. parameters.vertexUvs ? '#define USE_UV' : '',
  11057. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11058. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11059. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11060. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11061. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11062. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11063. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11064. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11065. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11066. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11067. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11068. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11069. 'uniform mat4 viewMatrix;',
  11070. 'uniform vec3 cameraPosition;',
  11071. 'uniform bool isOrthographic;',
  11072. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11073. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11074. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11075. parameters.dithering ? '#define DITHERING' : '',
  11076. parameters.format === RGBFormat ? '#define OPAQUE' : '',
  11077. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11078. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  11079. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  11080. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  11081. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  11082. parameters.specularTintMap ? getTexelDecodingFunction( 'specularTintMapTexelToLinear', parameters.specularTintMapEncoding ) : '',
  11083. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  11084. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11085. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11086. '\n'
  11087. ].filter( filterEmptyLine ).join( '\n' );
  11088. }
  11089. vertexShader = resolveIncludes( vertexShader );
  11090. vertexShader = replaceLightNums( vertexShader, parameters );
  11091. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11092. fragmentShader = resolveIncludes( fragmentShader );
  11093. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11094. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11095. vertexShader = unrollLoops( vertexShader );
  11096. fragmentShader = unrollLoops( fragmentShader );
  11097. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11098. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11099. versionString = '#version 300 es\n';
  11100. prefixVertex = [
  11101. '#define attribute in',
  11102. '#define varying out',
  11103. '#define texture2D texture'
  11104. ].join( '\n' ) + '\n' + prefixVertex;
  11105. prefixFragment = [
  11106. '#define varying in',
  11107. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  11108. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11109. '#define gl_FragDepthEXT gl_FragDepth',
  11110. '#define texture2D texture',
  11111. '#define textureCube texture',
  11112. '#define texture2DProj textureProj',
  11113. '#define texture2DLodEXT textureLod',
  11114. '#define texture2DProjLodEXT textureProjLod',
  11115. '#define textureCubeLodEXT textureLod',
  11116. '#define texture2DGradEXT textureGrad',
  11117. '#define texture2DProjGradEXT textureProjGrad',
  11118. '#define textureCubeGradEXT textureGrad'
  11119. ].join( '\n' ) + '\n' + prefixFragment;
  11120. }
  11121. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11122. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11123. // console.log( '*VERTEX*', vertexGlsl );
  11124. // console.log( '*FRAGMENT*', fragmentGlsl );
  11125. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11126. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11127. gl.attachShader( program, glVertexShader );
  11128. gl.attachShader( program, glFragmentShader );
  11129. // Force a particular attribute to index 0.
  11130. if ( parameters.index0AttributeName !== undefined ) {
  11131. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11132. } else if ( parameters.morphTargets === true ) {
  11133. // programs with morphTargets displace position out of attribute 0
  11134. gl.bindAttribLocation( program, 0, 'position' );
  11135. }
  11136. gl.linkProgram( program );
  11137. // check for link errors
  11138. if ( renderer.debug.checkShaderErrors ) {
  11139. const programLog = gl.getProgramInfoLog( program ).trim();
  11140. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11141. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11142. let runnable = true;
  11143. let haveDiagnostics = true;
  11144. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11145. runnable = false;
  11146. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11147. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11148. console.error(
  11149. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11150. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11151. 'Program Info Log: ' + programLog + '\n' +
  11152. vertexErrors + '\n' +
  11153. fragmentErrors
  11154. );
  11155. } else if ( programLog !== '' ) {
  11156. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11157. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11158. haveDiagnostics = false;
  11159. }
  11160. if ( haveDiagnostics ) {
  11161. this.diagnostics = {
  11162. runnable: runnable,
  11163. programLog: programLog,
  11164. vertexShader: {
  11165. log: vertexLog,
  11166. prefix: prefixVertex
  11167. },
  11168. fragmentShader: {
  11169. log: fragmentLog,
  11170. prefix: prefixFragment
  11171. }
  11172. };
  11173. }
  11174. }
  11175. // Clean up
  11176. // Crashes in iOS9 and iOS10. #18402
  11177. // gl.detachShader( program, glVertexShader );
  11178. // gl.detachShader( program, glFragmentShader );
  11179. gl.deleteShader( glVertexShader );
  11180. gl.deleteShader( glFragmentShader );
  11181. // set up caching for uniform locations
  11182. let cachedUniforms;
  11183. this.getUniforms = function () {
  11184. if ( cachedUniforms === undefined ) {
  11185. cachedUniforms = new WebGLUniforms( gl, program );
  11186. }
  11187. return cachedUniforms;
  11188. };
  11189. // set up caching for attribute locations
  11190. let cachedAttributes;
  11191. this.getAttributes = function () {
  11192. if ( cachedAttributes === undefined ) {
  11193. cachedAttributes = fetchAttributeLocations( gl, program );
  11194. }
  11195. return cachedAttributes;
  11196. };
  11197. // free resource
  11198. this.destroy = function () {
  11199. bindingStates.releaseStatesOfProgram( this );
  11200. gl.deleteProgram( program );
  11201. this.program = undefined;
  11202. };
  11203. //
  11204. this.name = parameters.shaderName;
  11205. this.id = programIdCount ++;
  11206. this.cacheKey = cacheKey;
  11207. this.usedTimes = 1;
  11208. this.program = program;
  11209. this.vertexShader = glVertexShader;
  11210. this.fragmentShader = glFragmentShader;
  11211. return this;
  11212. }
  11213. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11214. const programs = [];
  11215. const isWebGL2 = capabilities.isWebGL2;
  11216. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11217. const floatVertexTextures = capabilities.floatVertexTextures;
  11218. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11219. const vertexTextures = capabilities.vertexTextures;
  11220. let precision = capabilities.precision;
  11221. const shaderIDs = {
  11222. MeshDepthMaterial: 'depth',
  11223. MeshDistanceMaterial: 'distanceRGBA',
  11224. MeshNormalMaterial: 'normal',
  11225. MeshBasicMaterial: 'basic',
  11226. MeshLambertMaterial: 'lambert',
  11227. MeshPhongMaterial: 'phong',
  11228. MeshToonMaterial: 'toon',
  11229. MeshStandardMaterial: 'physical',
  11230. MeshPhysicalMaterial: 'physical',
  11231. MeshMatcapMaterial: 'matcap',
  11232. LineBasicMaterial: 'basic',
  11233. LineDashedMaterial: 'dashed',
  11234. PointsMaterial: 'points',
  11235. ShadowMaterial: 'shadow',
  11236. SpriteMaterial: 'sprite'
  11237. };
  11238. const parameterNames = [
  11239. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  11240. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  11241. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap',
  11242. 'objectSpaceNormalMap', 'tangentSpaceNormalMap',
  11243. 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap',
  11244. 'displacementMap',
  11245. 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap',
  11246. 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  11247. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  11248. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha',
  11249. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  11250. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  11251. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  11252. 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format',
  11253. 'sheenTint', 'transmission', 'transmissionMap', 'thicknessMap'
  11254. ];
  11255. function getMaxBones( object ) {
  11256. const skeleton = object.skeleton;
  11257. const bones = skeleton.bones;
  11258. if ( floatVertexTextures ) {
  11259. return 1024;
  11260. } else {
  11261. // default for when object is not specified
  11262. // ( for example when prebuilding shader to be used with multiple objects )
  11263. //
  11264. // - leave some extra space for other uniforms
  11265. // - limit here is ANGLE's 254 max uniform vectors
  11266. // (up to 54 should be safe)
  11267. const nVertexUniforms = maxVertexUniforms;
  11268. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11269. const maxBones = Math.min( nVertexMatrices, bones.length );
  11270. if ( maxBones < bones.length ) {
  11271. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11272. return 0;
  11273. }
  11274. return maxBones;
  11275. }
  11276. }
  11277. function getTextureEncodingFromMap( map ) {
  11278. let encoding;
  11279. if ( map && map.isTexture ) {
  11280. encoding = map.encoding;
  11281. } else if ( map && map.isWebGLRenderTarget ) {
  11282. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  11283. encoding = map.texture.encoding;
  11284. } else {
  11285. encoding = LinearEncoding;
  11286. }
  11287. return encoding;
  11288. }
  11289. function getParameters( material, lights, shadows, scene, object ) {
  11290. const fog = scene.fog;
  11291. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11292. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11293. const shaderID = shaderIDs[ material.type ];
  11294. // heuristics to create shader parameters according to lights in the scene
  11295. // (not to blow over maxLights budget)
  11296. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11297. if ( material.precision !== null ) {
  11298. precision = capabilities.getMaxPrecision( material.precision );
  11299. if ( precision !== material.precision ) {
  11300. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11301. }
  11302. }
  11303. let vertexShader, fragmentShader;
  11304. if ( shaderID ) {
  11305. const shader = ShaderLib[ shaderID ];
  11306. vertexShader = shader.vertexShader;
  11307. fragmentShader = shader.fragmentShader;
  11308. } else {
  11309. vertexShader = material.vertexShader;
  11310. fragmentShader = material.fragmentShader;
  11311. }
  11312. const currentRenderTarget = renderer.getRenderTarget();
  11313. const useAlphaTest = material.alphaTest > 0;
  11314. const useClearcoat = material.clearcoat > 0;
  11315. const parameters = {
  11316. isWebGL2: isWebGL2,
  11317. shaderID: shaderID,
  11318. shaderName: material.type,
  11319. vertexShader: vertexShader,
  11320. fragmentShader: fragmentShader,
  11321. defines: material.defines,
  11322. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11323. glslVersion: material.glslVersion,
  11324. precision: precision,
  11325. instancing: object.isInstancedMesh === true,
  11326. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11327. supportsVertexTextures: vertexTextures,
  11328. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  11329. map: !! material.map,
  11330. mapEncoding: getTextureEncodingFromMap( material.map ),
  11331. matcap: !! material.matcap,
  11332. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  11333. envMap: !! envMap,
  11334. envMapMode: envMap && envMap.mapping,
  11335. envMapEncoding: getTextureEncodingFromMap( envMap ),
  11336. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11337. lightMap: !! material.lightMap,
  11338. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  11339. aoMap: !! material.aoMap,
  11340. emissiveMap: !! material.emissiveMap,
  11341. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  11342. bumpMap: !! material.bumpMap,
  11343. normalMap: !! material.normalMap,
  11344. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11345. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11346. clearcoat: useClearcoat,
  11347. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11348. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11349. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11350. displacementMap: !! material.displacementMap,
  11351. roughnessMap: !! material.roughnessMap,
  11352. metalnessMap: !! material.metalnessMap,
  11353. specularMap: !! material.specularMap,
  11354. specularIntensityMap: !! material.specularIntensityMap,
  11355. specularTintMap: !! material.specularTintMap,
  11356. specularTintMapEncoding: getTextureEncodingFromMap( material.specularTintMap ),
  11357. alphaMap: !! material.alphaMap,
  11358. alphaTest: useAlphaTest,
  11359. gradientMap: !! material.gradientMap,
  11360. sheenTint: ( !! material.sheenTint && ( material.sheenTint.r > 0 || material.sheenTint.g > 0 || material.sheenTint.b > 0 ) ),
  11361. transmission: material.transmission > 0,
  11362. transmissionMap: !! material.transmissionMap,
  11363. thicknessMap: !! material.thicknessMap,
  11364. combine: material.combine,
  11365. vertexTangents: ( !! material.normalMap && !! object.geometry && !! object.geometry.attributes.tangent ),
  11366. vertexColors: material.vertexColors,
  11367. vertexAlphas: material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11368. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularTintMap,
  11369. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularTintMap ) && !! material.displacementMap,
  11370. fog: !! fog,
  11371. useFog: material.fog,
  11372. fogExp2: ( fog && fog.isFogExp2 ),
  11373. flatShading: !! material.flatShading,
  11374. sizeAttenuation: material.sizeAttenuation,
  11375. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11376. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11377. maxBones: maxBones,
  11378. useVertexTexture: floatVertexTextures,
  11379. morphTargets: !! object.geometry && !! object.geometry.morphAttributes.position,
  11380. morphNormals: !! object.geometry && !! object.geometry.morphAttributes.normal,
  11381. numDirLights: lights.directional.length,
  11382. numPointLights: lights.point.length,
  11383. numSpotLights: lights.spot.length,
  11384. numRectAreaLights: lights.rectArea.length,
  11385. numHemiLights: lights.hemi.length,
  11386. numDirLightShadows: lights.directionalShadowMap.length,
  11387. numPointLightShadows: lights.pointShadowMap.length,
  11388. numSpotLightShadows: lights.spotShadowMap.length,
  11389. numClippingPlanes: clipping.numPlanes,
  11390. numClipIntersection: clipping.numIntersection,
  11391. format: material.format,
  11392. dithering: material.dithering,
  11393. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11394. shadowMapType: renderer.shadowMap.type,
  11395. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11396. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11397. premultipliedAlpha: material.premultipliedAlpha,
  11398. doubleSided: material.side === DoubleSide,
  11399. flipSided: material.side === BackSide,
  11400. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11401. index0AttributeName: material.index0AttributeName,
  11402. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11403. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11404. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11405. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11406. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11407. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11408. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11409. customProgramCacheKey: material.customProgramCacheKey()
  11410. };
  11411. return parameters;
  11412. }
  11413. function getProgramCacheKey( parameters ) {
  11414. const array = [];
  11415. if ( parameters.shaderID ) {
  11416. array.push( parameters.shaderID );
  11417. } else {
  11418. array.push( parameters.fragmentShader );
  11419. array.push( parameters.vertexShader );
  11420. }
  11421. if ( parameters.defines !== undefined ) {
  11422. for ( const name in parameters.defines ) {
  11423. array.push( name );
  11424. array.push( parameters.defines[ name ] );
  11425. }
  11426. }
  11427. if ( parameters.isRawShaderMaterial === false ) {
  11428. for ( let i = 0; i < parameterNames.length; i ++ ) {
  11429. array.push( parameters[ parameterNames[ i ] ] );
  11430. }
  11431. array.push( renderer.outputEncoding );
  11432. array.push( renderer.gammaFactor );
  11433. }
  11434. array.push( parameters.customProgramCacheKey );
  11435. return array.join();
  11436. }
  11437. function getUniforms( material ) {
  11438. const shaderID = shaderIDs[ material.type ];
  11439. let uniforms;
  11440. if ( shaderID ) {
  11441. const shader = ShaderLib[ shaderID ];
  11442. uniforms = UniformsUtils.clone( shader.uniforms );
  11443. } else {
  11444. uniforms = material.uniforms;
  11445. }
  11446. return uniforms;
  11447. }
  11448. function acquireProgram( parameters, cacheKey ) {
  11449. let program;
  11450. // Check if code has been already compiled
  11451. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11452. const preexistingProgram = programs[ p ];
  11453. if ( preexistingProgram.cacheKey === cacheKey ) {
  11454. program = preexistingProgram;
  11455. ++ program.usedTimes;
  11456. break;
  11457. }
  11458. }
  11459. if ( program === undefined ) {
  11460. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11461. programs.push( program );
  11462. }
  11463. return program;
  11464. }
  11465. function releaseProgram( program ) {
  11466. if ( -- program.usedTimes === 0 ) {
  11467. // Remove from unordered set
  11468. const i = programs.indexOf( program );
  11469. programs[ i ] = programs[ programs.length - 1 ];
  11470. programs.pop();
  11471. // Free WebGL resources
  11472. program.destroy();
  11473. }
  11474. }
  11475. return {
  11476. getParameters: getParameters,
  11477. getProgramCacheKey: getProgramCacheKey,
  11478. getUniforms: getUniforms,
  11479. acquireProgram: acquireProgram,
  11480. releaseProgram: releaseProgram,
  11481. // Exposed for resource monitoring & error feedback via renderer.info:
  11482. programs: programs
  11483. };
  11484. }
  11485. function WebGLProperties() {
  11486. let properties = new WeakMap();
  11487. function get( object ) {
  11488. let map = properties.get( object );
  11489. if ( map === undefined ) {
  11490. map = {};
  11491. properties.set( object, map );
  11492. }
  11493. return map;
  11494. }
  11495. function remove( object ) {
  11496. properties.delete( object );
  11497. }
  11498. function update( object, key, value ) {
  11499. properties.get( object )[ key ] = value;
  11500. }
  11501. function dispose() {
  11502. properties = new WeakMap();
  11503. }
  11504. return {
  11505. get: get,
  11506. remove: remove,
  11507. update: update,
  11508. dispose: dispose
  11509. };
  11510. }
  11511. function painterSortStable( a, b ) {
  11512. if ( a.groupOrder !== b.groupOrder ) {
  11513. return a.groupOrder - b.groupOrder;
  11514. } else if ( a.renderOrder !== b.renderOrder ) {
  11515. return a.renderOrder - b.renderOrder;
  11516. } else if ( a.program !== b.program ) {
  11517. return a.program.id - b.program.id;
  11518. } else if ( a.material.id !== b.material.id ) {
  11519. return a.material.id - b.material.id;
  11520. } else if ( a.z !== b.z ) {
  11521. return a.z - b.z;
  11522. } else {
  11523. return a.id - b.id;
  11524. }
  11525. }
  11526. function reversePainterSortStable( a, b ) {
  11527. if ( a.groupOrder !== b.groupOrder ) {
  11528. return a.groupOrder - b.groupOrder;
  11529. } else if ( a.renderOrder !== b.renderOrder ) {
  11530. return a.renderOrder - b.renderOrder;
  11531. } else if ( a.z !== b.z ) {
  11532. return b.z - a.z;
  11533. } else {
  11534. return a.id - b.id;
  11535. }
  11536. }
  11537. function WebGLRenderList( properties ) {
  11538. const renderItems = [];
  11539. let renderItemsIndex = 0;
  11540. const opaque = [];
  11541. const transmissive = [];
  11542. const transparent = [];
  11543. const defaultProgram = { id: - 1 };
  11544. function init() {
  11545. renderItemsIndex = 0;
  11546. opaque.length = 0;
  11547. transmissive.length = 0;
  11548. transparent.length = 0;
  11549. }
  11550. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11551. let renderItem = renderItems[ renderItemsIndex ];
  11552. const materialProperties = properties.get( material );
  11553. if ( renderItem === undefined ) {
  11554. renderItem = {
  11555. id: object.id,
  11556. object: object,
  11557. geometry: geometry,
  11558. material: material,
  11559. program: materialProperties.program || defaultProgram,
  11560. groupOrder: groupOrder,
  11561. renderOrder: object.renderOrder,
  11562. z: z,
  11563. group: group
  11564. };
  11565. renderItems[ renderItemsIndex ] = renderItem;
  11566. } else {
  11567. renderItem.id = object.id;
  11568. renderItem.object = object;
  11569. renderItem.geometry = geometry;
  11570. renderItem.material = material;
  11571. renderItem.program = materialProperties.program || defaultProgram;
  11572. renderItem.groupOrder = groupOrder;
  11573. renderItem.renderOrder = object.renderOrder;
  11574. renderItem.z = z;
  11575. renderItem.group = group;
  11576. }
  11577. renderItemsIndex ++;
  11578. return renderItem;
  11579. }
  11580. function push( object, geometry, material, groupOrder, z, group ) {
  11581. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11582. if ( material.transmission > 0.0 ) {
  11583. transmissive.push( renderItem );
  11584. } else if ( material.transparent === true ) {
  11585. transparent.push( renderItem );
  11586. } else {
  11587. opaque.push( renderItem );
  11588. }
  11589. }
  11590. function unshift( object, geometry, material, groupOrder, z, group ) {
  11591. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11592. if ( material.transmission > 0.0 ) {
  11593. transmissive.unshift( renderItem );
  11594. } else if ( material.transparent === true ) {
  11595. transparent.unshift( renderItem );
  11596. } else {
  11597. opaque.unshift( renderItem );
  11598. }
  11599. }
  11600. function sort( customOpaqueSort, customTransparentSort ) {
  11601. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11602. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  11603. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11604. }
  11605. function finish() {
  11606. // Clear references from inactive renderItems in the list
  11607. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11608. const renderItem = renderItems[ i ];
  11609. if ( renderItem.id === null ) break;
  11610. renderItem.id = null;
  11611. renderItem.object = null;
  11612. renderItem.geometry = null;
  11613. renderItem.material = null;
  11614. renderItem.program = null;
  11615. renderItem.group = null;
  11616. }
  11617. }
  11618. return {
  11619. opaque: opaque,
  11620. transmissive: transmissive,
  11621. transparent: transparent,
  11622. init: init,
  11623. push: push,
  11624. unshift: unshift,
  11625. finish: finish,
  11626. sort: sort
  11627. };
  11628. }
  11629. function WebGLRenderLists( properties ) {
  11630. let lists = new WeakMap();
  11631. function get( scene, renderCallDepth ) {
  11632. let list;
  11633. if ( lists.has( scene ) === false ) {
  11634. list = new WebGLRenderList( properties );
  11635. lists.set( scene, [ list ] );
  11636. } else {
  11637. if ( renderCallDepth >= lists.get( scene ).length ) {
  11638. list = new WebGLRenderList( properties );
  11639. lists.get( scene ).push( list );
  11640. } else {
  11641. list = lists.get( scene )[ renderCallDepth ];
  11642. }
  11643. }
  11644. return list;
  11645. }
  11646. function dispose() {
  11647. lists = new WeakMap();
  11648. }
  11649. return {
  11650. get: get,
  11651. dispose: dispose
  11652. };
  11653. }
  11654. function UniformsCache() {
  11655. const lights = {};
  11656. return {
  11657. get: function ( light ) {
  11658. if ( lights[ light.id ] !== undefined ) {
  11659. return lights[ light.id ];
  11660. }
  11661. let uniforms;
  11662. switch ( light.type ) {
  11663. case 'DirectionalLight':
  11664. uniforms = {
  11665. direction: new Vector3(),
  11666. color: new Color()
  11667. };
  11668. break;
  11669. case 'SpotLight':
  11670. uniforms = {
  11671. position: new Vector3(),
  11672. direction: new Vector3(),
  11673. color: new Color(),
  11674. distance: 0,
  11675. coneCos: 0,
  11676. penumbraCos: 0,
  11677. decay: 0
  11678. };
  11679. break;
  11680. case 'PointLight':
  11681. uniforms = {
  11682. position: new Vector3(),
  11683. color: new Color(),
  11684. distance: 0,
  11685. decay: 0
  11686. };
  11687. break;
  11688. case 'HemisphereLight':
  11689. uniforms = {
  11690. direction: new Vector3(),
  11691. skyColor: new Color(),
  11692. groundColor: new Color()
  11693. };
  11694. break;
  11695. case 'RectAreaLight':
  11696. uniforms = {
  11697. color: new Color(),
  11698. position: new Vector3(),
  11699. halfWidth: new Vector3(),
  11700. halfHeight: new Vector3()
  11701. };
  11702. break;
  11703. }
  11704. lights[ light.id ] = uniforms;
  11705. return uniforms;
  11706. }
  11707. };
  11708. }
  11709. function ShadowUniformsCache() {
  11710. const lights = {};
  11711. return {
  11712. get: function ( light ) {
  11713. if ( lights[ light.id ] !== undefined ) {
  11714. return lights[ light.id ];
  11715. }
  11716. let uniforms;
  11717. switch ( light.type ) {
  11718. case 'DirectionalLight':
  11719. uniforms = {
  11720. shadowBias: 0,
  11721. shadowNormalBias: 0,
  11722. shadowRadius: 1,
  11723. shadowMapSize: new Vector2()
  11724. };
  11725. break;
  11726. case 'SpotLight':
  11727. uniforms = {
  11728. shadowBias: 0,
  11729. shadowNormalBias: 0,
  11730. shadowRadius: 1,
  11731. shadowMapSize: new Vector2()
  11732. };
  11733. break;
  11734. case 'PointLight':
  11735. uniforms = {
  11736. shadowBias: 0,
  11737. shadowNormalBias: 0,
  11738. shadowRadius: 1,
  11739. shadowMapSize: new Vector2(),
  11740. shadowCameraNear: 1,
  11741. shadowCameraFar: 1000
  11742. };
  11743. break;
  11744. // TODO (abelnation): set RectAreaLight shadow uniforms
  11745. }
  11746. lights[ light.id ] = uniforms;
  11747. return uniforms;
  11748. }
  11749. };
  11750. }
  11751. let nextVersion = 0;
  11752. function shadowCastingLightsFirst( lightA, lightB ) {
  11753. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11754. }
  11755. function WebGLLights( extensions, capabilities ) {
  11756. const cache = new UniformsCache();
  11757. const shadowCache = ShadowUniformsCache();
  11758. const state = {
  11759. version: 0,
  11760. hash: {
  11761. directionalLength: - 1,
  11762. pointLength: - 1,
  11763. spotLength: - 1,
  11764. rectAreaLength: - 1,
  11765. hemiLength: - 1,
  11766. numDirectionalShadows: - 1,
  11767. numPointShadows: - 1,
  11768. numSpotShadows: - 1
  11769. },
  11770. ambient: [ 0, 0, 0 ],
  11771. probe: [],
  11772. directional: [],
  11773. directionalShadow: [],
  11774. directionalShadowMap: [],
  11775. directionalShadowMatrix: [],
  11776. spot: [],
  11777. spotShadow: [],
  11778. spotShadowMap: [],
  11779. spotShadowMatrix: [],
  11780. rectArea: [],
  11781. rectAreaLTC1: null,
  11782. rectAreaLTC2: null,
  11783. point: [],
  11784. pointShadow: [],
  11785. pointShadowMap: [],
  11786. pointShadowMatrix: [],
  11787. hemi: []
  11788. };
  11789. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11790. const vector3 = new Vector3();
  11791. const matrix4 = new Matrix4();
  11792. const matrix42 = new Matrix4();
  11793. function setup( lights, physicallyCorrectLights ) {
  11794. let r = 0, g = 0, b = 0;
  11795. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11796. let directionalLength = 0;
  11797. let pointLength = 0;
  11798. let spotLength = 0;
  11799. let rectAreaLength = 0;
  11800. let hemiLength = 0;
  11801. let numDirectionalShadows = 0;
  11802. let numPointShadows = 0;
  11803. let numSpotShadows = 0;
  11804. lights.sort( shadowCastingLightsFirst );
  11805. // artist-friendly light intensity scaling factor
  11806. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  11807. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11808. const light = lights[ i ];
  11809. const color = light.color;
  11810. const intensity = light.intensity;
  11811. const distance = light.distance;
  11812. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11813. if ( light.isAmbientLight ) {
  11814. r += color.r * intensity * scaleFactor;
  11815. g += color.g * intensity * scaleFactor;
  11816. b += color.b * intensity * scaleFactor;
  11817. } else if ( light.isLightProbe ) {
  11818. for ( let j = 0; j < 9; j ++ ) {
  11819. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11820. }
  11821. } else if ( light.isDirectionalLight ) {
  11822. const uniforms = cache.get( light );
  11823. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  11824. if ( light.castShadow ) {
  11825. const shadow = light.shadow;
  11826. const shadowUniforms = shadowCache.get( light );
  11827. shadowUniforms.shadowBias = shadow.bias;
  11828. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11829. shadowUniforms.shadowRadius = shadow.radius;
  11830. shadowUniforms.shadowMapSize = shadow.mapSize;
  11831. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11832. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11833. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11834. numDirectionalShadows ++;
  11835. }
  11836. state.directional[ directionalLength ] = uniforms;
  11837. directionalLength ++;
  11838. } else if ( light.isSpotLight ) {
  11839. const uniforms = cache.get( light );
  11840. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11841. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  11842. uniforms.distance = distance;
  11843. uniforms.coneCos = Math.cos( light.angle );
  11844. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  11845. uniforms.decay = light.decay;
  11846. if ( light.castShadow ) {
  11847. const shadow = light.shadow;
  11848. const shadowUniforms = shadowCache.get( light );
  11849. shadowUniforms.shadowBias = shadow.bias;
  11850. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11851. shadowUniforms.shadowRadius = shadow.radius;
  11852. shadowUniforms.shadowMapSize = shadow.mapSize;
  11853. state.spotShadow[ spotLength ] = shadowUniforms;
  11854. state.spotShadowMap[ spotLength ] = shadowMap;
  11855. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  11856. numSpotShadows ++;
  11857. }
  11858. state.spot[ spotLength ] = uniforms;
  11859. spotLength ++;
  11860. } else if ( light.isRectAreaLight ) {
  11861. const uniforms = cache.get( light );
  11862. // (a) intensity is the total visible light emitted
  11863. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11864. // (b) intensity is the brightness of the light
  11865. uniforms.color.copy( color ).multiplyScalar( intensity );
  11866. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11867. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11868. state.rectArea[ rectAreaLength ] = uniforms;
  11869. rectAreaLength ++;
  11870. } else if ( light.isPointLight ) {
  11871. const uniforms = cache.get( light );
  11872. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  11873. uniforms.distance = light.distance;
  11874. uniforms.decay = light.decay;
  11875. if ( light.castShadow ) {
  11876. const shadow = light.shadow;
  11877. const shadowUniforms = shadowCache.get( light );
  11878. shadowUniforms.shadowBias = shadow.bias;
  11879. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11880. shadowUniforms.shadowRadius = shadow.radius;
  11881. shadowUniforms.shadowMapSize = shadow.mapSize;
  11882. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11883. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11884. state.pointShadow[ pointLength ] = shadowUniforms;
  11885. state.pointShadowMap[ pointLength ] = shadowMap;
  11886. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  11887. numPointShadows ++;
  11888. }
  11889. state.point[ pointLength ] = uniforms;
  11890. pointLength ++;
  11891. } else if ( light.isHemisphereLight ) {
  11892. const uniforms = cache.get( light );
  11893. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  11894. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  11895. state.hemi[ hemiLength ] = uniforms;
  11896. hemiLength ++;
  11897. }
  11898. }
  11899. if ( rectAreaLength > 0 ) {
  11900. if ( capabilities.isWebGL2 ) {
  11901. // WebGL 2
  11902. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11903. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11904. } else {
  11905. // WebGL 1
  11906. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  11907. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11908. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11909. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  11910. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11911. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11912. } else {
  11913. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  11914. }
  11915. }
  11916. }
  11917. state.ambient[ 0 ] = r;
  11918. state.ambient[ 1 ] = g;
  11919. state.ambient[ 2 ] = b;
  11920. const hash = state.hash;
  11921. if ( hash.directionalLength !== directionalLength ||
  11922. hash.pointLength !== pointLength ||
  11923. hash.spotLength !== spotLength ||
  11924. hash.rectAreaLength !== rectAreaLength ||
  11925. hash.hemiLength !== hemiLength ||
  11926. hash.numDirectionalShadows !== numDirectionalShadows ||
  11927. hash.numPointShadows !== numPointShadows ||
  11928. hash.numSpotShadows !== numSpotShadows ) {
  11929. state.directional.length = directionalLength;
  11930. state.spot.length = spotLength;
  11931. state.rectArea.length = rectAreaLength;
  11932. state.point.length = pointLength;
  11933. state.hemi.length = hemiLength;
  11934. state.directionalShadow.length = numDirectionalShadows;
  11935. state.directionalShadowMap.length = numDirectionalShadows;
  11936. state.pointShadow.length = numPointShadows;
  11937. state.pointShadowMap.length = numPointShadows;
  11938. state.spotShadow.length = numSpotShadows;
  11939. state.spotShadowMap.length = numSpotShadows;
  11940. state.directionalShadowMatrix.length = numDirectionalShadows;
  11941. state.pointShadowMatrix.length = numPointShadows;
  11942. state.spotShadowMatrix.length = numSpotShadows;
  11943. hash.directionalLength = directionalLength;
  11944. hash.pointLength = pointLength;
  11945. hash.spotLength = spotLength;
  11946. hash.rectAreaLength = rectAreaLength;
  11947. hash.hemiLength = hemiLength;
  11948. hash.numDirectionalShadows = numDirectionalShadows;
  11949. hash.numPointShadows = numPointShadows;
  11950. hash.numSpotShadows = numSpotShadows;
  11951. state.version = nextVersion ++;
  11952. }
  11953. }
  11954. function setupView( lights, camera ) {
  11955. let directionalLength = 0;
  11956. let pointLength = 0;
  11957. let spotLength = 0;
  11958. let rectAreaLength = 0;
  11959. let hemiLength = 0;
  11960. const viewMatrix = camera.matrixWorldInverse;
  11961. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11962. const light = lights[ i ];
  11963. if ( light.isDirectionalLight ) {
  11964. const uniforms = state.directional[ directionalLength ];
  11965. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11966. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11967. uniforms.direction.sub( vector3 );
  11968. uniforms.direction.transformDirection( viewMatrix );
  11969. directionalLength ++;
  11970. } else if ( light.isSpotLight ) {
  11971. const uniforms = state.spot[ spotLength ];
  11972. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11973. uniforms.position.applyMatrix4( viewMatrix );
  11974. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11975. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11976. uniforms.direction.sub( vector3 );
  11977. uniforms.direction.transformDirection( viewMatrix );
  11978. spotLength ++;
  11979. } else if ( light.isRectAreaLight ) {
  11980. const uniforms = state.rectArea[ rectAreaLength ];
  11981. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11982. uniforms.position.applyMatrix4( viewMatrix );
  11983. // extract local rotation of light to derive width/height half vectors
  11984. matrix42.identity();
  11985. matrix4.copy( light.matrixWorld );
  11986. matrix4.premultiply( viewMatrix );
  11987. matrix42.extractRotation( matrix4 );
  11988. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11989. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11990. uniforms.halfWidth.applyMatrix4( matrix42 );
  11991. uniforms.halfHeight.applyMatrix4( matrix42 );
  11992. rectAreaLength ++;
  11993. } else if ( light.isPointLight ) {
  11994. const uniforms = state.point[ pointLength ];
  11995. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11996. uniforms.position.applyMatrix4( viewMatrix );
  11997. pointLength ++;
  11998. } else if ( light.isHemisphereLight ) {
  11999. const uniforms = state.hemi[ hemiLength ];
  12000. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12001. uniforms.direction.transformDirection( viewMatrix );
  12002. uniforms.direction.normalize();
  12003. hemiLength ++;
  12004. }
  12005. }
  12006. }
  12007. return {
  12008. setup: setup,
  12009. setupView: setupView,
  12010. state: state
  12011. };
  12012. }
  12013. function WebGLRenderState( extensions, capabilities ) {
  12014. const lights = new WebGLLights( extensions, capabilities );
  12015. const lightsArray = [];
  12016. const shadowsArray = [];
  12017. function init() {
  12018. lightsArray.length = 0;
  12019. shadowsArray.length = 0;
  12020. }
  12021. function pushLight( light ) {
  12022. lightsArray.push( light );
  12023. }
  12024. function pushShadow( shadowLight ) {
  12025. shadowsArray.push( shadowLight );
  12026. }
  12027. function setupLights( physicallyCorrectLights ) {
  12028. lights.setup( lightsArray, physicallyCorrectLights );
  12029. }
  12030. function setupLightsView( camera ) {
  12031. lights.setupView( lightsArray, camera );
  12032. }
  12033. const state = {
  12034. lightsArray: lightsArray,
  12035. shadowsArray: shadowsArray,
  12036. lights: lights
  12037. };
  12038. return {
  12039. init: init,
  12040. state: state,
  12041. setupLights: setupLights,
  12042. setupLightsView: setupLightsView,
  12043. pushLight: pushLight,
  12044. pushShadow: pushShadow
  12045. };
  12046. }
  12047. function WebGLRenderStates( extensions, capabilities ) {
  12048. let renderStates = new WeakMap();
  12049. function get( scene, renderCallDepth = 0 ) {
  12050. let renderState;
  12051. if ( renderStates.has( scene ) === false ) {
  12052. renderState = new WebGLRenderState( extensions, capabilities );
  12053. renderStates.set( scene, [ renderState ] );
  12054. } else {
  12055. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12056. renderState = new WebGLRenderState( extensions, capabilities );
  12057. renderStates.get( scene ).push( renderState );
  12058. } else {
  12059. renderState = renderStates.get( scene )[ renderCallDepth ];
  12060. }
  12061. }
  12062. return renderState;
  12063. }
  12064. function dispose() {
  12065. renderStates = new WeakMap();
  12066. }
  12067. return {
  12068. get: get,
  12069. dispose: dispose
  12070. };
  12071. }
  12072. /**
  12073. * parameters = {
  12074. *
  12075. * opacity: <float>,
  12076. *
  12077. * map: new THREE.Texture( <Image> ),
  12078. *
  12079. * alphaMap: new THREE.Texture( <Image> ),
  12080. *
  12081. * displacementMap: new THREE.Texture( <Image> ),
  12082. * displacementScale: <float>,
  12083. * displacementBias: <float>,
  12084. *
  12085. * wireframe: <boolean>,
  12086. * wireframeLinewidth: <float>
  12087. * }
  12088. */
  12089. class MeshDepthMaterial extends Material {
  12090. constructor( parameters ) {
  12091. super();
  12092. this.type = 'MeshDepthMaterial';
  12093. this.depthPacking = BasicDepthPacking;
  12094. this.map = null;
  12095. this.alphaMap = null;
  12096. this.displacementMap = null;
  12097. this.displacementScale = 1;
  12098. this.displacementBias = 0;
  12099. this.wireframe = false;
  12100. this.wireframeLinewidth = 1;
  12101. this.fog = false;
  12102. this.setValues( parameters );
  12103. }
  12104. copy( source ) {
  12105. super.copy( source );
  12106. this.depthPacking = source.depthPacking;
  12107. this.map = source.map;
  12108. this.alphaMap = source.alphaMap;
  12109. this.displacementMap = source.displacementMap;
  12110. this.displacementScale = source.displacementScale;
  12111. this.displacementBias = source.displacementBias;
  12112. this.wireframe = source.wireframe;
  12113. this.wireframeLinewidth = source.wireframeLinewidth;
  12114. return this;
  12115. }
  12116. }
  12117. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12118. /**
  12119. * parameters = {
  12120. *
  12121. * referencePosition: <float>,
  12122. * nearDistance: <float>,
  12123. * farDistance: <float>,
  12124. *
  12125. * map: new THREE.Texture( <Image> ),
  12126. *
  12127. * alphaMap: new THREE.Texture( <Image> ),
  12128. *
  12129. * displacementMap: new THREE.Texture( <Image> ),
  12130. * displacementScale: <float>,
  12131. * displacementBias: <float>
  12132. *
  12133. * }
  12134. */
  12135. class MeshDistanceMaterial extends Material {
  12136. constructor( parameters ) {
  12137. super();
  12138. this.type = 'MeshDistanceMaterial';
  12139. this.referencePosition = new Vector3();
  12140. this.nearDistance = 1;
  12141. this.farDistance = 1000;
  12142. this.map = null;
  12143. this.alphaMap = null;
  12144. this.displacementMap = null;
  12145. this.displacementScale = 1;
  12146. this.displacementBias = 0;
  12147. this.fog = false;
  12148. this.setValues( parameters );
  12149. }
  12150. copy( source ) {
  12151. super.copy( source );
  12152. this.referencePosition.copy( source.referencePosition );
  12153. this.nearDistance = source.nearDistance;
  12154. this.farDistance = source.farDistance;
  12155. this.map = source.map;
  12156. this.alphaMap = source.alphaMap;
  12157. this.displacementMap = source.displacementMap;
  12158. this.displacementScale = source.displacementScale;
  12159. this.displacementBias = source.displacementBias;
  12160. return this;
  12161. }
  12162. }
  12163. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12164. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nuniform float samples;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12165. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12166. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12167. let _frustum = new Frustum();
  12168. const _shadowMapSize = new Vector2(),
  12169. _viewportSize = new Vector2(),
  12170. _viewport = new Vector4(),
  12171. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12172. _distanceMaterial = new MeshDistanceMaterial(),
  12173. _materialCache = {},
  12174. _maxTextureSize = _capabilities.maxTextureSize;
  12175. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12176. const shadowMaterialVertical = new ShaderMaterial( {
  12177. uniforms: {
  12178. shadow_pass: { value: null },
  12179. resolution: { value: new Vector2() },
  12180. radius: { value: 4.0 },
  12181. samples: { value: 8.0 }
  12182. },
  12183. vertexShader: vsm_vert,
  12184. fragmentShader: vsm_frag
  12185. } );
  12186. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12187. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12188. const fullScreenTri = new BufferGeometry();
  12189. fullScreenTri.setAttribute(
  12190. 'position',
  12191. new BufferAttribute(
  12192. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12193. 3
  12194. )
  12195. );
  12196. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12197. const scope = this;
  12198. this.enabled = false;
  12199. this.autoUpdate = true;
  12200. this.needsUpdate = false;
  12201. this.type = PCFShadowMap;
  12202. this.render = function ( lights, scene, camera ) {
  12203. if ( scope.enabled === false ) return;
  12204. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12205. if ( lights.length === 0 ) return;
  12206. const currentRenderTarget = _renderer.getRenderTarget();
  12207. const activeCubeFace = _renderer.getActiveCubeFace();
  12208. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12209. const _state = _renderer.state;
  12210. // Set GL state for depth map.
  12211. _state.setBlending( NoBlending );
  12212. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12213. _state.buffers.depth.setTest( true );
  12214. _state.setScissorTest( false );
  12215. // render depth map
  12216. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12217. const light = lights[ i ];
  12218. const shadow = light.shadow;
  12219. if ( shadow === undefined ) {
  12220. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12221. continue;
  12222. }
  12223. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12224. _shadowMapSize.copy( shadow.mapSize );
  12225. const shadowFrameExtents = shadow.getFrameExtents();
  12226. _shadowMapSize.multiply( shadowFrameExtents );
  12227. _viewportSize.copy( shadow.mapSize );
  12228. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12229. if ( _shadowMapSize.x > _maxTextureSize ) {
  12230. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12231. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12232. shadow.mapSize.x = _viewportSize.x;
  12233. }
  12234. if ( _shadowMapSize.y > _maxTextureSize ) {
  12235. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12236. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12237. shadow.mapSize.y = _viewportSize.y;
  12238. }
  12239. }
  12240. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12241. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12242. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12243. shadow.map.texture.name = light.name + '.shadowMap';
  12244. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12245. shadow.camera.updateProjectionMatrix();
  12246. }
  12247. if ( shadow.map === null ) {
  12248. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12249. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12250. shadow.map.texture.name = light.name + '.shadowMap';
  12251. shadow.camera.updateProjectionMatrix();
  12252. }
  12253. _renderer.setRenderTarget( shadow.map );
  12254. _renderer.clear();
  12255. const viewportCount = shadow.getViewportCount();
  12256. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12257. const viewport = shadow.getViewport( vp );
  12258. _viewport.set(
  12259. _viewportSize.x * viewport.x,
  12260. _viewportSize.y * viewport.y,
  12261. _viewportSize.x * viewport.z,
  12262. _viewportSize.y * viewport.w
  12263. );
  12264. _state.viewport( _viewport );
  12265. shadow.updateMatrices( light, vp );
  12266. _frustum = shadow.getFrustum();
  12267. renderObject( scene, camera, shadow.camera, light, this.type );
  12268. }
  12269. // do blur pass for VSM
  12270. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12271. VSMPass( shadow, camera );
  12272. }
  12273. shadow.needsUpdate = false;
  12274. }
  12275. scope.needsUpdate = false;
  12276. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12277. };
  12278. function VSMPass( shadow, camera ) {
  12279. const geometry = _objects.update( fullScreenMesh );
  12280. // vertical pass
  12281. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12282. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12283. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12284. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  12285. _renderer.setRenderTarget( shadow.mapPass );
  12286. _renderer.clear();
  12287. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12288. // horizontal pass
  12289. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12290. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12291. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12292. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  12293. _renderer.setRenderTarget( shadow.map );
  12294. _renderer.clear();
  12295. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12296. }
  12297. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12298. let result = null;
  12299. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12300. if ( customMaterial !== undefined ) {
  12301. result = customMaterial;
  12302. } else {
  12303. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12304. }
  12305. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) ||
  12306. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12307. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12308. // in this case we need a unique material instance reflecting the
  12309. // appropriate state
  12310. const keyA = result.uuid, keyB = material.uuid;
  12311. let materialsForVariant = _materialCache[ keyA ];
  12312. if ( materialsForVariant === undefined ) {
  12313. materialsForVariant = {};
  12314. _materialCache[ keyA ] = materialsForVariant;
  12315. }
  12316. let cachedMaterial = materialsForVariant[ keyB ];
  12317. if ( cachedMaterial === undefined ) {
  12318. cachedMaterial = result.clone();
  12319. materialsForVariant[ keyB ] = cachedMaterial;
  12320. }
  12321. result = cachedMaterial;
  12322. }
  12323. result.visible = material.visible;
  12324. result.wireframe = material.wireframe;
  12325. if ( type === VSMShadowMap ) {
  12326. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12327. } else {
  12328. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12329. }
  12330. result.alphaMap = material.alphaMap;
  12331. result.alphaTest = material.alphaTest;
  12332. result.clipShadows = material.clipShadows;
  12333. result.clippingPlanes = material.clippingPlanes;
  12334. result.clipIntersection = material.clipIntersection;
  12335. result.displacementMap = material.displacementMap;
  12336. result.displacementScale = material.displacementScale;
  12337. result.displacementBias = material.displacementBias;
  12338. result.wireframeLinewidth = material.wireframeLinewidth;
  12339. result.linewidth = material.linewidth;
  12340. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12341. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12342. result.nearDistance = shadowCameraNear;
  12343. result.farDistance = shadowCameraFar;
  12344. }
  12345. return result;
  12346. }
  12347. function renderObject( object, camera, shadowCamera, light, type ) {
  12348. if ( object.visible === false ) return;
  12349. const visible = object.layers.test( camera.layers );
  12350. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12351. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12352. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12353. const geometry = _objects.update( object );
  12354. const material = object.material;
  12355. if ( Array.isArray( material ) ) {
  12356. const groups = geometry.groups;
  12357. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12358. const group = groups[ k ];
  12359. const groupMaterial = material[ group.materialIndex ];
  12360. if ( groupMaterial && groupMaterial.visible ) {
  12361. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12362. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12363. }
  12364. }
  12365. } else if ( material.visible ) {
  12366. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12367. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12368. }
  12369. }
  12370. }
  12371. const children = object.children;
  12372. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12373. renderObject( children[ i ], camera, shadowCamera, light, type );
  12374. }
  12375. }
  12376. }
  12377. function WebGLState( gl, extensions, capabilities ) {
  12378. const isWebGL2 = capabilities.isWebGL2;
  12379. function ColorBuffer() {
  12380. let locked = false;
  12381. const color = new Vector4();
  12382. let currentColorMask = null;
  12383. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12384. return {
  12385. setMask: function ( colorMask ) {
  12386. if ( currentColorMask !== colorMask && ! locked ) {
  12387. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12388. currentColorMask = colorMask;
  12389. }
  12390. },
  12391. setLocked: function ( lock ) {
  12392. locked = lock;
  12393. },
  12394. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12395. if ( premultipliedAlpha === true ) {
  12396. r *= a; g *= a; b *= a;
  12397. }
  12398. color.set( r, g, b, a );
  12399. if ( currentColorClear.equals( color ) === false ) {
  12400. gl.clearColor( r, g, b, a );
  12401. currentColorClear.copy( color );
  12402. }
  12403. },
  12404. reset: function () {
  12405. locked = false;
  12406. currentColorMask = null;
  12407. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12408. }
  12409. };
  12410. }
  12411. function DepthBuffer() {
  12412. let locked = false;
  12413. let currentDepthMask = null;
  12414. let currentDepthFunc = null;
  12415. let currentDepthClear = null;
  12416. return {
  12417. setTest: function ( depthTest ) {
  12418. if ( depthTest ) {
  12419. enable( 2929 );
  12420. } else {
  12421. disable( 2929 );
  12422. }
  12423. },
  12424. setMask: function ( depthMask ) {
  12425. if ( currentDepthMask !== depthMask && ! locked ) {
  12426. gl.depthMask( depthMask );
  12427. currentDepthMask = depthMask;
  12428. }
  12429. },
  12430. setFunc: function ( depthFunc ) {
  12431. if ( currentDepthFunc !== depthFunc ) {
  12432. if ( depthFunc ) {
  12433. switch ( depthFunc ) {
  12434. case NeverDepth:
  12435. gl.depthFunc( 512 );
  12436. break;
  12437. case AlwaysDepth:
  12438. gl.depthFunc( 519 );
  12439. break;
  12440. case LessDepth:
  12441. gl.depthFunc( 513 );
  12442. break;
  12443. case LessEqualDepth:
  12444. gl.depthFunc( 515 );
  12445. break;
  12446. case EqualDepth:
  12447. gl.depthFunc( 514 );
  12448. break;
  12449. case GreaterEqualDepth:
  12450. gl.depthFunc( 518 );
  12451. break;
  12452. case GreaterDepth:
  12453. gl.depthFunc( 516 );
  12454. break;
  12455. case NotEqualDepth:
  12456. gl.depthFunc( 517 );
  12457. break;
  12458. default:
  12459. gl.depthFunc( 515 );
  12460. }
  12461. } else {
  12462. gl.depthFunc( 515 );
  12463. }
  12464. currentDepthFunc = depthFunc;
  12465. }
  12466. },
  12467. setLocked: function ( lock ) {
  12468. locked = lock;
  12469. },
  12470. setClear: function ( depth ) {
  12471. if ( currentDepthClear !== depth ) {
  12472. gl.clearDepth( depth );
  12473. currentDepthClear = depth;
  12474. }
  12475. },
  12476. reset: function () {
  12477. locked = false;
  12478. currentDepthMask = null;
  12479. currentDepthFunc = null;
  12480. currentDepthClear = null;
  12481. }
  12482. };
  12483. }
  12484. function StencilBuffer() {
  12485. let locked = false;
  12486. let currentStencilMask = null;
  12487. let currentStencilFunc = null;
  12488. let currentStencilRef = null;
  12489. let currentStencilFuncMask = null;
  12490. let currentStencilFail = null;
  12491. let currentStencilZFail = null;
  12492. let currentStencilZPass = null;
  12493. let currentStencilClear = null;
  12494. return {
  12495. setTest: function ( stencilTest ) {
  12496. if ( ! locked ) {
  12497. if ( stencilTest ) {
  12498. enable( 2960 );
  12499. } else {
  12500. disable( 2960 );
  12501. }
  12502. }
  12503. },
  12504. setMask: function ( stencilMask ) {
  12505. if ( currentStencilMask !== stencilMask && ! locked ) {
  12506. gl.stencilMask( stencilMask );
  12507. currentStencilMask = stencilMask;
  12508. }
  12509. },
  12510. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12511. if ( currentStencilFunc !== stencilFunc ||
  12512. currentStencilRef !== stencilRef ||
  12513. currentStencilFuncMask !== stencilMask ) {
  12514. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12515. currentStencilFunc = stencilFunc;
  12516. currentStencilRef = stencilRef;
  12517. currentStencilFuncMask = stencilMask;
  12518. }
  12519. },
  12520. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12521. if ( currentStencilFail !== stencilFail ||
  12522. currentStencilZFail !== stencilZFail ||
  12523. currentStencilZPass !== stencilZPass ) {
  12524. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12525. currentStencilFail = stencilFail;
  12526. currentStencilZFail = stencilZFail;
  12527. currentStencilZPass = stencilZPass;
  12528. }
  12529. },
  12530. setLocked: function ( lock ) {
  12531. locked = lock;
  12532. },
  12533. setClear: function ( stencil ) {
  12534. if ( currentStencilClear !== stencil ) {
  12535. gl.clearStencil( stencil );
  12536. currentStencilClear = stencil;
  12537. }
  12538. },
  12539. reset: function () {
  12540. locked = false;
  12541. currentStencilMask = null;
  12542. currentStencilFunc = null;
  12543. currentStencilRef = null;
  12544. currentStencilFuncMask = null;
  12545. currentStencilFail = null;
  12546. currentStencilZFail = null;
  12547. currentStencilZPass = null;
  12548. currentStencilClear = null;
  12549. }
  12550. };
  12551. }
  12552. //
  12553. const colorBuffer = new ColorBuffer();
  12554. const depthBuffer = new DepthBuffer();
  12555. const stencilBuffer = new StencilBuffer();
  12556. let enabledCapabilities = {};
  12557. let xrFramebuffer = null;
  12558. let currentBoundFramebuffers = {};
  12559. let currentProgram = null;
  12560. let currentBlendingEnabled = false;
  12561. let currentBlending = null;
  12562. let currentBlendEquation = null;
  12563. let currentBlendSrc = null;
  12564. let currentBlendDst = null;
  12565. let currentBlendEquationAlpha = null;
  12566. let currentBlendSrcAlpha = null;
  12567. let currentBlendDstAlpha = null;
  12568. let currentPremultipledAlpha = false;
  12569. let currentFlipSided = null;
  12570. let currentCullFace = null;
  12571. let currentLineWidth = null;
  12572. let currentPolygonOffsetFactor = null;
  12573. let currentPolygonOffsetUnits = null;
  12574. const maxTextures = gl.getParameter( 35661 );
  12575. let lineWidthAvailable = false;
  12576. let version = 0;
  12577. const glVersion = gl.getParameter( 7938 );
  12578. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12579. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12580. lineWidthAvailable = ( version >= 1.0 );
  12581. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12582. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12583. lineWidthAvailable = ( version >= 2.0 );
  12584. }
  12585. let currentTextureSlot = null;
  12586. let currentBoundTextures = {};
  12587. const scissorParam = gl.getParameter( 3088 );
  12588. const viewportParam = gl.getParameter( 2978 );
  12589. const currentScissor = new Vector4().fromArray( scissorParam );
  12590. const currentViewport = new Vector4().fromArray( viewportParam );
  12591. function createTexture( type, target, count ) {
  12592. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12593. const texture = gl.createTexture();
  12594. gl.bindTexture( type, texture );
  12595. gl.texParameteri( type, 10241, 9728 );
  12596. gl.texParameteri( type, 10240, 9728 );
  12597. for ( let i = 0; i < count; i ++ ) {
  12598. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12599. }
  12600. return texture;
  12601. }
  12602. const emptyTextures = {};
  12603. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12604. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12605. // init
  12606. colorBuffer.setClear( 0, 0, 0, 1 );
  12607. depthBuffer.setClear( 1 );
  12608. stencilBuffer.setClear( 0 );
  12609. enable( 2929 );
  12610. depthBuffer.setFunc( LessEqualDepth );
  12611. setFlipSided( false );
  12612. setCullFace( CullFaceBack );
  12613. enable( 2884 );
  12614. setBlending( NoBlending );
  12615. //
  12616. function enable( id ) {
  12617. if ( enabledCapabilities[ id ] !== true ) {
  12618. gl.enable( id );
  12619. enabledCapabilities[ id ] = true;
  12620. }
  12621. }
  12622. function disable( id ) {
  12623. if ( enabledCapabilities[ id ] !== false ) {
  12624. gl.disable( id );
  12625. enabledCapabilities[ id ] = false;
  12626. }
  12627. }
  12628. function bindXRFramebuffer( framebuffer ) {
  12629. if ( framebuffer !== xrFramebuffer ) {
  12630. gl.bindFramebuffer( 36160, framebuffer );
  12631. xrFramebuffer = framebuffer;
  12632. }
  12633. }
  12634. function bindFramebuffer( target, framebuffer ) {
  12635. if ( framebuffer === null && xrFramebuffer !== null ) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12636. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  12637. gl.bindFramebuffer( target, framebuffer );
  12638. currentBoundFramebuffers[ target ] = framebuffer;
  12639. if ( isWebGL2 ) {
  12640. // 36009 is equivalent to 36160
  12641. if ( target === 36009 ) {
  12642. currentBoundFramebuffers[ 36160 ] = framebuffer;
  12643. }
  12644. if ( target === 36160 ) {
  12645. currentBoundFramebuffers[ 36009 ] = framebuffer;
  12646. }
  12647. }
  12648. return true;
  12649. }
  12650. return false;
  12651. }
  12652. function useProgram( program ) {
  12653. if ( currentProgram !== program ) {
  12654. gl.useProgram( program );
  12655. currentProgram = program;
  12656. return true;
  12657. }
  12658. return false;
  12659. }
  12660. const equationToGL = {
  12661. [ AddEquation ]: 32774,
  12662. [ SubtractEquation ]: 32778,
  12663. [ ReverseSubtractEquation ]: 32779
  12664. };
  12665. if ( isWebGL2 ) {
  12666. equationToGL[ MinEquation ] = 32775;
  12667. equationToGL[ MaxEquation ] = 32776;
  12668. } else {
  12669. const extension = extensions.get( 'EXT_blend_minmax' );
  12670. if ( extension !== null ) {
  12671. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12672. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12673. }
  12674. }
  12675. const factorToGL = {
  12676. [ ZeroFactor ]: 0,
  12677. [ OneFactor ]: 1,
  12678. [ SrcColorFactor ]: 768,
  12679. [ SrcAlphaFactor ]: 770,
  12680. [ SrcAlphaSaturateFactor ]: 776,
  12681. [ DstColorFactor ]: 774,
  12682. [ DstAlphaFactor ]: 772,
  12683. [ OneMinusSrcColorFactor ]: 769,
  12684. [ OneMinusSrcAlphaFactor ]: 771,
  12685. [ OneMinusDstColorFactor ]: 775,
  12686. [ OneMinusDstAlphaFactor ]: 773
  12687. };
  12688. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12689. if ( blending === NoBlending ) {
  12690. if ( currentBlendingEnabled === true ) {
  12691. disable( 3042 );
  12692. currentBlendingEnabled = false;
  12693. }
  12694. return;
  12695. }
  12696. if ( currentBlendingEnabled === false ) {
  12697. enable( 3042 );
  12698. currentBlendingEnabled = true;
  12699. }
  12700. if ( blending !== CustomBlending ) {
  12701. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  12702. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  12703. gl.blendEquation( 32774 );
  12704. currentBlendEquation = AddEquation;
  12705. currentBlendEquationAlpha = AddEquation;
  12706. }
  12707. if ( premultipliedAlpha ) {
  12708. switch ( blending ) {
  12709. case NormalBlending:
  12710. gl.blendFuncSeparate( 1, 771, 1, 771 );
  12711. break;
  12712. case AdditiveBlending:
  12713. gl.blendFunc( 1, 1 );
  12714. break;
  12715. case SubtractiveBlending:
  12716. gl.blendFuncSeparate( 0, 0, 769, 771 );
  12717. break;
  12718. case MultiplyBlending:
  12719. gl.blendFuncSeparate( 0, 768, 0, 770 );
  12720. break;
  12721. default:
  12722. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12723. break;
  12724. }
  12725. } else {
  12726. switch ( blending ) {
  12727. case NormalBlending:
  12728. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12729. break;
  12730. case AdditiveBlending:
  12731. gl.blendFunc( 770, 1 );
  12732. break;
  12733. case SubtractiveBlending:
  12734. gl.blendFunc( 0, 769 );
  12735. break;
  12736. case MultiplyBlending:
  12737. gl.blendFunc( 0, 768 );
  12738. break;
  12739. default:
  12740. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12741. break;
  12742. }
  12743. }
  12744. currentBlendSrc = null;
  12745. currentBlendDst = null;
  12746. currentBlendSrcAlpha = null;
  12747. currentBlendDstAlpha = null;
  12748. currentBlending = blending;
  12749. currentPremultipledAlpha = premultipliedAlpha;
  12750. }
  12751. return;
  12752. }
  12753. // custom blending
  12754. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12755. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12756. blendDstAlpha = blendDstAlpha || blendDst;
  12757. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12758. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12759. currentBlendEquation = blendEquation;
  12760. currentBlendEquationAlpha = blendEquationAlpha;
  12761. }
  12762. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12763. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12764. currentBlendSrc = blendSrc;
  12765. currentBlendDst = blendDst;
  12766. currentBlendSrcAlpha = blendSrcAlpha;
  12767. currentBlendDstAlpha = blendDstAlpha;
  12768. }
  12769. currentBlending = blending;
  12770. currentPremultipledAlpha = null;
  12771. }
  12772. function setMaterial( material, frontFaceCW ) {
  12773. material.side === DoubleSide
  12774. ? disable( 2884 )
  12775. : enable( 2884 );
  12776. let flipSided = ( material.side === BackSide );
  12777. if ( frontFaceCW ) flipSided = ! flipSided;
  12778. setFlipSided( flipSided );
  12779. ( material.blending === NormalBlending && material.transparent === false )
  12780. ? setBlending( NoBlending )
  12781. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12782. depthBuffer.setFunc( material.depthFunc );
  12783. depthBuffer.setTest( material.depthTest );
  12784. depthBuffer.setMask( material.depthWrite );
  12785. colorBuffer.setMask( material.colorWrite );
  12786. const stencilWrite = material.stencilWrite;
  12787. stencilBuffer.setTest( stencilWrite );
  12788. if ( stencilWrite ) {
  12789. stencilBuffer.setMask( material.stencilWriteMask );
  12790. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12791. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12792. }
  12793. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12794. material.alphaToCoverage === true
  12795. ? enable( 32926 )
  12796. : disable( 32926 );
  12797. }
  12798. //
  12799. function setFlipSided( flipSided ) {
  12800. if ( currentFlipSided !== flipSided ) {
  12801. if ( flipSided ) {
  12802. gl.frontFace( 2304 );
  12803. } else {
  12804. gl.frontFace( 2305 );
  12805. }
  12806. currentFlipSided = flipSided;
  12807. }
  12808. }
  12809. function setCullFace( cullFace ) {
  12810. if ( cullFace !== CullFaceNone ) {
  12811. enable( 2884 );
  12812. if ( cullFace !== currentCullFace ) {
  12813. if ( cullFace === CullFaceBack ) {
  12814. gl.cullFace( 1029 );
  12815. } else if ( cullFace === CullFaceFront ) {
  12816. gl.cullFace( 1028 );
  12817. } else {
  12818. gl.cullFace( 1032 );
  12819. }
  12820. }
  12821. } else {
  12822. disable( 2884 );
  12823. }
  12824. currentCullFace = cullFace;
  12825. }
  12826. function setLineWidth( width ) {
  12827. if ( width !== currentLineWidth ) {
  12828. if ( lineWidthAvailable ) gl.lineWidth( width );
  12829. currentLineWidth = width;
  12830. }
  12831. }
  12832. function setPolygonOffset( polygonOffset, factor, units ) {
  12833. if ( polygonOffset ) {
  12834. enable( 32823 );
  12835. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  12836. gl.polygonOffset( factor, units );
  12837. currentPolygonOffsetFactor = factor;
  12838. currentPolygonOffsetUnits = units;
  12839. }
  12840. } else {
  12841. disable( 32823 );
  12842. }
  12843. }
  12844. function setScissorTest( scissorTest ) {
  12845. if ( scissorTest ) {
  12846. enable( 3089 );
  12847. } else {
  12848. disable( 3089 );
  12849. }
  12850. }
  12851. // texture
  12852. function activeTexture( webglSlot ) {
  12853. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  12854. if ( currentTextureSlot !== webglSlot ) {
  12855. gl.activeTexture( webglSlot );
  12856. currentTextureSlot = webglSlot;
  12857. }
  12858. }
  12859. function bindTexture( webglType, webglTexture ) {
  12860. if ( currentTextureSlot === null ) {
  12861. activeTexture();
  12862. }
  12863. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  12864. if ( boundTexture === undefined ) {
  12865. boundTexture = { type: undefined, texture: undefined };
  12866. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  12867. }
  12868. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  12869. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  12870. boundTexture.type = webglType;
  12871. boundTexture.texture = webglTexture;
  12872. }
  12873. }
  12874. function unbindTexture() {
  12875. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  12876. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  12877. gl.bindTexture( boundTexture.type, null );
  12878. boundTexture.type = undefined;
  12879. boundTexture.texture = undefined;
  12880. }
  12881. }
  12882. function compressedTexImage2D() {
  12883. try {
  12884. gl.compressedTexImage2D.apply( gl, arguments );
  12885. } catch ( error ) {
  12886. console.error( 'THREE.WebGLState:', error );
  12887. }
  12888. }
  12889. function texImage2D() {
  12890. try {
  12891. gl.texImage2D.apply( gl, arguments );
  12892. } catch ( error ) {
  12893. console.error( 'THREE.WebGLState:', error );
  12894. }
  12895. }
  12896. function texImage3D() {
  12897. try {
  12898. gl.texImage3D.apply( gl, arguments );
  12899. } catch ( error ) {
  12900. console.error( 'THREE.WebGLState:', error );
  12901. }
  12902. }
  12903. //
  12904. function scissor( scissor ) {
  12905. if ( currentScissor.equals( scissor ) === false ) {
  12906. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12907. currentScissor.copy( scissor );
  12908. }
  12909. }
  12910. function viewport( viewport ) {
  12911. if ( currentViewport.equals( viewport ) === false ) {
  12912. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12913. currentViewport.copy( viewport );
  12914. }
  12915. }
  12916. //
  12917. function reset() {
  12918. // reset state
  12919. gl.disable( 3042 );
  12920. gl.disable( 2884 );
  12921. gl.disable( 2929 );
  12922. gl.disable( 32823 );
  12923. gl.disable( 3089 );
  12924. gl.disable( 2960 );
  12925. gl.disable( 32926 );
  12926. gl.blendEquation( 32774 );
  12927. gl.blendFunc( 1, 0 );
  12928. gl.blendFuncSeparate( 1, 0, 1, 0 );
  12929. gl.colorMask( true, true, true, true );
  12930. gl.clearColor( 0, 0, 0, 0 );
  12931. gl.depthMask( true );
  12932. gl.depthFunc( 513 );
  12933. gl.clearDepth( 1 );
  12934. gl.stencilMask( 0xffffffff );
  12935. gl.stencilFunc( 519, 0, 0xffffffff );
  12936. gl.stencilOp( 7680, 7680, 7680 );
  12937. gl.clearStencil( 0 );
  12938. gl.cullFace( 1029 );
  12939. gl.frontFace( 2305 );
  12940. gl.polygonOffset( 0, 0 );
  12941. gl.activeTexture( 33984 );
  12942. gl.bindFramebuffer( 36160, null );
  12943. if ( isWebGL2 === true ) {
  12944. gl.bindFramebuffer( 36009, null );
  12945. gl.bindFramebuffer( 36008, null );
  12946. }
  12947. gl.useProgram( null );
  12948. gl.lineWidth( 1 );
  12949. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  12950. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  12951. // reset internals
  12952. enabledCapabilities = {};
  12953. currentTextureSlot = null;
  12954. currentBoundTextures = {};
  12955. xrFramebuffer = null;
  12956. currentBoundFramebuffers = {};
  12957. currentProgram = null;
  12958. currentBlendingEnabled = false;
  12959. currentBlending = null;
  12960. currentBlendEquation = null;
  12961. currentBlendSrc = null;
  12962. currentBlendDst = null;
  12963. currentBlendEquationAlpha = null;
  12964. currentBlendSrcAlpha = null;
  12965. currentBlendDstAlpha = null;
  12966. currentPremultipledAlpha = false;
  12967. currentFlipSided = null;
  12968. currentCullFace = null;
  12969. currentLineWidth = null;
  12970. currentPolygonOffsetFactor = null;
  12971. currentPolygonOffsetUnits = null;
  12972. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12973. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12974. colorBuffer.reset();
  12975. depthBuffer.reset();
  12976. stencilBuffer.reset();
  12977. }
  12978. return {
  12979. buffers: {
  12980. color: colorBuffer,
  12981. depth: depthBuffer,
  12982. stencil: stencilBuffer
  12983. },
  12984. enable: enable,
  12985. disable: disable,
  12986. bindFramebuffer: bindFramebuffer,
  12987. bindXRFramebuffer: bindXRFramebuffer,
  12988. useProgram: useProgram,
  12989. setBlending: setBlending,
  12990. setMaterial: setMaterial,
  12991. setFlipSided: setFlipSided,
  12992. setCullFace: setCullFace,
  12993. setLineWidth: setLineWidth,
  12994. setPolygonOffset: setPolygonOffset,
  12995. setScissorTest: setScissorTest,
  12996. activeTexture: activeTexture,
  12997. bindTexture: bindTexture,
  12998. unbindTexture: unbindTexture,
  12999. compressedTexImage2D: compressedTexImage2D,
  13000. texImage2D: texImage2D,
  13001. texImage3D: texImage3D,
  13002. scissor: scissor,
  13003. viewport: viewport,
  13004. reset: reset
  13005. };
  13006. }
  13007. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13008. const isWebGL2 = capabilities.isWebGL2;
  13009. const maxTextures = capabilities.maxTextures;
  13010. const maxCubemapSize = capabilities.maxCubemapSize;
  13011. const maxTextureSize = capabilities.maxTextureSize;
  13012. const maxSamples = capabilities.maxSamples;
  13013. const _videoTextures = new WeakMap();
  13014. let _canvas;
  13015. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13016. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13017. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13018. let useOffscreenCanvas = false;
  13019. try {
  13020. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13021. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13022. } catch ( err ) {
  13023. // Ignore any errors
  13024. }
  13025. function createCanvas( width, height ) {
  13026. // Use OffscreenCanvas when available. Specially needed in web workers
  13027. return useOffscreenCanvas ?
  13028. new OffscreenCanvas( width, height ) :
  13029. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13030. }
  13031. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13032. let scale = 1;
  13033. // handle case if texture exceeds max size
  13034. if ( image.width > maxSize || image.height > maxSize ) {
  13035. scale = maxSize / Math.max( image.width, image.height );
  13036. }
  13037. // only perform resize if necessary
  13038. if ( scale < 1 || needsPowerOfTwo === true ) {
  13039. // only perform resize for certain image types
  13040. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13041. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13042. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13043. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13044. const width = floor( scale * image.width );
  13045. const height = floor( scale * image.height );
  13046. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13047. // cube textures can't reuse the same canvas
  13048. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13049. canvas.width = width;
  13050. canvas.height = height;
  13051. const context = canvas.getContext( '2d' );
  13052. context.drawImage( image, 0, 0, width, height );
  13053. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13054. return canvas;
  13055. } else {
  13056. if ( 'data' in image ) {
  13057. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13058. }
  13059. return image;
  13060. }
  13061. }
  13062. return image;
  13063. }
  13064. function isPowerOfTwo$1( image ) {
  13065. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13066. }
  13067. function textureNeedsPowerOfTwo( texture ) {
  13068. if ( isWebGL2 ) return false;
  13069. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13070. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13071. }
  13072. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13073. return texture.generateMipmaps && supportsMips &&
  13074. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13075. }
  13076. function generateMipmap( target, texture, width, height, depth = 1 ) {
  13077. _gl.generateMipmap( target );
  13078. const textureProperties = properties.get( texture );
  13079. textureProperties.__maxMipLevel = Math.log2( Math.max( width, height, depth ) );
  13080. }
  13081. function getInternalFormat( internalFormatName, glFormat, glType ) {
  13082. if ( isWebGL2 === false ) return glFormat;
  13083. if ( internalFormatName !== null ) {
  13084. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13085. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13086. }
  13087. let internalFormat = glFormat;
  13088. if ( glFormat === 6403 ) {
  13089. if ( glType === 5126 ) internalFormat = 33326;
  13090. if ( glType === 5131 ) internalFormat = 33325;
  13091. if ( glType === 5121 ) internalFormat = 33321;
  13092. }
  13093. if ( glFormat === 6407 ) {
  13094. if ( glType === 5126 ) internalFormat = 34837;
  13095. if ( glType === 5131 ) internalFormat = 34843;
  13096. if ( glType === 5121 ) internalFormat = 32849;
  13097. }
  13098. if ( glFormat === 6408 ) {
  13099. if ( glType === 5126 ) internalFormat = 34836;
  13100. if ( glType === 5131 ) internalFormat = 34842;
  13101. if ( glType === 5121 ) internalFormat = 32856;
  13102. }
  13103. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13104. internalFormat === 34842 || internalFormat === 34836 ) {
  13105. extensions.get( 'EXT_color_buffer_float' );
  13106. }
  13107. return internalFormat;
  13108. }
  13109. // Fallback filters for non-power-of-2 textures
  13110. function filterFallback( f ) {
  13111. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13112. return 9728;
  13113. }
  13114. return 9729;
  13115. }
  13116. //
  13117. function onTextureDispose( event ) {
  13118. const texture = event.target;
  13119. texture.removeEventListener( 'dispose', onTextureDispose );
  13120. deallocateTexture( texture );
  13121. if ( texture.isVideoTexture ) {
  13122. _videoTextures.delete( texture );
  13123. }
  13124. info.memory.textures --;
  13125. }
  13126. function onRenderTargetDispose( event ) {
  13127. const renderTarget = event.target;
  13128. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13129. deallocateRenderTarget( renderTarget );
  13130. }
  13131. //
  13132. function deallocateTexture( texture ) {
  13133. const textureProperties = properties.get( texture );
  13134. if ( textureProperties.__webglInit === undefined ) return;
  13135. _gl.deleteTexture( textureProperties.__webglTexture );
  13136. properties.remove( texture );
  13137. }
  13138. function deallocateRenderTarget( renderTarget ) {
  13139. const texture = renderTarget.texture;
  13140. const renderTargetProperties = properties.get( renderTarget );
  13141. const textureProperties = properties.get( texture );
  13142. if ( ! renderTarget ) return;
  13143. if ( textureProperties.__webglTexture !== undefined ) {
  13144. _gl.deleteTexture( textureProperties.__webglTexture );
  13145. info.memory.textures --;
  13146. }
  13147. if ( renderTarget.depthTexture ) {
  13148. renderTarget.depthTexture.dispose();
  13149. }
  13150. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13151. for ( let i = 0; i < 6; i ++ ) {
  13152. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13153. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13154. }
  13155. } else {
  13156. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13157. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13158. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13159. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13160. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13161. }
  13162. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13163. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13164. const attachmentProperties = properties.get( texture[ i ] );
  13165. if ( attachmentProperties.__webglTexture ) {
  13166. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13167. info.memory.textures --;
  13168. }
  13169. properties.remove( texture[ i ] );
  13170. }
  13171. }
  13172. properties.remove( texture );
  13173. properties.remove( renderTarget );
  13174. }
  13175. //
  13176. let textureUnits = 0;
  13177. function resetTextureUnits() {
  13178. textureUnits = 0;
  13179. }
  13180. function allocateTextureUnit() {
  13181. const textureUnit = textureUnits;
  13182. if ( textureUnit >= maxTextures ) {
  13183. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13184. }
  13185. textureUnits += 1;
  13186. return textureUnit;
  13187. }
  13188. //
  13189. function setTexture2D( texture, slot ) {
  13190. const textureProperties = properties.get( texture );
  13191. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13192. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13193. const image = texture.image;
  13194. if ( image === undefined ) {
  13195. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13196. } else if ( image.complete === false ) {
  13197. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13198. } else {
  13199. uploadTexture( textureProperties, texture, slot );
  13200. return;
  13201. }
  13202. }
  13203. state.activeTexture( 33984 + slot );
  13204. state.bindTexture( 3553, textureProperties.__webglTexture );
  13205. }
  13206. function setTexture2DArray( texture, slot ) {
  13207. const textureProperties = properties.get( texture );
  13208. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13209. uploadTexture( textureProperties, texture, slot );
  13210. return;
  13211. }
  13212. state.activeTexture( 33984 + slot );
  13213. state.bindTexture( 35866, textureProperties.__webglTexture );
  13214. }
  13215. function setTexture3D( texture, slot ) {
  13216. const textureProperties = properties.get( texture );
  13217. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13218. uploadTexture( textureProperties, texture, slot );
  13219. return;
  13220. }
  13221. state.activeTexture( 33984 + slot );
  13222. state.bindTexture( 32879, textureProperties.__webglTexture );
  13223. }
  13224. function setTextureCube( texture, slot ) {
  13225. const textureProperties = properties.get( texture );
  13226. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13227. uploadCubeTexture( textureProperties, texture, slot );
  13228. return;
  13229. }
  13230. state.activeTexture( 33984 + slot );
  13231. state.bindTexture( 34067, textureProperties.__webglTexture );
  13232. }
  13233. const wrappingToGL = {
  13234. [ RepeatWrapping ]: 10497,
  13235. [ ClampToEdgeWrapping ]: 33071,
  13236. [ MirroredRepeatWrapping ]: 33648
  13237. };
  13238. const filterToGL = {
  13239. [ NearestFilter ]: 9728,
  13240. [ NearestMipmapNearestFilter ]: 9984,
  13241. [ NearestMipmapLinearFilter ]: 9986,
  13242. [ LinearFilter ]: 9729,
  13243. [ LinearMipmapNearestFilter ]: 9985,
  13244. [ LinearMipmapLinearFilter ]: 9987
  13245. };
  13246. function setTextureParameters( textureType, texture, supportsMips ) {
  13247. if ( supportsMips ) {
  13248. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13249. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13250. if ( textureType === 32879 || textureType === 35866 ) {
  13251. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13252. }
  13253. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13254. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13255. } else {
  13256. _gl.texParameteri( textureType, 10242, 33071 );
  13257. _gl.texParameteri( textureType, 10243, 33071 );
  13258. if ( textureType === 32879 || textureType === 35866 ) {
  13259. _gl.texParameteri( textureType, 32882, 33071 );
  13260. }
  13261. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13262. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13263. }
  13264. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13265. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13266. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13267. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13268. }
  13269. }
  13270. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13271. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13272. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13273. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13274. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13275. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13276. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13277. }
  13278. }
  13279. }
  13280. function initTexture( textureProperties, texture ) {
  13281. if ( textureProperties.__webglInit === undefined ) {
  13282. textureProperties.__webglInit = true;
  13283. texture.addEventListener( 'dispose', onTextureDispose );
  13284. textureProperties.__webglTexture = _gl.createTexture();
  13285. info.memory.textures ++;
  13286. }
  13287. }
  13288. function uploadTexture( textureProperties, texture, slot ) {
  13289. let textureType = 3553;
  13290. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13291. if ( texture.isDataTexture3D ) textureType = 32879;
  13292. initTexture( textureProperties, texture );
  13293. state.activeTexture( 33984 + slot );
  13294. state.bindTexture( textureType, textureProperties.__webglTexture );
  13295. _gl.pixelStorei( 37440, texture.flipY );
  13296. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13297. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13298. _gl.pixelStorei( 37443, 0 );
  13299. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13300. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13301. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13302. glFormat = utils.convert( texture.format );
  13303. let glType = utils.convert( texture.type ),
  13304. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13305. setTextureParameters( textureType, texture, supportsMips );
  13306. let mipmap;
  13307. const mipmaps = texture.mipmaps;
  13308. if ( texture.isDepthTexture ) {
  13309. // populate depth texture with dummy data
  13310. glInternalFormat = 6402;
  13311. if ( isWebGL2 ) {
  13312. if ( texture.type === FloatType ) {
  13313. glInternalFormat = 36012;
  13314. } else if ( texture.type === UnsignedIntType ) {
  13315. glInternalFormat = 33190;
  13316. } else if ( texture.type === UnsignedInt248Type ) {
  13317. glInternalFormat = 35056;
  13318. } else {
  13319. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13320. }
  13321. } else {
  13322. if ( texture.type === FloatType ) {
  13323. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13324. }
  13325. }
  13326. // validation checks for WebGL 1
  13327. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13328. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13329. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13330. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13331. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13332. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13333. texture.type = UnsignedShortType;
  13334. glType = utils.convert( texture.type );
  13335. }
  13336. }
  13337. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13338. // Depth stencil textures need the DEPTH_STENCIL internal format
  13339. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13340. glInternalFormat = 34041;
  13341. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13342. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13343. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13344. if ( texture.type !== UnsignedInt248Type ) {
  13345. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13346. texture.type = UnsignedInt248Type;
  13347. glType = utils.convert( texture.type );
  13348. }
  13349. }
  13350. //
  13351. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13352. } else if ( texture.isDataTexture ) {
  13353. // use manually created mipmaps if available
  13354. // if there are no manual mipmaps
  13355. // set 0 level mipmap and then use GL to generate other mipmap levels
  13356. if ( mipmaps.length > 0 && supportsMips ) {
  13357. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13358. mipmap = mipmaps[ i ];
  13359. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13360. }
  13361. texture.generateMipmaps = false;
  13362. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13363. } else {
  13364. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13365. textureProperties.__maxMipLevel = 0;
  13366. }
  13367. } else if ( texture.isCompressedTexture ) {
  13368. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13369. mipmap = mipmaps[ i ];
  13370. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13371. if ( glFormat !== null ) {
  13372. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13373. } else {
  13374. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13375. }
  13376. } else {
  13377. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13378. }
  13379. }
  13380. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13381. } else if ( texture.isDataTexture2DArray ) {
  13382. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13383. textureProperties.__maxMipLevel = 0;
  13384. } else if ( texture.isDataTexture3D ) {
  13385. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13386. textureProperties.__maxMipLevel = 0;
  13387. } else {
  13388. // regular Texture (image, video, canvas)
  13389. // use manually created mipmaps if available
  13390. // if there are no manual mipmaps
  13391. // set 0 level mipmap and then use GL to generate other mipmap levels
  13392. if ( mipmaps.length > 0 && supportsMips ) {
  13393. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13394. mipmap = mipmaps[ i ];
  13395. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13396. }
  13397. texture.generateMipmaps = false;
  13398. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13399. } else {
  13400. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13401. textureProperties.__maxMipLevel = 0;
  13402. }
  13403. }
  13404. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13405. generateMipmap( textureType, texture, image.width, image.height );
  13406. }
  13407. textureProperties.__version = texture.version;
  13408. if ( texture.onUpdate ) texture.onUpdate( texture );
  13409. }
  13410. function uploadCubeTexture( textureProperties, texture, slot ) {
  13411. if ( texture.image.length !== 6 ) return;
  13412. initTexture( textureProperties, texture );
  13413. state.activeTexture( 33984 + slot );
  13414. state.bindTexture( 34067, textureProperties.__webglTexture );
  13415. _gl.pixelStorei( 37440, texture.flipY );
  13416. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13417. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13418. _gl.pixelStorei( 37443, 0 );
  13419. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13420. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13421. const cubeImage = [];
  13422. for ( let i = 0; i < 6; i ++ ) {
  13423. if ( ! isCompressed && ! isDataTexture ) {
  13424. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13425. } else {
  13426. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13427. }
  13428. }
  13429. const image = cubeImage[ 0 ],
  13430. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13431. glFormat = utils.convert( texture.format ),
  13432. glType = utils.convert( texture.type ),
  13433. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13434. setTextureParameters( 34067, texture, supportsMips );
  13435. let mipmaps;
  13436. if ( isCompressed ) {
  13437. for ( let i = 0; i < 6; i ++ ) {
  13438. mipmaps = cubeImage[ i ].mipmaps;
  13439. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13440. const mipmap = mipmaps[ j ];
  13441. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13442. if ( glFormat !== null ) {
  13443. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13444. } else {
  13445. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13446. }
  13447. } else {
  13448. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13449. }
  13450. }
  13451. }
  13452. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13453. } else {
  13454. mipmaps = texture.mipmaps;
  13455. for ( let i = 0; i < 6; i ++ ) {
  13456. if ( isDataTexture ) {
  13457. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13458. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13459. const mipmap = mipmaps[ j ];
  13460. const mipmapImage = mipmap.image[ i ].image;
  13461. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13462. }
  13463. } else {
  13464. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13465. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13466. const mipmap = mipmaps[ j ];
  13467. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13468. }
  13469. }
  13470. }
  13471. textureProperties.__maxMipLevel = mipmaps.length;
  13472. }
  13473. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13474. // We assume images for cube map have the same size.
  13475. generateMipmap( 34067, texture, image.width, image.height );
  13476. }
  13477. textureProperties.__version = texture.version;
  13478. if ( texture.onUpdate ) texture.onUpdate( texture );
  13479. }
  13480. // Render targets
  13481. // Setup storage for target texture and bind it to correct framebuffer
  13482. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  13483. const glFormat = utils.convert( texture.format );
  13484. const glType = utils.convert( texture.type );
  13485. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13486. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  13487. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  13488. } else {
  13489. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13490. }
  13491. state.bindFramebuffer( 36160, framebuffer );
  13492. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  13493. state.bindFramebuffer( 36160, null );
  13494. }
  13495. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13496. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13497. _gl.bindRenderbuffer( 36161, renderbuffer );
  13498. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13499. let glInternalFormat = 33189;
  13500. if ( isMultisample ) {
  13501. const depthTexture = renderTarget.depthTexture;
  13502. if ( depthTexture && depthTexture.isDepthTexture ) {
  13503. if ( depthTexture.type === FloatType ) {
  13504. glInternalFormat = 36012;
  13505. } else if ( depthTexture.type === UnsignedIntType ) {
  13506. glInternalFormat = 33190;
  13507. }
  13508. }
  13509. const samples = getRenderTargetSamples( renderTarget );
  13510. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13511. } else {
  13512. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13513. }
  13514. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13515. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13516. if ( isMultisample ) {
  13517. const samples = getRenderTargetSamples( renderTarget );
  13518. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13519. } else {
  13520. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13521. }
  13522. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13523. } else {
  13524. // Use the first texture for MRT so far
  13525. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  13526. const glFormat = utils.convert( texture.format );
  13527. const glType = utils.convert( texture.type );
  13528. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13529. if ( isMultisample ) {
  13530. const samples = getRenderTargetSamples( renderTarget );
  13531. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13532. } else {
  13533. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13534. }
  13535. }
  13536. _gl.bindRenderbuffer( 36161, null );
  13537. }
  13538. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13539. function setupDepthTexture( framebuffer, renderTarget ) {
  13540. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  13541. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  13542. state.bindFramebuffer( 36160, framebuffer );
  13543. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13544. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  13545. }
  13546. // upload an empty depth texture with framebuffer size
  13547. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  13548. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13549. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13550. renderTarget.depthTexture.image.width = renderTarget.width;
  13551. renderTarget.depthTexture.image.height = renderTarget.height;
  13552. renderTarget.depthTexture.needsUpdate = true;
  13553. }
  13554. setTexture2D( renderTarget.depthTexture, 0 );
  13555. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13556. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13557. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  13558. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13559. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  13560. } else {
  13561. throw new Error( 'Unknown depthTexture format' );
  13562. }
  13563. }
  13564. // Setup GL resources for a non-texture depth buffer
  13565. function setupDepthRenderbuffer( renderTarget ) {
  13566. const renderTargetProperties = properties.get( renderTarget );
  13567. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13568. if ( renderTarget.depthTexture ) {
  13569. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  13570. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13571. } else {
  13572. if ( isCube ) {
  13573. renderTargetProperties.__webglDepthbuffer = [];
  13574. for ( let i = 0; i < 6; i ++ ) {
  13575. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  13576. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13577. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  13578. }
  13579. } else {
  13580. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  13581. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13582. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  13583. }
  13584. }
  13585. state.bindFramebuffer( 36160, null );
  13586. }
  13587. // Set up GL resources for the render target
  13588. function setupRenderTarget( renderTarget ) {
  13589. const texture = renderTarget.texture;
  13590. const renderTargetProperties = properties.get( renderTarget );
  13591. const textureProperties = properties.get( texture );
  13592. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13593. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  13594. textureProperties.__webglTexture = _gl.createTexture();
  13595. textureProperties.__version = texture.version;
  13596. info.memory.textures ++;
  13597. }
  13598. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13599. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  13600. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  13601. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  13602. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  13603. // Handles WebGL2 RGBFormat fallback - #18858
  13604. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  13605. texture.format = RGBAFormat;
  13606. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  13607. }
  13608. // Setup framebuffer
  13609. if ( isCube ) {
  13610. renderTargetProperties.__webglFramebuffer = [];
  13611. for ( let i = 0; i < 6; i ++ ) {
  13612. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13613. }
  13614. } else {
  13615. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13616. if ( isMultipleRenderTargets ) {
  13617. if ( capabilities.drawBuffers ) {
  13618. const textures = renderTarget.texture;
  13619. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13620. const attachmentProperties = properties.get( textures[ i ] );
  13621. if ( attachmentProperties.__webglTexture === undefined ) {
  13622. attachmentProperties.__webglTexture = _gl.createTexture();
  13623. info.memory.textures ++;
  13624. }
  13625. }
  13626. } else {
  13627. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  13628. }
  13629. } else if ( isMultisample ) {
  13630. if ( isWebGL2 ) {
  13631. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13632. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13633. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  13634. const glFormat = utils.convert( texture.format );
  13635. const glType = utils.convert( texture.type );
  13636. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13637. const samples = getRenderTargetSamples( renderTarget );
  13638. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13639. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  13640. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  13641. _gl.bindRenderbuffer( 36161, null );
  13642. if ( renderTarget.depthBuffer ) {
  13643. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13644. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  13645. }
  13646. state.bindFramebuffer( 36160, null );
  13647. } else {
  13648. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13649. }
  13650. }
  13651. }
  13652. // Setup color buffer
  13653. if ( isCube ) {
  13654. state.bindTexture( 34067, textureProperties.__webglTexture );
  13655. setTextureParameters( 34067, texture, supportsMips );
  13656. for ( let i = 0; i < 6; i ++ ) {
  13657. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  13658. }
  13659. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13660. generateMipmap( 34067, texture, renderTarget.width, renderTarget.height );
  13661. }
  13662. state.unbindTexture();
  13663. } else if ( isMultipleRenderTargets ) {
  13664. const textures = renderTarget.texture;
  13665. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13666. const attachment = textures[ i ];
  13667. const attachmentProperties = properties.get( attachment );
  13668. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  13669. setTextureParameters( 3553, attachment, supportsMips );
  13670. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  13671. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  13672. generateMipmap( 3553, attachment, renderTarget.width, renderTarget.height );
  13673. }
  13674. }
  13675. state.unbindTexture();
  13676. } else {
  13677. let glTextureType = 3553;
  13678. if ( isRenderTarget3D ) {
  13679. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13680. if ( isWebGL2 ) {
  13681. const isTexture3D = texture.isDataTexture3D;
  13682. glTextureType = isTexture3D ? 32879 : 35866;
  13683. } else {
  13684. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  13685. }
  13686. }
  13687. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  13688. setTextureParameters( glTextureType, texture, supportsMips );
  13689. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  13690. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13691. generateMipmap( glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth );
  13692. }
  13693. state.unbindTexture();
  13694. }
  13695. // Setup depth and stencil buffers
  13696. if ( renderTarget.depthBuffer ) {
  13697. setupDepthRenderbuffer( renderTarget );
  13698. }
  13699. }
  13700. function updateRenderTargetMipmap( renderTarget ) {
  13701. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  13702. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  13703. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13704. const texture = textures[ i ];
  13705. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13706. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13707. const webglTexture = properties.get( texture ).__webglTexture;
  13708. state.bindTexture( target, webglTexture );
  13709. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  13710. state.unbindTexture();
  13711. }
  13712. }
  13713. }
  13714. function updateMultisampleRenderTarget( renderTarget ) {
  13715. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  13716. if ( isWebGL2 ) {
  13717. const width = renderTarget.width;
  13718. const height = renderTarget.height;
  13719. let mask = 16384;
  13720. if ( renderTarget.depthBuffer ) mask |= 256;
  13721. if ( renderTarget.stencilBuffer ) mask |= 1024;
  13722. const renderTargetProperties = properties.get( renderTarget );
  13723. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  13724. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  13725. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  13726. state.bindFramebuffer( 36008, null );
  13727. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  13728. } else {
  13729. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13730. }
  13731. }
  13732. }
  13733. function getRenderTargetSamples( renderTarget ) {
  13734. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  13735. Math.min( maxSamples, renderTarget.samples ) : 0;
  13736. }
  13737. function updateVideoTexture( texture ) {
  13738. const frame = info.render.frame;
  13739. // Check the last frame we updated the VideoTexture
  13740. if ( _videoTextures.get( texture ) !== frame ) {
  13741. _videoTextures.set( texture, frame );
  13742. texture.update();
  13743. }
  13744. }
  13745. // backwards compatibility
  13746. let warnedTexture2D = false;
  13747. let warnedTextureCube = false;
  13748. function safeSetTexture2D( texture, slot ) {
  13749. if ( texture && texture.isWebGLRenderTarget ) {
  13750. if ( warnedTexture2D === false ) {
  13751. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  13752. warnedTexture2D = true;
  13753. }
  13754. texture = texture.texture;
  13755. }
  13756. setTexture2D( texture, slot );
  13757. }
  13758. function safeSetTextureCube( texture, slot ) {
  13759. if ( texture && texture.isWebGLCubeRenderTarget ) {
  13760. if ( warnedTextureCube === false ) {
  13761. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  13762. warnedTextureCube = true;
  13763. }
  13764. texture = texture.texture;
  13765. }
  13766. setTextureCube( texture, slot );
  13767. }
  13768. //
  13769. this.allocateTextureUnit = allocateTextureUnit;
  13770. this.resetTextureUnits = resetTextureUnits;
  13771. this.setTexture2D = setTexture2D;
  13772. this.setTexture2DArray = setTexture2DArray;
  13773. this.setTexture3D = setTexture3D;
  13774. this.setTextureCube = setTextureCube;
  13775. this.setupRenderTarget = setupRenderTarget;
  13776. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13777. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13778. this.safeSetTexture2D = safeSetTexture2D;
  13779. this.safeSetTextureCube = safeSetTextureCube;
  13780. }
  13781. function WebGLUtils( gl, extensions, capabilities ) {
  13782. const isWebGL2 = capabilities.isWebGL2;
  13783. function convert( p ) {
  13784. let extension;
  13785. if ( p === UnsignedByteType ) return 5121;
  13786. if ( p === UnsignedShort4444Type ) return 32819;
  13787. if ( p === UnsignedShort5551Type ) return 32820;
  13788. if ( p === UnsignedShort565Type ) return 33635;
  13789. if ( p === ByteType ) return 5120;
  13790. if ( p === ShortType ) return 5122;
  13791. if ( p === UnsignedShortType ) return 5123;
  13792. if ( p === IntType ) return 5124;
  13793. if ( p === UnsignedIntType ) return 5125;
  13794. if ( p === FloatType ) return 5126;
  13795. if ( p === HalfFloatType ) {
  13796. if ( isWebGL2 ) return 5131;
  13797. extension = extensions.get( 'OES_texture_half_float' );
  13798. if ( extension !== null ) {
  13799. return extension.HALF_FLOAT_OES;
  13800. } else {
  13801. return null;
  13802. }
  13803. }
  13804. if ( p === AlphaFormat ) return 6406;
  13805. if ( p === RGBFormat ) return 6407;
  13806. if ( p === RGBAFormat ) return 6408;
  13807. if ( p === LuminanceFormat ) return 6409;
  13808. if ( p === LuminanceAlphaFormat ) return 6410;
  13809. if ( p === DepthFormat ) return 6402;
  13810. if ( p === DepthStencilFormat ) return 34041;
  13811. if ( p === RedFormat ) return 6403;
  13812. // WebGL2 formats.
  13813. if ( p === RedIntegerFormat ) return 36244;
  13814. if ( p === RGFormat ) return 33319;
  13815. if ( p === RGIntegerFormat ) return 33320;
  13816. if ( p === RGBIntegerFormat ) return 36248;
  13817. if ( p === RGBAIntegerFormat ) return 36249;
  13818. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13819. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13820. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13821. if ( extension !== null ) {
  13822. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13823. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13824. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13825. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13826. } else {
  13827. return null;
  13828. }
  13829. }
  13830. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13831. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13832. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13833. if ( extension !== null ) {
  13834. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13835. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13836. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13837. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13838. } else {
  13839. return null;
  13840. }
  13841. }
  13842. if ( p === RGB_ETC1_Format ) {
  13843. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13844. if ( extension !== null ) {
  13845. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13846. } else {
  13847. return null;
  13848. }
  13849. }
  13850. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  13851. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  13852. if ( extension !== null ) {
  13853. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  13854. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13855. }
  13856. }
  13857. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  13858. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  13859. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  13860. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  13861. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  13862. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  13863. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  13864. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  13865. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  13866. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  13867. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  13868. if ( extension !== null ) {
  13869. // TODO Complete?
  13870. return p;
  13871. } else {
  13872. return null;
  13873. }
  13874. }
  13875. if ( p === RGBA_BPTC_Format ) {
  13876. extension = extensions.get( 'EXT_texture_compression_bptc' );
  13877. if ( extension !== null ) {
  13878. // TODO Complete?
  13879. return p;
  13880. } else {
  13881. return null;
  13882. }
  13883. }
  13884. if ( p === UnsignedInt248Type ) {
  13885. if ( isWebGL2 ) return 34042;
  13886. extension = extensions.get( 'WEBGL_depth_texture' );
  13887. if ( extension !== null ) {
  13888. return extension.UNSIGNED_INT_24_8_WEBGL;
  13889. } else {
  13890. return null;
  13891. }
  13892. }
  13893. }
  13894. return { convert: convert };
  13895. }
  13896. class ArrayCamera extends PerspectiveCamera {
  13897. constructor( array = [] ) {
  13898. super();
  13899. this.cameras = array;
  13900. }
  13901. }
  13902. ArrayCamera.prototype.isArrayCamera = true;
  13903. class Group extends Object3D {
  13904. constructor() {
  13905. super();
  13906. this.type = 'Group';
  13907. }
  13908. }
  13909. Group.prototype.isGroup = true;
  13910. const _moveEvent = { type: 'move' };
  13911. class WebXRController {
  13912. constructor() {
  13913. this._targetRay = null;
  13914. this._grip = null;
  13915. this._hand = null;
  13916. }
  13917. getHandSpace() {
  13918. if ( this._hand === null ) {
  13919. this._hand = new Group();
  13920. this._hand.matrixAutoUpdate = false;
  13921. this._hand.visible = false;
  13922. this._hand.joints = {};
  13923. this._hand.inputState = { pinching: false };
  13924. }
  13925. return this._hand;
  13926. }
  13927. getTargetRaySpace() {
  13928. if ( this._targetRay === null ) {
  13929. this._targetRay = new Group();
  13930. this._targetRay.matrixAutoUpdate = false;
  13931. this._targetRay.visible = false;
  13932. this._targetRay.hasLinearVelocity = false;
  13933. this._targetRay.linearVelocity = new Vector3();
  13934. this._targetRay.hasAngularVelocity = false;
  13935. this._targetRay.angularVelocity = new Vector3();
  13936. }
  13937. return this._targetRay;
  13938. }
  13939. getGripSpace() {
  13940. if ( this._grip === null ) {
  13941. this._grip = new Group();
  13942. this._grip.matrixAutoUpdate = false;
  13943. this._grip.visible = false;
  13944. this._grip.hasLinearVelocity = false;
  13945. this._grip.linearVelocity = new Vector3();
  13946. this._grip.hasAngularVelocity = false;
  13947. this._grip.angularVelocity = new Vector3();
  13948. }
  13949. return this._grip;
  13950. }
  13951. dispatchEvent( event ) {
  13952. if ( this._targetRay !== null ) {
  13953. this._targetRay.dispatchEvent( event );
  13954. }
  13955. if ( this._grip !== null ) {
  13956. this._grip.dispatchEvent( event );
  13957. }
  13958. if ( this._hand !== null ) {
  13959. this._hand.dispatchEvent( event );
  13960. }
  13961. return this;
  13962. }
  13963. disconnect( inputSource ) {
  13964. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13965. if ( this._targetRay !== null ) {
  13966. this._targetRay.visible = false;
  13967. }
  13968. if ( this._grip !== null ) {
  13969. this._grip.visible = false;
  13970. }
  13971. if ( this._hand !== null ) {
  13972. this._hand.visible = false;
  13973. }
  13974. return this;
  13975. }
  13976. update( inputSource, frame, referenceSpace ) {
  13977. let inputPose = null;
  13978. let gripPose = null;
  13979. let handPose = null;
  13980. const targetRay = this._targetRay;
  13981. const grip = this._grip;
  13982. const hand = this._hand;
  13983. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13984. if ( targetRay !== null ) {
  13985. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13986. if ( inputPose !== null ) {
  13987. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13988. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13989. if ( inputPose.linearVelocity ) {
  13990. targetRay.hasLinearVelocity = true;
  13991. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  13992. } else {
  13993. targetRay.hasLinearVelocity = false;
  13994. }
  13995. if ( inputPose.angularVelocity ) {
  13996. targetRay.hasAngularVelocity = true;
  13997. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  13998. } else {
  13999. targetRay.hasAngularVelocity = false;
  14000. }
  14001. this.dispatchEvent( _moveEvent );
  14002. }
  14003. }
  14004. if ( hand && inputSource.hand ) {
  14005. handPose = true;
  14006. for ( const inputjoint of inputSource.hand.values() ) {
  14007. // Update the joints groups with the XRJoint poses
  14008. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14009. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14010. // The transform of this joint will be updated with the joint pose on each frame
  14011. const joint = new Group();
  14012. joint.matrixAutoUpdate = false;
  14013. joint.visible = false;
  14014. hand.joints[ inputjoint.jointName ] = joint;
  14015. // ??
  14016. hand.add( joint );
  14017. }
  14018. const joint = hand.joints[ inputjoint.jointName ];
  14019. if ( jointPose !== null ) {
  14020. joint.matrix.fromArray( jointPose.transform.matrix );
  14021. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14022. joint.jointRadius = jointPose.radius;
  14023. }
  14024. joint.visible = jointPose !== null;
  14025. }
  14026. // Custom events
  14027. // Check pinchz
  14028. const indexTip = hand.joints[ 'index-finger-tip' ];
  14029. const thumbTip = hand.joints[ 'thumb-tip' ];
  14030. const distance = indexTip.position.distanceTo( thumbTip.position );
  14031. const distanceToPinch = 0.02;
  14032. const threshold = 0.005;
  14033. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14034. hand.inputState.pinching = false;
  14035. this.dispatchEvent( {
  14036. type: 'pinchend',
  14037. handedness: inputSource.handedness,
  14038. target: this
  14039. } );
  14040. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14041. hand.inputState.pinching = true;
  14042. this.dispatchEvent( {
  14043. type: 'pinchstart',
  14044. handedness: inputSource.handedness,
  14045. target: this
  14046. } );
  14047. }
  14048. } else {
  14049. if ( grip !== null && inputSource.gripSpace ) {
  14050. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14051. if ( gripPose !== null ) {
  14052. grip.matrix.fromArray( gripPose.transform.matrix );
  14053. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14054. if ( gripPose.linearVelocity ) {
  14055. grip.hasLinearVelocity = true;
  14056. grip.linearVelocity.copy( gripPose.linearVelocity );
  14057. } else {
  14058. grip.hasLinearVelocity = false;
  14059. }
  14060. if ( gripPose.angularVelocity ) {
  14061. grip.hasAngularVelocity = true;
  14062. grip.angularVelocity.copy( gripPose.angularVelocity );
  14063. } else {
  14064. grip.hasAngularVelocity = false;
  14065. }
  14066. }
  14067. }
  14068. }
  14069. }
  14070. if ( targetRay !== null ) {
  14071. targetRay.visible = ( inputPose !== null );
  14072. }
  14073. if ( grip !== null ) {
  14074. grip.visible = ( gripPose !== null );
  14075. }
  14076. if ( hand !== null ) {
  14077. hand.visible = ( handPose !== null );
  14078. }
  14079. return this;
  14080. }
  14081. }
  14082. class WebXRManager extends EventDispatcher {
  14083. constructor( renderer, gl ) {
  14084. super();
  14085. const scope = this;
  14086. const state = renderer.state;
  14087. let session = null;
  14088. let framebufferScaleFactor = 1.0;
  14089. let referenceSpace = null;
  14090. let referenceSpaceType = 'local-floor';
  14091. let pose = null;
  14092. let glBinding = null;
  14093. let glFramebuffer = null;
  14094. let glProjLayer = null;
  14095. let glBaseLayer = null;
  14096. let isMultisample = false;
  14097. let glMultisampledFramebuffer = null;
  14098. let glColorRenderbuffer = null;
  14099. let glDepthRenderbuffer = null;
  14100. let xrFrame = null;
  14101. let depthStyle = null;
  14102. let clearStyle = null;
  14103. const controllers = [];
  14104. const inputSourcesMap = new Map();
  14105. //
  14106. const cameraL = new PerspectiveCamera();
  14107. cameraL.layers.enable( 1 );
  14108. cameraL.viewport = new Vector4();
  14109. const cameraR = new PerspectiveCamera();
  14110. cameraR.layers.enable( 2 );
  14111. cameraR.viewport = new Vector4();
  14112. const cameras = [ cameraL, cameraR ];
  14113. const cameraVR = new ArrayCamera();
  14114. cameraVR.layers.enable( 1 );
  14115. cameraVR.layers.enable( 2 );
  14116. let _currentDepthNear = null;
  14117. let _currentDepthFar = null;
  14118. //
  14119. this.cameraAutoUpdate = true;
  14120. this.enabled = false;
  14121. this.isPresenting = false;
  14122. this.getController = function ( index ) {
  14123. let controller = controllers[ index ];
  14124. if ( controller === undefined ) {
  14125. controller = new WebXRController();
  14126. controllers[ index ] = controller;
  14127. }
  14128. return controller.getTargetRaySpace();
  14129. };
  14130. this.getControllerGrip = function ( index ) {
  14131. let controller = controllers[ index ];
  14132. if ( controller === undefined ) {
  14133. controller = new WebXRController();
  14134. controllers[ index ] = controller;
  14135. }
  14136. return controller.getGripSpace();
  14137. };
  14138. this.getHand = function ( index ) {
  14139. let controller = controllers[ index ];
  14140. if ( controller === undefined ) {
  14141. controller = new WebXRController();
  14142. controllers[ index ] = controller;
  14143. }
  14144. return controller.getHandSpace();
  14145. };
  14146. //
  14147. function onSessionEvent( event ) {
  14148. const controller = inputSourcesMap.get( event.inputSource );
  14149. if ( controller ) {
  14150. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14151. }
  14152. }
  14153. function onSessionEnd() {
  14154. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14155. controller.disconnect( inputSource );
  14156. } );
  14157. inputSourcesMap.clear();
  14158. _currentDepthNear = null;
  14159. _currentDepthFar = null;
  14160. // restore framebuffer/rendering state
  14161. state.bindXRFramebuffer( null );
  14162. renderer.setRenderTarget( renderer.getRenderTarget() );
  14163. if ( glFramebuffer ) gl.deleteFramebuffer( glFramebuffer );
  14164. if ( glMultisampledFramebuffer ) gl.deleteFramebuffer( glMultisampledFramebuffer );
  14165. if ( glColorRenderbuffer ) gl.deleteRenderbuffer( glColorRenderbuffer );
  14166. if ( glDepthRenderbuffer ) gl.deleteRenderbuffer( glDepthRenderbuffer );
  14167. glFramebuffer = null;
  14168. glMultisampledFramebuffer = null;
  14169. glColorRenderbuffer = null;
  14170. glDepthRenderbuffer = null;
  14171. glBaseLayer = null;
  14172. glProjLayer = null;
  14173. glBinding = null;
  14174. session = null;
  14175. //
  14176. animation.stop();
  14177. scope.isPresenting = false;
  14178. scope.dispatchEvent( { type: 'sessionend' } );
  14179. }
  14180. this.setFramebufferScaleFactor = function ( value ) {
  14181. framebufferScaleFactor = value;
  14182. if ( scope.isPresenting === true ) {
  14183. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14184. }
  14185. };
  14186. this.setReferenceSpaceType = function ( value ) {
  14187. referenceSpaceType = value;
  14188. if ( scope.isPresenting === true ) {
  14189. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14190. }
  14191. };
  14192. this.getReferenceSpace = function () {
  14193. return referenceSpace;
  14194. };
  14195. this.getBaseLayer = function () {
  14196. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14197. };
  14198. this.getBinding = function () {
  14199. return glBinding;
  14200. };
  14201. this.getFrame = function () {
  14202. return xrFrame;
  14203. };
  14204. this.getSession = function () {
  14205. return session;
  14206. };
  14207. this.setSession = async function ( value ) {
  14208. session = value;
  14209. if ( session !== null ) {
  14210. session.addEventListener( 'select', onSessionEvent );
  14211. session.addEventListener( 'selectstart', onSessionEvent );
  14212. session.addEventListener( 'selectend', onSessionEvent );
  14213. session.addEventListener( 'squeeze', onSessionEvent );
  14214. session.addEventListener( 'squeezestart', onSessionEvent );
  14215. session.addEventListener( 'squeezeend', onSessionEvent );
  14216. session.addEventListener( 'end', onSessionEnd );
  14217. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  14218. const attributes = gl.getContextAttributes();
  14219. if ( attributes.xrCompatible !== true ) {
  14220. await gl.makeXRCompatible();
  14221. }
  14222. if ( session.renderState.layers === undefined ) {
  14223. const layerInit = {
  14224. antialias: attributes.antialias,
  14225. alpha: attributes.alpha,
  14226. depth: attributes.depth,
  14227. stencil: attributes.stencil,
  14228. framebufferScaleFactor: framebufferScaleFactor
  14229. };
  14230. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14231. session.updateRenderState( { baseLayer: glBaseLayer } );
  14232. } else if ( gl instanceof WebGLRenderingContext ) {
  14233. // Use old style webgl layer because we can't use MSAA
  14234. // WebGL2 support.
  14235. const layerInit = {
  14236. antialias: true,
  14237. alpha: attributes.alpha,
  14238. depth: attributes.depth,
  14239. stencil: attributes.stencil,
  14240. framebufferScaleFactor: framebufferScaleFactor
  14241. };
  14242. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14243. session.updateRenderState( { layers: [ glBaseLayer ] } );
  14244. } else {
  14245. isMultisample = attributes.antialias;
  14246. let depthFormat = null;
  14247. if ( attributes.depth ) {
  14248. clearStyle = 256;
  14249. if ( attributes.stencil ) clearStyle |= 1024;
  14250. depthStyle = attributes.stencil ? 33306 : 36096;
  14251. depthFormat = attributes.stencil ? 35056 : 33190;
  14252. }
  14253. const projectionlayerInit = {
  14254. colorFormat: attributes.alpha ? 32856 : 32849,
  14255. depthFormat: depthFormat,
  14256. scaleFactor: framebufferScaleFactor
  14257. };
  14258. glBinding = new XRWebGLBinding( session, gl );
  14259. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  14260. glFramebuffer = gl.createFramebuffer();
  14261. session.updateRenderState( { layers: [ glProjLayer ] } );
  14262. if ( isMultisample ) {
  14263. glMultisampledFramebuffer = gl.createFramebuffer();
  14264. glColorRenderbuffer = gl.createRenderbuffer();
  14265. gl.bindRenderbuffer( 36161, glColorRenderbuffer );
  14266. gl.renderbufferStorageMultisample(
  14267. 36161,
  14268. 4,
  14269. 32856,
  14270. glProjLayer.textureWidth,
  14271. glProjLayer.textureHeight );
  14272. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  14273. gl.framebufferRenderbuffer( 36160, 36064, 36161, glColorRenderbuffer );
  14274. gl.bindRenderbuffer( 36161, null );
  14275. if ( depthFormat !== null ) {
  14276. glDepthRenderbuffer = gl.createRenderbuffer();
  14277. gl.bindRenderbuffer( 36161, glDepthRenderbuffer );
  14278. gl.renderbufferStorageMultisample( 36161, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight );
  14279. gl.framebufferRenderbuffer( 36160, depthStyle, 36161, glDepthRenderbuffer );
  14280. gl.bindRenderbuffer( 36161, null );
  14281. }
  14282. state.bindFramebuffer( 36160, null );
  14283. }
  14284. }
  14285. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  14286. animation.setContext( session );
  14287. animation.start();
  14288. scope.isPresenting = true;
  14289. scope.dispatchEvent( { type: 'sessionstart' } );
  14290. }
  14291. };
  14292. function onInputSourcesChange( event ) {
  14293. const inputSources = session.inputSources;
  14294. // Assign inputSources to available controllers
  14295. for ( let i = 0; i < controllers.length; i ++ ) {
  14296. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14297. }
  14298. // Notify disconnected
  14299. for ( let i = 0; i < event.removed.length; i ++ ) {
  14300. const inputSource = event.removed[ i ];
  14301. const controller = inputSourcesMap.get( inputSource );
  14302. if ( controller ) {
  14303. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14304. inputSourcesMap.delete( inputSource );
  14305. }
  14306. }
  14307. // Notify connected
  14308. for ( let i = 0; i < event.added.length; i ++ ) {
  14309. const inputSource = event.added[ i ];
  14310. const controller = inputSourcesMap.get( inputSource );
  14311. if ( controller ) {
  14312. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14313. }
  14314. }
  14315. }
  14316. //
  14317. const cameraLPos = new Vector3();
  14318. const cameraRPos = new Vector3();
  14319. /**
  14320. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14321. * the cameras' projection and world matrices have already been set.
  14322. * And that near and far planes are identical for both cameras.
  14323. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14324. */
  14325. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14326. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14327. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14328. const ipd = cameraLPos.distanceTo( cameraRPos );
  14329. const projL = cameraL.projectionMatrix.elements;
  14330. const projR = cameraR.projectionMatrix.elements;
  14331. // VR systems will have identical far and near planes, and
  14332. // most likely identical top and bottom frustum extents.
  14333. // Use the left camera for these values.
  14334. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14335. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14336. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14337. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14338. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14339. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14340. const left = near * leftFov;
  14341. const right = near * rightFov;
  14342. // Calculate the new camera's position offset from the
  14343. // left camera. xOffset should be roughly half `ipd`.
  14344. const zOffset = ipd / ( - leftFov + rightFov );
  14345. const xOffset = zOffset * - leftFov;
  14346. // TODO: Better way to apply this offset?
  14347. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14348. camera.translateX( xOffset );
  14349. camera.translateZ( zOffset );
  14350. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14351. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14352. // Find the union of the frustum values of the cameras and scale
  14353. // the values so that the near plane's position does not change in world space,
  14354. // although must now be relative to the new union camera.
  14355. const near2 = near + zOffset;
  14356. const far2 = far + zOffset;
  14357. const left2 = left - xOffset;
  14358. const right2 = right + ( ipd - xOffset );
  14359. const top2 = topFov * far / far2 * near2;
  14360. const bottom2 = bottomFov * far / far2 * near2;
  14361. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14362. }
  14363. function updateCamera( camera, parent ) {
  14364. if ( parent === null ) {
  14365. camera.matrixWorld.copy( camera.matrix );
  14366. } else {
  14367. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14368. }
  14369. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14370. }
  14371. this.updateCamera = function ( camera ) {
  14372. if ( session === null ) return;
  14373. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14374. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14375. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14376. // Note that the new renderState won't apply until the next frame. See #18320
  14377. session.updateRenderState( {
  14378. depthNear: cameraVR.near,
  14379. depthFar: cameraVR.far
  14380. } );
  14381. _currentDepthNear = cameraVR.near;
  14382. _currentDepthFar = cameraVR.far;
  14383. }
  14384. const parent = camera.parent;
  14385. const cameras = cameraVR.cameras;
  14386. updateCamera( cameraVR, parent );
  14387. for ( let i = 0; i < cameras.length; i ++ ) {
  14388. updateCamera( cameras[ i ], parent );
  14389. }
  14390. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  14391. // update user camera and its children
  14392. camera.position.copy( cameraVR.position );
  14393. camera.quaternion.copy( cameraVR.quaternion );
  14394. camera.scale.copy( cameraVR.scale );
  14395. camera.matrix.copy( cameraVR.matrix );
  14396. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14397. const children = camera.children;
  14398. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14399. children[ i ].updateMatrixWorld( true );
  14400. }
  14401. // update projection matrix for proper view frustum culling
  14402. if ( cameras.length === 2 ) {
  14403. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14404. } else {
  14405. // assume single camera setup (AR)
  14406. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14407. }
  14408. };
  14409. this.getCamera = function () {
  14410. return cameraVR;
  14411. };
  14412. this.getFoveation = function () {
  14413. if ( glProjLayer !== null ) {
  14414. return glProjLayer.fixedFoveation;
  14415. }
  14416. if ( glBaseLayer !== null ) {
  14417. return glBaseLayer.fixedFoveation;
  14418. }
  14419. return undefined;
  14420. };
  14421. this.setFoveation = function ( foveation ) {
  14422. // 0 = no foveation = full resolution
  14423. // 1 = maximum foveation = the edges render at lower resolution
  14424. if ( glProjLayer !== null ) {
  14425. glProjLayer.fixedFoveation = foveation;
  14426. }
  14427. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  14428. glBaseLayer.fixedFoveation = foveation;
  14429. }
  14430. };
  14431. // Animation Loop
  14432. let onAnimationFrameCallback = null;
  14433. function onAnimationFrame( time, frame ) {
  14434. pose = frame.getViewerPose( referenceSpace );
  14435. xrFrame = frame;
  14436. if ( pose !== null ) {
  14437. const views = pose.views;
  14438. if ( glBaseLayer !== null ) {
  14439. state.bindXRFramebuffer( glBaseLayer.framebuffer );
  14440. }
  14441. let cameraVRNeedsUpdate = false;
  14442. // check if it's necessary to rebuild cameraVR's camera list
  14443. if ( views.length !== cameraVR.cameras.length ) {
  14444. cameraVR.cameras.length = 0;
  14445. cameraVRNeedsUpdate = true;
  14446. }
  14447. for ( let i = 0; i < views.length; i ++ ) {
  14448. const view = views[ i ];
  14449. let viewport = null;
  14450. if ( glBaseLayer !== null ) {
  14451. viewport = glBaseLayer.getViewport( view );
  14452. } else {
  14453. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  14454. state.bindXRFramebuffer( glFramebuffer );
  14455. if ( glSubImage.depthStencilTexture !== undefined ) {
  14456. gl.framebufferTexture2D( 36160, depthStyle, 3553, glSubImage.depthStencilTexture, 0 );
  14457. }
  14458. gl.framebufferTexture2D( 36160, 36064, 3553, glSubImage.colorTexture, 0 );
  14459. viewport = glSubImage.viewport;
  14460. }
  14461. const camera = cameras[ i ];
  14462. camera.matrix.fromArray( view.transform.matrix );
  14463. camera.projectionMatrix.fromArray( view.projectionMatrix );
  14464. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  14465. if ( i === 0 ) {
  14466. cameraVR.matrix.copy( camera.matrix );
  14467. }
  14468. if ( cameraVRNeedsUpdate === true ) {
  14469. cameraVR.cameras.push( camera );
  14470. }
  14471. }
  14472. if ( isMultisample ) {
  14473. state.bindXRFramebuffer( glMultisampledFramebuffer );
  14474. if ( clearStyle !== null ) gl.clear( clearStyle );
  14475. }
  14476. }
  14477. //
  14478. const inputSources = session.inputSources;
  14479. for ( let i = 0; i < controllers.length; i ++ ) {
  14480. const controller = controllers[ i ];
  14481. const inputSource = inputSources[ i ];
  14482. controller.update( inputSource, frame, referenceSpace );
  14483. }
  14484. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  14485. if ( isMultisample ) {
  14486. const width = glProjLayer.textureWidth;
  14487. const height = glProjLayer.textureHeight;
  14488. state.bindFramebuffer( 36008, glMultisampledFramebuffer );
  14489. state.bindFramebuffer( 36009, glFramebuffer );
  14490. // Invalidate the depth here to avoid flush of the depth data to main memory.
  14491. gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14492. gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14493. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, 16384, 9728 );
  14494. // Invalidate the MSAA buffer because it's not needed anymore.
  14495. gl.invalidateFramebuffer( 36008, [ 36064 ] );
  14496. state.bindFramebuffer( 36008, null );
  14497. state.bindFramebuffer( 36009, null );
  14498. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  14499. }
  14500. xrFrame = null;
  14501. }
  14502. const animation = new WebGLAnimation();
  14503. animation.setAnimationLoop( onAnimationFrame );
  14504. this.setAnimationLoop = function ( callback ) {
  14505. onAnimationFrameCallback = callback;
  14506. };
  14507. this.dispose = function () {};
  14508. }
  14509. }
  14510. function WebGLMaterials( properties ) {
  14511. function refreshFogUniforms( uniforms, fog ) {
  14512. uniforms.fogColor.value.copy( fog.color );
  14513. if ( fog.isFog ) {
  14514. uniforms.fogNear.value = fog.near;
  14515. uniforms.fogFar.value = fog.far;
  14516. } else if ( fog.isFogExp2 ) {
  14517. uniforms.fogDensity.value = fog.density;
  14518. }
  14519. }
  14520. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  14521. if ( material.isMeshBasicMaterial ) {
  14522. refreshUniformsCommon( uniforms, material );
  14523. } else if ( material.isMeshLambertMaterial ) {
  14524. refreshUniformsCommon( uniforms, material );
  14525. refreshUniformsLambert( uniforms, material );
  14526. } else if ( material.isMeshToonMaterial ) {
  14527. refreshUniformsCommon( uniforms, material );
  14528. refreshUniformsToon( uniforms, material );
  14529. } else if ( material.isMeshPhongMaterial ) {
  14530. refreshUniformsCommon( uniforms, material );
  14531. refreshUniformsPhong( uniforms, material );
  14532. } else if ( material.isMeshStandardMaterial ) {
  14533. refreshUniformsCommon( uniforms, material );
  14534. if ( material.isMeshPhysicalMaterial ) {
  14535. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  14536. } else {
  14537. refreshUniformsStandard( uniforms, material );
  14538. }
  14539. } else if ( material.isMeshMatcapMaterial ) {
  14540. refreshUniformsCommon( uniforms, material );
  14541. refreshUniformsMatcap( uniforms, material );
  14542. } else if ( material.isMeshDepthMaterial ) {
  14543. refreshUniformsCommon( uniforms, material );
  14544. refreshUniformsDepth( uniforms, material );
  14545. } else if ( material.isMeshDistanceMaterial ) {
  14546. refreshUniformsCommon( uniforms, material );
  14547. refreshUniformsDistance( uniforms, material );
  14548. } else if ( material.isMeshNormalMaterial ) {
  14549. refreshUniformsCommon( uniforms, material );
  14550. refreshUniformsNormal( uniforms, material );
  14551. } else if ( material.isLineBasicMaterial ) {
  14552. refreshUniformsLine( uniforms, material );
  14553. if ( material.isLineDashedMaterial ) {
  14554. refreshUniformsDash( uniforms, material );
  14555. }
  14556. } else if ( material.isPointsMaterial ) {
  14557. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  14558. } else if ( material.isSpriteMaterial ) {
  14559. refreshUniformsSprites( uniforms, material );
  14560. } else if ( material.isShadowMaterial ) {
  14561. uniforms.color.value.copy( material.color );
  14562. uniforms.opacity.value = material.opacity;
  14563. } else if ( material.isShaderMaterial ) {
  14564. material.uniformsNeedUpdate = false; // #15581
  14565. }
  14566. }
  14567. function refreshUniformsCommon( uniforms, material ) {
  14568. uniforms.opacity.value = material.opacity;
  14569. if ( material.color ) {
  14570. uniforms.diffuse.value.copy( material.color );
  14571. }
  14572. if ( material.emissive ) {
  14573. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  14574. }
  14575. if ( material.map ) {
  14576. uniforms.map.value = material.map;
  14577. }
  14578. if ( material.alphaMap ) {
  14579. uniforms.alphaMap.value = material.alphaMap;
  14580. }
  14581. if ( material.specularMap ) {
  14582. uniforms.specularMap.value = material.specularMap;
  14583. }
  14584. if ( material.alphaTest > 0 ) {
  14585. uniforms.alphaTest.value = material.alphaTest;
  14586. }
  14587. const envMap = properties.get( material ).envMap;
  14588. if ( envMap ) {
  14589. uniforms.envMap.value = envMap;
  14590. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  14591. uniforms.reflectivity.value = material.reflectivity;
  14592. uniforms.ior.value = material.ior;
  14593. uniforms.refractionRatio.value = material.refractionRatio;
  14594. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  14595. if ( maxMipLevel !== undefined ) {
  14596. uniforms.maxMipLevel.value = maxMipLevel;
  14597. }
  14598. }
  14599. if ( material.lightMap ) {
  14600. uniforms.lightMap.value = material.lightMap;
  14601. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14602. }
  14603. if ( material.aoMap ) {
  14604. uniforms.aoMap.value = material.aoMap;
  14605. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14606. }
  14607. // uv repeat and offset setting priorities
  14608. // 1. color map
  14609. // 2. specular map
  14610. // 3. displacementMap map
  14611. // 4. normal map
  14612. // 5. bump map
  14613. // 6. roughnessMap map
  14614. // 7. metalnessMap map
  14615. // 8. alphaMap map
  14616. // 9. emissiveMap map
  14617. // 10. clearcoat map
  14618. // 11. clearcoat normal map
  14619. // 12. clearcoat roughnessMap map
  14620. // 13. specular intensity map
  14621. // 14. specular tint map
  14622. // 15. transmission map
  14623. // 16. thickness map
  14624. let uvScaleMap;
  14625. if ( material.map ) {
  14626. uvScaleMap = material.map;
  14627. } else if ( material.specularMap ) {
  14628. uvScaleMap = material.specularMap;
  14629. } else if ( material.displacementMap ) {
  14630. uvScaleMap = material.displacementMap;
  14631. } else if ( material.normalMap ) {
  14632. uvScaleMap = material.normalMap;
  14633. } else if ( material.bumpMap ) {
  14634. uvScaleMap = material.bumpMap;
  14635. } else if ( material.roughnessMap ) {
  14636. uvScaleMap = material.roughnessMap;
  14637. } else if ( material.metalnessMap ) {
  14638. uvScaleMap = material.metalnessMap;
  14639. } else if ( material.alphaMap ) {
  14640. uvScaleMap = material.alphaMap;
  14641. } else if ( material.emissiveMap ) {
  14642. uvScaleMap = material.emissiveMap;
  14643. } else if ( material.clearcoatMap ) {
  14644. uvScaleMap = material.clearcoatMap;
  14645. } else if ( material.clearcoatNormalMap ) {
  14646. uvScaleMap = material.clearcoatNormalMap;
  14647. } else if ( material.clearcoatRoughnessMap ) {
  14648. uvScaleMap = material.clearcoatRoughnessMap;
  14649. } else if ( material.specularIntensityMap ) {
  14650. uvScaleMap = material.specularIntensityMap;
  14651. } else if ( material.specularTintMap ) {
  14652. uvScaleMap = material.specularTintMap;
  14653. } else if ( material.transmissionMap ) {
  14654. uvScaleMap = material.transmissionMap;
  14655. } else if ( material.thicknessMap ) {
  14656. uvScaleMap = material.thicknessMap;
  14657. }
  14658. if ( uvScaleMap !== undefined ) {
  14659. // backwards compatibility
  14660. if ( uvScaleMap.isWebGLRenderTarget ) {
  14661. uvScaleMap = uvScaleMap.texture;
  14662. }
  14663. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14664. uvScaleMap.updateMatrix();
  14665. }
  14666. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14667. }
  14668. // uv repeat and offset setting priorities for uv2
  14669. // 1. ao map
  14670. // 2. light map
  14671. let uv2ScaleMap;
  14672. if ( material.aoMap ) {
  14673. uv2ScaleMap = material.aoMap;
  14674. } else if ( material.lightMap ) {
  14675. uv2ScaleMap = material.lightMap;
  14676. }
  14677. if ( uv2ScaleMap !== undefined ) {
  14678. // backwards compatibility
  14679. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  14680. uv2ScaleMap = uv2ScaleMap.texture;
  14681. }
  14682. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  14683. uv2ScaleMap.updateMatrix();
  14684. }
  14685. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  14686. }
  14687. }
  14688. function refreshUniformsLine( uniforms, material ) {
  14689. uniforms.diffuse.value.copy( material.color );
  14690. uniforms.opacity.value = material.opacity;
  14691. }
  14692. function refreshUniformsDash( uniforms, material ) {
  14693. uniforms.dashSize.value = material.dashSize;
  14694. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14695. uniforms.scale.value = material.scale;
  14696. }
  14697. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  14698. uniforms.diffuse.value.copy( material.color );
  14699. uniforms.opacity.value = material.opacity;
  14700. uniforms.size.value = material.size * pixelRatio;
  14701. uniforms.scale.value = height * 0.5;
  14702. if ( material.map ) {
  14703. uniforms.map.value = material.map;
  14704. }
  14705. if ( material.alphaMap ) {
  14706. uniforms.alphaMap.value = material.alphaMap;
  14707. }
  14708. if ( material.alphaTest > 0 ) {
  14709. uniforms.alphaTest.value = material.alphaTest;
  14710. }
  14711. // uv repeat and offset setting priorities
  14712. // 1. color map
  14713. // 2. alpha map
  14714. let uvScaleMap;
  14715. if ( material.map ) {
  14716. uvScaleMap = material.map;
  14717. } else if ( material.alphaMap ) {
  14718. uvScaleMap = material.alphaMap;
  14719. }
  14720. if ( uvScaleMap !== undefined ) {
  14721. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14722. uvScaleMap.updateMatrix();
  14723. }
  14724. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14725. }
  14726. }
  14727. function refreshUniformsSprites( uniforms, material ) {
  14728. uniforms.diffuse.value.copy( material.color );
  14729. uniforms.opacity.value = material.opacity;
  14730. uniforms.rotation.value = material.rotation;
  14731. if ( material.map ) {
  14732. uniforms.map.value = material.map;
  14733. }
  14734. if ( material.alphaMap ) {
  14735. uniforms.alphaMap.value = material.alphaMap;
  14736. }
  14737. if ( material.alphaTest > 0 ) {
  14738. uniforms.alphaTest.value = material.alphaTest;
  14739. }
  14740. // uv repeat and offset setting priorities
  14741. // 1. color map
  14742. // 2. alpha map
  14743. let uvScaleMap;
  14744. if ( material.map ) {
  14745. uvScaleMap = material.map;
  14746. } else if ( material.alphaMap ) {
  14747. uvScaleMap = material.alphaMap;
  14748. }
  14749. if ( uvScaleMap !== undefined ) {
  14750. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14751. uvScaleMap.updateMatrix();
  14752. }
  14753. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14754. }
  14755. }
  14756. function refreshUniformsLambert( uniforms, material ) {
  14757. if ( material.emissiveMap ) {
  14758. uniforms.emissiveMap.value = material.emissiveMap;
  14759. }
  14760. }
  14761. function refreshUniformsPhong( uniforms, material ) {
  14762. uniforms.specular.value.copy( material.specular );
  14763. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14764. if ( material.emissiveMap ) {
  14765. uniforms.emissiveMap.value = material.emissiveMap;
  14766. }
  14767. if ( material.bumpMap ) {
  14768. uniforms.bumpMap.value = material.bumpMap;
  14769. uniforms.bumpScale.value = material.bumpScale;
  14770. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14771. }
  14772. if ( material.normalMap ) {
  14773. uniforms.normalMap.value = material.normalMap;
  14774. uniforms.normalScale.value.copy( material.normalScale );
  14775. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14776. }
  14777. if ( material.displacementMap ) {
  14778. uniforms.displacementMap.value = material.displacementMap;
  14779. uniforms.displacementScale.value = material.displacementScale;
  14780. uniforms.displacementBias.value = material.displacementBias;
  14781. }
  14782. }
  14783. function refreshUniformsToon( uniforms, material ) {
  14784. if ( material.gradientMap ) {
  14785. uniforms.gradientMap.value = material.gradientMap;
  14786. }
  14787. if ( material.emissiveMap ) {
  14788. uniforms.emissiveMap.value = material.emissiveMap;
  14789. }
  14790. if ( material.bumpMap ) {
  14791. uniforms.bumpMap.value = material.bumpMap;
  14792. uniforms.bumpScale.value = material.bumpScale;
  14793. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14794. }
  14795. if ( material.normalMap ) {
  14796. uniforms.normalMap.value = material.normalMap;
  14797. uniforms.normalScale.value.copy( material.normalScale );
  14798. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14799. }
  14800. if ( material.displacementMap ) {
  14801. uniforms.displacementMap.value = material.displacementMap;
  14802. uniforms.displacementScale.value = material.displacementScale;
  14803. uniforms.displacementBias.value = material.displacementBias;
  14804. }
  14805. }
  14806. function refreshUniformsStandard( uniforms, material ) {
  14807. uniforms.roughness.value = material.roughness;
  14808. uniforms.metalness.value = material.metalness;
  14809. if ( material.roughnessMap ) {
  14810. uniforms.roughnessMap.value = material.roughnessMap;
  14811. }
  14812. if ( material.metalnessMap ) {
  14813. uniforms.metalnessMap.value = material.metalnessMap;
  14814. }
  14815. if ( material.emissiveMap ) {
  14816. uniforms.emissiveMap.value = material.emissiveMap;
  14817. }
  14818. if ( material.bumpMap ) {
  14819. uniforms.bumpMap.value = material.bumpMap;
  14820. uniforms.bumpScale.value = material.bumpScale;
  14821. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14822. }
  14823. if ( material.normalMap ) {
  14824. uniforms.normalMap.value = material.normalMap;
  14825. uniforms.normalScale.value.copy( material.normalScale );
  14826. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14827. }
  14828. if ( material.displacementMap ) {
  14829. uniforms.displacementMap.value = material.displacementMap;
  14830. uniforms.displacementScale.value = material.displacementScale;
  14831. uniforms.displacementBias.value = material.displacementBias;
  14832. }
  14833. const envMap = properties.get( material ).envMap;
  14834. if ( envMap ) {
  14835. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14836. uniforms.envMapIntensity.value = material.envMapIntensity;
  14837. }
  14838. }
  14839. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  14840. refreshUniformsStandard( uniforms, material );
  14841. uniforms.ior.value = material.ior; // also part of uniforms common
  14842. if ( material.sheenTint ) uniforms.sheenTint.value.copy( material.sheenTint );
  14843. if ( material.clearcoat > 0 ) {
  14844. uniforms.clearcoat.value = material.clearcoat;
  14845. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14846. if ( material.clearcoatMap ) {
  14847. uniforms.clearcoatMap.value = material.clearcoatMap;
  14848. }
  14849. if ( material.clearcoatRoughnessMap ) {
  14850. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14851. }
  14852. if ( material.clearcoatNormalMap ) {
  14853. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  14854. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14855. if ( material.side === BackSide ) {
  14856. uniforms.clearcoatNormalScale.value.negate();
  14857. }
  14858. }
  14859. }
  14860. if ( material.transmission > 0 ) {
  14861. uniforms.transmission.value = material.transmission;
  14862. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14863. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  14864. if ( material.transmissionMap ) {
  14865. uniforms.transmissionMap.value = material.transmissionMap;
  14866. }
  14867. uniforms.thickness.value = material.thickness;
  14868. if ( material.thicknessMap ) {
  14869. uniforms.thicknessMap.value = material.thicknessMap;
  14870. }
  14871. uniforms.attenuationDistance.value = material.attenuationDistance;
  14872. uniforms.attenuationTint.value.copy( material.attenuationTint );
  14873. }
  14874. uniforms.specularIntensity.value = material.specularIntensity;
  14875. uniforms.specularTint.value.copy( material.specularTint );
  14876. if ( material.specularIntensityMap ) {
  14877. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  14878. }
  14879. if ( material.specularTintMap ) {
  14880. uniforms.specularTintMap.value = material.specularTintMap;
  14881. }
  14882. }
  14883. function refreshUniformsMatcap( uniforms, material ) {
  14884. if ( material.matcap ) {
  14885. uniforms.matcap.value = material.matcap;
  14886. }
  14887. if ( material.bumpMap ) {
  14888. uniforms.bumpMap.value = material.bumpMap;
  14889. uniforms.bumpScale.value = material.bumpScale;
  14890. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14891. }
  14892. if ( material.normalMap ) {
  14893. uniforms.normalMap.value = material.normalMap;
  14894. uniforms.normalScale.value.copy( material.normalScale );
  14895. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14896. }
  14897. if ( material.displacementMap ) {
  14898. uniforms.displacementMap.value = material.displacementMap;
  14899. uniforms.displacementScale.value = material.displacementScale;
  14900. uniforms.displacementBias.value = material.displacementBias;
  14901. }
  14902. }
  14903. function refreshUniformsDepth( uniforms, material ) {
  14904. if ( material.displacementMap ) {
  14905. uniforms.displacementMap.value = material.displacementMap;
  14906. uniforms.displacementScale.value = material.displacementScale;
  14907. uniforms.displacementBias.value = material.displacementBias;
  14908. }
  14909. }
  14910. function refreshUniformsDistance( uniforms, material ) {
  14911. if ( material.displacementMap ) {
  14912. uniforms.displacementMap.value = material.displacementMap;
  14913. uniforms.displacementScale.value = material.displacementScale;
  14914. uniforms.displacementBias.value = material.displacementBias;
  14915. }
  14916. uniforms.referencePosition.value.copy( material.referencePosition );
  14917. uniforms.nearDistance.value = material.nearDistance;
  14918. uniforms.farDistance.value = material.farDistance;
  14919. }
  14920. function refreshUniformsNormal( uniforms, material ) {
  14921. if ( material.bumpMap ) {
  14922. uniforms.bumpMap.value = material.bumpMap;
  14923. uniforms.bumpScale.value = material.bumpScale;
  14924. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14925. }
  14926. if ( material.normalMap ) {
  14927. uniforms.normalMap.value = material.normalMap;
  14928. uniforms.normalScale.value.copy( material.normalScale );
  14929. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14930. }
  14931. if ( material.displacementMap ) {
  14932. uniforms.displacementMap.value = material.displacementMap;
  14933. uniforms.displacementScale.value = material.displacementScale;
  14934. uniforms.displacementBias.value = material.displacementBias;
  14935. }
  14936. }
  14937. return {
  14938. refreshFogUniforms: refreshFogUniforms,
  14939. refreshMaterialUniforms: refreshMaterialUniforms
  14940. };
  14941. }
  14942. function createCanvasElement() {
  14943. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14944. canvas.style.display = 'block';
  14945. return canvas;
  14946. }
  14947. function WebGLRenderer( parameters = {} ) {
  14948. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14949. _context = parameters.context !== undefined ? parameters.context : null,
  14950. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14951. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14952. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14953. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14954. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14955. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14956. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14957. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14958. let currentRenderList = null;
  14959. let currentRenderState = null;
  14960. // render() can be called from within a callback triggered by another render.
  14961. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14962. const renderListStack = [];
  14963. const renderStateStack = [];
  14964. // public properties
  14965. this.domElement = _canvas;
  14966. // Debug configuration container
  14967. this.debug = {
  14968. /**
  14969. * Enables error checking and reporting when shader programs are being compiled
  14970. * @type {boolean}
  14971. */
  14972. checkShaderErrors: true
  14973. };
  14974. // clearing
  14975. this.autoClear = true;
  14976. this.autoClearColor = true;
  14977. this.autoClearDepth = true;
  14978. this.autoClearStencil = true;
  14979. // scene graph
  14980. this.sortObjects = true;
  14981. // user-defined clipping
  14982. this.clippingPlanes = [];
  14983. this.localClippingEnabled = false;
  14984. // physically based shading
  14985. this.gammaFactor = 2.0; // for backwards compatibility
  14986. this.outputEncoding = LinearEncoding;
  14987. // physical lights
  14988. this.physicallyCorrectLights = false;
  14989. // tone mapping
  14990. this.toneMapping = NoToneMapping;
  14991. this.toneMappingExposure = 1.0;
  14992. // internal properties
  14993. const _this = this;
  14994. let _isContextLost = false;
  14995. // internal state cache
  14996. let _currentActiveCubeFace = 0;
  14997. let _currentActiveMipmapLevel = 0;
  14998. let _currentRenderTarget = null;
  14999. let _currentMaterialId = - 1;
  15000. let _currentCamera = null;
  15001. const _currentViewport = new Vector4();
  15002. const _currentScissor = new Vector4();
  15003. let _currentScissorTest = null;
  15004. //
  15005. let _width = _canvas.width;
  15006. let _height = _canvas.height;
  15007. let _pixelRatio = 1;
  15008. let _opaqueSort = null;
  15009. let _transparentSort = null;
  15010. const _viewport = new Vector4( 0, 0, _width, _height );
  15011. const _scissor = new Vector4( 0, 0, _width, _height );
  15012. let _scissorTest = false;
  15013. //
  15014. const _currentDrawBuffers = [];
  15015. // frustum
  15016. const _frustum = new Frustum();
  15017. // clipping
  15018. let _clippingEnabled = false;
  15019. let _localClippingEnabled = false;
  15020. // transmission
  15021. let _transmissionRenderTarget = null;
  15022. // camera matrices cache
  15023. const _projScreenMatrix = new Matrix4();
  15024. const _vector3 = new Vector3();
  15025. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  15026. function getTargetPixelRatio() {
  15027. return _currentRenderTarget === null ? _pixelRatio : 1;
  15028. }
  15029. // initialize
  15030. let _gl = _context;
  15031. function getContext( contextNames, contextAttributes ) {
  15032. for ( let i = 0; i < contextNames.length; i ++ ) {
  15033. const contextName = contextNames[ i ];
  15034. const context = _canvas.getContext( contextName, contextAttributes );
  15035. if ( context !== null ) return context;
  15036. }
  15037. return null;
  15038. }
  15039. try {
  15040. const contextAttributes = {
  15041. alpha: _alpha,
  15042. depth: _depth,
  15043. stencil: _stencil,
  15044. antialias: _antialias,
  15045. premultipliedAlpha: _premultipliedAlpha,
  15046. preserveDrawingBuffer: _preserveDrawingBuffer,
  15047. powerPreference: _powerPreference,
  15048. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15049. };
  15050. // event listeners must be registered before WebGL context is created, see #12753
  15051. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15052. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  15053. if ( _gl === null ) {
  15054. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  15055. if ( _this.isWebGL1Renderer === true ) {
  15056. contextNames.shift();
  15057. }
  15058. _gl = getContext( contextNames, contextAttributes );
  15059. if ( _gl === null ) {
  15060. if ( getContext( contextNames ) ) {
  15061. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  15062. } else {
  15063. throw new Error( 'Error creating WebGL context.' );
  15064. }
  15065. }
  15066. }
  15067. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15068. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15069. _gl.getShaderPrecisionFormat = function () {
  15070. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  15071. };
  15072. }
  15073. } catch ( error ) {
  15074. console.error( 'THREE.WebGLRenderer: ' + error.message );
  15075. throw error;
  15076. }
  15077. let extensions, capabilities, state, info;
  15078. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15079. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15080. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15081. let utils, bindingStates;
  15082. function initGLContext() {
  15083. extensions = new WebGLExtensions( _gl );
  15084. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  15085. extensions.init( capabilities );
  15086. utils = new WebGLUtils( _gl, extensions, capabilities );
  15087. state = new WebGLState( _gl, extensions, capabilities );
  15088. _currentDrawBuffers[ 0 ] = 1029;
  15089. info = new WebGLInfo( _gl );
  15090. properties = new WebGLProperties();
  15091. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  15092. cubemaps = new WebGLCubeMaps( _this );
  15093. cubeuvmaps = new WebGLCubeUVMaps( _this );
  15094. attributes = new WebGLAttributes( _gl, capabilities );
  15095. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  15096. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  15097. objects = new WebGLObjects( _gl, geometries, attributes, info );
  15098. morphtargets = new WebGLMorphtargets( _gl );
  15099. clipping = new WebGLClipping( properties );
  15100. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  15101. materials = new WebGLMaterials( properties );
  15102. renderLists = new WebGLRenderLists( properties );
  15103. renderStates = new WebGLRenderStates( extensions, capabilities );
  15104. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  15105. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  15106. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  15107. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  15108. info.programs = programCache.programs;
  15109. _this.capabilities = capabilities;
  15110. _this.extensions = extensions;
  15111. _this.properties = properties;
  15112. _this.renderLists = renderLists;
  15113. _this.shadowMap = shadowMap;
  15114. _this.state = state;
  15115. _this.info = info;
  15116. }
  15117. initGLContext();
  15118. // xr
  15119. const xr = new WebXRManager( _this, _gl );
  15120. this.xr = xr;
  15121. // API
  15122. this.getContext = function () {
  15123. return _gl;
  15124. };
  15125. this.getContextAttributes = function () {
  15126. return _gl.getContextAttributes();
  15127. };
  15128. this.forceContextLoss = function () {
  15129. const extension = extensions.get( 'WEBGL_lose_context' );
  15130. if ( extension ) extension.loseContext();
  15131. };
  15132. this.forceContextRestore = function () {
  15133. const extension = extensions.get( 'WEBGL_lose_context' );
  15134. if ( extension ) extension.restoreContext();
  15135. };
  15136. this.getPixelRatio = function () {
  15137. return _pixelRatio;
  15138. };
  15139. this.setPixelRatio = function ( value ) {
  15140. if ( value === undefined ) return;
  15141. _pixelRatio = value;
  15142. this.setSize( _width, _height, false );
  15143. };
  15144. this.getSize = function ( target ) {
  15145. return target.set( _width, _height );
  15146. };
  15147. this.setSize = function ( width, height, updateStyle ) {
  15148. if ( xr.isPresenting ) {
  15149. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  15150. return;
  15151. }
  15152. _width = width;
  15153. _height = height;
  15154. _canvas.width = Math.floor( width * _pixelRatio );
  15155. _canvas.height = Math.floor( height * _pixelRatio );
  15156. if ( updateStyle !== false ) {
  15157. _canvas.style.width = width + 'px';
  15158. _canvas.style.height = height + 'px';
  15159. }
  15160. this.setViewport( 0, 0, width, height );
  15161. };
  15162. this.getDrawingBufferSize = function ( target ) {
  15163. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  15164. };
  15165. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  15166. _width = width;
  15167. _height = height;
  15168. _pixelRatio = pixelRatio;
  15169. _canvas.width = Math.floor( width * pixelRatio );
  15170. _canvas.height = Math.floor( height * pixelRatio );
  15171. this.setViewport( 0, 0, width, height );
  15172. };
  15173. this.getCurrentViewport = function ( target ) {
  15174. return target.copy( _currentViewport );
  15175. };
  15176. this.getViewport = function ( target ) {
  15177. return target.copy( _viewport );
  15178. };
  15179. this.setViewport = function ( x, y, width, height ) {
  15180. if ( x.isVector4 ) {
  15181. _viewport.set( x.x, x.y, x.z, x.w );
  15182. } else {
  15183. _viewport.set( x, y, width, height );
  15184. }
  15185. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  15186. };
  15187. this.getScissor = function ( target ) {
  15188. return target.copy( _scissor );
  15189. };
  15190. this.setScissor = function ( x, y, width, height ) {
  15191. if ( x.isVector4 ) {
  15192. _scissor.set( x.x, x.y, x.z, x.w );
  15193. } else {
  15194. _scissor.set( x, y, width, height );
  15195. }
  15196. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  15197. };
  15198. this.getScissorTest = function () {
  15199. return _scissorTest;
  15200. };
  15201. this.setScissorTest = function ( boolean ) {
  15202. state.setScissorTest( _scissorTest = boolean );
  15203. };
  15204. this.setOpaqueSort = function ( method ) {
  15205. _opaqueSort = method;
  15206. };
  15207. this.setTransparentSort = function ( method ) {
  15208. _transparentSort = method;
  15209. };
  15210. // Clearing
  15211. this.getClearColor = function ( target ) {
  15212. return target.copy( background.getClearColor() );
  15213. };
  15214. this.setClearColor = function () {
  15215. background.setClearColor.apply( background, arguments );
  15216. };
  15217. this.getClearAlpha = function () {
  15218. return background.getClearAlpha();
  15219. };
  15220. this.setClearAlpha = function () {
  15221. background.setClearAlpha.apply( background, arguments );
  15222. };
  15223. this.clear = function ( color, depth, stencil ) {
  15224. let bits = 0;
  15225. if ( color === undefined || color ) bits |= 16384;
  15226. if ( depth === undefined || depth ) bits |= 256;
  15227. if ( stencil === undefined || stencil ) bits |= 1024;
  15228. _gl.clear( bits );
  15229. };
  15230. this.clearColor = function () {
  15231. this.clear( true, false, false );
  15232. };
  15233. this.clearDepth = function () {
  15234. this.clear( false, true, false );
  15235. };
  15236. this.clearStencil = function () {
  15237. this.clear( false, false, true );
  15238. };
  15239. //
  15240. this.dispose = function () {
  15241. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  15242. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  15243. renderLists.dispose();
  15244. renderStates.dispose();
  15245. properties.dispose();
  15246. cubemaps.dispose();
  15247. cubeuvmaps.dispose();
  15248. objects.dispose();
  15249. bindingStates.dispose();
  15250. xr.dispose();
  15251. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  15252. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  15253. if ( _transmissionRenderTarget ) {
  15254. _transmissionRenderTarget.dispose();
  15255. _transmissionRenderTarget = null;
  15256. }
  15257. animation.stop();
  15258. };
  15259. // Events
  15260. function onContextLost( event ) {
  15261. event.preventDefault();
  15262. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  15263. _isContextLost = true;
  15264. }
  15265. function onContextRestore( /* event */ ) {
  15266. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  15267. _isContextLost = false;
  15268. const infoAutoReset = info.autoReset;
  15269. const shadowMapEnabled = shadowMap.enabled;
  15270. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15271. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15272. const shadowMapType = shadowMap.type;
  15273. initGLContext();
  15274. info.autoReset = infoAutoReset;
  15275. shadowMap.enabled = shadowMapEnabled;
  15276. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15277. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15278. shadowMap.type = shadowMapType;
  15279. }
  15280. function onMaterialDispose( event ) {
  15281. const material = event.target;
  15282. material.removeEventListener( 'dispose', onMaterialDispose );
  15283. deallocateMaterial( material );
  15284. }
  15285. // Buffer deallocation
  15286. function deallocateMaterial( material ) {
  15287. releaseMaterialProgramReferences( material );
  15288. properties.remove( material );
  15289. }
  15290. function releaseMaterialProgramReferences( material ) {
  15291. const programs = properties.get( material ).programs;
  15292. if ( programs !== undefined ) {
  15293. programs.forEach( function ( program ) {
  15294. programCache.releaseProgram( program );
  15295. } );
  15296. }
  15297. }
  15298. // Buffer rendering
  15299. function renderObjectImmediate( object, program ) {
  15300. object.render( function ( object ) {
  15301. _this.renderBufferImmediate( object, program );
  15302. } );
  15303. }
  15304. this.renderBufferImmediate = function ( object, program ) {
  15305. bindingStates.initAttributes();
  15306. const buffers = properties.get( object );
  15307. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  15308. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  15309. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  15310. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  15311. const programAttributes = program.getAttributes();
  15312. if ( object.hasPositions ) {
  15313. _gl.bindBuffer( 34962, buffers.position );
  15314. _gl.bufferData( 34962, object.positionArray, 35048 );
  15315. bindingStates.enableAttribute( programAttributes.position.location );
  15316. _gl.vertexAttribPointer( programAttributes.position.location, 3, 5126, false, 0, 0 );
  15317. }
  15318. if ( object.hasNormals ) {
  15319. _gl.bindBuffer( 34962, buffers.normal );
  15320. _gl.bufferData( 34962, object.normalArray, 35048 );
  15321. bindingStates.enableAttribute( programAttributes.normal.location );
  15322. _gl.vertexAttribPointer( programAttributes.normal.location, 3, 5126, false, 0, 0 );
  15323. }
  15324. if ( object.hasUvs ) {
  15325. _gl.bindBuffer( 34962, buffers.uv );
  15326. _gl.bufferData( 34962, object.uvArray, 35048 );
  15327. bindingStates.enableAttribute( programAttributes.uv.location );
  15328. _gl.vertexAttribPointer( programAttributes.uv.location, 2, 5126, false, 0, 0 );
  15329. }
  15330. if ( object.hasColors ) {
  15331. _gl.bindBuffer( 34962, buffers.color );
  15332. _gl.bufferData( 34962, object.colorArray, 35048 );
  15333. bindingStates.enableAttribute( programAttributes.color.location );
  15334. _gl.vertexAttribPointer( programAttributes.color.location, 3, 5126, false, 0, 0 );
  15335. }
  15336. bindingStates.disableUnusedAttributes();
  15337. _gl.drawArrays( 4, 0, object.count );
  15338. object.count = 0;
  15339. };
  15340. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15341. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15342. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15343. const program = setProgram( camera, scene, material, object );
  15344. state.setMaterial( material, frontFaceCW );
  15345. //
  15346. let index = geometry.index;
  15347. const position = geometry.attributes.position;
  15348. //
  15349. if ( index === null ) {
  15350. if ( position === undefined || position.count === 0 ) return;
  15351. } else if ( index.count === 0 ) {
  15352. return;
  15353. }
  15354. //
  15355. let rangeFactor = 1;
  15356. if ( material.wireframe === true ) {
  15357. index = geometries.getWireframeAttribute( geometry );
  15358. rangeFactor = 2;
  15359. }
  15360. if ( geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined ) {
  15361. morphtargets.update( object, geometry, material, program );
  15362. }
  15363. bindingStates.setup( object, material, program, geometry, index );
  15364. let attribute;
  15365. let renderer = bufferRenderer;
  15366. if ( index !== null ) {
  15367. attribute = attributes.get( index );
  15368. renderer = indexedBufferRenderer;
  15369. renderer.setIndex( attribute );
  15370. }
  15371. //
  15372. const dataCount = ( index !== null ) ? index.count : position.count;
  15373. const rangeStart = geometry.drawRange.start * rangeFactor;
  15374. const rangeCount = geometry.drawRange.count * rangeFactor;
  15375. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15376. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15377. const drawStart = Math.max( rangeStart, groupStart );
  15378. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15379. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15380. if ( drawCount === 0 ) return;
  15381. //
  15382. if ( object.isMesh ) {
  15383. if ( material.wireframe === true ) {
  15384. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15385. renderer.setMode( 1 );
  15386. } else {
  15387. renderer.setMode( 4 );
  15388. }
  15389. } else if ( object.isLine ) {
  15390. let lineWidth = material.linewidth;
  15391. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15392. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15393. if ( object.isLineSegments ) {
  15394. renderer.setMode( 1 );
  15395. } else if ( object.isLineLoop ) {
  15396. renderer.setMode( 2 );
  15397. } else {
  15398. renderer.setMode( 3 );
  15399. }
  15400. } else if ( object.isPoints ) {
  15401. renderer.setMode( 0 );
  15402. } else if ( object.isSprite ) {
  15403. renderer.setMode( 4 );
  15404. }
  15405. if ( object.isInstancedMesh ) {
  15406. renderer.renderInstances( drawStart, drawCount, object.count );
  15407. } else if ( geometry.isInstancedBufferGeometry ) {
  15408. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15409. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15410. } else {
  15411. renderer.render( drawStart, drawCount );
  15412. }
  15413. };
  15414. // Compile
  15415. this.compile = function ( scene, camera ) {
  15416. currentRenderState = renderStates.get( scene );
  15417. currentRenderState.init();
  15418. renderStateStack.push( currentRenderState );
  15419. scene.traverseVisible( function ( object ) {
  15420. if ( object.isLight && object.layers.test( camera.layers ) ) {
  15421. currentRenderState.pushLight( object );
  15422. if ( object.castShadow ) {
  15423. currentRenderState.pushShadow( object );
  15424. }
  15425. }
  15426. } );
  15427. currentRenderState.setupLights( _this.physicallyCorrectLights );
  15428. scene.traverse( function ( object ) {
  15429. const material = object.material;
  15430. if ( material ) {
  15431. if ( Array.isArray( material ) ) {
  15432. for ( let i = 0; i < material.length; i ++ ) {
  15433. const material2 = material[ i ];
  15434. getProgram( material2, scene, object );
  15435. }
  15436. } else {
  15437. getProgram( material, scene, object );
  15438. }
  15439. }
  15440. } );
  15441. renderStateStack.pop();
  15442. currentRenderState = null;
  15443. };
  15444. // Animation Loop
  15445. let onAnimationFrameCallback = null;
  15446. function onAnimationFrame( time ) {
  15447. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15448. }
  15449. function onXRSessionStart() {
  15450. animation.stop();
  15451. }
  15452. function onXRSessionEnd() {
  15453. animation.start();
  15454. }
  15455. const animation = new WebGLAnimation();
  15456. animation.setAnimationLoop( onAnimationFrame );
  15457. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15458. this.setAnimationLoop = function ( callback ) {
  15459. onAnimationFrameCallback = callback;
  15460. xr.setAnimationLoop( callback );
  15461. ( callback === null ) ? animation.stop() : animation.start();
  15462. };
  15463. xr.addEventListener( 'sessionstart', onXRSessionStart );
  15464. xr.addEventListener( 'sessionend', onXRSessionEnd );
  15465. // Rendering
  15466. this.render = function ( scene, camera ) {
  15467. if ( camera !== undefined && camera.isCamera !== true ) {
  15468. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15469. return;
  15470. }
  15471. if ( _isContextLost === true ) return;
  15472. // update scene graph
  15473. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15474. // update camera matrices and frustum
  15475. if ( camera.parent === null ) camera.updateMatrixWorld();
  15476. if ( xr.enabled === true && xr.isPresenting === true ) {
  15477. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  15478. camera = xr.getCamera(); // use XR camera for rendering
  15479. }
  15480. //
  15481. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  15482. currentRenderState = renderStates.get( scene, renderStateStack.length );
  15483. currentRenderState.init();
  15484. renderStateStack.push( currentRenderState );
  15485. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15486. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  15487. _localClippingEnabled = this.localClippingEnabled;
  15488. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15489. currentRenderList = renderLists.get( scene, renderListStack.length );
  15490. currentRenderList.init();
  15491. renderListStack.push( currentRenderList );
  15492. projectObject( scene, camera, 0, _this.sortObjects );
  15493. currentRenderList.finish();
  15494. if ( _this.sortObjects === true ) {
  15495. currentRenderList.sort( _opaqueSort, _transparentSort );
  15496. }
  15497. //
  15498. if ( _clippingEnabled === true ) clipping.beginShadows();
  15499. const shadowsArray = currentRenderState.state.shadowsArray;
  15500. shadowMap.render( shadowsArray, scene, camera );
  15501. if ( _clippingEnabled === true ) clipping.endShadows();
  15502. //
  15503. if ( this.info.autoReset === true ) this.info.reset();
  15504. //
  15505. background.render( currentRenderList, scene );
  15506. // render scene
  15507. currentRenderState.setupLights( _this.physicallyCorrectLights );
  15508. if ( camera.isArrayCamera ) {
  15509. const cameras = camera.cameras;
  15510. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  15511. const camera2 = cameras[ i ];
  15512. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  15513. }
  15514. } else {
  15515. renderScene( currentRenderList, scene, camera );
  15516. }
  15517. //
  15518. if ( _currentRenderTarget !== null ) {
  15519. // resolve multisample renderbuffers to a single-sample texture if necessary
  15520. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  15521. // Generate mipmap if we're using any kind of mipmap filtering
  15522. textures.updateRenderTargetMipmap( _currentRenderTarget );
  15523. }
  15524. //
  15525. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  15526. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15527. state.buffers.depth.setTest( true );
  15528. state.buffers.depth.setMask( true );
  15529. state.buffers.color.setMask( true );
  15530. state.setPolygonOffset( false );
  15531. // _gl.finish();
  15532. bindingStates.resetDefaultState();
  15533. _currentMaterialId = - 1;
  15534. _currentCamera = null;
  15535. renderStateStack.pop();
  15536. if ( renderStateStack.length > 0 ) {
  15537. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  15538. } else {
  15539. currentRenderState = null;
  15540. }
  15541. renderListStack.pop();
  15542. if ( renderListStack.length > 0 ) {
  15543. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  15544. } else {
  15545. currentRenderList = null;
  15546. }
  15547. };
  15548. function projectObject( object, camera, groupOrder, sortObjects ) {
  15549. if ( object.visible === false ) return;
  15550. const visible = object.layers.test( camera.layers );
  15551. if ( visible ) {
  15552. if ( object.isGroup ) {
  15553. groupOrder = object.renderOrder;
  15554. } else if ( object.isLOD ) {
  15555. if ( object.autoUpdate === true ) object.update( camera );
  15556. } else if ( object.isLight ) {
  15557. currentRenderState.pushLight( object );
  15558. if ( object.castShadow ) {
  15559. currentRenderState.pushShadow( object );
  15560. }
  15561. } else if ( object.isSprite ) {
  15562. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  15563. if ( sortObjects ) {
  15564. _vector3.setFromMatrixPosition( object.matrixWorld )
  15565. .applyMatrix4( _projScreenMatrix );
  15566. }
  15567. const geometry = objects.update( object );
  15568. const material = object.material;
  15569. if ( material.visible ) {
  15570. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15571. }
  15572. }
  15573. } else if ( object.isImmediateRenderObject ) {
  15574. if ( sortObjects ) {
  15575. _vector3.setFromMatrixPosition( object.matrixWorld )
  15576. .applyMatrix4( _projScreenMatrix );
  15577. }
  15578. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  15579. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15580. if ( object.isSkinnedMesh ) {
  15581. // update skeleton only once in a frame
  15582. if ( object.skeleton.frame !== info.render.frame ) {
  15583. object.skeleton.update();
  15584. object.skeleton.frame = info.render.frame;
  15585. }
  15586. }
  15587. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  15588. if ( sortObjects ) {
  15589. _vector3.setFromMatrixPosition( object.matrixWorld )
  15590. .applyMatrix4( _projScreenMatrix );
  15591. }
  15592. const geometry = objects.update( object );
  15593. const material = object.material;
  15594. if ( Array.isArray( material ) ) {
  15595. const groups = geometry.groups;
  15596. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15597. const group = groups[ i ];
  15598. const groupMaterial = material[ group.materialIndex ];
  15599. if ( groupMaterial && groupMaterial.visible ) {
  15600. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  15601. }
  15602. }
  15603. } else if ( material.visible ) {
  15604. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15605. }
  15606. }
  15607. }
  15608. }
  15609. const children = object.children;
  15610. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15611. projectObject( children[ i ], camera, groupOrder, sortObjects );
  15612. }
  15613. }
  15614. function renderScene( currentRenderList, scene, camera, viewport ) {
  15615. const opaqueObjects = currentRenderList.opaque;
  15616. const transmissiveObjects = currentRenderList.transmissive;
  15617. const transparentObjects = currentRenderList.transparent;
  15618. currentRenderState.setupLightsView( camera );
  15619. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  15620. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  15621. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  15622. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  15623. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  15624. }
  15625. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  15626. if ( _transmissionRenderTarget === null ) {
  15627. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  15628. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  15629. _transmissionRenderTarget = new renderTargetType( 1024, 1024, {
  15630. generateMipmaps: true,
  15631. type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType,
  15632. minFilter: LinearMipmapLinearFilter,
  15633. magFilter: NearestFilter,
  15634. wrapS: ClampToEdgeWrapping,
  15635. wrapT: ClampToEdgeWrapping
  15636. } );
  15637. }
  15638. const currentRenderTarget = _this.getRenderTarget();
  15639. _this.setRenderTarget( _transmissionRenderTarget );
  15640. _this.clear();
  15641. // Turn off the features which can affect the frag color for opaque objects pass.
  15642. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  15643. const currentToneMapping = _this.toneMapping;
  15644. _this.toneMapping = NoToneMapping;
  15645. renderObjects( opaqueObjects, scene, camera );
  15646. _this.toneMapping = currentToneMapping;
  15647. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  15648. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  15649. _this.setRenderTarget( currentRenderTarget );
  15650. }
  15651. function renderObjects( renderList, scene, camera ) {
  15652. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15653. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  15654. const renderItem = renderList[ i ];
  15655. const object = renderItem.object;
  15656. const geometry = renderItem.geometry;
  15657. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15658. const group = renderItem.group;
  15659. if ( object.layers.test( camera.layers ) ) {
  15660. renderObject( object, scene, camera, geometry, material, group );
  15661. }
  15662. }
  15663. }
  15664. function renderObject( object, scene, camera, geometry, material, group ) {
  15665. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15666. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15667. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15668. if ( object.isImmediateRenderObject ) {
  15669. const program = setProgram( camera, scene, material, object );
  15670. state.setMaterial( material );
  15671. bindingStates.reset();
  15672. renderObjectImmediate( object, program );
  15673. } else {
  15674. if ( material.transparent === true && material.side === DoubleSide ) {
  15675. material.side = BackSide;
  15676. material.needsUpdate = true;
  15677. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15678. material.side = FrontSide;
  15679. material.needsUpdate = true;
  15680. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15681. material.side = DoubleSide;
  15682. } else {
  15683. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15684. }
  15685. }
  15686. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15687. }
  15688. function getProgram( material, scene, object ) {
  15689. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15690. const materialProperties = properties.get( material );
  15691. const lights = currentRenderState.state.lights;
  15692. const shadowsArray = currentRenderState.state.shadowsArray;
  15693. const lightsStateVersion = lights.state.version;
  15694. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  15695. const programCacheKey = programCache.getProgramCacheKey( parameters );
  15696. let programs = materialProperties.programs;
  15697. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  15698. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15699. materialProperties.fog = scene.fog;
  15700. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  15701. if ( programs === undefined ) {
  15702. // new material
  15703. material.addEventListener( 'dispose', onMaterialDispose );
  15704. programs = new Map();
  15705. materialProperties.programs = programs;
  15706. }
  15707. let program = programs.get( programCacheKey );
  15708. if ( program !== undefined ) {
  15709. // early out if program and light state is identical
  15710. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  15711. updateCommonMaterialProperties( material, parameters );
  15712. return program;
  15713. }
  15714. } else {
  15715. parameters.uniforms = programCache.getUniforms( material );
  15716. material.onBuild( parameters, _this );
  15717. material.onBeforeCompile( parameters, _this );
  15718. program = programCache.acquireProgram( parameters, programCacheKey );
  15719. programs.set( programCacheKey, program );
  15720. materialProperties.uniforms = parameters.uniforms;
  15721. }
  15722. const uniforms = materialProperties.uniforms;
  15723. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  15724. uniforms.clippingPlanes = clipping.uniform;
  15725. }
  15726. updateCommonMaterialProperties( material, parameters );
  15727. // store the light setup it was created for
  15728. materialProperties.needsLights = materialNeedsLights( material );
  15729. materialProperties.lightsStateVersion = lightsStateVersion;
  15730. if ( materialProperties.needsLights ) {
  15731. // wire up the material to this renderer's lighting state
  15732. uniforms.ambientLightColor.value = lights.state.ambient;
  15733. uniforms.lightProbe.value = lights.state.probe;
  15734. uniforms.directionalLights.value = lights.state.directional;
  15735. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15736. uniforms.spotLights.value = lights.state.spot;
  15737. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15738. uniforms.rectAreaLights.value = lights.state.rectArea;
  15739. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15740. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15741. uniforms.pointLights.value = lights.state.point;
  15742. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15743. uniforms.hemisphereLights.value = lights.state.hemi;
  15744. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15745. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15746. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15747. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15748. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15749. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  15750. // TODO (abelnation): add area lights shadow info to uniforms
  15751. }
  15752. const progUniforms = program.getUniforms();
  15753. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15754. materialProperties.currentProgram = program;
  15755. materialProperties.uniformsList = uniformsList;
  15756. return program;
  15757. }
  15758. function updateCommonMaterialProperties( material, parameters ) {
  15759. const materialProperties = properties.get( material );
  15760. materialProperties.outputEncoding = parameters.outputEncoding;
  15761. materialProperties.instancing = parameters.instancing;
  15762. materialProperties.skinning = parameters.skinning;
  15763. materialProperties.morphTargets = parameters.morphTargets;
  15764. materialProperties.morphNormals = parameters.morphNormals;
  15765. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  15766. materialProperties.numIntersection = parameters.numClipIntersection;
  15767. materialProperties.vertexAlphas = parameters.vertexAlphas;
  15768. materialProperties.vertexTangents = parameters.vertexTangents;
  15769. }
  15770. function setProgram( camera, scene, material, object ) {
  15771. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15772. textures.resetTextureUnits();
  15773. const fog = scene.fog;
  15774. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15775. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15776. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  15777. const vertexAlphas = material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  15778. const vertexTangents = !! object.geometry && !! object.geometry.attributes.tangent;
  15779. const morphTargets = !! object.geometry && !! object.geometry.morphAttributes.position;
  15780. const morphNormals = !! object.geometry && !! object.geometry.morphAttributes.normal;
  15781. const materialProperties = properties.get( material );
  15782. const lights = currentRenderState.state.lights;
  15783. if ( _clippingEnabled === true ) {
  15784. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  15785. const useCache =
  15786. camera === _currentCamera &&
  15787. material.id === _currentMaterialId;
  15788. // we might want to call this function with some ClippingGroup
  15789. // object instead of the material, once it becomes feasible
  15790. // (#8465, #8379)
  15791. clipping.setState( material, camera, useCache );
  15792. }
  15793. }
  15794. //
  15795. let needsProgramChange = false;
  15796. if ( material.version === materialProperties.__version ) {
  15797. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  15798. needsProgramChange = true;
  15799. } else if ( materialProperties.outputEncoding !== encoding ) {
  15800. needsProgramChange = true;
  15801. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  15802. needsProgramChange = true;
  15803. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  15804. needsProgramChange = true;
  15805. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  15806. needsProgramChange = true;
  15807. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  15808. needsProgramChange = true;
  15809. } else if ( materialProperties.envMap !== envMap ) {
  15810. needsProgramChange = true;
  15811. } else if ( material.fog && materialProperties.fog !== fog ) {
  15812. needsProgramChange = true;
  15813. } else if ( materialProperties.numClippingPlanes !== undefined &&
  15814. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  15815. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  15816. needsProgramChange = true;
  15817. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  15818. needsProgramChange = true;
  15819. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  15820. needsProgramChange = true;
  15821. } else if ( materialProperties.morphTargets !== morphTargets ) {
  15822. needsProgramChange = true;
  15823. } else if ( materialProperties.morphNormals !== morphNormals ) {
  15824. needsProgramChange = true;
  15825. }
  15826. } else {
  15827. needsProgramChange = true;
  15828. materialProperties.__version = material.version;
  15829. }
  15830. //
  15831. let program = materialProperties.currentProgram;
  15832. if ( needsProgramChange === true ) {
  15833. program = getProgram( material, scene, object );
  15834. }
  15835. let refreshProgram = false;
  15836. let refreshMaterial = false;
  15837. let refreshLights = false;
  15838. const p_uniforms = program.getUniforms(),
  15839. m_uniforms = materialProperties.uniforms;
  15840. if ( state.useProgram( program.program ) ) {
  15841. refreshProgram = true;
  15842. refreshMaterial = true;
  15843. refreshLights = true;
  15844. }
  15845. if ( material.id !== _currentMaterialId ) {
  15846. _currentMaterialId = material.id;
  15847. refreshMaterial = true;
  15848. }
  15849. if ( refreshProgram || _currentCamera !== camera ) {
  15850. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  15851. if ( capabilities.logarithmicDepthBuffer ) {
  15852. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15853. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15854. }
  15855. if ( _currentCamera !== camera ) {
  15856. _currentCamera = camera;
  15857. // lighting uniforms depend on the camera so enforce an update
  15858. // now, in case this material supports lights - or later, when
  15859. // the next material that does gets activated:
  15860. refreshMaterial = true; // set to true on material change
  15861. refreshLights = true; // remains set until update done
  15862. }
  15863. // load material specific uniforms
  15864. // (shader material also gets them for the sake of genericity)
  15865. if ( material.isShaderMaterial ||
  15866. material.isMeshPhongMaterial ||
  15867. material.isMeshToonMaterial ||
  15868. material.isMeshStandardMaterial ||
  15869. material.envMap ) {
  15870. const uCamPos = p_uniforms.map.cameraPosition;
  15871. if ( uCamPos !== undefined ) {
  15872. uCamPos.setValue( _gl,
  15873. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15874. }
  15875. }
  15876. if ( material.isMeshPhongMaterial ||
  15877. material.isMeshToonMaterial ||
  15878. material.isMeshLambertMaterial ||
  15879. material.isMeshBasicMaterial ||
  15880. material.isMeshStandardMaterial ||
  15881. material.isShaderMaterial ) {
  15882. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  15883. }
  15884. if ( material.isMeshPhongMaterial ||
  15885. material.isMeshToonMaterial ||
  15886. material.isMeshLambertMaterial ||
  15887. material.isMeshBasicMaterial ||
  15888. material.isMeshStandardMaterial ||
  15889. material.isShaderMaterial ||
  15890. material.isShadowMaterial ||
  15891. object.isSkinnedMesh ) {
  15892. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  15893. }
  15894. }
  15895. // skinning uniforms must be set even if material didn't change
  15896. // auto-setting of texture unit for bone texture must go before other textures
  15897. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15898. if ( object.isSkinnedMesh ) {
  15899. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  15900. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  15901. const skeleton = object.skeleton;
  15902. if ( skeleton ) {
  15903. if ( capabilities.floatVertexTextures ) {
  15904. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  15905. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  15906. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  15907. } else {
  15908. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  15909. }
  15910. }
  15911. }
  15912. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  15913. materialProperties.receiveShadow = object.receiveShadow;
  15914. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  15915. }
  15916. if ( refreshMaterial ) {
  15917. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  15918. if ( materialProperties.needsLights ) {
  15919. // the current material requires lighting info
  15920. // note: all lighting uniforms are always set correctly
  15921. // they simply reference the renderer's state for their
  15922. // values
  15923. //
  15924. // use the current material's .needsUpdate flags to set
  15925. // the GL state when required
  15926. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15927. }
  15928. // refresh uniforms common to several materials
  15929. if ( fog && material.fog ) {
  15930. materials.refreshFogUniforms( m_uniforms, fog );
  15931. }
  15932. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  15933. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15934. }
  15935. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  15936. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15937. material.uniformsNeedUpdate = false;
  15938. }
  15939. if ( material.isSpriteMaterial ) {
  15940. p_uniforms.setValue( _gl, 'center', object.center );
  15941. }
  15942. // common matrices
  15943. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  15944. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  15945. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  15946. return program;
  15947. }
  15948. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15949. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  15950. uniforms.ambientLightColor.needsUpdate = value;
  15951. uniforms.lightProbe.needsUpdate = value;
  15952. uniforms.directionalLights.needsUpdate = value;
  15953. uniforms.directionalLightShadows.needsUpdate = value;
  15954. uniforms.pointLights.needsUpdate = value;
  15955. uniforms.pointLightShadows.needsUpdate = value;
  15956. uniforms.spotLights.needsUpdate = value;
  15957. uniforms.spotLightShadows.needsUpdate = value;
  15958. uniforms.rectAreaLights.needsUpdate = value;
  15959. uniforms.hemisphereLights.needsUpdate = value;
  15960. }
  15961. function materialNeedsLights( material ) {
  15962. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  15963. material.isMeshStandardMaterial || material.isShadowMaterial ||
  15964. ( material.isShaderMaterial && material.lights === true );
  15965. }
  15966. this.getActiveCubeFace = function () {
  15967. return _currentActiveCubeFace;
  15968. };
  15969. this.getActiveMipmapLevel = function () {
  15970. return _currentActiveMipmapLevel;
  15971. };
  15972. this.getRenderTarget = function () {
  15973. return _currentRenderTarget;
  15974. };
  15975. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  15976. _currentRenderTarget = renderTarget;
  15977. _currentActiveCubeFace = activeCubeFace;
  15978. _currentActiveMipmapLevel = activeMipmapLevel;
  15979. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  15980. textures.setupRenderTarget( renderTarget );
  15981. }
  15982. let framebuffer = null;
  15983. let isCube = false;
  15984. let isRenderTarget3D = false;
  15985. if ( renderTarget ) {
  15986. const texture = renderTarget.texture;
  15987. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  15988. isRenderTarget3D = true;
  15989. }
  15990. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15991. if ( renderTarget.isWebGLCubeRenderTarget ) {
  15992. framebuffer = __webglFramebuffer[ activeCubeFace ];
  15993. isCube = true;
  15994. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  15995. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  15996. } else {
  15997. framebuffer = __webglFramebuffer;
  15998. }
  15999. _currentViewport.copy( renderTarget.viewport );
  16000. _currentScissor.copy( renderTarget.scissor );
  16001. _currentScissorTest = renderTarget.scissorTest;
  16002. } else {
  16003. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  16004. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  16005. _currentScissorTest = _scissorTest;
  16006. }
  16007. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  16008. if ( framebufferBound && capabilities.drawBuffers ) {
  16009. let needsUpdate = false;
  16010. if ( renderTarget ) {
  16011. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  16012. const textures = renderTarget.texture;
  16013. if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
  16014. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  16015. _currentDrawBuffers[ i ] = 36064 + i;
  16016. }
  16017. _currentDrawBuffers.length = textures.length;
  16018. needsUpdate = true;
  16019. }
  16020. } else {
  16021. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
  16022. _currentDrawBuffers[ 0 ] = 36064;
  16023. _currentDrawBuffers.length = 1;
  16024. needsUpdate = true;
  16025. }
  16026. }
  16027. } else {
  16028. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
  16029. _currentDrawBuffers[ 0 ] = 1029;
  16030. _currentDrawBuffers.length = 1;
  16031. needsUpdate = true;
  16032. }
  16033. }
  16034. if ( needsUpdate ) {
  16035. if ( capabilities.isWebGL2 ) {
  16036. _gl.drawBuffers( _currentDrawBuffers );
  16037. } else {
  16038. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
  16039. }
  16040. }
  16041. }
  16042. state.viewport( _currentViewport );
  16043. state.scissor( _currentScissor );
  16044. state.setScissorTest( _currentScissorTest );
  16045. if ( isCube ) {
  16046. const textureProperties = properties.get( renderTarget.texture );
  16047. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  16048. } else if ( isRenderTarget3D ) {
  16049. const textureProperties = properties.get( renderTarget.texture );
  16050. const layer = activeCubeFace || 0;
  16051. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  16052. }
  16053. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  16054. };
  16055. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  16056. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  16057. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16058. return;
  16059. }
  16060. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16061. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  16062. framebuffer = framebuffer[ activeCubeFaceIndex ];
  16063. }
  16064. if ( framebuffer ) {
  16065. state.bindFramebuffer( 36160, framebuffer );
  16066. try {
  16067. const texture = renderTarget.texture;
  16068. const textureFormat = texture.format;
  16069. const textureType = texture.type;
  16070. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  16071. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16072. return;
  16073. }
  16074. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  16075. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  16076. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  16077. ! halfFloatSupportedByExt ) {
  16078. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16079. return;
  16080. }
  16081. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  16082. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16083. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  16084. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  16085. }
  16086. } else {
  16087. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16088. }
  16089. } finally {
  16090. // restore framebuffer of current render target if necessary
  16091. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  16092. state.bindFramebuffer( 36160, framebuffer );
  16093. }
  16094. }
  16095. };
  16096. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  16097. const levelScale = Math.pow( 2, - level );
  16098. const width = Math.floor( texture.image.width * levelScale );
  16099. const height = Math.floor( texture.image.height * levelScale );
  16100. let glFormat = utils.convert( texture.format );
  16101. if ( capabilities.isWebGL2 ) {
  16102. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  16103. // Not needed in Chrome 93+
  16104. if ( glFormat === 6407 ) glFormat = 32849;
  16105. if ( glFormat === 6408 ) glFormat = 32856;
  16106. }
  16107. textures.setTexture2D( texture, 0 );
  16108. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  16109. state.unbindTexture();
  16110. };
  16111. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  16112. const width = srcTexture.image.width;
  16113. const height = srcTexture.image.height;
  16114. const glFormat = utils.convert( dstTexture.format );
  16115. const glType = utils.convert( dstTexture.type );
  16116. textures.setTexture2D( dstTexture, 0 );
  16117. // As another texture upload may have changed pixelStorei
  16118. // parameters, make sure they are correct for the dstTexture
  16119. _gl.pixelStorei( 37440, dstTexture.flipY );
  16120. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16121. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16122. if ( srcTexture.isDataTexture ) {
  16123. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  16124. } else {
  16125. if ( srcTexture.isCompressedTexture ) {
  16126. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  16127. } else {
  16128. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  16129. }
  16130. }
  16131. // Generate mipmaps only when copying level 0
  16132. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  16133. state.unbindTexture();
  16134. };
  16135. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  16136. if ( _this.isWebGL1Renderer ) {
  16137. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  16138. return;
  16139. }
  16140. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16141. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16142. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16143. const glFormat = utils.convert( dstTexture.format );
  16144. const glType = utils.convert( dstTexture.type );
  16145. let glTarget;
  16146. if ( dstTexture.isDataTexture3D ) {
  16147. textures.setTexture3D( dstTexture, 0 );
  16148. glTarget = 32879;
  16149. } else if ( dstTexture.isDataTexture2DArray ) {
  16150. textures.setTexture2DArray( dstTexture, 0 );
  16151. glTarget = 35866;
  16152. } else {
  16153. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  16154. return;
  16155. }
  16156. _gl.pixelStorei( 37440, dstTexture.flipY );
  16157. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16158. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16159. const unpackRowLen = _gl.getParameter( 3314 );
  16160. const unpackImageHeight = _gl.getParameter( 32878 );
  16161. const unpackSkipPixels = _gl.getParameter( 3316 );
  16162. const unpackSkipRows = _gl.getParameter( 3315 );
  16163. const unpackSkipImages = _gl.getParameter( 32877 );
  16164. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  16165. _gl.pixelStorei( 3314, image.width );
  16166. _gl.pixelStorei( 32878, image.height );
  16167. _gl.pixelStorei( 3316, sourceBox.min.x );
  16168. _gl.pixelStorei( 3315, sourceBox.min.y );
  16169. _gl.pixelStorei( 32877, sourceBox.min.z );
  16170. if ( srcTexture.isDataTexture || srcTexture.isDataTexture3D ) {
  16171. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  16172. } else {
  16173. if ( srcTexture.isCompressedTexture ) {
  16174. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  16175. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  16176. } else {
  16177. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  16178. }
  16179. }
  16180. _gl.pixelStorei( 3314, unpackRowLen );
  16181. _gl.pixelStorei( 32878, unpackImageHeight );
  16182. _gl.pixelStorei( 3316, unpackSkipPixels );
  16183. _gl.pixelStorei( 3315, unpackSkipRows );
  16184. _gl.pixelStorei( 32877, unpackSkipImages );
  16185. // Generate mipmaps only when copying level 0
  16186. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  16187. state.unbindTexture();
  16188. };
  16189. this.initTexture = function ( texture ) {
  16190. textures.setTexture2D( texture, 0 );
  16191. state.unbindTexture();
  16192. };
  16193. this.resetState = function () {
  16194. _currentActiveCubeFace = 0;
  16195. _currentActiveMipmapLevel = 0;
  16196. _currentRenderTarget = null;
  16197. state.reset();
  16198. bindingStates.reset();
  16199. };
  16200. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16201. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  16202. }
  16203. }
  16204. class WebGL1Renderer extends WebGLRenderer {}
  16205. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16206. class FogExp2 {
  16207. constructor( color, density = 0.00025 ) {
  16208. this.name = '';
  16209. this.color = new Color( color );
  16210. this.density = density;
  16211. }
  16212. clone() {
  16213. return new FogExp2( this.color, this.density );
  16214. }
  16215. toJSON( /* meta */ ) {
  16216. return {
  16217. type: 'FogExp2',
  16218. color: this.color.getHex(),
  16219. density: this.density
  16220. };
  16221. }
  16222. }
  16223. FogExp2.prototype.isFogExp2 = true;
  16224. class Fog {
  16225. constructor( color, near = 1, far = 1000 ) {
  16226. this.name = '';
  16227. this.color = new Color( color );
  16228. this.near = near;
  16229. this.far = far;
  16230. }
  16231. clone() {
  16232. return new Fog( this.color, this.near, this.far );
  16233. }
  16234. toJSON( /* meta */ ) {
  16235. return {
  16236. type: 'Fog',
  16237. color: this.color.getHex(),
  16238. near: this.near,
  16239. far: this.far
  16240. };
  16241. }
  16242. }
  16243. Fog.prototype.isFog = true;
  16244. class Scene extends Object3D {
  16245. constructor() {
  16246. super();
  16247. this.type = 'Scene';
  16248. this.background = null;
  16249. this.environment = null;
  16250. this.fog = null;
  16251. this.overrideMaterial = null;
  16252. this.autoUpdate = true; // checked by the renderer
  16253. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16254. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  16255. }
  16256. }
  16257. copy( source, recursive ) {
  16258. super.copy( source, recursive );
  16259. if ( source.background !== null ) this.background = source.background.clone();
  16260. if ( source.environment !== null ) this.environment = source.environment.clone();
  16261. if ( source.fog !== null ) this.fog = source.fog.clone();
  16262. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  16263. this.autoUpdate = source.autoUpdate;
  16264. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16265. return this;
  16266. }
  16267. toJSON( meta ) {
  16268. const data = super.toJSON( meta );
  16269. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  16270. return data;
  16271. }
  16272. }
  16273. Scene.prototype.isScene = true;
  16274. class InterleavedBuffer {
  16275. constructor( array, stride ) {
  16276. this.array = array;
  16277. this.stride = stride;
  16278. this.count = array !== undefined ? array.length / stride : 0;
  16279. this.usage = StaticDrawUsage;
  16280. this.updateRange = { offset: 0, count: - 1 };
  16281. this.version = 0;
  16282. this.uuid = generateUUID();
  16283. }
  16284. onUploadCallback() {}
  16285. set needsUpdate( value ) {
  16286. if ( value === true ) this.version ++;
  16287. }
  16288. setUsage( value ) {
  16289. this.usage = value;
  16290. return this;
  16291. }
  16292. copy( source ) {
  16293. this.array = new source.array.constructor( source.array );
  16294. this.count = source.count;
  16295. this.stride = source.stride;
  16296. this.usage = source.usage;
  16297. return this;
  16298. }
  16299. copyAt( index1, attribute, index2 ) {
  16300. index1 *= this.stride;
  16301. index2 *= attribute.stride;
  16302. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  16303. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  16304. }
  16305. return this;
  16306. }
  16307. set( value, offset = 0 ) {
  16308. this.array.set( value, offset );
  16309. return this;
  16310. }
  16311. clone( data ) {
  16312. if ( data.arrayBuffers === undefined ) {
  16313. data.arrayBuffers = {};
  16314. }
  16315. if ( this.array.buffer._uuid === undefined ) {
  16316. this.array.buffer._uuid = generateUUID();
  16317. }
  16318. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16319. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  16320. }
  16321. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  16322. const ib = new this.constructor( array, this.stride );
  16323. ib.setUsage( this.usage );
  16324. return ib;
  16325. }
  16326. onUpload( callback ) {
  16327. this.onUploadCallback = callback;
  16328. return this;
  16329. }
  16330. toJSON( data ) {
  16331. if ( data.arrayBuffers === undefined ) {
  16332. data.arrayBuffers = {};
  16333. }
  16334. // generate UUID for array buffer if necessary
  16335. if ( this.array.buffer._uuid === undefined ) {
  16336. this.array.buffer._uuid = generateUUID();
  16337. }
  16338. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16339. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  16340. }
  16341. //
  16342. return {
  16343. uuid: this.uuid,
  16344. buffer: this.array.buffer._uuid,
  16345. type: this.array.constructor.name,
  16346. stride: this.stride
  16347. };
  16348. }
  16349. }
  16350. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16351. const _vector$6 = /*@__PURE__*/ new Vector3();
  16352. class InterleavedBufferAttribute {
  16353. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  16354. this.name = '';
  16355. this.data = interleavedBuffer;
  16356. this.itemSize = itemSize;
  16357. this.offset = offset;
  16358. this.normalized = normalized === true;
  16359. }
  16360. get count() {
  16361. return this.data.count;
  16362. }
  16363. get array() {
  16364. return this.data.array;
  16365. }
  16366. set needsUpdate( value ) {
  16367. this.data.needsUpdate = value;
  16368. }
  16369. applyMatrix4( m ) {
  16370. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  16371. _vector$6.x = this.getX( i );
  16372. _vector$6.y = this.getY( i );
  16373. _vector$6.z = this.getZ( i );
  16374. _vector$6.applyMatrix4( m );
  16375. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16376. }
  16377. return this;
  16378. }
  16379. applyNormalMatrix( m ) {
  16380. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16381. _vector$6.x = this.getX( i );
  16382. _vector$6.y = this.getY( i );
  16383. _vector$6.z = this.getZ( i );
  16384. _vector$6.applyNormalMatrix( m );
  16385. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16386. }
  16387. return this;
  16388. }
  16389. transformDirection( m ) {
  16390. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16391. _vector$6.x = this.getX( i );
  16392. _vector$6.y = this.getY( i );
  16393. _vector$6.z = this.getZ( i );
  16394. _vector$6.transformDirection( m );
  16395. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16396. }
  16397. return this;
  16398. }
  16399. setX( index, x ) {
  16400. this.data.array[ index * this.data.stride + this.offset ] = x;
  16401. return this;
  16402. }
  16403. setY( index, y ) {
  16404. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  16405. return this;
  16406. }
  16407. setZ( index, z ) {
  16408. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  16409. return this;
  16410. }
  16411. setW( index, w ) {
  16412. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  16413. return this;
  16414. }
  16415. getX( index ) {
  16416. return this.data.array[ index * this.data.stride + this.offset ];
  16417. }
  16418. getY( index ) {
  16419. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  16420. }
  16421. getZ( index ) {
  16422. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  16423. }
  16424. getW( index ) {
  16425. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  16426. }
  16427. setXY( index, x, y ) {
  16428. index = index * this.data.stride + this.offset;
  16429. this.data.array[ index + 0 ] = x;
  16430. this.data.array[ index + 1 ] = y;
  16431. return this;
  16432. }
  16433. setXYZ( index, x, y, z ) {
  16434. index = index * this.data.stride + this.offset;
  16435. this.data.array[ index + 0 ] = x;
  16436. this.data.array[ index + 1 ] = y;
  16437. this.data.array[ index + 2 ] = z;
  16438. return this;
  16439. }
  16440. setXYZW( index, x, y, z, w ) {
  16441. index = index * this.data.stride + this.offset;
  16442. this.data.array[ index + 0 ] = x;
  16443. this.data.array[ index + 1 ] = y;
  16444. this.data.array[ index + 2 ] = z;
  16445. this.data.array[ index + 3 ] = w;
  16446. return this;
  16447. }
  16448. clone( data ) {
  16449. if ( data === undefined ) {
  16450. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  16451. const array = [];
  16452. for ( let i = 0; i < this.count; i ++ ) {
  16453. const index = i * this.data.stride + this.offset;
  16454. for ( let j = 0; j < this.itemSize; j ++ ) {
  16455. array.push( this.data.array[ index + j ] );
  16456. }
  16457. }
  16458. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  16459. } else {
  16460. if ( data.interleavedBuffers === undefined ) {
  16461. data.interleavedBuffers = {};
  16462. }
  16463. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16464. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  16465. }
  16466. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16467. }
  16468. }
  16469. toJSON( data ) {
  16470. if ( data === undefined ) {
  16471. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16472. const array = [];
  16473. for ( let i = 0; i < this.count; i ++ ) {
  16474. const index = i * this.data.stride + this.offset;
  16475. for ( let j = 0; j < this.itemSize; j ++ ) {
  16476. array.push( this.data.array[ index + j ] );
  16477. }
  16478. }
  16479. // deinterleave data and save it as an ordinary buffer attribute for now
  16480. return {
  16481. itemSize: this.itemSize,
  16482. type: this.array.constructor.name,
  16483. array: array,
  16484. normalized: this.normalized
  16485. };
  16486. } else {
  16487. // save as true interlaved attribtue
  16488. if ( data.interleavedBuffers === undefined ) {
  16489. data.interleavedBuffers = {};
  16490. }
  16491. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16492. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  16493. }
  16494. return {
  16495. isInterleavedBufferAttribute: true,
  16496. itemSize: this.itemSize,
  16497. data: this.data.uuid,
  16498. offset: this.offset,
  16499. normalized: this.normalized
  16500. };
  16501. }
  16502. }
  16503. }
  16504. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16505. /**
  16506. * parameters = {
  16507. * color: <hex>,
  16508. * map: new THREE.Texture( <Image> ),
  16509. * alphaMap: new THREE.Texture( <Image> ),
  16510. * rotation: <float>,
  16511. * sizeAttenuation: <bool>
  16512. * }
  16513. */
  16514. class SpriteMaterial extends Material {
  16515. constructor( parameters ) {
  16516. super();
  16517. this.type = 'SpriteMaterial';
  16518. this.color = new Color( 0xffffff );
  16519. this.map = null;
  16520. this.alphaMap = null;
  16521. this.rotation = 0;
  16522. this.sizeAttenuation = true;
  16523. this.transparent = true;
  16524. this.setValues( parameters );
  16525. }
  16526. copy( source ) {
  16527. super.copy( source );
  16528. this.color.copy( source.color );
  16529. this.map = source.map;
  16530. this.alphaMap = source.alphaMap;
  16531. this.rotation = source.rotation;
  16532. this.sizeAttenuation = source.sizeAttenuation;
  16533. return this;
  16534. }
  16535. }
  16536. SpriteMaterial.prototype.isSpriteMaterial = true;
  16537. let _geometry;
  16538. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16539. const _worldScale = /*@__PURE__*/ new Vector3();
  16540. const _mvPosition = /*@__PURE__*/ new Vector3();
  16541. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16542. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16543. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16544. const _vA = /*@__PURE__*/ new Vector3();
  16545. const _vB = /*@__PURE__*/ new Vector3();
  16546. const _vC = /*@__PURE__*/ new Vector3();
  16547. const _uvA = /*@__PURE__*/ new Vector2();
  16548. const _uvB = /*@__PURE__*/ new Vector2();
  16549. const _uvC = /*@__PURE__*/ new Vector2();
  16550. class Sprite extends Object3D {
  16551. constructor( material ) {
  16552. super();
  16553. this.type = 'Sprite';
  16554. if ( _geometry === undefined ) {
  16555. _geometry = new BufferGeometry();
  16556. const float32Array = new Float32Array( [
  16557. - 0.5, - 0.5, 0, 0, 0,
  16558. 0.5, - 0.5, 0, 1, 0,
  16559. 0.5, 0.5, 0, 1, 1,
  16560. - 0.5, 0.5, 0, 0, 1
  16561. ] );
  16562. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16563. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16564. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16565. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16566. }
  16567. this.geometry = _geometry;
  16568. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  16569. this.center = new Vector2( 0.5, 0.5 );
  16570. }
  16571. raycast( raycaster, intersects ) {
  16572. if ( raycaster.camera === null ) {
  16573. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16574. }
  16575. _worldScale.setFromMatrixScale( this.matrixWorld );
  16576. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16577. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16578. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16579. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16580. _worldScale.multiplyScalar( - _mvPosition.z );
  16581. }
  16582. const rotation = this.material.rotation;
  16583. let sin, cos;
  16584. if ( rotation !== 0 ) {
  16585. cos = Math.cos( rotation );
  16586. sin = Math.sin( rotation );
  16587. }
  16588. const center = this.center;
  16589. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16590. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16591. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16592. _uvA.set( 0, 0 );
  16593. _uvB.set( 1, 0 );
  16594. _uvC.set( 1, 1 );
  16595. // check first triangle
  16596. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  16597. if ( intersect === null ) {
  16598. // check second triangle
  16599. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16600. _uvB.set( 0, 1 );
  16601. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  16602. if ( intersect === null ) {
  16603. return;
  16604. }
  16605. }
  16606. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16607. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16608. intersects.push( {
  16609. distance: distance,
  16610. point: _intersectPoint.clone(),
  16611. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  16612. face: null,
  16613. object: this
  16614. } );
  16615. }
  16616. copy( source ) {
  16617. super.copy( source );
  16618. if ( source.center !== undefined ) this.center.copy( source.center );
  16619. this.material = source.material;
  16620. return this;
  16621. }
  16622. }
  16623. Sprite.prototype.isSprite = true;
  16624. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16625. // compute position in camera space
  16626. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16627. // to check if rotation is not zero
  16628. if ( sin !== undefined ) {
  16629. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16630. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16631. } else {
  16632. _rotatedPosition.copy( _alignedPosition );
  16633. }
  16634. vertexPosition.copy( mvPosition );
  16635. vertexPosition.x += _rotatedPosition.x;
  16636. vertexPosition.y += _rotatedPosition.y;
  16637. // transform to world space
  16638. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16639. }
  16640. const _v1$2 = /*@__PURE__*/ new Vector3();
  16641. const _v2$1 = /*@__PURE__*/ new Vector3();
  16642. class LOD extends Object3D {
  16643. constructor() {
  16644. super();
  16645. this._currentLevel = 0;
  16646. this.type = 'LOD';
  16647. Object.defineProperties( this, {
  16648. levels: {
  16649. enumerable: true,
  16650. value: []
  16651. },
  16652. isLOD: {
  16653. value: true,
  16654. }
  16655. } );
  16656. this.autoUpdate = true;
  16657. }
  16658. copy( source ) {
  16659. super.copy( source, false );
  16660. const levels = source.levels;
  16661. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16662. const level = levels[ i ];
  16663. this.addLevel( level.object.clone(), level.distance );
  16664. }
  16665. this.autoUpdate = source.autoUpdate;
  16666. return this;
  16667. }
  16668. addLevel( object, distance = 0 ) {
  16669. distance = Math.abs( distance );
  16670. const levels = this.levels;
  16671. let l;
  16672. for ( l = 0; l < levels.length; l ++ ) {
  16673. if ( distance < levels[ l ].distance ) {
  16674. break;
  16675. }
  16676. }
  16677. levels.splice( l, 0, { distance: distance, object: object } );
  16678. this.add( object );
  16679. return this;
  16680. }
  16681. getCurrentLevel() {
  16682. return this._currentLevel;
  16683. }
  16684. getObjectForDistance( distance ) {
  16685. const levels = this.levels;
  16686. if ( levels.length > 0 ) {
  16687. let i, l;
  16688. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16689. if ( distance < levels[ i ].distance ) {
  16690. break;
  16691. }
  16692. }
  16693. return levels[ i - 1 ].object;
  16694. }
  16695. return null;
  16696. }
  16697. raycast( raycaster, intersects ) {
  16698. const levels = this.levels;
  16699. if ( levels.length > 0 ) {
  16700. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16701. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16702. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16703. }
  16704. }
  16705. update( camera ) {
  16706. const levels = this.levels;
  16707. if ( levels.length > 1 ) {
  16708. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16709. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16710. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16711. levels[ 0 ].object.visible = true;
  16712. let i, l;
  16713. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16714. if ( distance >= levels[ i ].distance ) {
  16715. levels[ i - 1 ].object.visible = false;
  16716. levels[ i ].object.visible = true;
  16717. } else {
  16718. break;
  16719. }
  16720. }
  16721. this._currentLevel = i - 1;
  16722. for ( ; i < l; i ++ ) {
  16723. levels[ i ].object.visible = false;
  16724. }
  16725. }
  16726. }
  16727. toJSON( meta ) {
  16728. const data = super.toJSON( meta );
  16729. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16730. data.object.levels = [];
  16731. const levels = this.levels;
  16732. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16733. const level = levels[ i ];
  16734. data.object.levels.push( {
  16735. object: level.object.uuid,
  16736. distance: level.distance
  16737. } );
  16738. }
  16739. return data;
  16740. }
  16741. }
  16742. const _basePosition = /*@__PURE__*/ new Vector3();
  16743. const _skinIndex = /*@__PURE__*/ new Vector4();
  16744. const _skinWeight = /*@__PURE__*/ new Vector4();
  16745. const _vector$5 = /*@__PURE__*/ new Vector3();
  16746. const _matrix = /*@__PURE__*/ new Matrix4();
  16747. class SkinnedMesh extends Mesh {
  16748. constructor( geometry, material ) {
  16749. super( geometry, material );
  16750. this.type = 'SkinnedMesh';
  16751. this.bindMode = 'attached';
  16752. this.bindMatrix = new Matrix4();
  16753. this.bindMatrixInverse = new Matrix4();
  16754. }
  16755. copy( source ) {
  16756. super.copy( source );
  16757. this.bindMode = source.bindMode;
  16758. this.bindMatrix.copy( source.bindMatrix );
  16759. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  16760. this.skeleton = source.skeleton;
  16761. return this;
  16762. }
  16763. bind( skeleton, bindMatrix ) {
  16764. this.skeleton = skeleton;
  16765. if ( bindMatrix === undefined ) {
  16766. this.updateMatrixWorld( true );
  16767. this.skeleton.calculateInverses();
  16768. bindMatrix = this.matrixWorld;
  16769. }
  16770. this.bindMatrix.copy( bindMatrix );
  16771. this.bindMatrixInverse.copy( bindMatrix ).invert();
  16772. }
  16773. pose() {
  16774. this.skeleton.pose();
  16775. }
  16776. normalizeSkinWeights() {
  16777. const vector = new Vector4();
  16778. const skinWeight = this.geometry.attributes.skinWeight;
  16779. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  16780. vector.x = skinWeight.getX( i );
  16781. vector.y = skinWeight.getY( i );
  16782. vector.z = skinWeight.getZ( i );
  16783. vector.w = skinWeight.getW( i );
  16784. const scale = 1.0 / vector.manhattanLength();
  16785. if ( scale !== Infinity ) {
  16786. vector.multiplyScalar( scale );
  16787. } else {
  16788. vector.set( 1, 0, 0, 0 ); // do something reasonable
  16789. }
  16790. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  16791. }
  16792. }
  16793. updateMatrixWorld( force ) {
  16794. super.updateMatrixWorld( force );
  16795. if ( this.bindMode === 'attached' ) {
  16796. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  16797. } else if ( this.bindMode === 'detached' ) {
  16798. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  16799. } else {
  16800. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  16801. }
  16802. }
  16803. boneTransform( index, target ) {
  16804. const skeleton = this.skeleton;
  16805. const geometry = this.geometry;
  16806. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  16807. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  16808. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  16809. target.set( 0, 0, 0 );
  16810. for ( let i = 0; i < 4; i ++ ) {
  16811. const weight = _skinWeight.getComponent( i );
  16812. if ( weight !== 0 ) {
  16813. const boneIndex = _skinIndex.getComponent( i );
  16814. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  16815. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  16816. }
  16817. }
  16818. return target.applyMatrix4( this.bindMatrixInverse );
  16819. }
  16820. }
  16821. SkinnedMesh.prototype.isSkinnedMesh = true;
  16822. class Bone extends Object3D {
  16823. constructor() {
  16824. super();
  16825. this.type = 'Bone';
  16826. }
  16827. }
  16828. Bone.prototype.isBone = true;
  16829. class DataTexture extends Texture {
  16830. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  16831. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16832. this.image = { data: data, width: width, height: height };
  16833. this.magFilter = magFilter;
  16834. this.minFilter = minFilter;
  16835. this.generateMipmaps = false;
  16836. this.flipY = false;
  16837. this.unpackAlignment = 1;
  16838. this.needsUpdate = true;
  16839. }
  16840. }
  16841. DataTexture.prototype.isDataTexture = true;
  16842. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  16843. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  16844. class Skeleton {
  16845. constructor( bones = [], boneInverses = [] ) {
  16846. this.uuid = generateUUID();
  16847. this.bones = bones.slice( 0 );
  16848. this.boneInverses = boneInverses;
  16849. this.boneMatrices = null;
  16850. this.boneTexture = null;
  16851. this.boneTextureSize = 0;
  16852. this.frame = - 1;
  16853. this.init();
  16854. }
  16855. init() {
  16856. const bones = this.bones;
  16857. const boneInverses = this.boneInverses;
  16858. this.boneMatrices = new Float32Array( bones.length * 16 );
  16859. // calculate inverse bone matrices if necessary
  16860. if ( boneInverses.length === 0 ) {
  16861. this.calculateInverses();
  16862. } else {
  16863. // handle special case
  16864. if ( bones.length !== boneInverses.length ) {
  16865. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  16866. this.boneInverses = [];
  16867. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16868. this.boneInverses.push( new Matrix4() );
  16869. }
  16870. }
  16871. }
  16872. }
  16873. calculateInverses() {
  16874. this.boneInverses.length = 0;
  16875. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16876. const inverse = new Matrix4();
  16877. if ( this.bones[ i ] ) {
  16878. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  16879. }
  16880. this.boneInverses.push( inverse );
  16881. }
  16882. }
  16883. pose() {
  16884. // recover the bind-time world matrices
  16885. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16886. const bone = this.bones[ i ];
  16887. if ( bone ) {
  16888. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  16889. }
  16890. }
  16891. // compute the local matrices, positions, rotations and scales
  16892. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16893. const bone = this.bones[ i ];
  16894. if ( bone ) {
  16895. if ( bone.parent && bone.parent.isBone ) {
  16896. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  16897. bone.matrix.multiply( bone.matrixWorld );
  16898. } else {
  16899. bone.matrix.copy( bone.matrixWorld );
  16900. }
  16901. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  16902. }
  16903. }
  16904. }
  16905. update() {
  16906. const bones = this.bones;
  16907. const boneInverses = this.boneInverses;
  16908. const boneMatrices = this.boneMatrices;
  16909. const boneTexture = this.boneTexture;
  16910. // flatten bone matrices to array
  16911. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  16912. // compute the offset between the current and the original transform
  16913. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  16914. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  16915. _offsetMatrix.toArray( boneMatrices, i * 16 );
  16916. }
  16917. if ( boneTexture !== null ) {
  16918. boneTexture.needsUpdate = true;
  16919. }
  16920. }
  16921. clone() {
  16922. return new Skeleton( this.bones, this.boneInverses );
  16923. }
  16924. computeBoneTexture() {
  16925. // layout (1 matrix = 4 pixels)
  16926. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16927. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16928. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16929. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16930. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16931. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  16932. size = ceilPowerOfTwo( size );
  16933. size = Math.max( size, 4 );
  16934. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  16935. boneMatrices.set( this.boneMatrices ); // copy current values
  16936. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  16937. this.boneMatrices = boneMatrices;
  16938. this.boneTexture = boneTexture;
  16939. this.boneTextureSize = size;
  16940. return this;
  16941. }
  16942. getBoneByName( name ) {
  16943. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16944. const bone = this.bones[ i ];
  16945. if ( bone.name === name ) {
  16946. return bone;
  16947. }
  16948. }
  16949. return undefined;
  16950. }
  16951. dispose( ) {
  16952. if ( this.boneTexture !== null ) {
  16953. this.boneTexture.dispose();
  16954. this.boneTexture = null;
  16955. }
  16956. }
  16957. fromJSON( json, bones ) {
  16958. this.uuid = json.uuid;
  16959. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  16960. const uuid = json.bones[ i ];
  16961. let bone = bones[ uuid ];
  16962. if ( bone === undefined ) {
  16963. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  16964. bone = new Bone();
  16965. }
  16966. this.bones.push( bone );
  16967. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  16968. }
  16969. this.init();
  16970. return this;
  16971. }
  16972. toJSON() {
  16973. const data = {
  16974. metadata: {
  16975. version: 4.5,
  16976. type: 'Skeleton',
  16977. generator: 'Skeleton.toJSON'
  16978. },
  16979. bones: [],
  16980. boneInverses: []
  16981. };
  16982. data.uuid = this.uuid;
  16983. const bones = this.bones;
  16984. const boneInverses = this.boneInverses;
  16985. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  16986. const bone = bones[ i ];
  16987. data.bones.push( bone.uuid );
  16988. const boneInverse = boneInverses[ i ];
  16989. data.boneInverses.push( boneInverse.toArray() );
  16990. }
  16991. return data;
  16992. }
  16993. }
  16994. class InstancedBufferAttribute extends BufferAttribute {
  16995. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  16996. if ( typeof normalized === 'number' ) {
  16997. meshPerAttribute = normalized;
  16998. normalized = false;
  16999. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  17000. }
  17001. super( array, itemSize, normalized );
  17002. this.meshPerAttribute = meshPerAttribute;
  17003. }
  17004. copy( source ) {
  17005. super.copy( source );
  17006. this.meshPerAttribute = source.meshPerAttribute;
  17007. return this;
  17008. }
  17009. toJSON() {
  17010. const data = super.toJSON();
  17011. data.meshPerAttribute = this.meshPerAttribute;
  17012. data.isInstancedBufferAttribute = true;
  17013. return data;
  17014. }
  17015. }
  17016. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17017. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17018. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17019. const _instanceIntersects = [];
  17020. const _mesh = /*@__PURE__*/ new Mesh();
  17021. class InstancedMesh extends Mesh {
  17022. constructor( geometry, material, count ) {
  17023. super( geometry, material );
  17024. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  17025. this.instanceColor = null;
  17026. this.count = count;
  17027. this.frustumCulled = false;
  17028. }
  17029. copy( source ) {
  17030. super.copy( source );
  17031. this.instanceMatrix.copy( source.instanceMatrix );
  17032. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  17033. this.count = source.count;
  17034. return this;
  17035. }
  17036. getColorAt( index, color ) {
  17037. color.fromArray( this.instanceColor.array, index * 3 );
  17038. }
  17039. getMatrixAt( index, matrix ) {
  17040. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  17041. }
  17042. raycast( raycaster, intersects ) {
  17043. const matrixWorld = this.matrixWorld;
  17044. const raycastTimes = this.count;
  17045. _mesh.geometry = this.geometry;
  17046. _mesh.material = this.material;
  17047. if ( _mesh.material === undefined ) return;
  17048. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  17049. // calculate the world matrix for each instance
  17050. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  17051. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  17052. // the mesh represents this single instance
  17053. _mesh.matrixWorld = _instanceWorldMatrix;
  17054. _mesh.raycast( raycaster, _instanceIntersects );
  17055. // process the result of raycast
  17056. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  17057. const intersect = _instanceIntersects[ i ];
  17058. intersect.instanceId = instanceId;
  17059. intersect.object = this;
  17060. intersects.push( intersect );
  17061. }
  17062. _instanceIntersects.length = 0;
  17063. }
  17064. }
  17065. setColorAt( index, color ) {
  17066. if ( this.instanceColor === null ) {
  17067. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  17068. }
  17069. color.toArray( this.instanceColor.array, index * 3 );
  17070. }
  17071. setMatrixAt( index, matrix ) {
  17072. matrix.toArray( this.instanceMatrix.array, index * 16 );
  17073. }
  17074. updateMorphTargets() {
  17075. }
  17076. dispose() {
  17077. this.dispatchEvent( { type: 'dispose' } );
  17078. }
  17079. }
  17080. InstancedMesh.prototype.isInstancedMesh = true;
  17081. /**
  17082. * parameters = {
  17083. * color: <hex>,
  17084. * opacity: <float>,
  17085. *
  17086. * linewidth: <float>,
  17087. * linecap: "round",
  17088. * linejoin: "round"
  17089. * }
  17090. */
  17091. class LineBasicMaterial extends Material {
  17092. constructor( parameters ) {
  17093. super();
  17094. this.type = 'LineBasicMaterial';
  17095. this.color = new Color( 0xffffff );
  17096. this.linewidth = 1;
  17097. this.linecap = 'round';
  17098. this.linejoin = 'round';
  17099. this.setValues( parameters );
  17100. }
  17101. copy( source ) {
  17102. super.copy( source );
  17103. this.color.copy( source.color );
  17104. this.linewidth = source.linewidth;
  17105. this.linecap = source.linecap;
  17106. this.linejoin = source.linejoin;
  17107. return this;
  17108. }
  17109. }
  17110. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17111. const _start$1 = /*@__PURE__*/ new Vector3();
  17112. const _end$1 = /*@__PURE__*/ new Vector3();
  17113. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  17114. const _ray$1 = /*@__PURE__*/ new Ray();
  17115. const _sphere$1 = /*@__PURE__*/ new Sphere();
  17116. class Line extends Object3D {
  17117. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  17118. super();
  17119. this.type = 'Line';
  17120. this.geometry = geometry;
  17121. this.material = material;
  17122. this.updateMorphTargets();
  17123. }
  17124. copy( source ) {
  17125. super.copy( source );
  17126. this.material = source.material;
  17127. this.geometry = source.geometry;
  17128. return this;
  17129. }
  17130. computeLineDistances() {
  17131. const geometry = this.geometry;
  17132. if ( geometry.isBufferGeometry ) {
  17133. // we assume non-indexed geometry
  17134. if ( geometry.index === null ) {
  17135. const positionAttribute = geometry.attributes.position;
  17136. const lineDistances = [ 0 ];
  17137. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  17138. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  17139. _end$1.fromBufferAttribute( positionAttribute, i );
  17140. lineDistances[ i ] = lineDistances[ i - 1 ];
  17141. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  17142. }
  17143. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17144. } else {
  17145. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17146. }
  17147. } else if ( geometry.isGeometry ) {
  17148. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17149. }
  17150. return this;
  17151. }
  17152. raycast( raycaster, intersects ) {
  17153. const geometry = this.geometry;
  17154. const matrixWorld = this.matrixWorld;
  17155. const threshold = raycaster.params.Line.threshold;
  17156. const drawRange = geometry.drawRange;
  17157. // Checking boundingSphere distance to ray
  17158. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17159. _sphere$1.copy( geometry.boundingSphere );
  17160. _sphere$1.applyMatrix4( matrixWorld );
  17161. _sphere$1.radius += threshold;
  17162. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  17163. //
  17164. _inverseMatrix$1.copy( matrixWorld ).invert();
  17165. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  17166. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17167. const localThresholdSq = localThreshold * localThreshold;
  17168. const vStart = new Vector3();
  17169. const vEnd = new Vector3();
  17170. const interSegment = new Vector3();
  17171. const interRay = new Vector3();
  17172. const step = this.isLineSegments ? 2 : 1;
  17173. if ( geometry.isBufferGeometry ) {
  17174. const index = geometry.index;
  17175. const attributes = geometry.attributes;
  17176. const positionAttribute = attributes.position;
  17177. if ( index !== null ) {
  17178. const start = Math.max( 0, drawRange.start );
  17179. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17180. for ( let i = start, l = end - 1; i < l; i += step ) {
  17181. const a = index.getX( i );
  17182. const b = index.getX( i + 1 );
  17183. vStart.fromBufferAttribute( positionAttribute, a );
  17184. vEnd.fromBufferAttribute( positionAttribute, b );
  17185. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17186. if ( distSq > localThresholdSq ) continue;
  17187. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17188. const distance = raycaster.ray.origin.distanceTo( interRay );
  17189. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17190. intersects.push( {
  17191. distance: distance,
  17192. // What do we want? intersection point on the ray or on the segment??
  17193. // point: raycaster.ray.at( distance ),
  17194. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17195. index: i,
  17196. face: null,
  17197. faceIndex: null,
  17198. object: this
  17199. } );
  17200. }
  17201. } else {
  17202. const start = Math.max( 0, drawRange.start );
  17203. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17204. for ( let i = start, l = end - 1; i < l; i += step ) {
  17205. vStart.fromBufferAttribute( positionAttribute, i );
  17206. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  17207. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17208. if ( distSq > localThresholdSq ) continue;
  17209. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17210. const distance = raycaster.ray.origin.distanceTo( interRay );
  17211. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17212. intersects.push( {
  17213. distance: distance,
  17214. // What do we want? intersection point on the ray or on the segment??
  17215. // point: raycaster.ray.at( distance ),
  17216. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17217. index: i,
  17218. face: null,
  17219. faceIndex: null,
  17220. object: this
  17221. } );
  17222. }
  17223. }
  17224. } else if ( geometry.isGeometry ) {
  17225. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17226. }
  17227. }
  17228. updateMorphTargets() {
  17229. const geometry = this.geometry;
  17230. if ( geometry.isBufferGeometry ) {
  17231. const morphAttributes = geometry.morphAttributes;
  17232. const keys = Object.keys( morphAttributes );
  17233. if ( keys.length > 0 ) {
  17234. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17235. if ( morphAttribute !== undefined ) {
  17236. this.morphTargetInfluences = [];
  17237. this.morphTargetDictionary = {};
  17238. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17239. const name = morphAttribute[ m ].name || String( m );
  17240. this.morphTargetInfluences.push( 0 );
  17241. this.morphTargetDictionary[ name ] = m;
  17242. }
  17243. }
  17244. }
  17245. } else {
  17246. const morphTargets = geometry.morphTargets;
  17247. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17248. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17249. }
  17250. }
  17251. }
  17252. }
  17253. Line.prototype.isLine = true;
  17254. const _start = /*@__PURE__*/ new Vector3();
  17255. const _end = /*@__PURE__*/ new Vector3();
  17256. class LineSegments extends Line {
  17257. constructor( geometry, material ) {
  17258. super( geometry, material );
  17259. this.type = 'LineSegments';
  17260. }
  17261. computeLineDistances() {
  17262. const geometry = this.geometry;
  17263. if ( geometry.isBufferGeometry ) {
  17264. // we assume non-indexed geometry
  17265. if ( geometry.index === null ) {
  17266. const positionAttribute = geometry.attributes.position;
  17267. const lineDistances = [];
  17268. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  17269. _start.fromBufferAttribute( positionAttribute, i );
  17270. _end.fromBufferAttribute( positionAttribute, i + 1 );
  17271. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  17272. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  17273. }
  17274. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17275. } else {
  17276. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17277. }
  17278. } else if ( geometry.isGeometry ) {
  17279. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17280. }
  17281. return this;
  17282. }
  17283. }
  17284. LineSegments.prototype.isLineSegments = true;
  17285. class LineLoop extends Line {
  17286. constructor( geometry, material ) {
  17287. super( geometry, material );
  17288. this.type = 'LineLoop';
  17289. }
  17290. }
  17291. LineLoop.prototype.isLineLoop = true;
  17292. /**
  17293. * parameters = {
  17294. * color: <hex>,
  17295. * opacity: <float>,
  17296. * map: new THREE.Texture( <Image> ),
  17297. * alphaMap: new THREE.Texture( <Image> ),
  17298. *
  17299. * size: <float>,
  17300. * sizeAttenuation: <bool>
  17301. *
  17302. * }
  17303. */
  17304. class PointsMaterial extends Material {
  17305. constructor( parameters ) {
  17306. super();
  17307. this.type = 'PointsMaterial';
  17308. this.color = new Color( 0xffffff );
  17309. this.map = null;
  17310. this.alphaMap = null;
  17311. this.size = 1;
  17312. this.sizeAttenuation = true;
  17313. this.setValues( parameters );
  17314. }
  17315. copy( source ) {
  17316. super.copy( source );
  17317. this.color.copy( source.color );
  17318. this.map = source.map;
  17319. this.alphaMap = source.alphaMap;
  17320. this.size = source.size;
  17321. this.sizeAttenuation = source.sizeAttenuation;
  17322. return this;
  17323. }
  17324. }
  17325. PointsMaterial.prototype.isPointsMaterial = true;
  17326. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  17327. const _ray = /*@__PURE__*/ new Ray();
  17328. const _sphere = /*@__PURE__*/ new Sphere();
  17329. const _position$2 = /*@__PURE__*/ new Vector3();
  17330. class Points extends Object3D {
  17331. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  17332. super();
  17333. this.type = 'Points';
  17334. this.geometry = geometry;
  17335. this.material = material;
  17336. this.updateMorphTargets();
  17337. }
  17338. copy( source ) {
  17339. super.copy( source );
  17340. this.material = source.material;
  17341. this.geometry = source.geometry;
  17342. return this;
  17343. }
  17344. raycast( raycaster, intersects ) {
  17345. const geometry = this.geometry;
  17346. const matrixWorld = this.matrixWorld;
  17347. const threshold = raycaster.params.Points.threshold;
  17348. const drawRange = geometry.drawRange;
  17349. // Checking boundingSphere distance to ray
  17350. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17351. _sphere.copy( geometry.boundingSphere );
  17352. _sphere.applyMatrix4( matrixWorld );
  17353. _sphere.radius += threshold;
  17354. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  17355. //
  17356. _inverseMatrix.copy( matrixWorld ).invert();
  17357. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  17358. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17359. const localThresholdSq = localThreshold * localThreshold;
  17360. if ( geometry.isBufferGeometry ) {
  17361. const index = geometry.index;
  17362. const attributes = geometry.attributes;
  17363. const positionAttribute = attributes.position;
  17364. if ( index !== null ) {
  17365. const start = Math.max( 0, drawRange.start );
  17366. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17367. for ( let i = start, il = end; i < il; i ++ ) {
  17368. const a = index.getX( i );
  17369. _position$2.fromBufferAttribute( positionAttribute, a );
  17370. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17371. }
  17372. } else {
  17373. const start = Math.max( 0, drawRange.start );
  17374. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17375. for ( let i = start, l = end; i < l; i ++ ) {
  17376. _position$2.fromBufferAttribute( positionAttribute, i );
  17377. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17378. }
  17379. }
  17380. } else {
  17381. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17382. }
  17383. }
  17384. updateMorphTargets() {
  17385. const geometry = this.geometry;
  17386. if ( geometry.isBufferGeometry ) {
  17387. const morphAttributes = geometry.morphAttributes;
  17388. const keys = Object.keys( morphAttributes );
  17389. if ( keys.length > 0 ) {
  17390. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17391. if ( morphAttribute !== undefined ) {
  17392. this.morphTargetInfluences = [];
  17393. this.morphTargetDictionary = {};
  17394. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17395. const name = morphAttribute[ m ].name || String( m );
  17396. this.morphTargetInfluences.push( 0 );
  17397. this.morphTargetDictionary[ name ] = m;
  17398. }
  17399. }
  17400. }
  17401. } else {
  17402. const morphTargets = geometry.morphTargets;
  17403. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17404. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17405. }
  17406. }
  17407. }
  17408. }
  17409. Points.prototype.isPoints = true;
  17410. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  17411. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  17412. if ( rayPointDistanceSq < localThresholdSq ) {
  17413. const intersectPoint = new Vector3();
  17414. _ray.closestPointToPoint( point, intersectPoint );
  17415. intersectPoint.applyMatrix4( matrixWorld );
  17416. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  17417. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17418. intersects.push( {
  17419. distance: distance,
  17420. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  17421. point: intersectPoint,
  17422. index: index,
  17423. face: null,
  17424. object: object
  17425. } );
  17426. }
  17427. }
  17428. class VideoTexture extends Texture {
  17429. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17430. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17431. this.format = format !== undefined ? format : RGBFormat;
  17432. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17433. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17434. this.generateMipmaps = false;
  17435. const scope = this;
  17436. function updateVideo() {
  17437. scope.needsUpdate = true;
  17438. video.requestVideoFrameCallback( updateVideo );
  17439. }
  17440. if ( 'requestVideoFrameCallback' in video ) {
  17441. video.requestVideoFrameCallback( updateVideo );
  17442. }
  17443. }
  17444. clone() {
  17445. return new this.constructor( this.image ).copy( this );
  17446. }
  17447. update() {
  17448. const video = this.image;
  17449. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  17450. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  17451. this.needsUpdate = true;
  17452. }
  17453. }
  17454. }
  17455. VideoTexture.prototype.isVideoTexture = true;
  17456. class CompressedTexture extends Texture {
  17457. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  17458. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17459. this.image = { width: width, height: height };
  17460. this.mipmaps = mipmaps;
  17461. // no flipping for cube textures
  17462. // (also flipping doesn't work for compressed textures )
  17463. this.flipY = false;
  17464. // can't generate mipmaps for compressed textures
  17465. // mips must be embedded in DDS files
  17466. this.generateMipmaps = false;
  17467. }
  17468. }
  17469. CompressedTexture.prototype.isCompressedTexture = true;
  17470. class CanvasTexture extends Texture {
  17471. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17472. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17473. this.needsUpdate = true;
  17474. }
  17475. }
  17476. CanvasTexture.prototype.isCanvasTexture = true;
  17477. class DepthTexture extends Texture {
  17478. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  17479. format = format !== undefined ? format : DepthFormat;
  17480. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  17481. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  17482. }
  17483. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  17484. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  17485. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17486. this.image = { width: width, height: height };
  17487. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17488. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17489. this.flipY = false;
  17490. this.generateMipmaps = false;
  17491. }
  17492. }
  17493. DepthTexture.prototype.isDepthTexture = true;
  17494. class CircleGeometry extends BufferGeometry {
  17495. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17496. super();
  17497. this.type = 'CircleGeometry';
  17498. this.parameters = {
  17499. radius: radius,
  17500. segments: segments,
  17501. thetaStart: thetaStart,
  17502. thetaLength: thetaLength
  17503. };
  17504. segments = Math.max( 3, segments );
  17505. // buffers
  17506. const indices = [];
  17507. const vertices = [];
  17508. const normals = [];
  17509. const uvs = [];
  17510. // helper variables
  17511. const vertex = new Vector3();
  17512. const uv = new Vector2();
  17513. // center point
  17514. vertices.push( 0, 0, 0 );
  17515. normals.push( 0, 0, 1 );
  17516. uvs.push( 0.5, 0.5 );
  17517. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17518. const segment = thetaStart + s / segments * thetaLength;
  17519. // vertex
  17520. vertex.x = radius * Math.cos( segment );
  17521. vertex.y = radius * Math.sin( segment );
  17522. vertices.push( vertex.x, vertex.y, vertex.z );
  17523. // normal
  17524. normals.push( 0, 0, 1 );
  17525. // uvs
  17526. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17527. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17528. uvs.push( uv.x, uv.y );
  17529. }
  17530. // indices
  17531. for ( let i = 1; i <= segments; i ++ ) {
  17532. indices.push( i, i + 1, 0 );
  17533. }
  17534. // build geometry
  17535. this.setIndex( indices );
  17536. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17537. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17538. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17539. }
  17540. static fromJSON( data ) {
  17541. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  17542. }
  17543. }
  17544. class CylinderGeometry extends BufferGeometry {
  17545. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17546. super();
  17547. this.type = 'CylinderGeometry';
  17548. this.parameters = {
  17549. radiusTop: radiusTop,
  17550. radiusBottom: radiusBottom,
  17551. height: height,
  17552. radialSegments: radialSegments,
  17553. heightSegments: heightSegments,
  17554. openEnded: openEnded,
  17555. thetaStart: thetaStart,
  17556. thetaLength: thetaLength
  17557. };
  17558. const scope = this;
  17559. radialSegments = Math.floor( radialSegments );
  17560. heightSegments = Math.floor( heightSegments );
  17561. // buffers
  17562. const indices = [];
  17563. const vertices = [];
  17564. const normals = [];
  17565. const uvs = [];
  17566. // helper variables
  17567. let index = 0;
  17568. const indexArray = [];
  17569. const halfHeight = height / 2;
  17570. let groupStart = 0;
  17571. // generate geometry
  17572. generateTorso();
  17573. if ( openEnded === false ) {
  17574. if ( radiusTop > 0 ) generateCap( true );
  17575. if ( radiusBottom > 0 ) generateCap( false );
  17576. }
  17577. // build geometry
  17578. this.setIndex( indices );
  17579. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17580. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17581. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17582. function generateTorso() {
  17583. const normal = new Vector3();
  17584. const vertex = new Vector3();
  17585. let groupCount = 0;
  17586. // this will be used to calculate the normal
  17587. const slope = ( radiusBottom - radiusTop ) / height;
  17588. // generate vertices, normals and uvs
  17589. for ( let y = 0; y <= heightSegments; y ++ ) {
  17590. const indexRow = [];
  17591. const v = y / heightSegments;
  17592. // calculate the radius of the current row
  17593. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17594. for ( let x = 0; x <= radialSegments; x ++ ) {
  17595. const u = x / radialSegments;
  17596. const theta = u * thetaLength + thetaStart;
  17597. const sinTheta = Math.sin( theta );
  17598. const cosTheta = Math.cos( theta );
  17599. // vertex
  17600. vertex.x = radius * sinTheta;
  17601. vertex.y = - v * height + halfHeight;
  17602. vertex.z = radius * cosTheta;
  17603. vertices.push( vertex.x, vertex.y, vertex.z );
  17604. // normal
  17605. normal.set( sinTheta, slope, cosTheta ).normalize();
  17606. normals.push( normal.x, normal.y, normal.z );
  17607. // uv
  17608. uvs.push( u, 1 - v );
  17609. // save index of vertex in respective row
  17610. indexRow.push( index ++ );
  17611. }
  17612. // now save vertices of the row in our index array
  17613. indexArray.push( indexRow );
  17614. }
  17615. // generate indices
  17616. for ( let x = 0; x < radialSegments; x ++ ) {
  17617. for ( let y = 0; y < heightSegments; y ++ ) {
  17618. // we use the index array to access the correct indices
  17619. const a = indexArray[ y ][ x ];
  17620. const b = indexArray[ y + 1 ][ x ];
  17621. const c = indexArray[ y + 1 ][ x + 1 ];
  17622. const d = indexArray[ y ][ x + 1 ];
  17623. // faces
  17624. indices.push( a, b, d );
  17625. indices.push( b, c, d );
  17626. // update group counter
  17627. groupCount += 6;
  17628. }
  17629. }
  17630. // add a group to the geometry. this will ensure multi material support
  17631. scope.addGroup( groupStart, groupCount, 0 );
  17632. // calculate new start value for groups
  17633. groupStart += groupCount;
  17634. }
  17635. function generateCap( top ) {
  17636. // save the index of the first center vertex
  17637. const centerIndexStart = index;
  17638. const uv = new Vector2();
  17639. const vertex = new Vector3();
  17640. let groupCount = 0;
  17641. const radius = ( top === true ) ? radiusTop : radiusBottom;
  17642. const sign = ( top === true ) ? 1 : - 1;
  17643. // first we generate the center vertex data of the cap.
  17644. // because the geometry needs one set of uvs per face,
  17645. // we must generate a center vertex per face/segment
  17646. for ( let x = 1; x <= radialSegments; x ++ ) {
  17647. // vertex
  17648. vertices.push( 0, halfHeight * sign, 0 );
  17649. // normal
  17650. normals.push( 0, sign, 0 );
  17651. // uv
  17652. uvs.push( 0.5, 0.5 );
  17653. // increase index
  17654. index ++;
  17655. }
  17656. // save the index of the last center vertex
  17657. const centerIndexEnd = index;
  17658. // now we generate the surrounding vertices, normals and uvs
  17659. for ( let x = 0; x <= radialSegments; x ++ ) {
  17660. const u = x / radialSegments;
  17661. const theta = u * thetaLength + thetaStart;
  17662. const cosTheta = Math.cos( theta );
  17663. const sinTheta = Math.sin( theta );
  17664. // vertex
  17665. vertex.x = radius * sinTheta;
  17666. vertex.y = halfHeight * sign;
  17667. vertex.z = radius * cosTheta;
  17668. vertices.push( vertex.x, vertex.y, vertex.z );
  17669. // normal
  17670. normals.push( 0, sign, 0 );
  17671. // uv
  17672. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17673. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17674. uvs.push( uv.x, uv.y );
  17675. // increase index
  17676. index ++;
  17677. }
  17678. // generate indices
  17679. for ( let x = 0; x < radialSegments; x ++ ) {
  17680. const c = centerIndexStart + x;
  17681. const i = centerIndexEnd + x;
  17682. if ( top === true ) {
  17683. // face top
  17684. indices.push( i, i + 1, c );
  17685. } else {
  17686. // face bottom
  17687. indices.push( i + 1, i, c );
  17688. }
  17689. groupCount += 3;
  17690. }
  17691. // add a group to the geometry. this will ensure multi material support
  17692. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17693. // calculate new start value for groups
  17694. groupStart += groupCount;
  17695. }
  17696. }
  17697. static fromJSON( data ) {
  17698. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  17699. }
  17700. }
  17701. class ConeGeometry extends CylinderGeometry {
  17702. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17703. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17704. this.type = 'ConeGeometry';
  17705. this.parameters = {
  17706. radius: radius,
  17707. height: height,
  17708. radialSegments: radialSegments,
  17709. heightSegments: heightSegments,
  17710. openEnded: openEnded,
  17711. thetaStart: thetaStart,
  17712. thetaLength: thetaLength
  17713. };
  17714. }
  17715. static fromJSON( data ) {
  17716. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  17717. }
  17718. }
  17719. class PolyhedronGeometry extends BufferGeometry {
  17720. constructor( vertices, indices, radius = 1, detail = 0 ) {
  17721. super();
  17722. this.type = 'PolyhedronGeometry';
  17723. this.parameters = {
  17724. vertices: vertices,
  17725. indices: indices,
  17726. radius: radius,
  17727. detail: detail
  17728. };
  17729. // default buffer data
  17730. const vertexBuffer = [];
  17731. const uvBuffer = [];
  17732. // the subdivision creates the vertex buffer data
  17733. subdivide( detail );
  17734. // all vertices should lie on a conceptual sphere with a given radius
  17735. applyRadius( radius );
  17736. // finally, create the uv data
  17737. generateUVs();
  17738. // build non-indexed geometry
  17739. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  17740. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  17741. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  17742. if ( detail === 0 ) {
  17743. this.computeVertexNormals(); // flat normals
  17744. } else {
  17745. this.normalizeNormals(); // smooth normals
  17746. }
  17747. // helper functions
  17748. function subdivide( detail ) {
  17749. const a = new Vector3();
  17750. const b = new Vector3();
  17751. const c = new Vector3();
  17752. // iterate over all faces and apply a subdivison with the given detail value
  17753. for ( let i = 0; i < indices.length; i += 3 ) {
  17754. // get the vertices of the face
  17755. getVertexByIndex( indices[ i + 0 ], a );
  17756. getVertexByIndex( indices[ i + 1 ], b );
  17757. getVertexByIndex( indices[ i + 2 ], c );
  17758. // perform subdivision
  17759. subdivideFace( a, b, c, detail );
  17760. }
  17761. }
  17762. function subdivideFace( a, b, c, detail ) {
  17763. const cols = detail + 1;
  17764. // we use this multidimensional array as a data structure for creating the subdivision
  17765. const v = [];
  17766. // construct all of the vertices for this subdivision
  17767. for ( let i = 0; i <= cols; i ++ ) {
  17768. v[ i ] = [];
  17769. const aj = a.clone().lerp( c, i / cols );
  17770. const bj = b.clone().lerp( c, i / cols );
  17771. const rows = cols - i;
  17772. for ( let j = 0; j <= rows; j ++ ) {
  17773. if ( j === 0 && i === cols ) {
  17774. v[ i ][ j ] = aj;
  17775. } else {
  17776. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  17777. }
  17778. }
  17779. }
  17780. // construct all of the faces
  17781. for ( let i = 0; i < cols; i ++ ) {
  17782. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  17783. const k = Math.floor( j / 2 );
  17784. if ( j % 2 === 0 ) {
  17785. pushVertex( v[ i ][ k + 1 ] );
  17786. pushVertex( v[ i + 1 ][ k ] );
  17787. pushVertex( v[ i ][ k ] );
  17788. } else {
  17789. pushVertex( v[ i ][ k + 1 ] );
  17790. pushVertex( v[ i + 1 ][ k + 1 ] );
  17791. pushVertex( v[ i + 1 ][ k ] );
  17792. }
  17793. }
  17794. }
  17795. }
  17796. function applyRadius( radius ) {
  17797. const vertex = new Vector3();
  17798. // iterate over the entire buffer and apply the radius to each vertex
  17799. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17800. vertex.x = vertexBuffer[ i + 0 ];
  17801. vertex.y = vertexBuffer[ i + 1 ];
  17802. vertex.z = vertexBuffer[ i + 2 ];
  17803. vertex.normalize().multiplyScalar( radius );
  17804. vertexBuffer[ i + 0 ] = vertex.x;
  17805. vertexBuffer[ i + 1 ] = vertex.y;
  17806. vertexBuffer[ i + 2 ] = vertex.z;
  17807. }
  17808. }
  17809. function generateUVs() {
  17810. const vertex = new Vector3();
  17811. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17812. vertex.x = vertexBuffer[ i + 0 ];
  17813. vertex.y = vertexBuffer[ i + 1 ];
  17814. vertex.z = vertexBuffer[ i + 2 ];
  17815. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  17816. const v = inclination( vertex ) / Math.PI + 0.5;
  17817. uvBuffer.push( u, 1 - v );
  17818. }
  17819. correctUVs();
  17820. correctSeam();
  17821. }
  17822. function correctSeam() {
  17823. // handle case when face straddles the seam, see #3269
  17824. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  17825. // uv data of a single face
  17826. const x0 = uvBuffer[ i + 0 ];
  17827. const x1 = uvBuffer[ i + 2 ];
  17828. const x2 = uvBuffer[ i + 4 ];
  17829. const max = Math.max( x0, x1, x2 );
  17830. const min = Math.min( x0, x1, x2 );
  17831. // 0.9 is somewhat arbitrary
  17832. if ( max > 0.9 && min < 0.1 ) {
  17833. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  17834. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  17835. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  17836. }
  17837. }
  17838. }
  17839. function pushVertex( vertex ) {
  17840. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  17841. }
  17842. function getVertexByIndex( index, vertex ) {
  17843. const stride = index * 3;
  17844. vertex.x = vertices[ stride + 0 ];
  17845. vertex.y = vertices[ stride + 1 ];
  17846. vertex.z = vertices[ stride + 2 ];
  17847. }
  17848. function correctUVs() {
  17849. const a = new Vector3();
  17850. const b = new Vector3();
  17851. const c = new Vector3();
  17852. const centroid = new Vector3();
  17853. const uvA = new Vector2();
  17854. const uvB = new Vector2();
  17855. const uvC = new Vector2();
  17856. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  17857. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  17858. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  17859. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  17860. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  17861. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  17862. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  17863. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  17864. const azi = azimuth( centroid );
  17865. correctUV( uvA, j + 0, a, azi );
  17866. correctUV( uvB, j + 2, b, azi );
  17867. correctUV( uvC, j + 4, c, azi );
  17868. }
  17869. }
  17870. function correctUV( uv, stride, vector, azimuth ) {
  17871. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  17872. uvBuffer[ stride ] = uv.x - 1;
  17873. }
  17874. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  17875. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  17876. }
  17877. }
  17878. // Angle around the Y axis, counter-clockwise when looking from above.
  17879. function azimuth( vector ) {
  17880. return Math.atan2( vector.z, - vector.x );
  17881. }
  17882. // Angle above the XZ plane.
  17883. function inclination( vector ) {
  17884. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  17885. }
  17886. }
  17887. static fromJSON( data ) {
  17888. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  17889. }
  17890. }
  17891. class DodecahedronGeometry extends PolyhedronGeometry {
  17892. constructor( radius = 1, detail = 0 ) {
  17893. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17894. const r = 1 / t;
  17895. const vertices = [
  17896. // (±1, ±1, ±1)
  17897. - 1, - 1, - 1, - 1, - 1, 1,
  17898. - 1, 1, - 1, - 1, 1, 1,
  17899. 1, - 1, - 1, 1, - 1, 1,
  17900. 1, 1, - 1, 1, 1, 1,
  17901. // (0, ±1/φ, ±φ)
  17902. 0, - r, - t, 0, - r, t,
  17903. 0, r, - t, 0, r, t,
  17904. // (±1/φ, ±φ, 0)
  17905. - r, - t, 0, - r, t, 0,
  17906. r, - t, 0, r, t, 0,
  17907. // (±φ, 0, ±1/φ)
  17908. - t, 0, - r, t, 0, - r,
  17909. - t, 0, r, t, 0, r
  17910. ];
  17911. const indices = [
  17912. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  17913. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  17914. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  17915. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  17916. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  17917. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  17918. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  17919. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  17920. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  17921. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  17922. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  17923. 1, 12, 14, 1, 14, 5, 1, 5, 9
  17924. ];
  17925. super( vertices, indices, radius, detail );
  17926. this.type = 'DodecahedronGeometry';
  17927. this.parameters = {
  17928. radius: radius,
  17929. detail: detail
  17930. };
  17931. }
  17932. static fromJSON( data ) {
  17933. return new DodecahedronGeometry( data.radius, data.detail );
  17934. }
  17935. }
  17936. const _v0 = new Vector3();
  17937. const _v1$1 = new Vector3();
  17938. const _normal = new Vector3();
  17939. const _triangle = new Triangle();
  17940. class EdgesGeometry extends BufferGeometry {
  17941. constructor( geometry, thresholdAngle ) {
  17942. super();
  17943. this.type = 'EdgesGeometry';
  17944. this.parameters = {
  17945. thresholdAngle: thresholdAngle
  17946. };
  17947. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  17948. if ( geometry.isGeometry === true ) {
  17949. console.error( 'THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17950. return;
  17951. }
  17952. const precisionPoints = 4;
  17953. const precision = Math.pow( 10, precisionPoints );
  17954. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  17955. const indexAttr = geometry.getIndex();
  17956. const positionAttr = geometry.getAttribute( 'position' );
  17957. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  17958. const indexArr = [ 0, 0, 0 ];
  17959. const vertKeys = [ 'a', 'b', 'c' ];
  17960. const hashes = new Array( 3 );
  17961. const edgeData = {};
  17962. const vertices = [];
  17963. for ( let i = 0; i < indexCount; i += 3 ) {
  17964. if ( indexAttr ) {
  17965. indexArr[ 0 ] = indexAttr.getX( i );
  17966. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  17967. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  17968. } else {
  17969. indexArr[ 0 ] = i;
  17970. indexArr[ 1 ] = i + 1;
  17971. indexArr[ 2 ] = i + 2;
  17972. }
  17973. const { a, b, c } = _triangle;
  17974. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  17975. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  17976. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  17977. _triangle.getNormal( _normal );
  17978. // create hashes for the edge from the vertices
  17979. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  17980. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  17981. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  17982. // skip degenerate triangles
  17983. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  17984. continue;
  17985. }
  17986. // iterate over every edge
  17987. for ( let j = 0; j < 3; j ++ ) {
  17988. // get the first and next vertex making up the edge
  17989. const jNext = ( j + 1 ) % 3;
  17990. const vecHash0 = hashes[ j ];
  17991. const vecHash1 = hashes[ jNext ];
  17992. const v0 = _triangle[ vertKeys[ j ] ];
  17993. const v1 = _triangle[ vertKeys[ jNext ] ];
  17994. const hash = `${ vecHash0 }_${ vecHash1 }`;
  17995. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  17996. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  17997. // if we found a sibling edge add it into the vertex array if
  17998. // it meets the angle threshold and delete the edge from the map.
  17999. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18000. vertices.push( v0.x, v0.y, v0.z );
  18001. vertices.push( v1.x, v1.y, v1.z );
  18002. }
  18003. edgeData[ reverseHash ] = null;
  18004. } else if ( ! ( hash in edgeData ) ) {
  18005. // if we've already got an edge here then skip adding a new one
  18006. edgeData[ hash ] = {
  18007. index0: indexArr[ j ],
  18008. index1: indexArr[ jNext ],
  18009. normal: _normal.clone(),
  18010. };
  18011. }
  18012. }
  18013. }
  18014. // iterate over all remaining, unmatched edges and add them to the vertex array
  18015. for ( const key in edgeData ) {
  18016. if ( edgeData[ key ] ) {
  18017. const { index0, index1 } = edgeData[ key ];
  18018. _v0.fromBufferAttribute( positionAttr, index0 );
  18019. _v1$1.fromBufferAttribute( positionAttr, index1 );
  18020. vertices.push( _v0.x, _v0.y, _v0.z );
  18021. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  18022. }
  18023. }
  18024. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18025. }
  18026. }
  18027. /**
  18028. * Extensible curve object.
  18029. *
  18030. * Some common of curve methods:
  18031. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18032. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18033. * .getPoints(), .getSpacedPoints()
  18034. * .getLength()
  18035. * .updateArcLengths()
  18036. *
  18037. * This following curves inherit from THREE.Curve:
  18038. *
  18039. * -- 2D curves --
  18040. * THREE.ArcCurve
  18041. * THREE.CubicBezierCurve
  18042. * THREE.EllipseCurve
  18043. * THREE.LineCurve
  18044. * THREE.QuadraticBezierCurve
  18045. * THREE.SplineCurve
  18046. *
  18047. * -- 3D curves --
  18048. * THREE.CatmullRomCurve3
  18049. * THREE.CubicBezierCurve3
  18050. * THREE.LineCurve3
  18051. * THREE.QuadraticBezierCurve3
  18052. *
  18053. * A series of curves can be represented as a THREE.CurvePath.
  18054. *
  18055. **/
  18056. class Curve {
  18057. constructor() {
  18058. this.type = 'Curve';
  18059. this.arcLengthDivisions = 200;
  18060. }
  18061. // Virtual base class method to overwrite and implement in subclasses
  18062. // - t [0 .. 1]
  18063. getPoint( /* t, optionalTarget */ ) {
  18064. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18065. return null;
  18066. }
  18067. // Get point at relative position in curve according to arc length
  18068. // - u [0 .. 1]
  18069. getPointAt( u, optionalTarget ) {
  18070. const t = this.getUtoTmapping( u );
  18071. return this.getPoint( t, optionalTarget );
  18072. }
  18073. // Get sequence of points using getPoint( t )
  18074. getPoints( divisions = 5 ) {
  18075. const points = [];
  18076. for ( let d = 0; d <= divisions; d ++ ) {
  18077. points.push( this.getPoint( d / divisions ) );
  18078. }
  18079. return points;
  18080. }
  18081. // Get sequence of points using getPointAt( u )
  18082. getSpacedPoints( divisions = 5 ) {
  18083. const points = [];
  18084. for ( let d = 0; d <= divisions; d ++ ) {
  18085. points.push( this.getPointAt( d / divisions ) );
  18086. }
  18087. return points;
  18088. }
  18089. // Get total curve arc length
  18090. getLength() {
  18091. const lengths = this.getLengths();
  18092. return lengths[ lengths.length - 1 ];
  18093. }
  18094. // Get list of cumulative segment lengths
  18095. getLengths( divisions = this.arcLengthDivisions ) {
  18096. if ( this.cacheArcLengths &&
  18097. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18098. ! this.needsUpdate ) {
  18099. return this.cacheArcLengths;
  18100. }
  18101. this.needsUpdate = false;
  18102. const cache = [];
  18103. let current, last = this.getPoint( 0 );
  18104. let sum = 0;
  18105. cache.push( 0 );
  18106. for ( let p = 1; p <= divisions; p ++ ) {
  18107. current = this.getPoint( p / divisions );
  18108. sum += current.distanceTo( last );
  18109. cache.push( sum );
  18110. last = current;
  18111. }
  18112. this.cacheArcLengths = cache;
  18113. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18114. }
  18115. updateArcLengths() {
  18116. this.needsUpdate = true;
  18117. this.getLengths();
  18118. }
  18119. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18120. getUtoTmapping( u, distance ) {
  18121. const arcLengths = this.getLengths();
  18122. let i = 0;
  18123. const il = arcLengths.length;
  18124. let targetArcLength; // The targeted u distance value to get
  18125. if ( distance ) {
  18126. targetArcLength = distance;
  18127. } else {
  18128. targetArcLength = u * arcLengths[ il - 1 ];
  18129. }
  18130. // binary search for the index with largest value smaller than target u distance
  18131. let low = 0, high = il - 1, comparison;
  18132. while ( low <= high ) {
  18133. i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  18134. comparison = arcLengths[ i ] - targetArcLength;
  18135. if ( comparison < 0 ) {
  18136. low = i + 1;
  18137. } else if ( comparison > 0 ) {
  18138. high = i - 1;
  18139. } else {
  18140. high = i;
  18141. break;
  18142. // DONE
  18143. }
  18144. }
  18145. i = high;
  18146. if ( arcLengths[ i ] === targetArcLength ) {
  18147. return i / ( il - 1 );
  18148. }
  18149. // we could get finer grain at lengths, or use simple interpolation between two points
  18150. const lengthBefore = arcLengths[ i ];
  18151. const lengthAfter = arcLengths[ i + 1 ];
  18152. const segmentLength = lengthAfter - lengthBefore;
  18153. // determine where we are between the 'before' and 'after' points
  18154. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18155. // add that fractional amount to t
  18156. const t = ( i + segmentFraction ) / ( il - 1 );
  18157. return t;
  18158. }
  18159. // Returns a unit vector tangent at t
  18160. // In case any sub curve does not implement its tangent derivation,
  18161. // 2 points a small delta apart will be used to find its gradient
  18162. // which seems to give a reasonable approximation
  18163. getTangent( t, optionalTarget ) {
  18164. const delta = 0.0001;
  18165. let t1 = t - delta;
  18166. let t2 = t + delta;
  18167. // Capping in case of danger
  18168. if ( t1 < 0 ) t1 = 0;
  18169. if ( t2 > 1 ) t2 = 1;
  18170. const pt1 = this.getPoint( t1 );
  18171. const pt2 = this.getPoint( t2 );
  18172. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18173. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18174. return tangent;
  18175. }
  18176. getTangentAt( u, optionalTarget ) {
  18177. const t = this.getUtoTmapping( u );
  18178. return this.getTangent( t, optionalTarget );
  18179. }
  18180. computeFrenetFrames( segments, closed ) {
  18181. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18182. const normal = new Vector3();
  18183. const tangents = [];
  18184. const normals = [];
  18185. const binormals = [];
  18186. const vec = new Vector3();
  18187. const mat = new Matrix4();
  18188. // compute the tangent vectors for each segment on the curve
  18189. for ( let i = 0; i <= segments; i ++ ) {
  18190. const u = i / segments;
  18191. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18192. tangents[ i ].normalize();
  18193. }
  18194. // select an initial normal vector perpendicular to the first tangent vector,
  18195. // and in the direction of the minimum tangent xyz component
  18196. normals[ 0 ] = new Vector3();
  18197. binormals[ 0 ] = new Vector3();
  18198. let min = Number.MAX_VALUE;
  18199. const tx = Math.abs( tangents[ 0 ].x );
  18200. const ty = Math.abs( tangents[ 0 ].y );
  18201. const tz = Math.abs( tangents[ 0 ].z );
  18202. if ( tx <= min ) {
  18203. min = tx;
  18204. normal.set( 1, 0, 0 );
  18205. }
  18206. if ( ty <= min ) {
  18207. min = ty;
  18208. normal.set( 0, 1, 0 );
  18209. }
  18210. if ( tz <= min ) {
  18211. normal.set( 0, 0, 1 );
  18212. }
  18213. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18214. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18215. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18216. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18217. for ( let i = 1; i <= segments; i ++ ) {
  18218. normals[ i ] = normals[ i - 1 ].clone();
  18219. binormals[ i ] = binormals[ i - 1 ].clone();
  18220. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18221. if ( vec.length() > Number.EPSILON ) {
  18222. vec.normalize();
  18223. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18224. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18225. }
  18226. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18227. }
  18228. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18229. if ( closed === true ) {
  18230. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18231. theta /= segments;
  18232. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18233. theta = - theta;
  18234. }
  18235. for ( let i = 1; i <= segments; i ++ ) {
  18236. // twist a little...
  18237. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18238. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18239. }
  18240. }
  18241. return {
  18242. tangents: tangents,
  18243. normals: normals,
  18244. binormals: binormals
  18245. };
  18246. }
  18247. clone() {
  18248. return new this.constructor().copy( this );
  18249. }
  18250. copy( source ) {
  18251. this.arcLengthDivisions = source.arcLengthDivisions;
  18252. return this;
  18253. }
  18254. toJSON() {
  18255. const data = {
  18256. metadata: {
  18257. version: 4.5,
  18258. type: 'Curve',
  18259. generator: 'Curve.toJSON'
  18260. }
  18261. };
  18262. data.arcLengthDivisions = this.arcLengthDivisions;
  18263. data.type = this.type;
  18264. return data;
  18265. }
  18266. fromJSON( json ) {
  18267. this.arcLengthDivisions = json.arcLengthDivisions;
  18268. return this;
  18269. }
  18270. }
  18271. class EllipseCurve extends Curve {
  18272. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18273. super();
  18274. this.type = 'EllipseCurve';
  18275. this.aX = aX;
  18276. this.aY = aY;
  18277. this.xRadius = xRadius;
  18278. this.yRadius = yRadius;
  18279. this.aStartAngle = aStartAngle;
  18280. this.aEndAngle = aEndAngle;
  18281. this.aClockwise = aClockwise;
  18282. this.aRotation = aRotation;
  18283. }
  18284. getPoint( t, optionalTarget ) {
  18285. const point = optionalTarget || new Vector2();
  18286. const twoPi = Math.PI * 2;
  18287. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18288. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18289. // ensures that deltaAngle is 0 .. 2 PI
  18290. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18291. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18292. if ( deltaAngle < Number.EPSILON ) {
  18293. if ( samePoints ) {
  18294. deltaAngle = 0;
  18295. } else {
  18296. deltaAngle = twoPi;
  18297. }
  18298. }
  18299. if ( this.aClockwise === true && ! samePoints ) {
  18300. if ( deltaAngle === twoPi ) {
  18301. deltaAngle = - twoPi;
  18302. } else {
  18303. deltaAngle = deltaAngle - twoPi;
  18304. }
  18305. }
  18306. const angle = this.aStartAngle + t * deltaAngle;
  18307. let x = this.aX + this.xRadius * Math.cos( angle );
  18308. let y = this.aY + this.yRadius * Math.sin( angle );
  18309. if ( this.aRotation !== 0 ) {
  18310. const cos = Math.cos( this.aRotation );
  18311. const sin = Math.sin( this.aRotation );
  18312. const tx = x - this.aX;
  18313. const ty = y - this.aY;
  18314. // Rotate the point about the center of the ellipse.
  18315. x = tx * cos - ty * sin + this.aX;
  18316. y = tx * sin + ty * cos + this.aY;
  18317. }
  18318. return point.set( x, y );
  18319. }
  18320. copy( source ) {
  18321. super.copy( source );
  18322. this.aX = source.aX;
  18323. this.aY = source.aY;
  18324. this.xRadius = source.xRadius;
  18325. this.yRadius = source.yRadius;
  18326. this.aStartAngle = source.aStartAngle;
  18327. this.aEndAngle = source.aEndAngle;
  18328. this.aClockwise = source.aClockwise;
  18329. this.aRotation = source.aRotation;
  18330. return this;
  18331. }
  18332. toJSON() {
  18333. const data = super.toJSON();
  18334. data.aX = this.aX;
  18335. data.aY = this.aY;
  18336. data.xRadius = this.xRadius;
  18337. data.yRadius = this.yRadius;
  18338. data.aStartAngle = this.aStartAngle;
  18339. data.aEndAngle = this.aEndAngle;
  18340. data.aClockwise = this.aClockwise;
  18341. data.aRotation = this.aRotation;
  18342. return data;
  18343. }
  18344. fromJSON( json ) {
  18345. super.fromJSON( json );
  18346. this.aX = json.aX;
  18347. this.aY = json.aY;
  18348. this.xRadius = json.xRadius;
  18349. this.yRadius = json.yRadius;
  18350. this.aStartAngle = json.aStartAngle;
  18351. this.aEndAngle = json.aEndAngle;
  18352. this.aClockwise = json.aClockwise;
  18353. this.aRotation = json.aRotation;
  18354. return this;
  18355. }
  18356. }
  18357. EllipseCurve.prototype.isEllipseCurve = true;
  18358. class ArcCurve extends EllipseCurve {
  18359. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18360. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18361. this.type = 'ArcCurve';
  18362. }
  18363. }
  18364. ArcCurve.prototype.isArcCurve = true;
  18365. /**
  18366. * Centripetal CatmullRom Curve - which is useful for avoiding
  18367. * cusps and self-intersections in non-uniform catmull rom curves.
  18368. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18369. *
  18370. * curve.type accepts centripetal(default), chordal and catmullrom
  18371. * curve.tension is used for catmullrom which defaults to 0.5
  18372. */
  18373. /*
  18374. Based on an optimized c++ solution in
  18375. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18376. - http://ideone.com/NoEbVM
  18377. This CubicPoly class could be used for reusing some variables and calculations,
  18378. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18379. which can be placed in CurveUtils.
  18380. */
  18381. function CubicPoly() {
  18382. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18383. /*
  18384. * Compute coefficients for a cubic polynomial
  18385. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18386. * such that
  18387. * p(0) = x0, p(1) = x1
  18388. * and
  18389. * p'(0) = t0, p'(1) = t1.
  18390. */
  18391. function init( x0, x1, t0, t1 ) {
  18392. c0 = x0;
  18393. c1 = t0;
  18394. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18395. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18396. }
  18397. return {
  18398. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  18399. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18400. },
  18401. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18402. // compute tangents when parameterized in [t1,t2]
  18403. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18404. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18405. // rescale tangents for parametrization in [0,1]
  18406. t1 *= dt1;
  18407. t2 *= dt1;
  18408. init( x1, x2, t1, t2 );
  18409. },
  18410. calc: function ( t ) {
  18411. const t2 = t * t;
  18412. const t3 = t2 * t;
  18413. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18414. }
  18415. };
  18416. }
  18417. //
  18418. const tmp = new Vector3();
  18419. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  18420. class CatmullRomCurve3 extends Curve {
  18421. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18422. super();
  18423. this.type = 'CatmullRomCurve3';
  18424. this.points = points;
  18425. this.closed = closed;
  18426. this.curveType = curveType;
  18427. this.tension = tension;
  18428. }
  18429. getPoint( t, optionalTarget = new Vector3() ) {
  18430. const point = optionalTarget;
  18431. const points = this.points;
  18432. const l = points.length;
  18433. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18434. let intPoint = Math.floor( p );
  18435. let weight = p - intPoint;
  18436. if ( this.closed ) {
  18437. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18438. } else if ( weight === 0 && intPoint === l - 1 ) {
  18439. intPoint = l - 2;
  18440. weight = 1;
  18441. }
  18442. let p0, p3; // 4 points (p1 & p2 defined below)
  18443. if ( this.closed || intPoint > 0 ) {
  18444. p0 = points[ ( intPoint - 1 ) % l ];
  18445. } else {
  18446. // extrapolate first point
  18447. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18448. p0 = tmp;
  18449. }
  18450. const p1 = points[ intPoint % l ];
  18451. const p2 = points[ ( intPoint + 1 ) % l ];
  18452. if ( this.closed || intPoint + 2 < l ) {
  18453. p3 = points[ ( intPoint + 2 ) % l ];
  18454. } else {
  18455. // extrapolate last point
  18456. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18457. p3 = tmp;
  18458. }
  18459. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18460. // init Centripetal / Chordal Catmull-Rom
  18461. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18462. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18463. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18464. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18465. // safety check for repeated points
  18466. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18467. if ( dt0 < 1e-4 ) dt0 = dt1;
  18468. if ( dt2 < 1e-4 ) dt2 = dt1;
  18469. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18470. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18471. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18472. } else if ( this.curveType === 'catmullrom' ) {
  18473. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18474. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18475. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18476. }
  18477. point.set(
  18478. px.calc( weight ),
  18479. py.calc( weight ),
  18480. pz.calc( weight )
  18481. );
  18482. return point;
  18483. }
  18484. copy( source ) {
  18485. super.copy( source );
  18486. this.points = [];
  18487. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18488. const point = source.points[ i ];
  18489. this.points.push( point.clone() );
  18490. }
  18491. this.closed = source.closed;
  18492. this.curveType = source.curveType;
  18493. this.tension = source.tension;
  18494. return this;
  18495. }
  18496. toJSON() {
  18497. const data = super.toJSON();
  18498. data.points = [];
  18499. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18500. const point = this.points[ i ];
  18501. data.points.push( point.toArray() );
  18502. }
  18503. data.closed = this.closed;
  18504. data.curveType = this.curveType;
  18505. data.tension = this.tension;
  18506. return data;
  18507. }
  18508. fromJSON( json ) {
  18509. super.fromJSON( json );
  18510. this.points = [];
  18511. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18512. const point = json.points[ i ];
  18513. this.points.push( new Vector3().fromArray( point ) );
  18514. }
  18515. this.closed = json.closed;
  18516. this.curveType = json.curveType;
  18517. this.tension = json.tension;
  18518. return this;
  18519. }
  18520. }
  18521. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18522. /**
  18523. * Bezier Curves formulas obtained from
  18524. * http://en.wikipedia.org/wiki/Bézier_curve
  18525. */
  18526. function CatmullRom( t, p0, p1, p2, p3 ) {
  18527. const v0 = ( p2 - p0 ) * 0.5;
  18528. const v1 = ( p3 - p1 ) * 0.5;
  18529. const t2 = t * t;
  18530. const t3 = t * t2;
  18531. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18532. }
  18533. //
  18534. function QuadraticBezierP0( t, p ) {
  18535. const k = 1 - t;
  18536. return k * k * p;
  18537. }
  18538. function QuadraticBezierP1( t, p ) {
  18539. return 2 * ( 1 - t ) * t * p;
  18540. }
  18541. function QuadraticBezierP2( t, p ) {
  18542. return t * t * p;
  18543. }
  18544. function QuadraticBezier( t, p0, p1, p2 ) {
  18545. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18546. QuadraticBezierP2( t, p2 );
  18547. }
  18548. //
  18549. function CubicBezierP0( t, p ) {
  18550. const k = 1 - t;
  18551. return k * k * k * p;
  18552. }
  18553. function CubicBezierP1( t, p ) {
  18554. const k = 1 - t;
  18555. return 3 * k * k * t * p;
  18556. }
  18557. function CubicBezierP2( t, p ) {
  18558. return 3 * ( 1 - t ) * t * t * p;
  18559. }
  18560. function CubicBezierP3( t, p ) {
  18561. return t * t * t * p;
  18562. }
  18563. function CubicBezier( t, p0, p1, p2, p3 ) {
  18564. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18565. CubicBezierP3( t, p3 );
  18566. }
  18567. class CubicBezierCurve extends Curve {
  18568. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18569. super();
  18570. this.type = 'CubicBezierCurve';
  18571. this.v0 = v0;
  18572. this.v1 = v1;
  18573. this.v2 = v2;
  18574. this.v3 = v3;
  18575. }
  18576. getPoint( t, optionalTarget = new Vector2() ) {
  18577. const point = optionalTarget;
  18578. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18579. point.set(
  18580. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18581. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18582. );
  18583. return point;
  18584. }
  18585. copy( source ) {
  18586. super.copy( source );
  18587. this.v0.copy( source.v0 );
  18588. this.v1.copy( source.v1 );
  18589. this.v2.copy( source.v2 );
  18590. this.v3.copy( source.v3 );
  18591. return this;
  18592. }
  18593. toJSON() {
  18594. const data = super.toJSON();
  18595. data.v0 = this.v0.toArray();
  18596. data.v1 = this.v1.toArray();
  18597. data.v2 = this.v2.toArray();
  18598. data.v3 = this.v3.toArray();
  18599. return data;
  18600. }
  18601. fromJSON( json ) {
  18602. super.fromJSON( json );
  18603. this.v0.fromArray( json.v0 );
  18604. this.v1.fromArray( json.v1 );
  18605. this.v2.fromArray( json.v2 );
  18606. this.v3.fromArray( json.v3 );
  18607. return this;
  18608. }
  18609. }
  18610. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18611. class CubicBezierCurve3 extends Curve {
  18612. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18613. super();
  18614. this.type = 'CubicBezierCurve3';
  18615. this.v0 = v0;
  18616. this.v1 = v1;
  18617. this.v2 = v2;
  18618. this.v3 = v3;
  18619. }
  18620. getPoint( t, optionalTarget = new Vector3() ) {
  18621. const point = optionalTarget;
  18622. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18623. point.set(
  18624. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18625. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18626. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18627. );
  18628. return point;
  18629. }
  18630. copy( source ) {
  18631. super.copy( source );
  18632. this.v0.copy( source.v0 );
  18633. this.v1.copy( source.v1 );
  18634. this.v2.copy( source.v2 );
  18635. this.v3.copy( source.v3 );
  18636. return this;
  18637. }
  18638. toJSON() {
  18639. const data = super.toJSON();
  18640. data.v0 = this.v0.toArray();
  18641. data.v1 = this.v1.toArray();
  18642. data.v2 = this.v2.toArray();
  18643. data.v3 = this.v3.toArray();
  18644. return data;
  18645. }
  18646. fromJSON( json ) {
  18647. super.fromJSON( json );
  18648. this.v0.fromArray( json.v0 );
  18649. this.v1.fromArray( json.v1 );
  18650. this.v2.fromArray( json.v2 );
  18651. this.v3.fromArray( json.v3 );
  18652. return this;
  18653. }
  18654. }
  18655. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18656. class LineCurve extends Curve {
  18657. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  18658. super();
  18659. this.type = 'LineCurve';
  18660. this.v1 = v1;
  18661. this.v2 = v2;
  18662. }
  18663. getPoint( t, optionalTarget = new Vector2() ) {
  18664. const point = optionalTarget;
  18665. if ( t === 1 ) {
  18666. point.copy( this.v2 );
  18667. } else {
  18668. point.copy( this.v2 ).sub( this.v1 );
  18669. point.multiplyScalar( t ).add( this.v1 );
  18670. }
  18671. return point;
  18672. }
  18673. // Line curve is linear, so we can overwrite default getPointAt
  18674. getPointAt( u, optionalTarget ) {
  18675. return this.getPoint( u, optionalTarget );
  18676. }
  18677. getTangent( t, optionalTarget ) {
  18678. const tangent = optionalTarget || new Vector2();
  18679. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  18680. return tangent;
  18681. }
  18682. copy( source ) {
  18683. super.copy( source );
  18684. this.v1.copy( source.v1 );
  18685. this.v2.copy( source.v2 );
  18686. return this;
  18687. }
  18688. toJSON() {
  18689. const data = super.toJSON();
  18690. data.v1 = this.v1.toArray();
  18691. data.v2 = this.v2.toArray();
  18692. return data;
  18693. }
  18694. fromJSON( json ) {
  18695. super.fromJSON( json );
  18696. this.v1.fromArray( json.v1 );
  18697. this.v2.fromArray( json.v2 );
  18698. return this;
  18699. }
  18700. }
  18701. LineCurve.prototype.isLineCurve = true;
  18702. class LineCurve3 extends Curve {
  18703. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  18704. super();
  18705. this.type = 'LineCurve3';
  18706. this.isLineCurve3 = true;
  18707. this.v1 = v1;
  18708. this.v2 = v2;
  18709. }
  18710. getPoint( t, optionalTarget = new Vector3() ) {
  18711. const point = optionalTarget;
  18712. if ( t === 1 ) {
  18713. point.copy( this.v2 );
  18714. } else {
  18715. point.copy( this.v2 ).sub( this.v1 );
  18716. point.multiplyScalar( t ).add( this.v1 );
  18717. }
  18718. return point;
  18719. }
  18720. // Line curve is linear, so we can overwrite default getPointAt
  18721. getPointAt( u, optionalTarget ) {
  18722. return this.getPoint( u, optionalTarget );
  18723. }
  18724. copy( source ) {
  18725. super.copy( source );
  18726. this.v1.copy( source.v1 );
  18727. this.v2.copy( source.v2 );
  18728. return this;
  18729. }
  18730. toJSON() {
  18731. const data = super.toJSON();
  18732. data.v1 = this.v1.toArray();
  18733. data.v2 = this.v2.toArray();
  18734. return data;
  18735. }
  18736. fromJSON( json ) {
  18737. super.fromJSON( json );
  18738. this.v1.fromArray( json.v1 );
  18739. this.v2.fromArray( json.v2 );
  18740. return this;
  18741. }
  18742. }
  18743. class QuadraticBezierCurve extends Curve {
  18744. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  18745. super();
  18746. this.type = 'QuadraticBezierCurve';
  18747. this.v0 = v0;
  18748. this.v1 = v1;
  18749. this.v2 = v2;
  18750. }
  18751. getPoint( t, optionalTarget = new Vector2() ) {
  18752. const point = optionalTarget;
  18753. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18754. point.set(
  18755. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18756. QuadraticBezier( t, v0.y, v1.y, v2.y )
  18757. );
  18758. return point;
  18759. }
  18760. copy( source ) {
  18761. super.copy( source );
  18762. this.v0.copy( source.v0 );
  18763. this.v1.copy( source.v1 );
  18764. this.v2.copy( source.v2 );
  18765. return this;
  18766. }
  18767. toJSON() {
  18768. const data = super.toJSON();
  18769. data.v0 = this.v0.toArray();
  18770. data.v1 = this.v1.toArray();
  18771. data.v2 = this.v2.toArray();
  18772. return data;
  18773. }
  18774. fromJSON( json ) {
  18775. super.fromJSON( json );
  18776. this.v0.fromArray( json.v0 );
  18777. this.v1.fromArray( json.v1 );
  18778. this.v2.fromArray( json.v2 );
  18779. return this;
  18780. }
  18781. }
  18782. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  18783. class QuadraticBezierCurve3 extends Curve {
  18784. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  18785. super();
  18786. this.type = 'QuadraticBezierCurve3';
  18787. this.v0 = v0;
  18788. this.v1 = v1;
  18789. this.v2 = v2;
  18790. }
  18791. getPoint( t, optionalTarget = new Vector3() ) {
  18792. const point = optionalTarget;
  18793. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18794. point.set(
  18795. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18796. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  18797. QuadraticBezier( t, v0.z, v1.z, v2.z )
  18798. );
  18799. return point;
  18800. }
  18801. copy( source ) {
  18802. super.copy( source );
  18803. this.v0.copy( source.v0 );
  18804. this.v1.copy( source.v1 );
  18805. this.v2.copy( source.v2 );
  18806. return this;
  18807. }
  18808. toJSON() {
  18809. const data = super.toJSON();
  18810. data.v0 = this.v0.toArray();
  18811. data.v1 = this.v1.toArray();
  18812. data.v2 = this.v2.toArray();
  18813. return data;
  18814. }
  18815. fromJSON( json ) {
  18816. super.fromJSON( json );
  18817. this.v0.fromArray( json.v0 );
  18818. this.v1.fromArray( json.v1 );
  18819. this.v2.fromArray( json.v2 );
  18820. return this;
  18821. }
  18822. }
  18823. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  18824. class SplineCurve extends Curve {
  18825. constructor( points = [] ) {
  18826. super();
  18827. this.type = 'SplineCurve';
  18828. this.points = points;
  18829. }
  18830. getPoint( t, optionalTarget = new Vector2() ) {
  18831. const point = optionalTarget;
  18832. const points = this.points;
  18833. const p = ( points.length - 1 ) * t;
  18834. const intPoint = Math.floor( p );
  18835. const weight = p - intPoint;
  18836. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18837. const p1 = points[ intPoint ];
  18838. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18839. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18840. point.set(
  18841. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  18842. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  18843. );
  18844. return point;
  18845. }
  18846. copy( source ) {
  18847. super.copy( source );
  18848. this.points = [];
  18849. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18850. const point = source.points[ i ];
  18851. this.points.push( point.clone() );
  18852. }
  18853. return this;
  18854. }
  18855. toJSON() {
  18856. const data = super.toJSON();
  18857. data.points = [];
  18858. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18859. const point = this.points[ i ];
  18860. data.points.push( point.toArray() );
  18861. }
  18862. return data;
  18863. }
  18864. fromJSON( json ) {
  18865. super.fromJSON( json );
  18866. this.points = [];
  18867. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18868. const point = json.points[ i ];
  18869. this.points.push( new Vector2().fromArray( point ) );
  18870. }
  18871. return this;
  18872. }
  18873. }
  18874. SplineCurve.prototype.isSplineCurve = true;
  18875. var Curves = /*#__PURE__*/Object.freeze({
  18876. __proto__: null,
  18877. ArcCurve: ArcCurve,
  18878. CatmullRomCurve3: CatmullRomCurve3,
  18879. CubicBezierCurve: CubicBezierCurve,
  18880. CubicBezierCurve3: CubicBezierCurve3,
  18881. EllipseCurve: EllipseCurve,
  18882. LineCurve: LineCurve,
  18883. LineCurve3: LineCurve3,
  18884. QuadraticBezierCurve: QuadraticBezierCurve,
  18885. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18886. SplineCurve: SplineCurve
  18887. });
  18888. /**
  18889. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18890. */
  18891. const Earcut = {
  18892. triangulate: function ( data, holeIndices, dim = 2 ) {
  18893. const hasHoles = holeIndices && holeIndices.length;
  18894. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  18895. let outerNode = linkedList( data, 0, outerLen, dim, true );
  18896. const triangles = [];
  18897. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  18898. let minX, minY, maxX, maxY, x, y, invSize;
  18899. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  18900. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18901. if ( data.length > 80 * dim ) {
  18902. minX = maxX = data[ 0 ];
  18903. minY = maxY = data[ 1 ];
  18904. for ( let i = dim; i < outerLen; i += dim ) {
  18905. x = data[ i ];
  18906. y = data[ i + 1 ];
  18907. if ( x < minX ) minX = x;
  18908. if ( y < minY ) minY = y;
  18909. if ( x > maxX ) maxX = x;
  18910. if ( y > maxY ) maxY = y;
  18911. }
  18912. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18913. invSize = Math.max( maxX - minX, maxY - minY );
  18914. invSize = invSize !== 0 ? 1 / invSize : 0;
  18915. }
  18916. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  18917. return triangles;
  18918. }
  18919. };
  18920. // create a circular doubly linked list from polygon points in the specified winding order
  18921. function linkedList( data, start, end, dim, clockwise ) {
  18922. let i, last;
  18923. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  18924. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18925. } else {
  18926. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18927. }
  18928. if ( last && equals( last, last.next ) ) {
  18929. removeNode( last );
  18930. last = last.next;
  18931. }
  18932. return last;
  18933. }
  18934. // eliminate colinear or duplicate points
  18935. function filterPoints( start, end ) {
  18936. if ( ! start ) return start;
  18937. if ( ! end ) end = start;
  18938. let p = start,
  18939. again;
  18940. do {
  18941. again = false;
  18942. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  18943. removeNode( p );
  18944. p = end = p.prev;
  18945. if ( p === p.next ) break;
  18946. again = true;
  18947. } else {
  18948. p = p.next;
  18949. }
  18950. } while ( again || p !== end );
  18951. return end;
  18952. }
  18953. // main ear slicing loop which triangulates a polygon (given as a linked list)
  18954. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  18955. if ( ! ear ) return;
  18956. // interlink polygon nodes in z-order
  18957. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  18958. let stop = ear,
  18959. prev, next;
  18960. // iterate through ears, slicing them one by one
  18961. while ( ear.prev !== ear.next ) {
  18962. prev = ear.prev;
  18963. next = ear.next;
  18964. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  18965. // cut off the triangle
  18966. triangles.push( prev.i / dim );
  18967. triangles.push( ear.i / dim );
  18968. triangles.push( next.i / dim );
  18969. removeNode( ear );
  18970. // skipping the next vertex leads to less sliver triangles
  18971. ear = next.next;
  18972. stop = next.next;
  18973. continue;
  18974. }
  18975. ear = next;
  18976. // if we looped through the whole remaining polygon and can't find any more ears
  18977. if ( ear === stop ) {
  18978. // try filtering points and slicing again
  18979. if ( ! pass ) {
  18980. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  18981. // if this didn't work, try curing all small self-intersections locally
  18982. } else if ( pass === 1 ) {
  18983. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  18984. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  18985. // as a last resort, try splitting the remaining polygon into two
  18986. } else if ( pass === 2 ) {
  18987. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  18988. }
  18989. break;
  18990. }
  18991. }
  18992. }
  18993. // check whether a polygon node forms a valid ear with adjacent nodes
  18994. function isEar( ear ) {
  18995. const a = ear.prev,
  18996. b = ear,
  18997. c = ear.next;
  18998. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  18999. // now make sure we don't have other points inside the potential ear
  19000. let p = ear.next.next;
  19001. while ( p !== ear.prev ) {
  19002. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19003. area( p.prev, p, p.next ) >= 0 ) return false;
  19004. p = p.next;
  19005. }
  19006. return true;
  19007. }
  19008. function isEarHashed( ear, minX, minY, invSize ) {
  19009. const a = ear.prev,
  19010. b = ear,
  19011. c = ear.next;
  19012. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19013. // triangle bbox; min & max are calculated like this for speed
  19014. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  19015. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  19016. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  19017. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  19018. // z-order range for the current triangle bbox;
  19019. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  19020. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  19021. let p = ear.prevZ,
  19022. n = ear.nextZ;
  19023. // look for points inside the triangle in both directions
  19024. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  19025. if ( p !== ear.prev && p !== ear.next &&
  19026. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19027. area( p.prev, p, p.next ) >= 0 ) return false;
  19028. p = p.prevZ;
  19029. if ( n !== ear.prev && n !== ear.next &&
  19030. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19031. area( n.prev, n, n.next ) >= 0 ) return false;
  19032. n = n.nextZ;
  19033. }
  19034. // look for remaining points in decreasing z-order
  19035. while ( p && p.z >= minZ ) {
  19036. if ( p !== ear.prev && p !== ear.next &&
  19037. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19038. area( p.prev, p, p.next ) >= 0 ) return false;
  19039. p = p.prevZ;
  19040. }
  19041. // look for remaining points in increasing z-order
  19042. while ( n && n.z <= maxZ ) {
  19043. if ( n !== ear.prev && n !== ear.next &&
  19044. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19045. area( n.prev, n, n.next ) >= 0 ) return false;
  19046. n = n.nextZ;
  19047. }
  19048. return true;
  19049. }
  19050. // go through all polygon nodes and cure small local self-intersections
  19051. function cureLocalIntersections( start, triangles, dim ) {
  19052. let p = start;
  19053. do {
  19054. const a = p.prev,
  19055. b = p.next.next;
  19056. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  19057. triangles.push( a.i / dim );
  19058. triangles.push( p.i / dim );
  19059. triangles.push( b.i / dim );
  19060. // remove two nodes involved
  19061. removeNode( p );
  19062. removeNode( p.next );
  19063. p = start = b;
  19064. }
  19065. p = p.next;
  19066. } while ( p !== start );
  19067. return filterPoints( p );
  19068. }
  19069. // try splitting polygon into two and triangulate them independently
  19070. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  19071. // look for a valid diagonal that divides the polygon into two
  19072. let a = start;
  19073. do {
  19074. let b = a.next.next;
  19075. while ( b !== a.prev ) {
  19076. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  19077. // split the polygon in two by the diagonal
  19078. let c = splitPolygon( a, b );
  19079. // filter colinear points around the cuts
  19080. a = filterPoints( a, a.next );
  19081. c = filterPoints( c, c.next );
  19082. // run earcut on each half
  19083. earcutLinked( a, triangles, dim, minX, minY, invSize );
  19084. earcutLinked( c, triangles, dim, minX, minY, invSize );
  19085. return;
  19086. }
  19087. b = b.next;
  19088. }
  19089. a = a.next;
  19090. } while ( a !== start );
  19091. }
  19092. // link every hole into the outer loop, producing a single-ring polygon without holes
  19093. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  19094. const queue = [];
  19095. let i, len, start, end, list;
  19096. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  19097. start = holeIndices[ i ] * dim;
  19098. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  19099. list = linkedList( data, start, end, dim, false );
  19100. if ( list === list.next ) list.steiner = true;
  19101. queue.push( getLeftmost( list ) );
  19102. }
  19103. queue.sort( compareX );
  19104. // process holes from left to right
  19105. for ( i = 0; i < queue.length; i ++ ) {
  19106. eliminateHole( queue[ i ], outerNode );
  19107. outerNode = filterPoints( outerNode, outerNode.next );
  19108. }
  19109. return outerNode;
  19110. }
  19111. function compareX( a, b ) {
  19112. return a.x - b.x;
  19113. }
  19114. // find a bridge between vertices that connects hole with an outer ring and and link it
  19115. function eliminateHole( hole, outerNode ) {
  19116. outerNode = findHoleBridge( hole, outerNode );
  19117. if ( outerNode ) {
  19118. const b = splitPolygon( outerNode, hole );
  19119. // filter collinear points around the cuts
  19120. filterPoints( outerNode, outerNode.next );
  19121. filterPoints( b, b.next );
  19122. }
  19123. }
  19124. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19125. function findHoleBridge( hole, outerNode ) {
  19126. let p = outerNode;
  19127. const hx = hole.x;
  19128. const hy = hole.y;
  19129. let qx = - Infinity, m;
  19130. // find a segment intersected by a ray from the hole's leftmost point to the left;
  19131. // segment's endpoint with lesser x will be potential connection point
  19132. do {
  19133. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  19134. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  19135. if ( x <= hx && x > qx ) {
  19136. qx = x;
  19137. if ( x === hx ) {
  19138. if ( hy === p.y ) return p;
  19139. if ( hy === p.next.y ) return p.next;
  19140. }
  19141. m = p.x < p.next.x ? p : p.next;
  19142. }
  19143. }
  19144. p = p.next;
  19145. } while ( p !== outerNode );
  19146. if ( ! m ) return null;
  19147. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  19148. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19149. // if there are no points found, we have a valid connection;
  19150. // otherwise choose the point of the minimum angle with the ray as connection point
  19151. const stop = m,
  19152. mx = m.x,
  19153. my = m.y;
  19154. let tanMin = Infinity, tan;
  19155. p = m;
  19156. do {
  19157. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  19158. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  19159. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  19160. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  19161. m = p;
  19162. tanMin = tan;
  19163. }
  19164. }
  19165. p = p.next;
  19166. } while ( p !== stop );
  19167. return m;
  19168. }
  19169. // whether sector in vertex m contains sector in vertex p in the same coordinates
  19170. function sectorContainsSector( m, p ) {
  19171. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  19172. }
  19173. // interlink polygon nodes in z-order
  19174. function indexCurve( start, minX, minY, invSize ) {
  19175. let p = start;
  19176. do {
  19177. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  19178. p.prevZ = p.prev;
  19179. p.nextZ = p.next;
  19180. p = p.next;
  19181. } while ( p !== start );
  19182. p.prevZ.nextZ = null;
  19183. p.prevZ = null;
  19184. sortLinked( p );
  19185. }
  19186. // Simon Tatham's linked list merge sort algorithm
  19187. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19188. function sortLinked( list ) {
  19189. let i, p, q, e, tail, numMerges, pSize, qSize,
  19190. inSize = 1;
  19191. do {
  19192. p = list;
  19193. list = null;
  19194. tail = null;
  19195. numMerges = 0;
  19196. while ( p ) {
  19197. numMerges ++;
  19198. q = p;
  19199. pSize = 0;
  19200. for ( i = 0; i < inSize; i ++ ) {
  19201. pSize ++;
  19202. q = q.nextZ;
  19203. if ( ! q ) break;
  19204. }
  19205. qSize = inSize;
  19206. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  19207. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  19208. e = p;
  19209. p = p.nextZ;
  19210. pSize --;
  19211. } else {
  19212. e = q;
  19213. q = q.nextZ;
  19214. qSize --;
  19215. }
  19216. if ( tail ) tail.nextZ = e;
  19217. else list = e;
  19218. e.prevZ = tail;
  19219. tail = e;
  19220. }
  19221. p = q;
  19222. }
  19223. tail.nextZ = null;
  19224. inSize *= 2;
  19225. } while ( numMerges > 1 );
  19226. return list;
  19227. }
  19228. // z-order of a point given coords and inverse of the longer side of data bbox
  19229. function zOrder( x, y, minX, minY, invSize ) {
  19230. // coords are transformed into non-negative 15-bit integer range
  19231. x = 32767 * ( x - minX ) * invSize;
  19232. y = 32767 * ( y - minY ) * invSize;
  19233. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  19234. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  19235. x = ( x | ( x << 2 ) ) & 0x33333333;
  19236. x = ( x | ( x << 1 ) ) & 0x55555555;
  19237. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  19238. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  19239. y = ( y | ( y << 2 ) ) & 0x33333333;
  19240. y = ( y | ( y << 1 ) ) & 0x55555555;
  19241. return x | ( y << 1 );
  19242. }
  19243. // find the leftmost node of a polygon ring
  19244. function getLeftmost( start ) {
  19245. let p = start,
  19246. leftmost = start;
  19247. do {
  19248. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  19249. p = p.next;
  19250. } while ( p !== start );
  19251. return leftmost;
  19252. }
  19253. // check if a point lies within a convex triangle
  19254. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  19255. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  19256. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  19257. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  19258. }
  19259. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19260. function isValidDiagonal( a, b ) {
  19261. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  19262. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  19263. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  19264. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  19265. }
  19266. // signed area of a triangle
  19267. function area( p, q, r ) {
  19268. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  19269. }
  19270. // check if two points are equal
  19271. function equals( p1, p2 ) {
  19272. return p1.x === p2.x && p1.y === p2.y;
  19273. }
  19274. // check if two segments intersect
  19275. function intersects( p1, q1, p2, q2 ) {
  19276. const o1 = sign( area( p1, q1, p2 ) );
  19277. const o2 = sign( area( p1, q1, q2 ) );
  19278. const o3 = sign( area( p2, q2, p1 ) );
  19279. const o4 = sign( area( p2, q2, q1 ) );
  19280. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  19281. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19282. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19283. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19284. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19285. return false;
  19286. }
  19287. // for collinear points p, q, r, check if point q lies on segment pr
  19288. function onSegment( p, q, r ) {
  19289. return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );
  19290. }
  19291. function sign( num ) {
  19292. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  19293. }
  19294. // check if a polygon diagonal intersects any polygon segments
  19295. function intersectsPolygon( a, b ) {
  19296. let p = a;
  19297. do {
  19298. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  19299. intersects( p, p.next, a, b ) ) return true;
  19300. p = p.next;
  19301. } while ( p !== a );
  19302. return false;
  19303. }
  19304. // check if a polygon diagonal is locally inside the polygon
  19305. function locallyInside( a, b ) {
  19306. return area( a.prev, a, a.next ) < 0 ?
  19307. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  19308. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  19309. }
  19310. // check if the middle point of a polygon diagonal is inside the polygon
  19311. function middleInside( a, b ) {
  19312. let p = a,
  19313. inside = false;
  19314. const px = ( a.x + b.x ) / 2,
  19315. py = ( a.y + b.y ) / 2;
  19316. do {
  19317. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  19318. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  19319. inside = ! inside;
  19320. p = p.next;
  19321. } while ( p !== a );
  19322. return inside;
  19323. }
  19324. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19325. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19326. function splitPolygon( a, b ) {
  19327. const a2 = new Node( a.i, a.x, a.y ),
  19328. b2 = new Node( b.i, b.x, b.y ),
  19329. an = a.next,
  19330. bp = b.prev;
  19331. a.next = b;
  19332. b.prev = a;
  19333. a2.next = an;
  19334. an.prev = a2;
  19335. b2.next = a2;
  19336. a2.prev = b2;
  19337. bp.next = b2;
  19338. b2.prev = bp;
  19339. return b2;
  19340. }
  19341. // create a node and optionally link it with previous one (in a circular doubly linked list)
  19342. function insertNode( i, x, y, last ) {
  19343. const p = new Node( i, x, y );
  19344. if ( ! last ) {
  19345. p.prev = p;
  19346. p.next = p;
  19347. } else {
  19348. p.next = last.next;
  19349. p.prev = last;
  19350. last.next.prev = p;
  19351. last.next = p;
  19352. }
  19353. return p;
  19354. }
  19355. function removeNode( p ) {
  19356. p.next.prev = p.prev;
  19357. p.prev.next = p.next;
  19358. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  19359. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  19360. }
  19361. function Node( i, x, y ) {
  19362. // vertex index in coordinates array
  19363. this.i = i;
  19364. // vertex coordinates
  19365. this.x = x;
  19366. this.y = y;
  19367. // previous and next vertex nodes in a polygon ring
  19368. this.prev = null;
  19369. this.next = null;
  19370. // z-order curve value
  19371. this.z = null;
  19372. // previous and next nodes in z-order
  19373. this.prevZ = null;
  19374. this.nextZ = null;
  19375. // indicates whether this is a steiner point
  19376. this.steiner = false;
  19377. }
  19378. function signedArea( data, start, end, dim ) {
  19379. let sum = 0;
  19380. for ( let i = start, j = end - dim; i < end; i += dim ) {
  19381. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  19382. j = i;
  19383. }
  19384. return sum;
  19385. }
  19386. class ShapeUtils {
  19387. // calculate area of the contour polygon
  19388. static area( contour ) {
  19389. const n = contour.length;
  19390. let a = 0.0;
  19391. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  19392. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19393. }
  19394. return a * 0.5;
  19395. }
  19396. static isClockWise( pts ) {
  19397. return ShapeUtils.area( pts ) < 0;
  19398. }
  19399. static triangulateShape( contour, holes ) {
  19400. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19401. const holeIndices = []; // array of hole indices
  19402. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19403. removeDupEndPts( contour );
  19404. addContour( vertices, contour );
  19405. //
  19406. let holeIndex = contour.length;
  19407. holes.forEach( removeDupEndPts );
  19408. for ( let i = 0; i < holes.length; i ++ ) {
  19409. holeIndices.push( holeIndex );
  19410. holeIndex += holes[ i ].length;
  19411. addContour( vertices, holes[ i ] );
  19412. }
  19413. //
  19414. const triangles = Earcut.triangulate( vertices, holeIndices );
  19415. //
  19416. for ( let i = 0; i < triangles.length; i += 3 ) {
  19417. faces.push( triangles.slice( i, i + 3 ) );
  19418. }
  19419. return faces;
  19420. }
  19421. }
  19422. function removeDupEndPts( points ) {
  19423. const l = points.length;
  19424. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19425. points.pop();
  19426. }
  19427. }
  19428. function addContour( vertices, contour ) {
  19429. for ( let i = 0; i < contour.length; i ++ ) {
  19430. vertices.push( contour[ i ].x );
  19431. vertices.push( contour[ i ].y );
  19432. }
  19433. }
  19434. /**
  19435. * Creates extruded geometry from a path shape.
  19436. *
  19437. * parameters = {
  19438. *
  19439. * curveSegments: <int>, // number of points on the curves
  19440. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19441. * depth: <float>, // Depth to extrude the shape
  19442. *
  19443. * bevelEnabled: <bool>, // turn on bevel
  19444. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19445. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19446. * bevelOffset: <float>, // how far from shape outline does bevel start
  19447. * bevelSegments: <int>, // number of bevel layers
  19448. *
  19449. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19450. *
  19451. * UVGenerator: <Object> // object that provides UV generator functions
  19452. *
  19453. * }
  19454. */
  19455. class ExtrudeGeometry extends BufferGeometry {
  19456. constructor( shapes, options ) {
  19457. super();
  19458. this.type = 'ExtrudeGeometry';
  19459. this.parameters = {
  19460. shapes: shapes,
  19461. options: options
  19462. };
  19463. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  19464. const scope = this;
  19465. const verticesArray = [];
  19466. const uvArray = [];
  19467. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19468. const shape = shapes[ i ];
  19469. addShape( shape );
  19470. }
  19471. // build geometry
  19472. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  19473. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  19474. this.computeVertexNormals();
  19475. // functions
  19476. function addShape( shape ) {
  19477. const placeholder = [];
  19478. // options
  19479. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19480. const steps = options.steps !== undefined ? options.steps : 1;
  19481. let depth = options.depth !== undefined ? options.depth : 100;
  19482. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19483. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19484. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19485. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19486. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19487. const extrudePath = options.extrudePath;
  19488. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  19489. // deprecated options
  19490. if ( options.amount !== undefined ) {
  19491. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  19492. depth = options.amount;
  19493. }
  19494. //
  19495. let extrudePts, extrudeByPath = false;
  19496. let splineTube, binormal, normal, position2;
  19497. if ( extrudePath ) {
  19498. extrudePts = extrudePath.getSpacedPoints( steps );
  19499. extrudeByPath = true;
  19500. bevelEnabled = false; // bevels not supported for path extrusion
  19501. // SETUP TNB variables
  19502. // TODO1 - have a .isClosed in spline?
  19503. splineTube = extrudePath.computeFrenetFrames( steps, false );
  19504. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19505. binormal = new Vector3();
  19506. normal = new Vector3();
  19507. position2 = new Vector3();
  19508. }
  19509. // Safeguards if bevels are not enabled
  19510. if ( ! bevelEnabled ) {
  19511. bevelSegments = 0;
  19512. bevelThickness = 0;
  19513. bevelSize = 0;
  19514. bevelOffset = 0;
  19515. }
  19516. // Variables initialization
  19517. const shapePoints = shape.extractPoints( curveSegments );
  19518. let vertices = shapePoints.shape;
  19519. const holes = shapePoints.holes;
  19520. const reverse = ! ShapeUtils.isClockWise( vertices );
  19521. if ( reverse ) {
  19522. vertices = vertices.reverse();
  19523. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19524. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19525. const ahole = holes[ h ];
  19526. if ( ShapeUtils.isClockWise( ahole ) ) {
  19527. holes[ h ] = ahole.reverse();
  19528. }
  19529. }
  19530. }
  19531. const faces = ShapeUtils.triangulateShape( vertices, holes );
  19532. /* Vertices */
  19533. const contour = vertices; // vertices has all points but contour has only points of circumference
  19534. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19535. const ahole = holes[ h ];
  19536. vertices = vertices.concat( ahole );
  19537. }
  19538. function scalePt2( pt, vec, size ) {
  19539. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  19540. return vec.clone().multiplyScalar( size ).add( pt );
  19541. }
  19542. const vlen = vertices.length, flen = faces.length;
  19543. // Find directions for point movement
  19544. function getBevelVec( inPt, inPrev, inNext ) {
  19545. // computes for inPt the corresponding point inPt' on a new contour
  19546. // shifted by 1 unit (length of normalized vector) to the left
  19547. // if we walk along contour clockwise, this new contour is outside the old one
  19548. //
  19549. // inPt' is the intersection of the two lines parallel to the two
  19550. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19551. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19552. // good reading for geometry algorithms (here: line-line intersection)
  19553. // http://geomalgorithms.com/a05-_intersect-1.html
  19554. const v_prev_x = inPt.x - inPrev.x,
  19555. v_prev_y = inPt.y - inPrev.y;
  19556. const v_next_x = inNext.x - inPt.x,
  19557. v_next_y = inNext.y - inPt.y;
  19558. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19559. // check for collinear edges
  19560. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19561. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19562. // not collinear
  19563. // length of vectors for normalizing
  19564. const v_prev_len = Math.sqrt( v_prev_lensq );
  19565. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19566. // shift adjacent points by unit vectors to the left
  19567. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19568. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19569. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19570. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19571. // scaling factor for v_prev to intersection point
  19572. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19573. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19574. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19575. // vector from inPt to intersection point
  19576. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19577. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19578. // Don't normalize!, otherwise sharp corners become ugly
  19579. // but prevent crazy spikes
  19580. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19581. if ( v_trans_lensq <= 2 ) {
  19582. return new Vector2( v_trans_x, v_trans_y );
  19583. } else {
  19584. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19585. }
  19586. } else {
  19587. // handle special case of collinear edges
  19588. let direction_eq = false; // assumes: opposite
  19589. if ( v_prev_x > Number.EPSILON ) {
  19590. if ( v_next_x > Number.EPSILON ) {
  19591. direction_eq = true;
  19592. }
  19593. } else {
  19594. if ( v_prev_x < - Number.EPSILON ) {
  19595. if ( v_next_x < - Number.EPSILON ) {
  19596. direction_eq = true;
  19597. }
  19598. } else {
  19599. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19600. direction_eq = true;
  19601. }
  19602. }
  19603. }
  19604. if ( direction_eq ) {
  19605. // console.log("Warning: lines are a straight sequence");
  19606. v_trans_x = - v_prev_y;
  19607. v_trans_y = v_prev_x;
  19608. shrink_by = Math.sqrt( v_prev_lensq );
  19609. } else {
  19610. // console.log("Warning: lines are a straight spike");
  19611. v_trans_x = v_prev_x;
  19612. v_trans_y = v_prev_y;
  19613. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19614. }
  19615. }
  19616. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19617. }
  19618. const contourMovements = [];
  19619. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19620. if ( j === il ) j = 0;
  19621. if ( k === il ) k = 0;
  19622. // (j)---(i)---(k)
  19623. // console.log('i,j,k', i, j , k)
  19624. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19625. }
  19626. const holesMovements = [];
  19627. let oneHoleMovements, verticesMovements = contourMovements.concat();
  19628. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19629. const ahole = holes[ h ];
  19630. oneHoleMovements = [];
  19631. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19632. if ( j === il ) j = 0;
  19633. if ( k === il ) k = 0;
  19634. // (j)---(i)---(k)
  19635. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19636. }
  19637. holesMovements.push( oneHoleMovements );
  19638. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19639. }
  19640. // Loop bevelSegments, 1 for the front, 1 for the back
  19641. for ( let b = 0; b < bevelSegments; b ++ ) {
  19642. //for ( b = bevelSegments; b > 0; b -- ) {
  19643. const t = b / bevelSegments;
  19644. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19645. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19646. // contract shape
  19647. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19648. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19649. v( vert.x, vert.y, - z );
  19650. }
  19651. // expand holes
  19652. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19653. const ahole = holes[ h ];
  19654. oneHoleMovements = holesMovements[ h ];
  19655. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19656. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19657. v( vert.x, vert.y, - z );
  19658. }
  19659. }
  19660. }
  19661. const bs = bevelSize + bevelOffset;
  19662. // Back facing vertices
  19663. for ( let i = 0; i < vlen; i ++ ) {
  19664. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19665. if ( ! extrudeByPath ) {
  19666. v( vert.x, vert.y, 0 );
  19667. } else {
  19668. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19669. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19670. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19671. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19672. v( position2.x, position2.y, position2.z );
  19673. }
  19674. }
  19675. // Add stepped vertices...
  19676. // Including front facing vertices
  19677. for ( let s = 1; s <= steps; s ++ ) {
  19678. for ( let i = 0; i < vlen; i ++ ) {
  19679. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19680. if ( ! extrudeByPath ) {
  19681. v( vert.x, vert.y, depth / steps * s );
  19682. } else {
  19683. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19684. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19685. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19686. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19687. v( position2.x, position2.y, position2.z );
  19688. }
  19689. }
  19690. }
  19691. // Add bevel segments planes
  19692. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19693. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  19694. const t = b / bevelSegments;
  19695. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19696. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19697. // contract shape
  19698. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19699. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19700. v( vert.x, vert.y, depth + z );
  19701. }
  19702. // expand holes
  19703. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19704. const ahole = holes[ h ];
  19705. oneHoleMovements = holesMovements[ h ];
  19706. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19707. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19708. if ( ! extrudeByPath ) {
  19709. v( vert.x, vert.y, depth + z );
  19710. } else {
  19711. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19712. }
  19713. }
  19714. }
  19715. }
  19716. /* Faces */
  19717. // Top and bottom faces
  19718. buildLidFaces();
  19719. // Sides faces
  19720. buildSideFaces();
  19721. ///// Internal functions
  19722. function buildLidFaces() {
  19723. const start = verticesArray.length / 3;
  19724. if ( bevelEnabled ) {
  19725. let layer = 0; // steps + 1
  19726. let offset = vlen * layer;
  19727. // Bottom faces
  19728. for ( let i = 0; i < flen; i ++ ) {
  19729. const face = faces[ i ];
  19730. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19731. }
  19732. layer = steps + bevelSegments * 2;
  19733. offset = vlen * layer;
  19734. // Top faces
  19735. for ( let i = 0; i < flen; i ++ ) {
  19736. const face = faces[ i ];
  19737. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19738. }
  19739. } else {
  19740. // Bottom faces
  19741. for ( let i = 0; i < flen; i ++ ) {
  19742. const face = faces[ i ];
  19743. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19744. }
  19745. // Top faces
  19746. for ( let i = 0; i < flen; i ++ ) {
  19747. const face = faces[ i ];
  19748. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19749. }
  19750. }
  19751. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  19752. }
  19753. // Create faces for the z-sides of the shape
  19754. function buildSideFaces() {
  19755. const start = verticesArray.length / 3;
  19756. let layeroffset = 0;
  19757. sidewalls( contour, layeroffset );
  19758. layeroffset += contour.length;
  19759. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19760. const ahole = holes[ h ];
  19761. sidewalls( ahole, layeroffset );
  19762. //, true
  19763. layeroffset += ahole.length;
  19764. }
  19765. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  19766. }
  19767. function sidewalls( contour, layeroffset ) {
  19768. let i = contour.length;
  19769. while ( -- i >= 0 ) {
  19770. const j = i;
  19771. let k = i - 1;
  19772. if ( k < 0 ) k = contour.length - 1;
  19773. //console.log('b', i,j, i-1, k,vertices.length);
  19774. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  19775. const slen1 = vlen * s;
  19776. const slen2 = vlen * ( s + 1 );
  19777. const a = layeroffset + j + slen1,
  19778. b = layeroffset + k + slen1,
  19779. c = layeroffset + k + slen2,
  19780. d = layeroffset + j + slen2;
  19781. f4( a, b, c, d );
  19782. }
  19783. }
  19784. }
  19785. function v( x, y, z ) {
  19786. placeholder.push( x );
  19787. placeholder.push( y );
  19788. placeholder.push( z );
  19789. }
  19790. function f3( a, b, c ) {
  19791. addVertex( a );
  19792. addVertex( b );
  19793. addVertex( c );
  19794. const nextIndex = verticesArray.length / 3;
  19795. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19796. addUV( uvs[ 0 ] );
  19797. addUV( uvs[ 1 ] );
  19798. addUV( uvs[ 2 ] );
  19799. }
  19800. function f4( a, b, c, d ) {
  19801. addVertex( a );
  19802. addVertex( b );
  19803. addVertex( d );
  19804. addVertex( b );
  19805. addVertex( c );
  19806. addVertex( d );
  19807. const nextIndex = verticesArray.length / 3;
  19808. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19809. addUV( uvs[ 0 ] );
  19810. addUV( uvs[ 1 ] );
  19811. addUV( uvs[ 3 ] );
  19812. addUV( uvs[ 1 ] );
  19813. addUV( uvs[ 2 ] );
  19814. addUV( uvs[ 3 ] );
  19815. }
  19816. function addVertex( index ) {
  19817. verticesArray.push( placeholder[ index * 3 + 0 ] );
  19818. verticesArray.push( placeholder[ index * 3 + 1 ] );
  19819. verticesArray.push( placeholder[ index * 3 + 2 ] );
  19820. }
  19821. function addUV( vector2 ) {
  19822. uvArray.push( vector2.x );
  19823. uvArray.push( vector2.y );
  19824. }
  19825. }
  19826. }
  19827. toJSON() {
  19828. const data = super.toJSON();
  19829. const shapes = this.parameters.shapes;
  19830. const options = this.parameters.options;
  19831. return toJSON$1( shapes, options, data );
  19832. }
  19833. static fromJSON( data, shapes ) {
  19834. const geometryShapes = [];
  19835. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  19836. const shape = shapes[ data.shapes[ j ] ];
  19837. geometryShapes.push( shape );
  19838. }
  19839. const extrudePath = data.options.extrudePath;
  19840. if ( extrudePath !== undefined ) {
  19841. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  19842. }
  19843. return new ExtrudeGeometry( geometryShapes, data.options );
  19844. }
  19845. }
  19846. const WorldUVGenerator = {
  19847. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  19848. const a_x = vertices[ indexA * 3 ];
  19849. const a_y = vertices[ indexA * 3 + 1 ];
  19850. const b_x = vertices[ indexB * 3 ];
  19851. const b_y = vertices[ indexB * 3 + 1 ];
  19852. const c_x = vertices[ indexC * 3 ];
  19853. const c_y = vertices[ indexC * 3 + 1 ];
  19854. return [
  19855. new Vector2( a_x, a_y ),
  19856. new Vector2( b_x, b_y ),
  19857. new Vector2( c_x, c_y )
  19858. ];
  19859. },
  19860. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  19861. const a_x = vertices[ indexA * 3 ];
  19862. const a_y = vertices[ indexA * 3 + 1 ];
  19863. const a_z = vertices[ indexA * 3 + 2 ];
  19864. const b_x = vertices[ indexB * 3 ];
  19865. const b_y = vertices[ indexB * 3 + 1 ];
  19866. const b_z = vertices[ indexB * 3 + 2 ];
  19867. const c_x = vertices[ indexC * 3 ];
  19868. const c_y = vertices[ indexC * 3 + 1 ];
  19869. const c_z = vertices[ indexC * 3 + 2 ];
  19870. const d_x = vertices[ indexD * 3 ];
  19871. const d_y = vertices[ indexD * 3 + 1 ];
  19872. const d_z = vertices[ indexD * 3 + 2 ];
  19873. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  19874. return [
  19875. new Vector2( a_x, 1 - a_z ),
  19876. new Vector2( b_x, 1 - b_z ),
  19877. new Vector2( c_x, 1 - c_z ),
  19878. new Vector2( d_x, 1 - d_z )
  19879. ];
  19880. } else {
  19881. return [
  19882. new Vector2( a_y, 1 - a_z ),
  19883. new Vector2( b_y, 1 - b_z ),
  19884. new Vector2( c_y, 1 - c_z ),
  19885. new Vector2( d_y, 1 - d_z )
  19886. ];
  19887. }
  19888. }
  19889. };
  19890. function toJSON$1( shapes, options, data ) {
  19891. data.shapes = [];
  19892. if ( Array.isArray( shapes ) ) {
  19893. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19894. const shape = shapes[ i ];
  19895. data.shapes.push( shape.uuid );
  19896. }
  19897. } else {
  19898. data.shapes.push( shapes.uuid );
  19899. }
  19900. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  19901. return data;
  19902. }
  19903. class IcosahedronGeometry extends PolyhedronGeometry {
  19904. constructor( radius = 1, detail = 0 ) {
  19905. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19906. const vertices = [
  19907. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19908. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19909. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19910. ];
  19911. const indices = [
  19912. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19913. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19914. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19915. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19916. ];
  19917. super( vertices, indices, radius, detail );
  19918. this.type = 'IcosahedronGeometry';
  19919. this.parameters = {
  19920. radius: radius,
  19921. detail: detail
  19922. };
  19923. }
  19924. static fromJSON( data ) {
  19925. return new IcosahedronGeometry( data.radius, data.detail );
  19926. }
  19927. }
  19928. class LatheGeometry extends BufferGeometry {
  19929. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  19930. super();
  19931. this.type = 'LatheGeometry';
  19932. this.parameters = {
  19933. points: points,
  19934. segments: segments,
  19935. phiStart: phiStart,
  19936. phiLength: phiLength
  19937. };
  19938. segments = Math.floor( segments );
  19939. // clamp phiLength so it's in range of [ 0, 2PI ]
  19940. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19941. // buffers
  19942. const indices = [];
  19943. const vertices = [];
  19944. const uvs = [];
  19945. // helper variables
  19946. const inverseSegments = 1.0 / segments;
  19947. const vertex = new Vector3();
  19948. const uv = new Vector2();
  19949. // generate vertices and uvs
  19950. for ( let i = 0; i <= segments; i ++ ) {
  19951. const phi = phiStart + i * inverseSegments * phiLength;
  19952. const sin = Math.sin( phi );
  19953. const cos = Math.cos( phi );
  19954. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19955. // vertex
  19956. vertex.x = points[ j ].x * sin;
  19957. vertex.y = points[ j ].y;
  19958. vertex.z = points[ j ].x * cos;
  19959. vertices.push( vertex.x, vertex.y, vertex.z );
  19960. // uv
  19961. uv.x = i / segments;
  19962. uv.y = j / ( points.length - 1 );
  19963. uvs.push( uv.x, uv.y );
  19964. }
  19965. }
  19966. // indices
  19967. for ( let i = 0; i < segments; i ++ ) {
  19968. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19969. const base = j + i * points.length;
  19970. const a = base;
  19971. const b = base + points.length;
  19972. const c = base + points.length + 1;
  19973. const d = base + 1;
  19974. // faces
  19975. indices.push( a, b, d );
  19976. indices.push( b, c, d );
  19977. }
  19978. }
  19979. // build geometry
  19980. this.setIndex( indices );
  19981. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19982. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19983. // generate normals
  19984. this.computeVertexNormals();
  19985. // if the geometry is closed, we need to average the normals along the seam.
  19986. // because the corresponding vertices are identical (but still have different UVs).
  19987. if ( phiLength === Math.PI * 2 ) {
  19988. const normals = this.attributes.normal.array;
  19989. const n1 = new Vector3();
  19990. const n2 = new Vector3();
  19991. const n = new Vector3();
  19992. // this is the buffer offset for the last line of vertices
  19993. const base = segments * points.length * 3;
  19994. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  19995. // select the normal of the vertex in the first line
  19996. n1.x = normals[ j + 0 ];
  19997. n1.y = normals[ j + 1 ];
  19998. n1.z = normals[ j + 2 ];
  19999. // select the normal of the vertex in the last line
  20000. n2.x = normals[ base + j + 0 ];
  20001. n2.y = normals[ base + j + 1 ];
  20002. n2.z = normals[ base + j + 2 ];
  20003. // average normals
  20004. n.addVectors( n1, n2 ).normalize();
  20005. // assign the new values to both normals
  20006. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  20007. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  20008. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  20009. }
  20010. }
  20011. }
  20012. static fromJSON( data ) {
  20013. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20014. }
  20015. }
  20016. class OctahedronGeometry extends PolyhedronGeometry {
  20017. constructor( radius = 1, detail = 0 ) {
  20018. const vertices = [
  20019. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  20020. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  20021. ];
  20022. const indices = [
  20023. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20024. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20025. 1, 3, 4, 1, 4, 2
  20026. ];
  20027. super( vertices, indices, radius, detail );
  20028. this.type = 'OctahedronGeometry';
  20029. this.parameters = {
  20030. radius: radius,
  20031. detail: detail
  20032. };
  20033. }
  20034. static fromJSON( data ) {
  20035. return new OctahedronGeometry( data.radius, data.detail );
  20036. }
  20037. }
  20038. /**
  20039. * Parametric Surfaces Geometry
  20040. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  20041. */
  20042. class ParametricGeometry extends BufferGeometry {
  20043. constructor( func, slices, stacks ) {
  20044. super();
  20045. this.type = 'ParametricGeometry';
  20046. this.parameters = {
  20047. func: func,
  20048. slices: slices,
  20049. stacks: stacks
  20050. };
  20051. // buffers
  20052. const indices = [];
  20053. const vertices = [];
  20054. const normals = [];
  20055. const uvs = [];
  20056. const EPS = 0.00001;
  20057. const normal = new Vector3();
  20058. const p0 = new Vector3(), p1 = new Vector3();
  20059. const pu = new Vector3(), pv = new Vector3();
  20060. if ( func.length < 3 ) {
  20061. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  20062. }
  20063. // generate vertices, normals and uvs
  20064. const sliceCount = slices + 1;
  20065. for ( let i = 0; i <= stacks; i ++ ) {
  20066. const v = i / stacks;
  20067. for ( let j = 0; j <= slices; j ++ ) {
  20068. const u = j / slices;
  20069. // vertex
  20070. func( u, v, p0 );
  20071. vertices.push( p0.x, p0.y, p0.z );
  20072. // normal
  20073. // approximate tangent vectors via finite differences
  20074. if ( u - EPS >= 0 ) {
  20075. func( u - EPS, v, p1 );
  20076. pu.subVectors( p0, p1 );
  20077. } else {
  20078. func( u + EPS, v, p1 );
  20079. pu.subVectors( p1, p0 );
  20080. }
  20081. if ( v - EPS >= 0 ) {
  20082. func( u, v - EPS, p1 );
  20083. pv.subVectors( p0, p1 );
  20084. } else {
  20085. func( u, v + EPS, p1 );
  20086. pv.subVectors( p1, p0 );
  20087. }
  20088. // cross product of tangent vectors returns surface normal
  20089. normal.crossVectors( pu, pv ).normalize();
  20090. normals.push( normal.x, normal.y, normal.z );
  20091. // uv
  20092. uvs.push( u, v );
  20093. }
  20094. }
  20095. // generate indices
  20096. for ( let i = 0; i < stacks; i ++ ) {
  20097. for ( let j = 0; j < slices; j ++ ) {
  20098. const a = i * sliceCount + j;
  20099. const b = i * sliceCount + j + 1;
  20100. const c = ( i + 1 ) * sliceCount + j + 1;
  20101. const d = ( i + 1 ) * sliceCount + j;
  20102. // faces one and two
  20103. indices.push( a, b, d );
  20104. indices.push( b, c, d );
  20105. }
  20106. }
  20107. // build geometry
  20108. this.setIndex( indices );
  20109. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20110. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20111. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20112. }
  20113. }
  20114. class RingGeometry extends BufferGeometry {
  20115. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20116. super();
  20117. this.type = 'RingGeometry';
  20118. this.parameters = {
  20119. innerRadius: innerRadius,
  20120. outerRadius: outerRadius,
  20121. thetaSegments: thetaSegments,
  20122. phiSegments: phiSegments,
  20123. thetaStart: thetaStart,
  20124. thetaLength: thetaLength
  20125. };
  20126. thetaSegments = Math.max( 3, thetaSegments );
  20127. phiSegments = Math.max( 1, phiSegments );
  20128. // buffers
  20129. const indices = [];
  20130. const vertices = [];
  20131. const normals = [];
  20132. const uvs = [];
  20133. // some helper variables
  20134. let radius = innerRadius;
  20135. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20136. const vertex = new Vector3();
  20137. const uv = new Vector2();
  20138. // generate vertices, normals and uvs
  20139. for ( let j = 0; j <= phiSegments; j ++ ) {
  20140. for ( let i = 0; i <= thetaSegments; i ++ ) {
  20141. // values are generate from the inside of the ring to the outside
  20142. const segment = thetaStart + i / thetaSegments * thetaLength;
  20143. // vertex
  20144. vertex.x = radius * Math.cos( segment );
  20145. vertex.y = radius * Math.sin( segment );
  20146. vertices.push( vertex.x, vertex.y, vertex.z );
  20147. // normal
  20148. normals.push( 0, 0, 1 );
  20149. // uv
  20150. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20151. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20152. uvs.push( uv.x, uv.y );
  20153. }
  20154. // increase the radius for next row of vertices
  20155. radius += radiusStep;
  20156. }
  20157. // indices
  20158. for ( let j = 0; j < phiSegments; j ++ ) {
  20159. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  20160. for ( let i = 0; i < thetaSegments; i ++ ) {
  20161. const segment = i + thetaSegmentLevel;
  20162. const a = segment;
  20163. const b = segment + thetaSegments + 1;
  20164. const c = segment + thetaSegments + 2;
  20165. const d = segment + 1;
  20166. // faces
  20167. indices.push( a, b, d );
  20168. indices.push( b, c, d );
  20169. }
  20170. }
  20171. // build geometry
  20172. this.setIndex( indices );
  20173. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20174. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20175. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20176. }
  20177. static fromJSON( data ) {
  20178. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  20179. }
  20180. }
  20181. class ShapeGeometry extends BufferGeometry {
  20182. constructor( shapes, curveSegments = 12 ) {
  20183. super();
  20184. this.type = 'ShapeGeometry';
  20185. this.parameters = {
  20186. shapes: shapes,
  20187. curveSegments: curveSegments
  20188. };
  20189. // buffers
  20190. const indices = [];
  20191. const vertices = [];
  20192. const normals = [];
  20193. const uvs = [];
  20194. // helper variables
  20195. let groupStart = 0;
  20196. let groupCount = 0;
  20197. // allow single and array values for "shapes" parameter
  20198. if ( Array.isArray( shapes ) === false ) {
  20199. addShape( shapes );
  20200. } else {
  20201. for ( let i = 0; i < shapes.length; i ++ ) {
  20202. addShape( shapes[ i ] );
  20203. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20204. groupStart += groupCount;
  20205. groupCount = 0;
  20206. }
  20207. }
  20208. // build geometry
  20209. this.setIndex( indices );
  20210. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20211. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20212. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20213. // helper functions
  20214. function addShape( shape ) {
  20215. const indexOffset = vertices.length / 3;
  20216. const points = shape.extractPoints( curveSegments );
  20217. let shapeVertices = points.shape;
  20218. const shapeHoles = points.holes;
  20219. // check direction of vertices
  20220. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20221. shapeVertices = shapeVertices.reverse();
  20222. }
  20223. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20224. const shapeHole = shapeHoles[ i ];
  20225. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20226. shapeHoles[ i ] = shapeHole.reverse();
  20227. }
  20228. }
  20229. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20230. // join vertices of inner and outer paths to a single array
  20231. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20232. const shapeHole = shapeHoles[ i ];
  20233. shapeVertices = shapeVertices.concat( shapeHole );
  20234. }
  20235. // vertices, normals, uvs
  20236. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20237. const vertex = shapeVertices[ i ];
  20238. vertices.push( vertex.x, vertex.y, 0 );
  20239. normals.push( 0, 0, 1 );
  20240. uvs.push( vertex.x, vertex.y ); // world uvs
  20241. }
  20242. // incides
  20243. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20244. const face = faces[ i ];
  20245. const a = face[ 0 ] + indexOffset;
  20246. const b = face[ 1 ] + indexOffset;
  20247. const c = face[ 2 ] + indexOffset;
  20248. indices.push( a, b, c );
  20249. groupCount += 3;
  20250. }
  20251. }
  20252. }
  20253. toJSON() {
  20254. const data = super.toJSON();
  20255. const shapes = this.parameters.shapes;
  20256. return toJSON( shapes, data );
  20257. }
  20258. static fromJSON( data, shapes ) {
  20259. const geometryShapes = [];
  20260. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20261. const shape = shapes[ data.shapes[ j ] ];
  20262. geometryShapes.push( shape );
  20263. }
  20264. return new ShapeGeometry( geometryShapes, data.curveSegments );
  20265. }
  20266. }
  20267. function toJSON( shapes, data ) {
  20268. data.shapes = [];
  20269. if ( Array.isArray( shapes ) ) {
  20270. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20271. const shape = shapes[ i ];
  20272. data.shapes.push( shape.uuid );
  20273. }
  20274. } else {
  20275. data.shapes.push( shapes.uuid );
  20276. }
  20277. return data;
  20278. }
  20279. class SphereGeometry extends BufferGeometry {
  20280. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  20281. super();
  20282. this.type = 'SphereGeometry';
  20283. this.parameters = {
  20284. radius: radius,
  20285. widthSegments: widthSegments,
  20286. heightSegments: heightSegments,
  20287. phiStart: phiStart,
  20288. phiLength: phiLength,
  20289. thetaStart: thetaStart,
  20290. thetaLength: thetaLength
  20291. };
  20292. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  20293. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  20294. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  20295. let index = 0;
  20296. const grid = [];
  20297. const vertex = new Vector3();
  20298. const normal = new Vector3();
  20299. // buffers
  20300. const indices = [];
  20301. const vertices = [];
  20302. const normals = [];
  20303. const uvs = [];
  20304. // generate vertices, normals and uvs
  20305. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  20306. const verticesRow = [];
  20307. const v = iy / heightSegments;
  20308. // special case for the poles
  20309. let uOffset = 0;
  20310. if ( iy == 0 && thetaStart == 0 ) {
  20311. uOffset = 0.5 / widthSegments;
  20312. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  20313. uOffset = - 0.5 / widthSegments;
  20314. }
  20315. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  20316. const u = ix / widthSegments;
  20317. // vertex
  20318. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20319. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20320. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20321. vertices.push( vertex.x, vertex.y, vertex.z );
  20322. // normal
  20323. normal.copy( vertex ).normalize();
  20324. normals.push( normal.x, normal.y, normal.z );
  20325. // uv
  20326. uvs.push( u + uOffset, 1 - v );
  20327. verticesRow.push( index ++ );
  20328. }
  20329. grid.push( verticesRow );
  20330. }
  20331. // indices
  20332. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  20333. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20334. const a = grid[ iy ][ ix + 1 ];
  20335. const b = grid[ iy ][ ix ];
  20336. const c = grid[ iy + 1 ][ ix ];
  20337. const d = grid[ iy + 1 ][ ix + 1 ];
  20338. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20339. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20340. }
  20341. }
  20342. // build geometry
  20343. this.setIndex( indices );
  20344. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20345. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20346. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20347. }
  20348. static fromJSON( data ) {
  20349. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  20350. }
  20351. }
  20352. class TetrahedronGeometry extends PolyhedronGeometry {
  20353. constructor( radius = 1, detail = 0 ) {
  20354. const vertices = [
  20355. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20356. ];
  20357. const indices = [
  20358. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20359. ];
  20360. super( vertices, indices, radius, detail );
  20361. this.type = 'TetrahedronGeometry';
  20362. this.parameters = {
  20363. radius: radius,
  20364. detail: detail
  20365. };
  20366. }
  20367. static fromJSON( data ) {
  20368. return new TetrahedronGeometry( data.radius, data.detail );
  20369. }
  20370. }
  20371. /**
  20372. * Text = 3D Text
  20373. *
  20374. * parameters = {
  20375. * font: <THREE.Font>, // font
  20376. *
  20377. * size: <float>, // size of the text
  20378. * height: <float>, // thickness to extrude text
  20379. * curveSegments: <int>, // number of points on the curves
  20380. *
  20381. * bevelEnabled: <bool>, // turn on bevel
  20382. * bevelThickness: <float>, // how deep into text bevel goes
  20383. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20384. * bevelOffset: <float> // how far from text outline does bevel start
  20385. * }
  20386. */
  20387. class TextGeometry extends ExtrudeGeometry {
  20388. constructor( text, parameters = {} ) {
  20389. const font = parameters.font;
  20390. if ( ! ( font && font.isFont ) ) {
  20391. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20392. return new BufferGeometry();
  20393. }
  20394. const shapes = font.generateShapes( text, parameters.size );
  20395. // translate parameters to ExtrudeGeometry API
  20396. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  20397. // defaults
  20398. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20399. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20400. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20401. super( shapes, parameters );
  20402. this.type = 'TextGeometry';
  20403. }
  20404. }
  20405. class TorusGeometry extends BufferGeometry {
  20406. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  20407. super();
  20408. this.type = 'TorusGeometry';
  20409. this.parameters = {
  20410. radius: radius,
  20411. tube: tube,
  20412. radialSegments: radialSegments,
  20413. tubularSegments: tubularSegments,
  20414. arc: arc
  20415. };
  20416. radialSegments = Math.floor( radialSegments );
  20417. tubularSegments = Math.floor( tubularSegments );
  20418. // buffers
  20419. const indices = [];
  20420. const vertices = [];
  20421. const normals = [];
  20422. const uvs = [];
  20423. // helper variables
  20424. const center = new Vector3();
  20425. const vertex = new Vector3();
  20426. const normal = new Vector3();
  20427. // generate vertices, normals and uvs
  20428. for ( let j = 0; j <= radialSegments; j ++ ) {
  20429. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20430. const u = i / tubularSegments * arc;
  20431. const v = j / radialSegments * Math.PI * 2;
  20432. // vertex
  20433. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20434. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20435. vertex.z = tube * Math.sin( v );
  20436. vertices.push( vertex.x, vertex.y, vertex.z );
  20437. // normal
  20438. center.x = radius * Math.cos( u );
  20439. center.y = radius * Math.sin( u );
  20440. normal.subVectors( vertex, center ).normalize();
  20441. normals.push( normal.x, normal.y, normal.z );
  20442. // uv
  20443. uvs.push( i / tubularSegments );
  20444. uvs.push( j / radialSegments );
  20445. }
  20446. }
  20447. // generate indices
  20448. for ( let j = 1; j <= radialSegments; j ++ ) {
  20449. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20450. // indices
  20451. const a = ( tubularSegments + 1 ) * j + i - 1;
  20452. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20453. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20454. const d = ( tubularSegments + 1 ) * j + i;
  20455. // faces
  20456. indices.push( a, b, d );
  20457. indices.push( b, c, d );
  20458. }
  20459. }
  20460. // build geometry
  20461. this.setIndex( indices );
  20462. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20463. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20464. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20465. }
  20466. static fromJSON( data ) {
  20467. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  20468. }
  20469. }
  20470. class TorusKnotGeometry extends BufferGeometry {
  20471. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20472. super();
  20473. this.type = 'TorusKnotGeometry';
  20474. this.parameters = {
  20475. radius: radius,
  20476. tube: tube,
  20477. tubularSegments: tubularSegments,
  20478. radialSegments: radialSegments,
  20479. p: p,
  20480. q: q
  20481. };
  20482. tubularSegments = Math.floor( tubularSegments );
  20483. radialSegments = Math.floor( radialSegments );
  20484. // buffers
  20485. const indices = [];
  20486. const vertices = [];
  20487. const normals = [];
  20488. const uvs = [];
  20489. // helper variables
  20490. const vertex = new Vector3();
  20491. const normal = new Vector3();
  20492. const P1 = new Vector3();
  20493. const P2 = new Vector3();
  20494. const B = new Vector3();
  20495. const T = new Vector3();
  20496. const N = new Vector3();
  20497. // generate vertices, normals and uvs
  20498. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20499. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20500. const u = i / tubularSegments * p * Math.PI * 2;
  20501. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20502. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20503. calculatePositionOnCurve( u, p, q, radius, P1 );
  20504. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20505. // calculate orthonormal basis
  20506. T.subVectors( P2, P1 );
  20507. N.addVectors( P2, P1 );
  20508. B.crossVectors( T, N );
  20509. N.crossVectors( B, T );
  20510. // normalize B, N. T can be ignored, we don't use it
  20511. B.normalize();
  20512. N.normalize();
  20513. for ( let j = 0; j <= radialSegments; ++ j ) {
  20514. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20515. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20516. const v = j / radialSegments * Math.PI * 2;
  20517. const cx = - tube * Math.cos( v );
  20518. const cy = tube * Math.sin( v );
  20519. // now calculate the final vertex position.
  20520. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20521. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20522. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20523. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20524. vertices.push( vertex.x, vertex.y, vertex.z );
  20525. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20526. normal.subVectors( vertex, P1 ).normalize();
  20527. normals.push( normal.x, normal.y, normal.z );
  20528. // uv
  20529. uvs.push( i / tubularSegments );
  20530. uvs.push( j / radialSegments );
  20531. }
  20532. }
  20533. // generate indices
  20534. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20535. for ( let i = 1; i <= radialSegments; i ++ ) {
  20536. // indices
  20537. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20538. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20539. const c = ( radialSegments + 1 ) * j + i;
  20540. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20541. // faces
  20542. indices.push( a, b, d );
  20543. indices.push( b, c, d );
  20544. }
  20545. }
  20546. // build geometry
  20547. this.setIndex( indices );
  20548. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20549. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20550. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20551. // this function calculates the current position on the torus curve
  20552. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20553. const cu = Math.cos( u );
  20554. const su = Math.sin( u );
  20555. const quOverP = q / p * u;
  20556. const cs = Math.cos( quOverP );
  20557. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20558. position.y = radius * ( 2 + cs ) * su * 0.5;
  20559. position.z = radius * Math.sin( quOverP ) * 0.5;
  20560. }
  20561. }
  20562. static fromJSON( data ) {
  20563. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  20564. }
  20565. }
  20566. class TubeGeometry extends BufferGeometry {
  20567. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  20568. super();
  20569. this.type = 'TubeGeometry';
  20570. this.parameters = {
  20571. path: path,
  20572. tubularSegments: tubularSegments,
  20573. radius: radius,
  20574. radialSegments: radialSegments,
  20575. closed: closed
  20576. };
  20577. const frames = path.computeFrenetFrames( tubularSegments, closed );
  20578. // expose internals
  20579. this.tangents = frames.tangents;
  20580. this.normals = frames.normals;
  20581. this.binormals = frames.binormals;
  20582. // helper variables
  20583. const vertex = new Vector3();
  20584. const normal = new Vector3();
  20585. const uv = new Vector2();
  20586. let P = new Vector3();
  20587. // buffer
  20588. const vertices = [];
  20589. const normals = [];
  20590. const uvs = [];
  20591. const indices = [];
  20592. // create buffer data
  20593. generateBufferData();
  20594. // build geometry
  20595. this.setIndex( indices );
  20596. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20597. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20598. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20599. // functions
  20600. function generateBufferData() {
  20601. for ( let i = 0; i < tubularSegments; i ++ ) {
  20602. generateSegment( i );
  20603. }
  20604. // if the geometry is not closed, generate the last row of vertices and normals
  20605. // at the regular position on the given path
  20606. //
  20607. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20608. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20609. // uvs are generated in a separate function.
  20610. // this makes it easy compute correct values for closed geometries
  20611. generateUVs();
  20612. // finally create faces
  20613. generateIndices();
  20614. }
  20615. function generateSegment( i ) {
  20616. // we use getPointAt to sample evenly distributed points from the given path
  20617. P = path.getPointAt( i / tubularSegments, P );
  20618. // retrieve corresponding normal and binormal
  20619. const N = frames.normals[ i ];
  20620. const B = frames.binormals[ i ];
  20621. // generate normals and vertices for the current segment
  20622. for ( let j = 0; j <= radialSegments; j ++ ) {
  20623. const v = j / radialSegments * Math.PI * 2;
  20624. const sin = Math.sin( v );
  20625. const cos = - Math.cos( v );
  20626. // normal
  20627. normal.x = ( cos * N.x + sin * B.x );
  20628. normal.y = ( cos * N.y + sin * B.y );
  20629. normal.z = ( cos * N.z + sin * B.z );
  20630. normal.normalize();
  20631. normals.push( normal.x, normal.y, normal.z );
  20632. // vertex
  20633. vertex.x = P.x + radius * normal.x;
  20634. vertex.y = P.y + radius * normal.y;
  20635. vertex.z = P.z + radius * normal.z;
  20636. vertices.push( vertex.x, vertex.y, vertex.z );
  20637. }
  20638. }
  20639. function generateIndices() {
  20640. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20641. for ( let i = 1; i <= radialSegments; i ++ ) {
  20642. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20643. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20644. const c = ( radialSegments + 1 ) * j + i;
  20645. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20646. // faces
  20647. indices.push( a, b, d );
  20648. indices.push( b, c, d );
  20649. }
  20650. }
  20651. }
  20652. function generateUVs() {
  20653. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20654. for ( let j = 0; j <= radialSegments; j ++ ) {
  20655. uv.x = i / tubularSegments;
  20656. uv.y = j / radialSegments;
  20657. uvs.push( uv.x, uv.y );
  20658. }
  20659. }
  20660. }
  20661. }
  20662. toJSON() {
  20663. const data = super.toJSON();
  20664. data.path = this.parameters.path.toJSON();
  20665. return data;
  20666. }
  20667. static fromJSON( data ) {
  20668. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20669. // User defined curves or instances of CurvePath will not be deserialized.
  20670. return new TubeGeometry(
  20671. new Curves[ data.path.type ]().fromJSON( data.path ),
  20672. data.tubularSegments,
  20673. data.radius,
  20674. data.radialSegments,
  20675. data.closed
  20676. );
  20677. }
  20678. }
  20679. class WireframeGeometry extends BufferGeometry {
  20680. constructor( geometry ) {
  20681. super();
  20682. this.type = 'WireframeGeometry';
  20683. if ( geometry.isGeometry === true ) {
  20684. console.error( 'THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  20685. return;
  20686. }
  20687. // buffer
  20688. const vertices = [];
  20689. const edges = new Set();
  20690. // helper variables
  20691. const start = new Vector3();
  20692. const end = new Vector3();
  20693. if ( geometry.index !== null ) {
  20694. // indexed BufferGeometry
  20695. const position = geometry.attributes.position;
  20696. const indices = geometry.index;
  20697. let groups = geometry.groups;
  20698. if ( groups.length === 0 ) {
  20699. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20700. }
  20701. // create a data structure that contains all eges without duplicates
  20702. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  20703. const group = groups[ o ];
  20704. const groupStart = group.start;
  20705. const groupCount = group.count;
  20706. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  20707. for ( let j = 0; j < 3; j ++ ) {
  20708. const index1 = indices.getX( i + j );
  20709. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  20710. start.fromBufferAttribute( position, index1 );
  20711. end.fromBufferAttribute( position, index2 );
  20712. if ( isUniqueEdge( start, end, edges ) === true ) {
  20713. vertices.push( start.x, start.y, start.z );
  20714. vertices.push( end.x, end.y, end.z );
  20715. }
  20716. }
  20717. }
  20718. }
  20719. } else {
  20720. // non-indexed BufferGeometry
  20721. const position = geometry.attributes.position;
  20722. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20723. for ( let j = 0; j < 3; j ++ ) {
  20724. // three edges per triangle, an edge is represented as (index1, index2)
  20725. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20726. const index1 = 3 * i + j;
  20727. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  20728. start.fromBufferAttribute( position, index1 );
  20729. end.fromBufferAttribute( position, index2 );
  20730. if ( isUniqueEdge( start, end, edges ) === true ) {
  20731. vertices.push( start.x, start.y, start.z );
  20732. vertices.push( end.x, end.y, end.z );
  20733. }
  20734. }
  20735. }
  20736. }
  20737. // build geometry
  20738. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20739. }
  20740. }
  20741. function isUniqueEdge( start, end, edges ) {
  20742. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  20743. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  20744. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  20745. return false;
  20746. } else {
  20747. edges.add( hash1, hash2 );
  20748. return true;
  20749. }
  20750. }
  20751. var Geometries = /*#__PURE__*/Object.freeze({
  20752. __proto__: null,
  20753. BoxGeometry: BoxGeometry,
  20754. BoxBufferGeometry: BoxGeometry,
  20755. CircleGeometry: CircleGeometry,
  20756. CircleBufferGeometry: CircleGeometry,
  20757. ConeGeometry: ConeGeometry,
  20758. ConeBufferGeometry: ConeGeometry,
  20759. CylinderGeometry: CylinderGeometry,
  20760. CylinderBufferGeometry: CylinderGeometry,
  20761. DodecahedronGeometry: DodecahedronGeometry,
  20762. DodecahedronBufferGeometry: DodecahedronGeometry,
  20763. EdgesGeometry: EdgesGeometry,
  20764. ExtrudeGeometry: ExtrudeGeometry,
  20765. ExtrudeBufferGeometry: ExtrudeGeometry,
  20766. IcosahedronGeometry: IcosahedronGeometry,
  20767. IcosahedronBufferGeometry: IcosahedronGeometry,
  20768. LatheGeometry: LatheGeometry,
  20769. LatheBufferGeometry: LatheGeometry,
  20770. OctahedronGeometry: OctahedronGeometry,
  20771. OctahedronBufferGeometry: OctahedronGeometry,
  20772. ParametricGeometry: ParametricGeometry,
  20773. ParametricBufferGeometry: ParametricGeometry,
  20774. PlaneGeometry: PlaneGeometry,
  20775. PlaneBufferGeometry: PlaneGeometry,
  20776. PolyhedronGeometry: PolyhedronGeometry,
  20777. PolyhedronBufferGeometry: PolyhedronGeometry,
  20778. RingGeometry: RingGeometry,
  20779. RingBufferGeometry: RingGeometry,
  20780. ShapeGeometry: ShapeGeometry,
  20781. ShapeBufferGeometry: ShapeGeometry,
  20782. SphereGeometry: SphereGeometry,
  20783. SphereBufferGeometry: SphereGeometry,
  20784. TetrahedronGeometry: TetrahedronGeometry,
  20785. TetrahedronBufferGeometry: TetrahedronGeometry,
  20786. TextGeometry: TextGeometry,
  20787. TextBufferGeometry: TextGeometry,
  20788. TorusGeometry: TorusGeometry,
  20789. TorusBufferGeometry: TorusGeometry,
  20790. TorusKnotGeometry: TorusKnotGeometry,
  20791. TorusKnotBufferGeometry: TorusKnotGeometry,
  20792. TubeGeometry: TubeGeometry,
  20793. TubeBufferGeometry: TubeGeometry,
  20794. WireframeGeometry: WireframeGeometry
  20795. });
  20796. /**
  20797. * parameters = {
  20798. * color: <THREE.Color>
  20799. * }
  20800. */
  20801. class ShadowMaterial extends Material {
  20802. constructor( parameters ) {
  20803. super();
  20804. this.type = 'ShadowMaterial';
  20805. this.color = new Color( 0x000000 );
  20806. this.transparent = true;
  20807. this.setValues( parameters );
  20808. }
  20809. copy( source ) {
  20810. super.copy( source );
  20811. this.color.copy( source.color );
  20812. return this;
  20813. }
  20814. }
  20815. ShadowMaterial.prototype.isShadowMaterial = true;
  20816. /**
  20817. * parameters = {
  20818. * color: <hex>,
  20819. * roughness: <float>,
  20820. * metalness: <float>,
  20821. * opacity: <float>,
  20822. *
  20823. * map: new THREE.Texture( <Image> ),
  20824. *
  20825. * lightMap: new THREE.Texture( <Image> ),
  20826. * lightMapIntensity: <float>
  20827. *
  20828. * aoMap: new THREE.Texture( <Image> ),
  20829. * aoMapIntensity: <float>
  20830. *
  20831. * emissive: <hex>,
  20832. * emissiveIntensity: <float>
  20833. * emissiveMap: new THREE.Texture( <Image> ),
  20834. *
  20835. * bumpMap: new THREE.Texture( <Image> ),
  20836. * bumpScale: <float>,
  20837. *
  20838. * normalMap: new THREE.Texture( <Image> ),
  20839. * normalMapType: THREE.TangentSpaceNormalMap,
  20840. * normalScale: <Vector2>,
  20841. *
  20842. * displacementMap: new THREE.Texture( <Image> ),
  20843. * displacementScale: <float>,
  20844. * displacementBias: <float>,
  20845. *
  20846. * roughnessMap: new THREE.Texture( <Image> ),
  20847. *
  20848. * metalnessMap: new THREE.Texture( <Image> ),
  20849. *
  20850. * alphaMap: new THREE.Texture( <Image> ),
  20851. *
  20852. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20853. * envMapIntensity: <float>
  20854. *
  20855. * refractionRatio: <float>,
  20856. *
  20857. * wireframe: <boolean>,
  20858. * wireframeLinewidth: <float>,
  20859. *
  20860. * flatShading: <bool>
  20861. * }
  20862. */
  20863. class MeshStandardMaterial extends Material {
  20864. constructor( parameters ) {
  20865. super();
  20866. this.defines = { 'STANDARD': '' };
  20867. this.type = 'MeshStandardMaterial';
  20868. this.color = new Color( 0xffffff ); // diffuse
  20869. this.roughness = 1.0;
  20870. this.metalness = 0.0;
  20871. this.map = null;
  20872. this.lightMap = null;
  20873. this.lightMapIntensity = 1.0;
  20874. this.aoMap = null;
  20875. this.aoMapIntensity = 1.0;
  20876. this.emissive = new Color( 0x000000 );
  20877. this.emissiveIntensity = 1.0;
  20878. this.emissiveMap = null;
  20879. this.bumpMap = null;
  20880. this.bumpScale = 1;
  20881. this.normalMap = null;
  20882. this.normalMapType = TangentSpaceNormalMap;
  20883. this.normalScale = new Vector2( 1, 1 );
  20884. this.displacementMap = null;
  20885. this.displacementScale = 1;
  20886. this.displacementBias = 0;
  20887. this.roughnessMap = null;
  20888. this.metalnessMap = null;
  20889. this.alphaMap = null;
  20890. this.envMap = null;
  20891. this.envMapIntensity = 1.0;
  20892. this.refractionRatio = 0.98;
  20893. this.wireframe = false;
  20894. this.wireframeLinewidth = 1;
  20895. this.wireframeLinecap = 'round';
  20896. this.wireframeLinejoin = 'round';
  20897. this.flatShading = false;
  20898. this.setValues( parameters );
  20899. }
  20900. copy( source ) {
  20901. super.copy( source );
  20902. this.defines = { 'STANDARD': '' };
  20903. this.color.copy( source.color );
  20904. this.roughness = source.roughness;
  20905. this.metalness = source.metalness;
  20906. this.map = source.map;
  20907. this.lightMap = source.lightMap;
  20908. this.lightMapIntensity = source.lightMapIntensity;
  20909. this.aoMap = source.aoMap;
  20910. this.aoMapIntensity = source.aoMapIntensity;
  20911. this.emissive.copy( source.emissive );
  20912. this.emissiveMap = source.emissiveMap;
  20913. this.emissiveIntensity = source.emissiveIntensity;
  20914. this.bumpMap = source.bumpMap;
  20915. this.bumpScale = source.bumpScale;
  20916. this.normalMap = source.normalMap;
  20917. this.normalMapType = source.normalMapType;
  20918. this.normalScale.copy( source.normalScale );
  20919. this.displacementMap = source.displacementMap;
  20920. this.displacementScale = source.displacementScale;
  20921. this.displacementBias = source.displacementBias;
  20922. this.roughnessMap = source.roughnessMap;
  20923. this.metalnessMap = source.metalnessMap;
  20924. this.alphaMap = source.alphaMap;
  20925. this.envMap = source.envMap;
  20926. this.envMapIntensity = source.envMapIntensity;
  20927. this.refractionRatio = source.refractionRatio;
  20928. this.wireframe = source.wireframe;
  20929. this.wireframeLinewidth = source.wireframeLinewidth;
  20930. this.wireframeLinecap = source.wireframeLinecap;
  20931. this.wireframeLinejoin = source.wireframeLinejoin;
  20932. this.flatShading = source.flatShading;
  20933. return this;
  20934. }
  20935. }
  20936. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20937. /**
  20938. * parameters = {
  20939. * clearcoat: <float>,
  20940. * clearcoatMap: new THREE.Texture( <Image> ),
  20941. * clearcoatRoughness: <float>,
  20942. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20943. * clearcoatNormalScale: <Vector2>,
  20944. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20945. *
  20946. * ior: <float>,
  20947. * reflectivity: <float>,
  20948. *
  20949. * sheenTint: <Color>,
  20950. *
  20951. * transmission: <float>,
  20952. * transmissionMap: new THREE.Texture( <Image> ),
  20953. *
  20954. * thickness: <float>,
  20955. * thicknessMap: new THREE.Texture( <Image> ),
  20956. * attenuationDistance: <float>,
  20957. * attenuationTint: <Color>,
  20958. *
  20959. * specularIntensity: <float>,
  20960. * specularIntensityhMap: new THREE.Texture( <Image> ),
  20961. * specularTint: <Color>,
  20962. * specularTintMap: new THREE.Texture( <Image> )
  20963. * }
  20964. */
  20965. class MeshPhysicalMaterial extends MeshStandardMaterial {
  20966. constructor( parameters ) {
  20967. super();
  20968. this.defines = {
  20969. 'STANDARD': '',
  20970. 'PHYSICAL': ''
  20971. };
  20972. this.type = 'MeshPhysicalMaterial';
  20973. this.clearcoatMap = null;
  20974. this.clearcoatRoughness = 0.0;
  20975. this.clearcoatRoughnessMap = null;
  20976. this.clearcoatNormalScale = new Vector2( 1, 1 );
  20977. this.clearcoatNormalMap = null;
  20978. this.ior = 1.5;
  20979. Object.defineProperty( this, 'reflectivity', {
  20980. get: function () {
  20981. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  20982. },
  20983. set: function ( reflectivity ) {
  20984. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  20985. }
  20986. } );
  20987. this.sheenTint = new Color( 0x000000 );
  20988. this.transmission = 0.0;
  20989. this.transmissionMap = null;
  20990. this.thickness = 0.01;
  20991. this.thicknessMap = null;
  20992. this.attenuationDistance = 0.0;
  20993. this.attenuationTint = new Color( 1, 1, 1 );
  20994. this.specularIntensity = 1.0;
  20995. this.specularIntensityMap = null;
  20996. this.specularTint = new Color( 1, 1, 1 );
  20997. this.specularTintMap = null;
  20998. this._clearcoat = 0;
  20999. this._transmission = 0;
  21000. this.setValues( parameters );
  21001. }
  21002. get clearcoat() {
  21003. return this._clearcoat;
  21004. }
  21005. set clearcoat( value ) {
  21006. if ( this._clearcoat > 0 !== value > 0 ) {
  21007. this.version ++;
  21008. }
  21009. this._clearcoat = value;
  21010. }
  21011. get transmission() {
  21012. return this._transmission;
  21013. }
  21014. set transmission( value ) {
  21015. if ( this._transmission > 0 !== value > 0 ) {
  21016. this.version ++;
  21017. }
  21018. this._transmission = value;
  21019. }
  21020. copy( source ) {
  21021. super.copy( source );
  21022. this.defines = {
  21023. 'STANDARD': '',
  21024. 'PHYSICAL': ''
  21025. };
  21026. this.clearcoat = source.clearcoat;
  21027. this.clearcoatMap = source.clearcoatMap;
  21028. this.clearcoatRoughness = source.clearcoatRoughness;
  21029. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21030. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21031. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  21032. this.ior = source.ior;
  21033. this.sheenTint.copy( source.sheenTint );
  21034. this.transmission = source.transmission;
  21035. this.transmissionMap = source.transmissionMap;
  21036. this.thickness = source.thickness;
  21037. this.thicknessMap = source.thicknessMap;
  21038. this.attenuationDistance = source.attenuationDistance;
  21039. this.attenuationTint.copy( source.attenuationTint );
  21040. this.specularIntensity = source.specularIntensity;
  21041. this.specularIntensityMap = source.specularIntensityMap;
  21042. this.specularTint.copy( source.specularTint );
  21043. this.specularTintMap = source.specularTintMap;
  21044. return this;
  21045. }
  21046. }
  21047. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21048. /**
  21049. * parameters = {
  21050. * color: <hex>,
  21051. * specular: <hex>,
  21052. * shininess: <float>,
  21053. * opacity: <float>,
  21054. *
  21055. * map: new THREE.Texture( <Image> ),
  21056. *
  21057. * lightMap: new THREE.Texture( <Image> ),
  21058. * lightMapIntensity: <float>
  21059. *
  21060. * aoMap: new THREE.Texture( <Image> ),
  21061. * aoMapIntensity: <float>
  21062. *
  21063. * emissive: <hex>,
  21064. * emissiveIntensity: <float>
  21065. * emissiveMap: new THREE.Texture( <Image> ),
  21066. *
  21067. * bumpMap: new THREE.Texture( <Image> ),
  21068. * bumpScale: <float>,
  21069. *
  21070. * normalMap: new THREE.Texture( <Image> ),
  21071. * normalMapType: THREE.TangentSpaceNormalMap,
  21072. * normalScale: <Vector2>,
  21073. *
  21074. * displacementMap: new THREE.Texture( <Image> ),
  21075. * displacementScale: <float>,
  21076. * displacementBias: <float>,
  21077. *
  21078. * specularMap: new THREE.Texture( <Image> ),
  21079. *
  21080. * alphaMap: new THREE.Texture( <Image> ),
  21081. *
  21082. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21083. * combine: THREE.MultiplyOperation,
  21084. * reflectivity: <float>,
  21085. * refractionRatio: <float>,
  21086. *
  21087. * wireframe: <boolean>,
  21088. * wireframeLinewidth: <float>,
  21089. *
  21090. * flatShading: <bool>
  21091. * }
  21092. */
  21093. class MeshPhongMaterial extends Material {
  21094. constructor( parameters ) {
  21095. super();
  21096. this.type = 'MeshPhongMaterial';
  21097. this.color = new Color( 0xffffff ); // diffuse
  21098. this.specular = new Color( 0x111111 );
  21099. this.shininess = 30;
  21100. this.map = null;
  21101. this.lightMap = null;
  21102. this.lightMapIntensity = 1.0;
  21103. this.aoMap = null;
  21104. this.aoMapIntensity = 1.0;
  21105. this.emissive = new Color( 0x000000 );
  21106. this.emissiveIntensity = 1.0;
  21107. this.emissiveMap = null;
  21108. this.bumpMap = null;
  21109. this.bumpScale = 1;
  21110. this.normalMap = null;
  21111. this.normalMapType = TangentSpaceNormalMap;
  21112. this.normalScale = new Vector2( 1, 1 );
  21113. this.displacementMap = null;
  21114. this.displacementScale = 1;
  21115. this.displacementBias = 0;
  21116. this.specularMap = null;
  21117. this.alphaMap = null;
  21118. this.envMap = null;
  21119. this.combine = MultiplyOperation;
  21120. this.reflectivity = 1;
  21121. this.refractionRatio = 0.98;
  21122. this.wireframe = false;
  21123. this.wireframeLinewidth = 1;
  21124. this.wireframeLinecap = 'round';
  21125. this.wireframeLinejoin = 'round';
  21126. this.flatShading = false;
  21127. this.setValues( parameters );
  21128. }
  21129. copy( source ) {
  21130. super.copy( source );
  21131. this.color.copy( source.color );
  21132. this.specular.copy( source.specular );
  21133. this.shininess = source.shininess;
  21134. this.map = source.map;
  21135. this.lightMap = source.lightMap;
  21136. this.lightMapIntensity = source.lightMapIntensity;
  21137. this.aoMap = source.aoMap;
  21138. this.aoMapIntensity = source.aoMapIntensity;
  21139. this.emissive.copy( source.emissive );
  21140. this.emissiveMap = source.emissiveMap;
  21141. this.emissiveIntensity = source.emissiveIntensity;
  21142. this.bumpMap = source.bumpMap;
  21143. this.bumpScale = source.bumpScale;
  21144. this.normalMap = source.normalMap;
  21145. this.normalMapType = source.normalMapType;
  21146. this.normalScale.copy( source.normalScale );
  21147. this.displacementMap = source.displacementMap;
  21148. this.displacementScale = source.displacementScale;
  21149. this.displacementBias = source.displacementBias;
  21150. this.specularMap = source.specularMap;
  21151. this.alphaMap = source.alphaMap;
  21152. this.envMap = source.envMap;
  21153. this.combine = source.combine;
  21154. this.reflectivity = source.reflectivity;
  21155. this.refractionRatio = source.refractionRatio;
  21156. this.wireframe = source.wireframe;
  21157. this.wireframeLinewidth = source.wireframeLinewidth;
  21158. this.wireframeLinecap = source.wireframeLinecap;
  21159. this.wireframeLinejoin = source.wireframeLinejoin;
  21160. this.flatShading = source.flatShading;
  21161. return this;
  21162. }
  21163. }
  21164. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21165. /**
  21166. * parameters = {
  21167. * color: <hex>,
  21168. *
  21169. * map: new THREE.Texture( <Image> ),
  21170. * gradientMap: new THREE.Texture( <Image> ),
  21171. *
  21172. * lightMap: new THREE.Texture( <Image> ),
  21173. * lightMapIntensity: <float>
  21174. *
  21175. * aoMap: new THREE.Texture( <Image> ),
  21176. * aoMapIntensity: <float>
  21177. *
  21178. * emissive: <hex>,
  21179. * emissiveIntensity: <float>
  21180. * emissiveMap: new THREE.Texture( <Image> ),
  21181. *
  21182. * bumpMap: new THREE.Texture( <Image> ),
  21183. * bumpScale: <float>,
  21184. *
  21185. * normalMap: new THREE.Texture( <Image> ),
  21186. * normalMapType: THREE.TangentSpaceNormalMap,
  21187. * normalScale: <Vector2>,
  21188. *
  21189. * displacementMap: new THREE.Texture( <Image> ),
  21190. * displacementScale: <float>,
  21191. * displacementBias: <float>,
  21192. *
  21193. * alphaMap: new THREE.Texture( <Image> ),
  21194. *
  21195. * wireframe: <boolean>,
  21196. * wireframeLinewidth: <float>,
  21197. *
  21198. * }
  21199. */
  21200. class MeshToonMaterial extends Material {
  21201. constructor( parameters ) {
  21202. super();
  21203. this.defines = { 'TOON': '' };
  21204. this.type = 'MeshToonMaterial';
  21205. this.color = new Color( 0xffffff );
  21206. this.map = null;
  21207. this.gradientMap = null;
  21208. this.lightMap = null;
  21209. this.lightMapIntensity = 1.0;
  21210. this.aoMap = null;
  21211. this.aoMapIntensity = 1.0;
  21212. this.emissive = new Color( 0x000000 );
  21213. this.emissiveIntensity = 1.0;
  21214. this.emissiveMap = null;
  21215. this.bumpMap = null;
  21216. this.bumpScale = 1;
  21217. this.normalMap = null;
  21218. this.normalMapType = TangentSpaceNormalMap;
  21219. this.normalScale = new Vector2( 1, 1 );
  21220. this.displacementMap = null;
  21221. this.displacementScale = 1;
  21222. this.displacementBias = 0;
  21223. this.alphaMap = null;
  21224. this.wireframe = false;
  21225. this.wireframeLinewidth = 1;
  21226. this.wireframeLinecap = 'round';
  21227. this.wireframeLinejoin = 'round';
  21228. this.setValues( parameters );
  21229. }
  21230. copy( source ) {
  21231. super.copy( source );
  21232. this.color.copy( source.color );
  21233. this.map = source.map;
  21234. this.gradientMap = source.gradientMap;
  21235. this.lightMap = source.lightMap;
  21236. this.lightMapIntensity = source.lightMapIntensity;
  21237. this.aoMap = source.aoMap;
  21238. this.aoMapIntensity = source.aoMapIntensity;
  21239. this.emissive.copy( source.emissive );
  21240. this.emissiveMap = source.emissiveMap;
  21241. this.emissiveIntensity = source.emissiveIntensity;
  21242. this.bumpMap = source.bumpMap;
  21243. this.bumpScale = source.bumpScale;
  21244. this.normalMap = source.normalMap;
  21245. this.normalMapType = source.normalMapType;
  21246. this.normalScale.copy( source.normalScale );
  21247. this.displacementMap = source.displacementMap;
  21248. this.displacementScale = source.displacementScale;
  21249. this.displacementBias = source.displacementBias;
  21250. this.alphaMap = source.alphaMap;
  21251. this.wireframe = source.wireframe;
  21252. this.wireframeLinewidth = source.wireframeLinewidth;
  21253. this.wireframeLinecap = source.wireframeLinecap;
  21254. this.wireframeLinejoin = source.wireframeLinejoin;
  21255. return this;
  21256. }
  21257. }
  21258. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21259. /**
  21260. * parameters = {
  21261. * opacity: <float>,
  21262. *
  21263. * bumpMap: new THREE.Texture( <Image> ),
  21264. * bumpScale: <float>,
  21265. *
  21266. * normalMap: new THREE.Texture( <Image> ),
  21267. * normalMapType: THREE.TangentSpaceNormalMap,
  21268. * normalScale: <Vector2>,
  21269. *
  21270. * displacementMap: new THREE.Texture( <Image> ),
  21271. * displacementScale: <float>,
  21272. * displacementBias: <float>,
  21273. *
  21274. * wireframe: <boolean>,
  21275. * wireframeLinewidth: <float>
  21276. *
  21277. * flatShading: <bool>
  21278. * }
  21279. */
  21280. class MeshNormalMaterial extends Material {
  21281. constructor( parameters ) {
  21282. super();
  21283. this.type = 'MeshNormalMaterial';
  21284. this.bumpMap = null;
  21285. this.bumpScale = 1;
  21286. this.normalMap = null;
  21287. this.normalMapType = TangentSpaceNormalMap;
  21288. this.normalScale = new Vector2( 1, 1 );
  21289. this.displacementMap = null;
  21290. this.displacementScale = 1;
  21291. this.displacementBias = 0;
  21292. this.wireframe = false;
  21293. this.wireframeLinewidth = 1;
  21294. this.fog = false;
  21295. this.flatShading = false;
  21296. this.setValues( parameters );
  21297. }
  21298. copy( source ) {
  21299. super.copy( source );
  21300. this.bumpMap = source.bumpMap;
  21301. this.bumpScale = source.bumpScale;
  21302. this.normalMap = source.normalMap;
  21303. this.normalMapType = source.normalMapType;
  21304. this.normalScale.copy( source.normalScale );
  21305. this.displacementMap = source.displacementMap;
  21306. this.displacementScale = source.displacementScale;
  21307. this.displacementBias = source.displacementBias;
  21308. this.wireframe = source.wireframe;
  21309. this.wireframeLinewidth = source.wireframeLinewidth;
  21310. this.flatShading = source.flatShading;
  21311. return this;
  21312. }
  21313. }
  21314. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21315. /**
  21316. * parameters = {
  21317. * color: <hex>,
  21318. * opacity: <float>,
  21319. *
  21320. * map: new THREE.Texture( <Image> ),
  21321. *
  21322. * lightMap: new THREE.Texture( <Image> ),
  21323. * lightMapIntensity: <float>
  21324. *
  21325. * aoMap: new THREE.Texture( <Image> ),
  21326. * aoMapIntensity: <float>
  21327. *
  21328. * emissive: <hex>,
  21329. * emissiveIntensity: <float>
  21330. * emissiveMap: new THREE.Texture( <Image> ),
  21331. *
  21332. * specularMap: new THREE.Texture( <Image> ),
  21333. *
  21334. * alphaMap: new THREE.Texture( <Image> ),
  21335. *
  21336. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21337. * combine: THREE.Multiply,
  21338. * reflectivity: <float>,
  21339. * refractionRatio: <float>,
  21340. *
  21341. * wireframe: <boolean>,
  21342. * wireframeLinewidth: <float>,
  21343. *
  21344. * }
  21345. */
  21346. class MeshLambertMaterial extends Material {
  21347. constructor( parameters ) {
  21348. super();
  21349. this.type = 'MeshLambertMaterial';
  21350. this.color = new Color( 0xffffff ); // diffuse
  21351. this.map = null;
  21352. this.lightMap = null;
  21353. this.lightMapIntensity = 1.0;
  21354. this.aoMap = null;
  21355. this.aoMapIntensity = 1.0;
  21356. this.emissive = new Color( 0x000000 );
  21357. this.emissiveIntensity = 1.0;
  21358. this.emissiveMap = null;
  21359. this.specularMap = null;
  21360. this.alphaMap = null;
  21361. this.envMap = null;
  21362. this.combine = MultiplyOperation;
  21363. this.reflectivity = 1;
  21364. this.refractionRatio = 0.98;
  21365. this.wireframe = false;
  21366. this.wireframeLinewidth = 1;
  21367. this.wireframeLinecap = 'round';
  21368. this.wireframeLinejoin = 'round';
  21369. this.setValues( parameters );
  21370. }
  21371. copy( source ) {
  21372. super.copy( source );
  21373. this.color.copy( source.color );
  21374. this.map = source.map;
  21375. this.lightMap = source.lightMap;
  21376. this.lightMapIntensity = source.lightMapIntensity;
  21377. this.aoMap = source.aoMap;
  21378. this.aoMapIntensity = source.aoMapIntensity;
  21379. this.emissive.copy( source.emissive );
  21380. this.emissiveMap = source.emissiveMap;
  21381. this.emissiveIntensity = source.emissiveIntensity;
  21382. this.specularMap = source.specularMap;
  21383. this.alphaMap = source.alphaMap;
  21384. this.envMap = source.envMap;
  21385. this.combine = source.combine;
  21386. this.reflectivity = source.reflectivity;
  21387. this.refractionRatio = source.refractionRatio;
  21388. this.wireframe = source.wireframe;
  21389. this.wireframeLinewidth = source.wireframeLinewidth;
  21390. this.wireframeLinecap = source.wireframeLinecap;
  21391. this.wireframeLinejoin = source.wireframeLinejoin;
  21392. return this;
  21393. }
  21394. }
  21395. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21396. /**
  21397. * parameters = {
  21398. * color: <hex>,
  21399. * opacity: <float>,
  21400. *
  21401. * matcap: new THREE.Texture( <Image> ),
  21402. *
  21403. * map: new THREE.Texture( <Image> ),
  21404. *
  21405. * bumpMap: new THREE.Texture( <Image> ),
  21406. * bumpScale: <float>,
  21407. *
  21408. * normalMap: new THREE.Texture( <Image> ),
  21409. * normalMapType: THREE.TangentSpaceNormalMap,
  21410. * normalScale: <Vector2>,
  21411. *
  21412. * displacementMap: new THREE.Texture( <Image> ),
  21413. * displacementScale: <float>,
  21414. * displacementBias: <float>,
  21415. *
  21416. * alphaMap: new THREE.Texture( <Image> ),
  21417. *
  21418. * flatShading: <bool>
  21419. * }
  21420. */
  21421. class MeshMatcapMaterial extends Material {
  21422. constructor( parameters ) {
  21423. super();
  21424. this.defines = { 'MATCAP': '' };
  21425. this.type = 'MeshMatcapMaterial';
  21426. this.color = new Color( 0xffffff ); // diffuse
  21427. this.matcap = null;
  21428. this.map = null;
  21429. this.bumpMap = null;
  21430. this.bumpScale = 1;
  21431. this.normalMap = null;
  21432. this.normalMapType = TangentSpaceNormalMap;
  21433. this.normalScale = new Vector2( 1, 1 );
  21434. this.displacementMap = null;
  21435. this.displacementScale = 1;
  21436. this.displacementBias = 0;
  21437. this.alphaMap = null;
  21438. this.flatShading = false;
  21439. this.setValues( parameters );
  21440. }
  21441. copy( source ) {
  21442. super.copy( source );
  21443. this.defines = { 'MATCAP': '' };
  21444. this.color.copy( source.color );
  21445. this.matcap = source.matcap;
  21446. this.map = source.map;
  21447. this.bumpMap = source.bumpMap;
  21448. this.bumpScale = source.bumpScale;
  21449. this.normalMap = source.normalMap;
  21450. this.normalMapType = source.normalMapType;
  21451. this.normalScale.copy( source.normalScale );
  21452. this.displacementMap = source.displacementMap;
  21453. this.displacementScale = source.displacementScale;
  21454. this.displacementBias = source.displacementBias;
  21455. this.alphaMap = source.alphaMap;
  21456. this.flatShading = source.flatShading;
  21457. return this;
  21458. }
  21459. }
  21460. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21461. /**
  21462. * parameters = {
  21463. * color: <hex>,
  21464. * opacity: <float>,
  21465. *
  21466. * linewidth: <float>,
  21467. *
  21468. * scale: <float>,
  21469. * dashSize: <float>,
  21470. * gapSize: <float>
  21471. * }
  21472. */
  21473. class LineDashedMaterial extends LineBasicMaterial {
  21474. constructor( parameters ) {
  21475. super();
  21476. this.type = 'LineDashedMaterial';
  21477. this.scale = 1;
  21478. this.dashSize = 3;
  21479. this.gapSize = 1;
  21480. this.setValues( parameters );
  21481. }
  21482. copy( source ) {
  21483. super.copy( source );
  21484. this.scale = source.scale;
  21485. this.dashSize = source.dashSize;
  21486. this.gapSize = source.gapSize;
  21487. return this;
  21488. }
  21489. }
  21490. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21491. var Materials = /*#__PURE__*/Object.freeze({
  21492. __proto__: null,
  21493. ShadowMaterial: ShadowMaterial,
  21494. SpriteMaterial: SpriteMaterial,
  21495. RawShaderMaterial: RawShaderMaterial,
  21496. ShaderMaterial: ShaderMaterial,
  21497. PointsMaterial: PointsMaterial,
  21498. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21499. MeshStandardMaterial: MeshStandardMaterial,
  21500. MeshPhongMaterial: MeshPhongMaterial,
  21501. MeshToonMaterial: MeshToonMaterial,
  21502. MeshNormalMaterial: MeshNormalMaterial,
  21503. MeshLambertMaterial: MeshLambertMaterial,
  21504. MeshDepthMaterial: MeshDepthMaterial,
  21505. MeshDistanceMaterial: MeshDistanceMaterial,
  21506. MeshBasicMaterial: MeshBasicMaterial,
  21507. MeshMatcapMaterial: MeshMatcapMaterial,
  21508. LineDashedMaterial: LineDashedMaterial,
  21509. LineBasicMaterial: LineBasicMaterial,
  21510. Material: Material
  21511. });
  21512. const AnimationUtils = {
  21513. // same as Array.prototype.slice, but also works on typed arrays
  21514. arraySlice: function ( array, from, to ) {
  21515. if ( AnimationUtils.isTypedArray( array ) ) {
  21516. // in ios9 array.subarray(from, undefined) will return empty array
  21517. // but array.subarray(from) or array.subarray(from, len) is correct
  21518. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  21519. }
  21520. return array.slice( from, to );
  21521. },
  21522. // converts an array to a specific type
  21523. convertArray: function ( array, type, forceClone ) {
  21524. if ( ! array || // let 'undefined' and 'null' pass
  21525. ! forceClone && array.constructor === type ) return array;
  21526. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21527. return new type( array ); // create typed array
  21528. }
  21529. return Array.prototype.slice.call( array ); // create Array
  21530. },
  21531. isTypedArray: function ( object ) {
  21532. return ArrayBuffer.isView( object ) &&
  21533. ! ( object instanceof DataView );
  21534. },
  21535. // returns an array by which times and values can be sorted
  21536. getKeyframeOrder: function ( times ) {
  21537. function compareTime( i, j ) {
  21538. return times[ i ] - times[ j ];
  21539. }
  21540. const n = times.length;
  21541. const result = new Array( n );
  21542. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21543. result.sort( compareTime );
  21544. return result;
  21545. },
  21546. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21547. sortedArray: function ( values, stride, order ) {
  21548. const nValues = values.length;
  21549. const result = new values.constructor( nValues );
  21550. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  21551. const srcOffset = order[ i ] * stride;
  21552. for ( let j = 0; j !== stride; ++ j ) {
  21553. result[ dstOffset ++ ] = values[ srcOffset + j ];
  21554. }
  21555. }
  21556. return result;
  21557. },
  21558. // function for parsing AOS keyframe formats
  21559. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  21560. let i = 1, key = jsonKeys[ 0 ];
  21561. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  21562. key = jsonKeys[ i ++ ];
  21563. }
  21564. if ( key === undefined ) return; // no data
  21565. let value = key[ valuePropertyName ];
  21566. if ( value === undefined ) return; // no data
  21567. if ( Array.isArray( value ) ) {
  21568. do {
  21569. value = key[ valuePropertyName ];
  21570. if ( value !== undefined ) {
  21571. times.push( key.time );
  21572. values.push.apply( values, value ); // push all elements
  21573. }
  21574. key = jsonKeys[ i ++ ];
  21575. } while ( key !== undefined );
  21576. } else if ( value.toArray !== undefined ) {
  21577. // ...assume THREE.Math-ish
  21578. do {
  21579. value = key[ valuePropertyName ];
  21580. if ( value !== undefined ) {
  21581. times.push( key.time );
  21582. value.toArray( values, values.length );
  21583. }
  21584. key = jsonKeys[ i ++ ];
  21585. } while ( key !== undefined );
  21586. } else {
  21587. // otherwise push as-is
  21588. do {
  21589. value = key[ valuePropertyName ];
  21590. if ( value !== undefined ) {
  21591. times.push( key.time );
  21592. values.push( value );
  21593. }
  21594. key = jsonKeys[ i ++ ];
  21595. } while ( key !== undefined );
  21596. }
  21597. },
  21598. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  21599. const clip = sourceClip.clone();
  21600. clip.name = name;
  21601. const tracks = [];
  21602. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21603. const track = clip.tracks[ i ];
  21604. const valueSize = track.getValueSize();
  21605. const times = [];
  21606. const values = [];
  21607. for ( let j = 0; j < track.times.length; ++ j ) {
  21608. const frame = track.times[ j ] * fps;
  21609. if ( frame < startFrame || frame >= endFrame ) continue;
  21610. times.push( track.times[ j ] );
  21611. for ( let k = 0; k < valueSize; ++ k ) {
  21612. values.push( track.values[ j * valueSize + k ] );
  21613. }
  21614. }
  21615. if ( times.length === 0 ) continue;
  21616. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  21617. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  21618. tracks.push( track );
  21619. }
  21620. clip.tracks = tracks;
  21621. // find minimum .times value across all tracks in the trimmed clip
  21622. let minStartTime = Infinity;
  21623. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21624. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  21625. minStartTime = clip.tracks[ i ].times[ 0 ];
  21626. }
  21627. }
  21628. // shift all tracks such that clip begins at t=0
  21629. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21630. clip.tracks[ i ].shift( - 1 * minStartTime );
  21631. }
  21632. clip.resetDuration();
  21633. return clip;
  21634. },
  21635. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  21636. if ( fps <= 0 ) fps = 30;
  21637. const numTracks = referenceClip.tracks.length;
  21638. const referenceTime = referenceFrame / fps;
  21639. // Make each track's values relative to the values at the reference frame
  21640. for ( let i = 0; i < numTracks; ++ i ) {
  21641. const referenceTrack = referenceClip.tracks[ i ];
  21642. const referenceTrackType = referenceTrack.ValueTypeName;
  21643. // Skip this track if it's non-numeric
  21644. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  21645. // Find the track in the target clip whose name and type matches the reference track
  21646. const targetTrack = targetClip.tracks.find( function ( track ) {
  21647. return track.name === referenceTrack.name
  21648. && track.ValueTypeName === referenceTrackType;
  21649. } );
  21650. if ( targetTrack === undefined ) continue;
  21651. let referenceOffset = 0;
  21652. const referenceValueSize = referenceTrack.getValueSize();
  21653. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21654. referenceOffset = referenceValueSize / 3;
  21655. }
  21656. let targetOffset = 0;
  21657. const targetValueSize = targetTrack.getValueSize();
  21658. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21659. targetOffset = targetValueSize / 3;
  21660. }
  21661. const lastIndex = referenceTrack.times.length - 1;
  21662. let referenceValue;
  21663. // Find the value to subtract out of the track
  21664. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  21665. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21666. const startIndex = referenceOffset;
  21667. const endIndex = referenceValueSize - referenceOffset;
  21668. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21669. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  21670. // Reference frame is after the last keyframe, so just use the last keyframe
  21671. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21672. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21673. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21674. } else {
  21675. // Interpolate to the reference value
  21676. const interpolant = referenceTrack.createInterpolant();
  21677. const startIndex = referenceOffset;
  21678. const endIndex = referenceValueSize - referenceOffset;
  21679. interpolant.evaluate( referenceTime );
  21680. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  21681. }
  21682. // Conjugate the quaternion
  21683. if ( referenceTrackType === 'quaternion' ) {
  21684. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  21685. referenceQuat.toArray( referenceValue );
  21686. }
  21687. // Subtract the reference value from all of the track values
  21688. const numTimes = targetTrack.times.length;
  21689. for ( let j = 0; j < numTimes; ++ j ) {
  21690. const valueStart = j * targetValueSize + targetOffset;
  21691. if ( referenceTrackType === 'quaternion' ) {
  21692. // Multiply the conjugate for quaternion track types
  21693. Quaternion.multiplyQuaternionsFlat(
  21694. targetTrack.values,
  21695. valueStart,
  21696. referenceValue,
  21697. 0,
  21698. targetTrack.values,
  21699. valueStart
  21700. );
  21701. } else {
  21702. const valueEnd = targetValueSize - targetOffset * 2;
  21703. // Subtract each value for all other numeric track types
  21704. for ( let k = 0; k < valueEnd; ++ k ) {
  21705. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  21706. }
  21707. }
  21708. }
  21709. }
  21710. targetClip.blendMode = AdditiveAnimationBlendMode;
  21711. return targetClip;
  21712. }
  21713. };
  21714. /**
  21715. * Abstract base class of interpolants over parametric samples.
  21716. *
  21717. * The parameter domain is one dimensional, typically the time or a path
  21718. * along a curve defined by the data.
  21719. *
  21720. * The sample values can have any dimensionality and derived classes may
  21721. * apply special interpretations to the data.
  21722. *
  21723. * This class provides the interval seek in a Template Method, deferring
  21724. * the actual interpolation to derived classes.
  21725. *
  21726. * Time complexity is O(1) for linear access crossing at most two points
  21727. * and O(log N) for random access, where N is the number of positions.
  21728. *
  21729. * References:
  21730. *
  21731. * http://www.oodesign.com/template-method-pattern.html
  21732. *
  21733. */
  21734. class Interpolant {
  21735. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21736. this.parameterPositions = parameterPositions;
  21737. this._cachedIndex = 0;
  21738. this.resultBuffer = resultBuffer !== undefined ?
  21739. resultBuffer : new sampleValues.constructor( sampleSize );
  21740. this.sampleValues = sampleValues;
  21741. this.valueSize = sampleSize;
  21742. this.settings = null;
  21743. this.DefaultSettings_ = {};
  21744. }
  21745. evaluate( t ) {
  21746. const pp = this.parameterPositions;
  21747. let i1 = this._cachedIndex,
  21748. t1 = pp[ i1 ],
  21749. t0 = pp[ i1 - 1 ];
  21750. validate_interval: {
  21751. seek: {
  21752. let right;
  21753. linear_scan: {
  21754. //- See http://jsperf.com/comparison-to-undefined/3
  21755. //- slower code:
  21756. //-
  21757. //- if ( t >= t1 || t1 === undefined ) {
  21758. forward_scan: if ( ! ( t < t1 ) ) {
  21759. for ( let giveUpAt = i1 + 2; ; ) {
  21760. if ( t1 === undefined ) {
  21761. if ( t < t0 ) break forward_scan;
  21762. // after end
  21763. i1 = pp.length;
  21764. this._cachedIndex = i1;
  21765. return this.afterEnd_( i1 - 1, t, t0 );
  21766. }
  21767. if ( i1 === giveUpAt ) break; // this loop
  21768. t0 = t1;
  21769. t1 = pp[ ++ i1 ];
  21770. if ( t < t1 ) {
  21771. // we have arrived at the sought interval
  21772. break seek;
  21773. }
  21774. }
  21775. // prepare binary search on the right side of the index
  21776. right = pp.length;
  21777. break linear_scan;
  21778. }
  21779. //- slower code:
  21780. //- if ( t < t0 || t0 === undefined ) {
  21781. if ( ! ( t >= t0 ) ) {
  21782. // looping?
  21783. const t1global = pp[ 1 ];
  21784. if ( t < t1global ) {
  21785. i1 = 2; // + 1, using the scan for the details
  21786. t0 = t1global;
  21787. }
  21788. // linear reverse scan
  21789. for ( let giveUpAt = i1 - 2; ; ) {
  21790. if ( t0 === undefined ) {
  21791. // before start
  21792. this._cachedIndex = 0;
  21793. return this.beforeStart_( 0, t, t1 );
  21794. }
  21795. if ( i1 === giveUpAt ) break; // this loop
  21796. t1 = t0;
  21797. t0 = pp[ -- i1 - 1 ];
  21798. if ( t >= t0 ) {
  21799. // we have arrived at the sought interval
  21800. break seek;
  21801. }
  21802. }
  21803. // prepare binary search on the left side of the index
  21804. right = i1;
  21805. i1 = 0;
  21806. break linear_scan;
  21807. }
  21808. // the interval is valid
  21809. break validate_interval;
  21810. } // linear scan
  21811. // binary search
  21812. while ( i1 < right ) {
  21813. const mid = ( i1 + right ) >>> 1;
  21814. if ( t < pp[ mid ] ) {
  21815. right = mid;
  21816. } else {
  21817. i1 = mid + 1;
  21818. }
  21819. }
  21820. t1 = pp[ i1 ];
  21821. t0 = pp[ i1 - 1 ];
  21822. // check boundary cases, again
  21823. if ( t0 === undefined ) {
  21824. this._cachedIndex = 0;
  21825. return this.beforeStart_( 0, t, t1 );
  21826. }
  21827. if ( t1 === undefined ) {
  21828. i1 = pp.length;
  21829. this._cachedIndex = i1;
  21830. return this.afterEnd_( i1 - 1, t0, t );
  21831. }
  21832. } // seek
  21833. this._cachedIndex = i1;
  21834. this.intervalChanged_( i1, t0, t1 );
  21835. } // validate_interval
  21836. return this.interpolate_( i1, t0, t, t1 );
  21837. }
  21838. getSettings_() {
  21839. return this.settings || this.DefaultSettings_;
  21840. }
  21841. copySampleValue_( index ) {
  21842. // copies a sample value to the result buffer
  21843. const result = this.resultBuffer,
  21844. values = this.sampleValues,
  21845. stride = this.valueSize,
  21846. offset = index * stride;
  21847. for ( let i = 0; i !== stride; ++ i ) {
  21848. result[ i ] = values[ offset + i ];
  21849. }
  21850. return result;
  21851. }
  21852. // Template methods for derived classes:
  21853. interpolate_( /* i1, t0, t, t1 */ ) {
  21854. throw new Error( 'call to abstract method' );
  21855. // implementations shall return this.resultBuffer
  21856. }
  21857. intervalChanged_( /* i1, t0, t1 */ ) {
  21858. // empty
  21859. }
  21860. }
  21861. // ALIAS DEFINITIONS
  21862. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  21863. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  21864. /**
  21865. * Fast and simple cubic spline interpolant.
  21866. *
  21867. * It was derived from a Hermitian construction setting the first derivative
  21868. * at each sample position to the linear slope between neighboring positions
  21869. * over their parameter interval.
  21870. */
  21871. class CubicInterpolant extends Interpolant {
  21872. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21873. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  21874. this._weightPrev = - 0;
  21875. this._offsetPrev = - 0;
  21876. this._weightNext = - 0;
  21877. this._offsetNext = - 0;
  21878. this.DefaultSettings_ = {
  21879. endingStart: ZeroCurvatureEnding,
  21880. endingEnd: ZeroCurvatureEnding
  21881. };
  21882. }
  21883. intervalChanged_( i1, t0, t1 ) {
  21884. const pp = this.parameterPositions;
  21885. let iPrev = i1 - 2,
  21886. iNext = i1 + 1,
  21887. tPrev = pp[ iPrev ],
  21888. tNext = pp[ iNext ];
  21889. if ( tPrev === undefined ) {
  21890. switch ( this.getSettings_().endingStart ) {
  21891. case ZeroSlopeEnding:
  21892. // f'(t0) = 0
  21893. iPrev = i1;
  21894. tPrev = 2 * t0 - t1;
  21895. break;
  21896. case WrapAroundEnding:
  21897. // use the other end of the curve
  21898. iPrev = pp.length - 2;
  21899. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  21900. break;
  21901. default: // ZeroCurvatureEnding
  21902. // f''(t0) = 0 a.k.a. Natural Spline
  21903. iPrev = i1;
  21904. tPrev = t1;
  21905. }
  21906. }
  21907. if ( tNext === undefined ) {
  21908. switch ( this.getSettings_().endingEnd ) {
  21909. case ZeroSlopeEnding:
  21910. // f'(tN) = 0
  21911. iNext = i1;
  21912. tNext = 2 * t1 - t0;
  21913. break;
  21914. case WrapAroundEnding:
  21915. // use the other end of the curve
  21916. iNext = 1;
  21917. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  21918. break;
  21919. default: // ZeroCurvatureEnding
  21920. // f''(tN) = 0, a.k.a. Natural Spline
  21921. iNext = i1 - 1;
  21922. tNext = t0;
  21923. }
  21924. }
  21925. const halfDt = ( t1 - t0 ) * 0.5,
  21926. stride = this.valueSize;
  21927. this._weightPrev = halfDt / ( t0 - tPrev );
  21928. this._weightNext = halfDt / ( tNext - t1 );
  21929. this._offsetPrev = iPrev * stride;
  21930. this._offsetNext = iNext * stride;
  21931. }
  21932. interpolate_( i1, t0, t, t1 ) {
  21933. const result = this.resultBuffer,
  21934. values = this.sampleValues,
  21935. stride = this.valueSize,
  21936. o1 = i1 * stride, o0 = o1 - stride,
  21937. oP = this._offsetPrev, oN = this._offsetNext,
  21938. wP = this._weightPrev, wN = this._weightNext,
  21939. p = ( t - t0 ) / ( t1 - t0 ),
  21940. pp = p * p,
  21941. ppp = pp * p;
  21942. // evaluate polynomials
  21943. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  21944. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  21945. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  21946. const sN = wN * ppp - wN * pp;
  21947. // combine data linearly
  21948. for ( let i = 0; i !== stride; ++ i ) {
  21949. result[ i ] =
  21950. sP * values[ oP + i ] +
  21951. s0 * values[ o0 + i ] +
  21952. s1 * values[ o1 + i ] +
  21953. sN * values[ oN + i ];
  21954. }
  21955. return result;
  21956. }
  21957. }
  21958. class LinearInterpolant extends Interpolant {
  21959. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21960. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  21961. }
  21962. interpolate_( i1, t0, t, t1 ) {
  21963. const result = this.resultBuffer,
  21964. values = this.sampleValues,
  21965. stride = this.valueSize,
  21966. offset1 = i1 * stride,
  21967. offset0 = offset1 - stride,
  21968. weight1 = ( t - t0 ) / ( t1 - t0 ),
  21969. weight0 = 1 - weight1;
  21970. for ( let i = 0; i !== stride; ++ i ) {
  21971. result[ i ] =
  21972. values[ offset0 + i ] * weight0 +
  21973. values[ offset1 + i ] * weight1;
  21974. }
  21975. return result;
  21976. }
  21977. }
  21978. /**
  21979. *
  21980. * Interpolant that evaluates to the sample value at the position preceeding
  21981. * the parameter.
  21982. */
  21983. class DiscreteInterpolant extends Interpolant {
  21984. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21985. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  21986. }
  21987. interpolate_( i1 /*, t0, t, t1 */ ) {
  21988. return this.copySampleValue_( i1 - 1 );
  21989. }
  21990. }
  21991. class KeyframeTrack {
  21992. constructor( name, times, values, interpolation ) {
  21993. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  21994. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  21995. this.name = name;
  21996. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  21997. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  21998. this.setInterpolation( interpolation || this.DefaultInterpolation );
  21999. }
  22000. // Serialization (in static context, because of constructor invocation
  22001. // and automatic invocation of .toJSON):
  22002. static toJSON( track ) {
  22003. const trackType = track.constructor;
  22004. let json;
  22005. // derived classes can define a static toJSON method
  22006. if ( trackType.toJSON !== this.toJSON ) {
  22007. json = trackType.toJSON( track );
  22008. } else {
  22009. // by default, we assume the data can be serialized as-is
  22010. json = {
  22011. 'name': track.name,
  22012. 'times': AnimationUtils.convertArray( track.times, Array ),
  22013. 'values': AnimationUtils.convertArray( track.values, Array )
  22014. };
  22015. const interpolation = track.getInterpolation();
  22016. if ( interpolation !== track.DefaultInterpolation ) {
  22017. json.interpolation = interpolation;
  22018. }
  22019. }
  22020. json.type = track.ValueTypeName; // mandatory
  22021. return json;
  22022. }
  22023. InterpolantFactoryMethodDiscrete( result ) {
  22024. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22025. }
  22026. InterpolantFactoryMethodLinear( result ) {
  22027. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22028. }
  22029. InterpolantFactoryMethodSmooth( result ) {
  22030. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22031. }
  22032. setInterpolation( interpolation ) {
  22033. let factoryMethod;
  22034. switch ( interpolation ) {
  22035. case InterpolateDiscrete:
  22036. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22037. break;
  22038. case InterpolateLinear:
  22039. factoryMethod = this.InterpolantFactoryMethodLinear;
  22040. break;
  22041. case InterpolateSmooth:
  22042. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22043. break;
  22044. }
  22045. if ( factoryMethod === undefined ) {
  22046. const message = 'unsupported interpolation for ' +
  22047. this.ValueTypeName + ' keyframe track named ' + this.name;
  22048. if ( this.createInterpolant === undefined ) {
  22049. // fall back to default, unless the default itself is messed up
  22050. if ( interpolation !== this.DefaultInterpolation ) {
  22051. this.setInterpolation( this.DefaultInterpolation );
  22052. } else {
  22053. throw new Error( message ); // fatal, in this case
  22054. }
  22055. }
  22056. console.warn( 'THREE.KeyframeTrack:', message );
  22057. return this;
  22058. }
  22059. this.createInterpolant = factoryMethod;
  22060. return this;
  22061. }
  22062. getInterpolation() {
  22063. switch ( this.createInterpolant ) {
  22064. case this.InterpolantFactoryMethodDiscrete:
  22065. return InterpolateDiscrete;
  22066. case this.InterpolantFactoryMethodLinear:
  22067. return InterpolateLinear;
  22068. case this.InterpolantFactoryMethodSmooth:
  22069. return InterpolateSmooth;
  22070. }
  22071. }
  22072. getValueSize() {
  22073. return this.values.length / this.times.length;
  22074. }
  22075. // move all keyframes either forwards or backwards in time
  22076. shift( timeOffset ) {
  22077. if ( timeOffset !== 0.0 ) {
  22078. const times = this.times;
  22079. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22080. times[ i ] += timeOffset;
  22081. }
  22082. }
  22083. return this;
  22084. }
  22085. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22086. scale( timeScale ) {
  22087. if ( timeScale !== 1.0 ) {
  22088. const times = this.times;
  22089. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22090. times[ i ] *= timeScale;
  22091. }
  22092. }
  22093. return this;
  22094. }
  22095. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22096. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22097. trim( startTime, endTime ) {
  22098. const times = this.times,
  22099. nKeys = times.length;
  22100. let from = 0,
  22101. to = nKeys - 1;
  22102. while ( from !== nKeys && times[ from ] < startTime ) {
  22103. ++ from;
  22104. }
  22105. while ( to !== - 1 && times[ to ] > endTime ) {
  22106. -- to;
  22107. }
  22108. ++ to; // inclusive -> exclusive bound
  22109. if ( from !== 0 || to !== nKeys ) {
  22110. // empty tracks are forbidden, so keep at least one keyframe
  22111. if ( from >= to ) {
  22112. to = Math.max( to, 1 );
  22113. from = to - 1;
  22114. }
  22115. const stride = this.getValueSize();
  22116. this.times = AnimationUtils.arraySlice( times, from, to );
  22117. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  22118. }
  22119. return this;
  22120. }
  22121. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22122. validate() {
  22123. let valid = true;
  22124. const valueSize = this.getValueSize();
  22125. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22126. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22127. valid = false;
  22128. }
  22129. const times = this.times,
  22130. values = this.values,
  22131. nKeys = times.length;
  22132. if ( nKeys === 0 ) {
  22133. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22134. valid = false;
  22135. }
  22136. let prevTime = null;
  22137. for ( let i = 0; i !== nKeys; i ++ ) {
  22138. const currTime = times[ i ];
  22139. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22140. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22141. valid = false;
  22142. break;
  22143. }
  22144. if ( prevTime !== null && prevTime > currTime ) {
  22145. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22146. valid = false;
  22147. break;
  22148. }
  22149. prevTime = currTime;
  22150. }
  22151. if ( values !== undefined ) {
  22152. if ( AnimationUtils.isTypedArray( values ) ) {
  22153. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22154. const value = values[ i ];
  22155. if ( isNaN( value ) ) {
  22156. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22157. valid = false;
  22158. break;
  22159. }
  22160. }
  22161. }
  22162. }
  22163. return valid;
  22164. }
  22165. // removes equivalent sequential keys as common in morph target sequences
  22166. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22167. optimize() {
  22168. // times or values may be shared with other tracks, so overwriting is unsafe
  22169. const times = AnimationUtils.arraySlice( this.times ),
  22170. values = AnimationUtils.arraySlice( this.values ),
  22171. stride = this.getValueSize(),
  22172. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22173. lastIndex = times.length - 1;
  22174. let writeIndex = 1;
  22175. for ( let i = 1; i < lastIndex; ++ i ) {
  22176. let keep = false;
  22177. const time = times[ i ];
  22178. const timeNext = times[ i + 1 ];
  22179. // remove adjacent keyframes scheduled at the same time
  22180. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  22181. if ( ! smoothInterpolation ) {
  22182. // remove unnecessary keyframes same as their neighbors
  22183. const offset = i * stride,
  22184. offsetP = offset - stride,
  22185. offsetN = offset + stride;
  22186. for ( let j = 0; j !== stride; ++ j ) {
  22187. const value = values[ offset + j ];
  22188. if ( value !== values[ offsetP + j ] ||
  22189. value !== values[ offsetN + j ] ) {
  22190. keep = true;
  22191. break;
  22192. }
  22193. }
  22194. } else {
  22195. keep = true;
  22196. }
  22197. }
  22198. // in-place compaction
  22199. if ( keep ) {
  22200. if ( i !== writeIndex ) {
  22201. times[ writeIndex ] = times[ i ];
  22202. const readOffset = i * stride,
  22203. writeOffset = writeIndex * stride;
  22204. for ( let j = 0; j !== stride; ++ j ) {
  22205. values[ writeOffset + j ] = values[ readOffset + j ];
  22206. }
  22207. }
  22208. ++ writeIndex;
  22209. }
  22210. }
  22211. // flush last keyframe (compaction looks ahead)
  22212. if ( lastIndex > 0 ) {
  22213. times[ writeIndex ] = times[ lastIndex ];
  22214. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22215. values[ writeOffset + j ] = values[ readOffset + j ];
  22216. }
  22217. ++ writeIndex;
  22218. }
  22219. if ( writeIndex !== times.length ) {
  22220. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22221. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22222. } else {
  22223. this.times = times;
  22224. this.values = values;
  22225. }
  22226. return this;
  22227. }
  22228. clone() {
  22229. const times = AnimationUtils.arraySlice( this.times, 0 );
  22230. const values = AnimationUtils.arraySlice( this.values, 0 );
  22231. const TypedKeyframeTrack = this.constructor;
  22232. const track = new TypedKeyframeTrack( this.name, times, values );
  22233. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22234. track.createInterpolant = this.createInterpolant;
  22235. return track;
  22236. }
  22237. }
  22238. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22239. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22240. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22241. /**
  22242. * A Track of Boolean keyframe values.
  22243. */
  22244. class BooleanKeyframeTrack extends KeyframeTrack {}
  22245. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22246. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22247. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22248. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22249. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22250. /**
  22251. * A Track of keyframe values that represent color.
  22252. */
  22253. class ColorKeyframeTrack extends KeyframeTrack {}
  22254. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  22255. /**
  22256. * A Track of numeric keyframe values.
  22257. */
  22258. class NumberKeyframeTrack extends KeyframeTrack {}
  22259. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  22260. /**
  22261. * Spherical linear unit quaternion interpolant.
  22262. */
  22263. class QuaternionLinearInterpolant extends Interpolant {
  22264. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22265. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22266. }
  22267. interpolate_( i1, t0, t, t1 ) {
  22268. const result = this.resultBuffer,
  22269. values = this.sampleValues,
  22270. stride = this.valueSize,
  22271. alpha = ( t - t0 ) / ( t1 - t0 );
  22272. let offset = i1 * stride;
  22273. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22274. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22275. }
  22276. return result;
  22277. }
  22278. }
  22279. /**
  22280. * A Track of quaternion keyframe values.
  22281. */
  22282. class QuaternionKeyframeTrack extends KeyframeTrack {
  22283. InterpolantFactoryMethodLinear( result ) {
  22284. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22285. }
  22286. }
  22287. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  22288. // ValueBufferType is inherited
  22289. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22290. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22291. /**
  22292. * A Track that interpolates Strings
  22293. */
  22294. class StringKeyframeTrack extends KeyframeTrack {}
  22295. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22296. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22297. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22298. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22299. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22300. /**
  22301. * A Track of vectored keyframe values.
  22302. */
  22303. class VectorKeyframeTrack extends KeyframeTrack {}
  22304. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  22305. class AnimationClip {
  22306. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  22307. this.name = name;
  22308. this.tracks = tracks;
  22309. this.duration = duration;
  22310. this.blendMode = blendMode;
  22311. this.uuid = generateUUID();
  22312. // this means it should figure out its duration by scanning the tracks
  22313. if ( this.duration < 0 ) {
  22314. this.resetDuration();
  22315. }
  22316. }
  22317. static parse( json ) {
  22318. const tracks = [],
  22319. jsonTracks = json.tracks,
  22320. frameTime = 1.0 / ( json.fps || 1.0 );
  22321. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22322. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22323. }
  22324. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  22325. clip.uuid = json.uuid;
  22326. return clip;
  22327. }
  22328. static toJSON( clip ) {
  22329. const tracks = [],
  22330. clipTracks = clip.tracks;
  22331. const json = {
  22332. 'name': clip.name,
  22333. 'duration': clip.duration,
  22334. 'tracks': tracks,
  22335. 'uuid': clip.uuid,
  22336. 'blendMode': clip.blendMode
  22337. };
  22338. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22339. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22340. }
  22341. return json;
  22342. }
  22343. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  22344. const numMorphTargets = morphTargetSequence.length;
  22345. const tracks = [];
  22346. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22347. let times = [];
  22348. let values = [];
  22349. times.push(
  22350. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22351. i,
  22352. ( i + 1 ) % numMorphTargets );
  22353. values.push( 0, 1, 0 );
  22354. const order = AnimationUtils.getKeyframeOrder( times );
  22355. times = AnimationUtils.sortedArray( times, 1, order );
  22356. values = AnimationUtils.sortedArray( values, 1, order );
  22357. // if there is a key at the first frame, duplicate it as the
  22358. // last frame as well for perfect loop.
  22359. if ( ! noLoop && times[ 0 ] === 0 ) {
  22360. times.push( numMorphTargets );
  22361. values.push( values[ 0 ] );
  22362. }
  22363. tracks.push(
  22364. new NumberKeyframeTrack(
  22365. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22366. times, values
  22367. ).scale( 1.0 / fps ) );
  22368. }
  22369. return new this( name, - 1, tracks );
  22370. }
  22371. static findByName( objectOrClipArray, name ) {
  22372. let clipArray = objectOrClipArray;
  22373. if ( ! Array.isArray( objectOrClipArray ) ) {
  22374. const o = objectOrClipArray;
  22375. clipArray = o.geometry && o.geometry.animations || o.animations;
  22376. }
  22377. for ( let i = 0; i < clipArray.length; i ++ ) {
  22378. if ( clipArray[ i ].name === name ) {
  22379. return clipArray[ i ];
  22380. }
  22381. }
  22382. return null;
  22383. }
  22384. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  22385. const animationToMorphTargets = {};
  22386. // tested with https://regex101.com/ on trick sequences
  22387. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22388. const pattern = /^([\w-]*?)([\d]+)$/;
  22389. // sort morph target names into animation groups based
  22390. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22391. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22392. const morphTarget = morphTargets[ i ];
  22393. const parts = morphTarget.name.match( pattern );
  22394. if ( parts && parts.length > 1 ) {
  22395. const name = parts[ 1 ];
  22396. let animationMorphTargets = animationToMorphTargets[ name ];
  22397. if ( ! animationMorphTargets ) {
  22398. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22399. }
  22400. animationMorphTargets.push( morphTarget );
  22401. }
  22402. }
  22403. const clips = [];
  22404. for ( const name in animationToMorphTargets ) {
  22405. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22406. }
  22407. return clips;
  22408. }
  22409. // parse the animation.hierarchy format
  22410. static parseAnimation( animation, bones ) {
  22411. if ( ! animation ) {
  22412. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22413. return null;
  22414. }
  22415. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22416. // only return track if there are actually keys.
  22417. if ( animationKeys.length !== 0 ) {
  22418. const times = [];
  22419. const values = [];
  22420. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  22421. // empty keys are filtered out, so check again
  22422. if ( times.length !== 0 ) {
  22423. destTracks.push( new trackType( trackName, times, values ) );
  22424. }
  22425. }
  22426. };
  22427. const tracks = [];
  22428. const clipName = animation.name || 'default';
  22429. const fps = animation.fps || 30;
  22430. const blendMode = animation.blendMode;
  22431. // automatic length determination in AnimationClip.
  22432. let duration = animation.length || - 1;
  22433. const hierarchyTracks = animation.hierarchy || [];
  22434. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22435. const animationKeys = hierarchyTracks[ h ].keys;
  22436. // skip empty tracks
  22437. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22438. // process morph targets
  22439. if ( animationKeys[ 0 ].morphTargets ) {
  22440. // figure out all morph targets used in this track
  22441. const morphTargetNames = {};
  22442. let k;
  22443. for ( k = 0; k < animationKeys.length; k ++ ) {
  22444. if ( animationKeys[ k ].morphTargets ) {
  22445. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22446. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  22447. }
  22448. }
  22449. }
  22450. // create a track for each morph target with all zero
  22451. // morphTargetInfluences except for the keys in which
  22452. // the morphTarget is named.
  22453. for ( const morphTargetName in morphTargetNames ) {
  22454. const times = [];
  22455. const values = [];
  22456. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22457. const animationKey = animationKeys[ k ];
  22458. times.push( animationKey.time );
  22459. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22460. }
  22461. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22462. }
  22463. duration = morphTargetNames.length * ( fps || 1.0 );
  22464. } else {
  22465. // ...assume skeletal animation
  22466. const boneName = '.bones[' + bones[ h ].name + ']';
  22467. addNonemptyTrack(
  22468. VectorKeyframeTrack, boneName + '.position',
  22469. animationKeys, 'pos', tracks );
  22470. addNonemptyTrack(
  22471. QuaternionKeyframeTrack, boneName + '.quaternion',
  22472. animationKeys, 'rot', tracks );
  22473. addNonemptyTrack(
  22474. VectorKeyframeTrack, boneName + '.scale',
  22475. animationKeys, 'scl', tracks );
  22476. }
  22477. }
  22478. if ( tracks.length === 0 ) {
  22479. return null;
  22480. }
  22481. const clip = new this( clipName, duration, tracks, blendMode );
  22482. return clip;
  22483. }
  22484. resetDuration() {
  22485. const tracks = this.tracks;
  22486. let duration = 0;
  22487. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22488. const track = this.tracks[ i ];
  22489. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22490. }
  22491. this.duration = duration;
  22492. return this;
  22493. }
  22494. trim() {
  22495. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22496. this.tracks[ i ].trim( 0, this.duration );
  22497. }
  22498. return this;
  22499. }
  22500. validate() {
  22501. let valid = true;
  22502. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22503. valid = valid && this.tracks[ i ].validate();
  22504. }
  22505. return valid;
  22506. }
  22507. optimize() {
  22508. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22509. this.tracks[ i ].optimize();
  22510. }
  22511. return this;
  22512. }
  22513. clone() {
  22514. const tracks = [];
  22515. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22516. tracks.push( this.tracks[ i ].clone() );
  22517. }
  22518. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  22519. }
  22520. toJSON() {
  22521. return this.constructor.toJSON( this );
  22522. }
  22523. }
  22524. function getTrackTypeForValueTypeName( typeName ) {
  22525. switch ( typeName.toLowerCase() ) {
  22526. case 'scalar':
  22527. case 'double':
  22528. case 'float':
  22529. case 'number':
  22530. case 'integer':
  22531. return NumberKeyframeTrack;
  22532. case 'vector':
  22533. case 'vector2':
  22534. case 'vector3':
  22535. case 'vector4':
  22536. return VectorKeyframeTrack;
  22537. case 'color':
  22538. return ColorKeyframeTrack;
  22539. case 'quaternion':
  22540. return QuaternionKeyframeTrack;
  22541. case 'bool':
  22542. case 'boolean':
  22543. return BooleanKeyframeTrack;
  22544. case 'string':
  22545. return StringKeyframeTrack;
  22546. }
  22547. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22548. }
  22549. function parseKeyframeTrack( json ) {
  22550. if ( json.type === undefined ) {
  22551. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  22552. }
  22553. const trackType = getTrackTypeForValueTypeName( json.type );
  22554. if ( json.times === undefined ) {
  22555. const times = [], values = [];
  22556. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  22557. json.times = times;
  22558. json.values = values;
  22559. }
  22560. // derived classes can define a static parse method
  22561. if ( trackType.parse !== undefined ) {
  22562. return trackType.parse( json );
  22563. } else {
  22564. // by default, we assume a constructor compatible with the base
  22565. return new trackType( json.name, json.times, json.values, json.interpolation );
  22566. }
  22567. }
  22568. const Cache = {
  22569. enabled: false,
  22570. files: {},
  22571. add: function ( key, file ) {
  22572. if ( this.enabled === false ) return;
  22573. // console.log( 'THREE.Cache', 'Adding key:', key );
  22574. this.files[ key ] = file;
  22575. },
  22576. get: function ( key ) {
  22577. if ( this.enabled === false ) return;
  22578. // console.log( 'THREE.Cache', 'Checking key:', key );
  22579. return this.files[ key ];
  22580. },
  22581. remove: function ( key ) {
  22582. delete this.files[ key ];
  22583. },
  22584. clear: function () {
  22585. this.files = {};
  22586. }
  22587. };
  22588. class LoadingManager {
  22589. constructor( onLoad, onProgress, onError ) {
  22590. const scope = this;
  22591. let isLoading = false;
  22592. let itemsLoaded = 0;
  22593. let itemsTotal = 0;
  22594. let urlModifier = undefined;
  22595. const handlers = [];
  22596. // Refer to #5689 for the reason why we don't set .onStart
  22597. // in the constructor
  22598. this.onStart = undefined;
  22599. this.onLoad = onLoad;
  22600. this.onProgress = onProgress;
  22601. this.onError = onError;
  22602. this.itemStart = function ( url ) {
  22603. itemsTotal ++;
  22604. if ( isLoading === false ) {
  22605. if ( scope.onStart !== undefined ) {
  22606. scope.onStart( url, itemsLoaded, itemsTotal );
  22607. }
  22608. }
  22609. isLoading = true;
  22610. };
  22611. this.itemEnd = function ( url ) {
  22612. itemsLoaded ++;
  22613. if ( scope.onProgress !== undefined ) {
  22614. scope.onProgress( url, itemsLoaded, itemsTotal );
  22615. }
  22616. if ( itemsLoaded === itemsTotal ) {
  22617. isLoading = false;
  22618. if ( scope.onLoad !== undefined ) {
  22619. scope.onLoad();
  22620. }
  22621. }
  22622. };
  22623. this.itemError = function ( url ) {
  22624. if ( scope.onError !== undefined ) {
  22625. scope.onError( url );
  22626. }
  22627. };
  22628. this.resolveURL = function ( url ) {
  22629. if ( urlModifier ) {
  22630. return urlModifier( url );
  22631. }
  22632. return url;
  22633. };
  22634. this.setURLModifier = function ( transform ) {
  22635. urlModifier = transform;
  22636. return this;
  22637. };
  22638. this.addHandler = function ( regex, loader ) {
  22639. handlers.push( regex, loader );
  22640. return this;
  22641. };
  22642. this.removeHandler = function ( regex ) {
  22643. const index = handlers.indexOf( regex );
  22644. if ( index !== - 1 ) {
  22645. handlers.splice( index, 2 );
  22646. }
  22647. return this;
  22648. };
  22649. this.getHandler = function ( file ) {
  22650. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  22651. const regex = handlers[ i ];
  22652. const loader = handlers[ i + 1 ];
  22653. if ( regex.global ) regex.lastIndex = 0; // see #17920
  22654. if ( regex.test( file ) ) {
  22655. return loader;
  22656. }
  22657. }
  22658. return null;
  22659. };
  22660. }
  22661. }
  22662. const DefaultLoadingManager = new LoadingManager();
  22663. class Loader {
  22664. constructor( manager ) {
  22665. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22666. this.crossOrigin = 'anonymous';
  22667. this.withCredentials = false;
  22668. this.path = '';
  22669. this.resourcePath = '';
  22670. this.requestHeader = {};
  22671. }
  22672. load( /* url, onLoad, onProgress, onError */ ) {}
  22673. loadAsync( url, onProgress ) {
  22674. const scope = this;
  22675. return new Promise( function ( resolve, reject ) {
  22676. scope.load( url, resolve, onProgress, reject );
  22677. } );
  22678. }
  22679. parse( /* data */ ) {}
  22680. setCrossOrigin( crossOrigin ) {
  22681. this.crossOrigin = crossOrigin;
  22682. return this;
  22683. }
  22684. setWithCredentials( value ) {
  22685. this.withCredentials = value;
  22686. return this;
  22687. }
  22688. setPath( path ) {
  22689. this.path = path;
  22690. return this;
  22691. }
  22692. setResourcePath( resourcePath ) {
  22693. this.resourcePath = resourcePath;
  22694. return this;
  22695. }
  22696. setRequestHeader( requestHeader ) {
  22697. this.requestHeader = requestHeader;
  22698. return this;
  22699. }
  22700. }
  22701. const loading = {};
  22702. class FileLoader extends Loader {
  22703. constructor( manager ) {
  22704. super( manager );
  22705. }
  22706. load( url, onLoad, onProgress, onError ) {
  22707. if ( url === undefined ) url = '';
  22708. if ( this.path !== undefined ) url = this.path + url;
  22709. url = this.manager.resolveURL( url );
  22710. const scope = this;
  22711. const cached = Cache.get( url );
  22712. if ( cached !== undefined ) {
  22713. scope.manager.itemStart( url );
  22714. setTimeout( function () {
  22715. if ( onLoad ) onLoad( cached );
  22716. scope.manager.itemEnd( url );
  22717. }, 0 );
  22718. return cached;
  22719. }
  22720. // Check if request is duplicate
  22721. if ( loading[ url ] !== undefined ) {
  22722. loading[ url ].push( {
  22723. onLoad: onLoad,
  22724. onProgress: onProgress,
  22725. onError: onError
  22726. } );
  22727. return;
  22728. }
  22729. // Check for data: URI
  22730. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22731. const dataUriRegexResult = url.match( dataUriRegex );
  22732. let request;
  22733. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22734. if ( dataUriRegexResult ) {
  22735. const mimeType = dataUriRegexResult[ 1 ];
  22736. const isBase64 = !! dataUriRegexResult[ 2 ];
  22737. let data = dataUriRegexResult[ 3 ];
  22738. data = decodeURIComponent( data );
  22739. if ( isBase64 ) data = atob( data );
  22740. try {
  22741. let response;
  22742. const responseType = ( this.responseType || '' ).toLowerCase();
  22743. switch ( responseType ) {
  22744. case 'arraybuffer':
  22745. case 'blob':
  22746. const view = new Uint8Array( data.length );
  22747. for ( let i = 0; i < data.length; i ++ ) {
  22748. view[ i ] = data.charCodeAt( i );
  22749. }
  22750. if ( responseType === 'blob' ) {
  22751. response = new Blob( [ view.buffer ], { type: mimeType } );
  22752. } else {
  22753. response = view.buffer;
  22754. }
  22755. break;
  22756. case 'document':
  22757. const parser = new DOMParser();
  22758. response = parser.parseFromString( data, mimeType );
  22759. break;
  22760. case 'json':
  22761. response = JSON.parse( data );
  22762. break;
  22763. default: // 'text' or other
  22764. response = data;
  22765. break;
  22766. }
  22767. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22768. setTimeout( function () {
  22769. if ( onLoad ) onLoad( response );
  22770. scope.manager.itemEnd( url );
  22771. }, 0 );
  22772. } catch ( error ) {
  22773. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22774. setTimeout( function () {
  22775. if ( onError ) onError( error );
  22776. scope.manager.itemError( url );
  22777. scope.manager.itemEnd( url );
  22778. }, 0 );
  22779. }
  22780. } else {
  22781. // Initialise array for duplicate requests
  22782. loading[ url ] = [];
  22783. loading[ url ].push( {
  22784. onLoad: onLoad,
  22785. onProgress: onProgress,
  22786. onError: onError
  22787. } );
  22788. request = new XMLHttpRequest();
  22789. request.open( 'GET', url, true );
  22790. request.addEventListener( 'load', function ( event ) {
  22791. const response = this.response;
  22792. const callbacks = loading[ url ];
  22793. delete loading[ url ];
  22794. if ( this.status === 200 || this.status === 0 ) {
  22795. // Some browsers return HTTP Status 0 when using non-http protocol
  22796. // e.g. 'file://' or 'data://'. Handle as success.
  22797. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22798. // Add to cache only on HTTP success, so that we do not cache
  22799. // error response bodies as proper responses to requests.
  22800. Cache.add( url, response );
  22801. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22802. const callback = callbacks[ i ];
  22803. if ( callback.onLoad ) callback.onLoad( response );
  22804. }
  22805. scope.manager.itemEnd( url );
  22806. } else {
  22807. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22808. const callback = callbacks[ i ];
  22809. if ( callback.onError ) callback.onError( event );
  22810. }
  22811. scope.manager.itemError( url );
  22812. scope.manager.itemEnd( url );
  22813. }
  22814. }, false );
  22815. request.addEventListener( 'progress', function ( event ) {
  22816. const callbacks = loading[ url ];
  22817. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22818. const callback = callbacks[ i ];
  22819. if ( callback.onProgress ) callback.onProgress( event );
  22820. }
  22821. }, false );
  22822. request.addEventListener( 'error', function ( event ) {
  22823. const callbacks = loading[ url ];
  22824. delete loading[ url ];
  22825. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22826. const callback = callbacks[ i ];
  22827. if ( callback.onError ) callback.onError( event );
  22828. }
  22829. scope.manager.itemError( url );
  22830. scope.manager.itemEnd( url );
  22831. }, false );
  22832. request.addEventListener( 'abort', function ( event ) {
  22833. const callbacks = loading[ url ];
  22834. delete loading[ url ];
  22835. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22836. const callback = callbacks[ i ];
  22837. if ( callback.onError ) callback.onError( event );
  22838. }
  22839. scope.manager.itemError( url );
  22840. scope.manager.itemEnd( url );
  22841. }, false );
  22842. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22843. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22844. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22845. for ( const header in this.requestHeader ) {
  22846. request.setRequestHeader( header, this.requestHeader[ header ] );
  22847. }
  22848. request.send( null );
  22849. }
  22850. scope.manager.itemStart( url );
  22851. return request;
  22852. }
  22853. setResponseType( value ) {
  22854. this.responseType = value;
  22855. return this;
  22856. }
  22857. setMimeType( value ) {
  22858. this.mimeType = value;
  22859. return this;
  22860. }
  22861. }
  22862. class AnimationLoader extends Loader {
  22863. constructor( manager ) {
  22864. super( manager );
  22865. }
  22866. load( url, onLoad, onProgress, onError ) {
  22867. const scope = this;
  22868. const loader = new FileLoader( this.manager );
  22869. loader.setPath( this.path );
  22870. loader.setRequestHeader( this.requestHeader );
  22871. loader.setWithCredentials( this.withCredentials );
  22872. loader.load( url, function ( text ) {
  22873. try {
  22874. onLoad( scope.parse( JSON.parse( text ) ) );
  22875. } catch ( e ) {
  22876. if ( onError ) {
  22877. onError( e );
  22878. } else {
  22879. console.error( e );
  22880. }
  22881. scope.manager.itemError( url );
  22882. }
  22883. }, onProgress, onError );
  22884. }
  22885. parse( json ) {
  22886. const animations = [];
  22887. for ( let i = 0; i < json.length; i ++ ) {
  22888. const clip = AnimationClip.parse( json[ i ] );
  22889. animations.push( clip );
  22890. }
  22891. return animations;
  22892. }
  22893. }
  22894. /**
  22895. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22896. *
  22897. * Sub classes have to implement the parse() method which will be used in load().
  22898. */
  22899. class CompressedTextureLoader extends Loader {
  22900. constructor( manager ) {
  22901. super( manager );
  22902. }
  22903. load( url, onLoad, onProgress, onError ) {
  22904. const scope = this;
  22905. const images = [];
  22906. const texture = new CompressedTexture();
  22907. const loader = new FileLoader( this.manager );
  22908. loader.setPath( this.path );
  22909. loader.setResponseType( 'arraybuffer' );
  22910. loader.setRequestHeader( this.requestHeader );
  22911. loader.setWithCredentials( scope.withCredentials );
  22912. let loaded = 0;
  22913. function loadTexture( i ) {
  22914. loader.load( url[ i ], function ( buffer ) {
  22915. const texDatas = scope.parse( buffer, true );
  22916. images[ i ] = {
  22917. width: texDatas.width,
  22918. height: texDatas.height,
  22919. format: texDatas.format,
  22920. mipmaps: texDatas.mipmaps
  22921. };
  22922. loaded += 1;
  22923. if ( loaded === 6 ) {
  22924. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  22925. texture.image = images;
  22926. texture.format = texDatas.format;
  22927. texture.needsUpdate = true;
  22928. if ( onLoad ) onLoad( texture );
  22929. }
  22930. }, onProgress, onError );
  22931. }
  22932. if ( Array.isArray( url ) ) {
  22933. for ( let i = 0, il = url.length; i < il; ++ i ) {
  22934. loadTexture( i );
  22935. }
  22936. } else {
  22937. // compressed cubemap texture stored in a single DDS file
  22938. loader.load( url, function ( buffer ) {
  22939. const texDatas = scope.parse( buffer, true );
  22940. if ( texDatas.isCubemap ) {
  22941. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22942. for ( let f = 0; f < faces; f ++ ) {
  22943. images[ f ] = { mipmaps: [] };
  22944. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  22945. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22946. images[ f ].format = texDatas.format;
  22947. images[ f ].width = texDatas.width;
  22948. images[ f ].height = texDatas.height;
  22949. }
  22950. }
  22951. texture.image = images;
  22952. } else {
  22953. texture.image.width = texDatas.width;
  22954. texture.image.height = texDatas.height;
  22955. texture.mipmaps = texDatas.mipmaps;
  22956. }
  22957. if ( texDatas.mipmapCount === 1 ) {
  22958. texture.minFilter = LinearFilter;
  22959. }
  22960. texture.format = texDatas.format;
  22961. texture.needsUpdate = true;
  22962. if ( onLoad ) onLoad( texture );
  22963. }, onProgress, onError );
  22964. }
  22965. return texture;
  22966. }
  22967. }
  22968. class ImageLoader extends Loader {
  22969. constructor( manager ) {
  22970. super( manager );
  22971. }
  22972. load( url, onLoad, onProgress, onError ) {
  22973. if ( this.path !== undefined ) url = this.path + url;
  22974. url = this.manager.resolveURL( url );
  22975. const scope = this;
  22976. const cached = Cache.get( url );
  22977. if ( cached !== undefined ) {
  22978. scope.manager.itemStart( url );
  22979. setTimeout( function () {
  22980. if ( onLoad ) onLoad( cached );
  22981. scope.manager.itemEnd( url );
  22982. }, 0 );
  22983. return cached;
  22984. }
  22985. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22986. function onImageLoad() {
  22987. image.removeEventListener( 'load', onImageLoad, false );
  22988. image.removeEventListener( 'error', onImageError, false );
  22989. Cache.add( url, this );
  22990. if ( onLoad ) onLoad( this );
  22991. scope.manager.itemEnd( url );
  22992. }
  22993. function onImageError( event ) {
  22994. image.removeEventListener( 'load', onImageLoad, false );
  22995. image.removeEventListener( 'error', onImageError, false );
  22996. if ( onError ) onError( event );
  22997. scope.manager.itemError( url );
  22998. scope.manager.itemEnd( url );
  22999. }
  23000. image.addEventListener( 'load', onImageLoad, false );
  23001. image.addEventListener( 'error', onImageError, false );
  23002. if ( url.substr( 0, 5 ) !== 'data:' ) {
  23003. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23004. }
  23005. scope.manager.itemStart( url );
  23006. image.src = url;
  23007. return image;
  23008. }
  23009. }
  23010. class CubeTextureLoader extends Loader {
  23011. constructor( manager ) {
  23012. super( manager );
  23013. }
  23014. load( urls, onLoad, onProgress, onError ) {
  23015. const texture = new CubeTexture();
  23016. const loader = new ImageLoader( this.manager );
  23017. loader.setCrossOrigin( this.crossOrigin );
  23018. loader.setPath( this.path );
  23019. let loaded = 0;
  23020. function loadTexture( i ) {
  23021. loader.load( urls[ i ], function ( image ) {
  23022. texture.images[ i ] = image;
  23023. loaded ++;
  23024. if ( loaded === 6 ) {
  23025. texture.needsUpdate = true;
  23026. if ( onLoad ) onLoad( texture );
  23027. }
  23028. }, undefined, onError );
  23029. }
  23030. for ( let i = 0; i < urls.length; ++ i ) {
  23031. loadTexture( i );
  23032. }
  23033. return texture;
  23034. }
  23035. }
  23036. /**
  23037. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23038. *
  23039. * Sub classes have to implement the parse() method which will be used in load().
  23040. */
  23041. class DataTextureLoader extends Loader {
  23042. constructor( manager ) {
  23043. super( manager );
  23044. }
  23045. load( url, onLoad, onProgress, onError ) {
  23046. const scope = this;
  23047. const texture = new DataTexture();
  23048. const loader = new FileLoader( this.manager );
  23049. loader.setResponseType( 'arraybuffer' );
  23050. loader.setRequestHeader( this.requestHeader );
  23051. loader.setPath( this.path );
  23052. loader.setWithCredentials( scope.withCredentials );
  23053. loader.load( url, function ( buffer ) {
  23054. const texData = scope.parse( buffer );
  23055. if ( ! texData ) return;
  23056. if ( texData.image !== undefined ) {
  23057. texture.image = texData.image;
  23058. } else if ( texData.data !== undefined ) {
  23059. texture.image.width = texData.width;
  23060. texture.image.height = texData.height;
  23061. texture.image.data = texData.data;
  23062. }
  23063. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23064. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23065. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23066. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23067. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23068. if ( texData.encoding !== undefined ) {
  23069. texture.encoding = texData.encoding;
  23070. }
  23071. if ( texData.flipY !== undefined ) {
  23072. texture.flipY = texData.flipY;
  23073. }
  23074. if ( texData.format !== undefined ) {
  23075. texture.format = texData.format;
  23076. }
  23077. if ( texData.type !== undefined ) {
  23078. texture.type = texData.type;
  23079. }
  23080. if ( texData.mipmaps !== undefined ) {
  23081. texture.mipmaps = texData.mipmaps;
  23082. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23083. }
  23084. if ( texData.mipmapCount === 1 ) {
  23085. texture.minFilter = LinearFilter;
  23086. }
  23087. if ( texData.generateMipmaps !== undefined ) {
  23088. texture.generateMipmaps = texData.generateMipmaps;
  23089. }
  23090. texture.needsUpdate = true;
  23091. if ( onLoad ) onLoad( texture, texData );
  23092. }, onProgress, onError );
  23093. return texture;
  23094. }
  23095. }
  23096. class TextureLoader extends Loader {
  23097. constructor( manager ) {
  23098. super( manager );
  23099. }
  23100. load( url, onLoad, onProgress, onError ) {
  23101. const texture = new Texture();
  23102. const loader = new ImageLoader( this.manager );
  23103. loader.setCrossOrigin( this.crossOrigin );
  23104. loader.setPath( this.path );
  23105. loader.load( url, function ( image ) {
  23106. texture.image = image;
  23107. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  23108. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  23109. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  23110. texture.needsUpdate = true;
  23111. if ( onLoad !== undefined ) {
  23112. onLoad( texture );
  23113. }
  23114. }, onProgress, onError );
  23115. return texture;
  23116. }
  23117. }
  23118. /**************************************************************
  23119. * Curved Path - a curve path is simply a array of connected
  23120. * curves, but retains the api of a curve
  23121. **************************************************************/
  23122. class CurvePath extends Curve {
  23123. constructor() {
  23124. super();
  23125. this.type = 'CurvePath';
  23126. this.curves = [];
  23127. this.autoClose = false; // Automatically closes the path
  23128. }
  23129. add( curve ) {
  23130. this.curves.push( curve );
  23131. }
  23132. closePath() {
  23133. // Add a line curve if start and end of lines are not connected
  23134. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23135. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23136. if ( ! startPoint.equals( endPoint ) ) {
  23137. this.curves.push( new LineCurve( endPoint, startPoint ) );
  23138. }
  23139. }
  23140. // To get accurate point with reference to
  23141. // entire path distance at time t,
  23142. // following has to be done:
  23143. // 1. Length of each sub path have to be known
  23144. // 2. Locate and identify type of curve
  23145. // 3. Get t for the curve
  23146. // 4. Return curve.getPointAt(t')
  23147. getPoint( t ) {
  23148. const d = t * this.getLength();
  23149. const curveLengths = this.getCurveLengths();
  23150. let i = 0;
  23151. // To think about boundaries points.
  23152. while ( i < curveLengths.length ) {
  23153. if ( curveLengths[ i ] >= d ) {
  23154. const diff = curveLengths[ i ] - d;
  23155. const curve = this.curves[ i ];
  23156. const segmentLength = curve.getLength();
  23157. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23158. return curve.getPointAt( u );
  23159. }
  23160. i ++;
  23161. }
  23162. return null;
  23163. // loop where sum != 0, sum > d , sum+1 <d
  23164. }
  23165. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23166. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23167. // getPoint() depends on getLength
  23168. getLength() {
  23169. const lens = this.getCurveLengths();
  23170. return lens[ lens.length - 1 ];
  23171. }
  23172. // cacheLengths must be recalculated.
  23173. updateArcLengths() {
  23174. this.needsUpdate = true;
  23175. this.cacheLengths = null;
  23176. this.getCurveLengths();
  23177. }
  23178. // Compute lengths and cache them
  23179. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23180. getCurveLengths() {
  23181. // We use cache values if curves and cache array are same length
  23182. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23183. return this.cacheLengths;
  23184. }
  23185. // Get length of sub-curve
  23186. // Push sums into cached array
  23187. const lengths = [];
  23188. let sums = 0;
  23189. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23190. sums += this.curves[ i ].getLength();
  23191. lengths.push( sums );
  23192. }
  23193. this.cacheLengths = lengths;
  23194. return lengths;
  23195. }
  23196. getSpacedPoints( divisions = 40 ) {
  23197. const points = [];
  23198. for ( let i = 0; i <= divisions; i ++ ) {
  23199. points.push( this.getPoint( i / divisions ) );
  23200. }
  23201. if ( this.autoClose ) {
  23202. points.push( points[ 0 ] );
  23203. }
  23204. return points;
  23205. }
  23206. getPoints( divisions = 12 ) {
  23207. const points = [];
  23208. let last;
  23209. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23210. const curve = curves[ i ];
  23211. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  23212. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  23213. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  23214. : divisions;
  23215. const pts = curve.getPoints( resolution );
  23216. for ( let j = 0; j < pts.length; j ++ ) {
  23217. const point = pts[ j ];
  23218. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23219. points.push( point );
  23220. last = point;
  23221. }
  23222. }
  23223. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23224. points.push( points[ 0 ] );
  23225. }
  23226. return points;
  23227. }
  23228. copy( source ) {
  23229. super.copy( source );
  23230. this.curves = [];
  23231. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23232. const curve = source.curves[ i ];
  23233. this.curves.push( curve.clone() );
  23234. }
  23235. this.autoClose = source.autoClose;
  23236. return this;
  23237. }
  23238. toJSON() {
  23239. const data = super.toJSON();
  23240. data.autoClose = this.autoClose;
  23241. data.curves = [];
  23242. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23243. const curve = this.curves[ i ];
  23244. data.curves.push( curve.toJSON() );
  23245. }
  23246. return data;
  23247. }
  23248. fromJSON( json ) {
  23249. super.fromJSON( json );
  23250. this.autoClose = json.autoClose;
  23251. this.curves = [];
  23252. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23253. const curve = json.curves[ i ];
  23254. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23255. }
  23256. return this;
  23257. }
  23258. }
  23259. class Path extends CurvePath {
  23260. constructor( points ) {
  23261. super();
  23262. this.type = 'Path';
  23263. this.currentPoint = new Vector2();
  23264. if ( points ) {
  23265. this.setFromPoints( points );
  23266. }
  23267. }
  23268. setFromPoints( points ) {
  23269. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23270. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23271. this.lineTo( points[ i ].x, points[ i ].y );
  23272. }
  23273. return this;
  23274. }
  23275. moveTo( x, y ) {
  23276. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23277. return this;
  23278. }
  23279. lineTo( x, y ) {
  23280. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  23281. this.curves.push( curve );
  23282. this.currentPoint.set( x, y );
  23283. return this;
  23284. }
  23285. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  23286. const curve = new QuadraticBezierCurve(
  23287. this.currentPoint.clone(),
  23288. new Vector2( aCPx, aCPy ),
  23289. new Vector2( aX, aY )
  23290. );
  23291. this.curves.push( curve );
  23292. this.currentPoint.set( aX, aY );
  23293. return this;
  23294. }
  23295. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23296. const curve = new CubicBezierCurve(
  23297. this.currentPoint.clone(),
  23298. new Vector2( aCP1x, aCP1y ),
  23299. new Vector2( aCP2x, aCP2y ),
  23300. new Vector2( aX, aY )
  23301. );
  23302. this.curves.push( curve );
  23303. this.currentPoint.set( aX, aY );
  23304. return this;
  23305. }
  23306. splineThru( pts /*Array of Vector*/ ) {
  23307. const npts = [ this.currentPoint.clone() ].concat( pts );
  23308. const curve = new SplineCurve( npts );
  23309. this.curves.push( curve );
  23310. this.currentPoint.copy( pts[ pts.length - 1 ] );
  23311. return this;
  23312. }
  23313. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23314. const x0 = this.currentPoint.x;
  23315. const y0 = this.currentPoint.y;
  23316. this.absarc( aX + x0, aY + y0, aRadius,
  23317. aStartAngle, aEndAngle, aClockwise );
  23318. return this;
  23319. }
  23320. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23321. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23322. return this;
  23323. }
  23324. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23325. const x0 = this.currentPoint.x;
  23326. const y0 = this.currentPoint.y;
  23327. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23328. return this;
  23329. }
  23330. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23331. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23332. if ( this.curves.length > 0 ) {
  23333. // if a previous curve is present, attempt to join
  23334. const firstPoint = curve.getPoint( 0 );
  23335. if ( ! firstPoint.equals( this.currentPoint ) ) {
  23336. this.lineTo( firstPoint.x, firstPoint.y );
  23337. }
  23338. }
  23339. this.curves.push( curve );
  23340. const lastPoint = curve.getPoint( 1 );
  23341. this.currentPoint.copy( lastPoint );
  23342. return this;
  23343. }
  23344. copy( source ) {
  23345. super.copy( source );
  23346. this.currentPoint.copy( source.currentPoint );
  23347. return this;
  23348. }
  23349. toJSON() {
  23350. const data = super.toJSON();
  23351. data.currentPoint = this.currentPoint.toArray();
  23352. return data;
  23353. }
  23354. fromJSON( json ) {
  23355. super.fromJSON( json );
  23356. this.currentPoint.fromArray( json.currentPoint );
  23357. return this;
  23358. }
  23359. }
  23360. class Shape extends Path {
  23361. constructor( points ) {
  23362. super( points );
  23363. this.uuid = generateUUID();
  23364. this.type = 'Shape';
  23365. this.holes = [];
  23366. }
  23367. getPointsHoles( divisions ) {
  23368. const holesPts = [];
  23369. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  23370. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  23371. }
  23372. return holesPts;
  23373. }
  23374. // get points of shape and holes (keypoints based on segments parameter)
  23375. extractPoints( divisions ) {
  23376. return {
  23377. shape: this.getPoints( divisions ),
  23378. holes: this.getPointsHoles( divisions )
  23379. };
  23380. }
  23381. copy( source ) {
  23382. super.copy( source );
  23383. this.holes = [];
  23384. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  23385. const hole = source.holes[ i ];
  23386. this.holes.push( hole.clone() );
  23387. }
  23388. return this;
  23389. }
  23390. toJSON() {
  23391. const data = super.toJSON();
  23392. data.uuid = this.uuid;
  23393. data.holes = [];
  23394. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  23395. const hole = this.holes[ i ];
  23396. data.holes.push( hole.toJSON() );
  23397. }
  23398. return data;
  23399. }
  23400. fromJSON( json ) {
  23401. super.fromJSON( json );
  23402. this.uuid = json.uuid;
  23403. this.holes = [];
  23404. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  23405. const hole = json.holes[ i ];
  23406. this.holes.push( new Path().fromJSON( hole ) );
  23407. }
  23408. return this;
  23409. }
  23410. }
  23411. class Light extends Object3D {
  23412. constructor( color, intensity = 1 ) {
  23413. super();
  23414. this.type = 'Light';
  23415. this.color = new Color( color );
  23416. this.intensity = intensity;
  23417. }
  23418. dispose() {
  23419. // Empty here in base class; some subclasses override.
  23420. }
  23421. copy( source ) {
  23422. super.copy( source );
  23423. this.color.copy( source.color );
  23424. this.intensity = source.intensity;
  23425. return this;
  23426. }
  23427. toJSON( meta ) {
  23428. const data = super.toJSON( meta );
  23429. data.object.color = this.color.getHex();
  23430. data.object.intensity = this.intensity;
  23431. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23432. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23433. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23434. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23435. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23436. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23437. return data;
  23438. }
  23439. }
  23440. Light.prototype.isLight = true;
  23441. class HemisphereLight extends Light {
  23442. constructor( skyColor, groundColor, intensity ) {
  23443. super( skyColor, intensity );
  23444. this.type = 'HemisphereLight';
  23445. this.position.copy( Object3D.DefaultUp );
  23446. this.updateMatrix();
  23447. this.groundColor = new Color( groundColor );
  23448. }
  23449. copy( source ) {
  23450. Light.prototype.copy.call( this, source );
  23451. this.groundColor.copy( source.groundColor );
  23452. return this;
  23453. }
  23454. }
  23455. HemisphereLight.prototype.isHemisphereLight = true;
  23456. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23457. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23458. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23459. class LightShadow {
  23460. constructor( camera ) {
  23461. this.camera = camera;
  23462. this.bias = 0;
  23463. this.normalBias = 0;
  23464. this.radius = 1;
  23465. this.blurSamples = 8;
  23466. this.mapSize = new Vector2( 512, 512 );
  23467. this.map = null;
  23468. this.mapPass = null;
  23469. this.matrix = new Matrix4();
  23470. this.autoUpdate = true;
  23471. this.needsUpdate = false;
  23472. this._frustum = new Frustum();
  23473. this._frameExtents = new Vector2( 1, 1 );
  23474. this._viewportCount = 1;
  23475. this._viewports = [
  23476. new Vector4( 0, 0, 1, 1 )
  23477. ];
  23478. }
  23479. getViewportCount() {
  23480. return this._viewportCount;
  23481. }
  23482. getFrustum() {
  23483. return this._frustum;
  23484. }
  23485. updateMatrices( light ) {
  23486. const shadowCamera = this.camera;
  23487. const shadowMatrix = this.matrix;
  23488. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  23489. shadowCamera.position.copy( _lightPositionWorld$1 );
  23490. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  23491. shadowCamera.lookAt( _lookTarget$1 );
  23492. shadowCamera.updateMatrixWorld();
  23493. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23494. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  23495. shadowMatrix.set(
  23496. 0.5, 0.0, 0.0, 0.5,
  23497. 0.0, 0.5, 0.0, 0.5,
  23498. 0.0, 0.0, 0.5, 0.5,
  23499. 0.0, 0.0, 0.0, 1.0
  23500. );
  23501. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23502. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23503. }
  23504. getViewport( viewportIndex ) {
  23505. return this._viewports[ viewportIndex ];
  23506. }
  23507. getFrameExtents() {
  23508. return this._frameExtents;
  23509. }
  23510. dispose() {
  23511. if ( this.map ) {
  23512. this.map.dispose();
  23513. }
  23514. if ( this.mapPass ) {
  23515. this.mapPass.dispose();
  23516. }
  23517. }
  23518. copy( source ) {
  23519. this.camera = source.camera.clone();
  23520. this.bias = source.bias;
  23521. this.radius = source.radius;
  23522. this.mapSize.copy( source.mapSize );
  23523. return this;
  23524. }
  23525. clone() {
  23526. return new this.constructor().copy( this );
  23527. }
  23528. toJSON() {
  23529. const object = {};
  23530. if ( this.bias !== 0 ) object.bias = this.bias;
  23531. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23532. if ( this.radius !== 1 ) object.radius = this.radius;
  23533. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23534. object.camera = this.camera.toJSON( false ).object;
  23535. delete object.camera.matrix;
  23536. return object;
  23537. }
  23538. }
  23539. class SpotLightShadow extends LightShadow {
  23540. constructor() {
  23541. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23542. this.focus = 1;
  23543. }
  23544. updateMatrices( light ) {
  23545. const camera = this.camera;
  23546. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23547. const aspect = this.mapSize.width / this.mapSize.height;
  23548. const far = light.distance || camera.far;
  23549. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23550. camera.fov = fov;
  23551. camera.aspect = aspect;
  23552. camera.far = far;
  23553. camera.updateProjectionMatrix();
  23554. }
  23555. super.updateMatrices( light );
  23556. }
  23557. copy( source ) {
  23558. super.copy( source );
  23559. this.focus = source.focus;
  23560. return this;
  23561. }
  23562. }
  23563. SpotLightShadow.prototype.isSpotLightShadow = true;
  23564. class SpotLight extends Light {
  23565. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  23566. super( color, intensity );
  23567. this.type = 'SpotLight';
  23568. this.position.copy( Object3D.DefaultUp );
  23569. this.updateMatrix();
  23570. this.target = new Object3D();
  23571. this.distance = distance;
  23572. this.angle = angle;
  23573. this.penumbra = penumbra;
  23574. this.decay = decay; // for physically correct lights, should be 2.
  23575. this.shadow = new SpotLightShadow();
  23576. }
  23577. get power() {
  23578. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23579. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23580. return this.intensity * Math.PI;
  23581. }
  23582. set power( power ) {
  23583. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23584. this.intensity = power / Math.PI;
  23585. }
  23586. dispose() {
  23587. this.shadow.dispose();
  23588. }
  23589. copy( source ) {
  23590. super.copy( source );
  23591. this.distance = source.distance;
  23592. this.angle = source.angle;
  23593. this.penumbra = source.penumbra;
  23594. this.decay = source.decay;
  23595. this.target = source.target.clone();
  23596. this.shadow = source.shadow.clone();
  23597. return this;
  23598. }
  23599. }
  23600. SpotLight.prototype.isSpotLight = true;
  23601. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  23602. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  23603. const _lookTarget = /*@__PURE__*/ new Vector3();
  23604. class PointLightShadow extends LightShadow {
  23605. constructor() {
  23606. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23607. this._frameExtents = new Vector2( 4, 2 );
  23608. this._viewportCount = 6;
  23609. this._viewports = [
  23610. // These viewports map a cube-map onto a 2D texture with the
  23611. // following orientation:
  23612. //
  23613. // xzXZ
  23614. // y Y
  23615. //
  23616. // X - Positive x direction
  23617. // x - Negative x direction
  23618. // Y - Positive y direction
  23619. // y - Negative y direction
  23620. // Z - Positive z direction
  23621. // z - Negative z direction
  23622. // positive X
  23623. new Vector4( 2, 1, 1, 1 ),
  23624. // negative X
  23625. new Vector4( 0, 1, 1, 1 ),
  23626. // positive Z
  23627. new Vector4( 3, 1, 1, 1 ),
  23628. // negative Z
  23629. new Vector4( 1, 1, 1, 1 ),
  23630. // positive Y
  23631. new Vector4( 3, 0, 1, 1 ),
  23632. // negative Y
  23633. new Vector4( 1, 0, 1, 1 )
  23634. ];
  23635. this._cubeDirections = [
  23636. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23637. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  23638. ];
  23639. this._cubeUps = [
  23640. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23641. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  23642. ];
  23643. }
  23644. updateMatrices( light, viewportIndex = 0 ) {
  23645. const camera = this.camera;
  23646. const shadowMatrix = this.matrix;
  23647. const far = light.distance || camera.far;
  23648. if ( far !== camera.far ) {
  23649. camera.far = far;
  23650. camera.updateProjectionMatrix();
  23651. }
  23652. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23653. camera.position.copy( _lightPositionWorld );
  23654. _lookTarget.copy( camera.position );
  23655. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23656. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23657. camera.lookAt( _lookTarget );
  23658. camera.updateMatrixWorld();
  23659. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  23660. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23661. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  23662. }
  23663. }
  23664. PointLightShadow.prototype.isPointLightShadow = true;
  23665. class PointLight extends Light {
  23666. constructor( color, intensity, distance = 0, decay = 1 ) {
  23667. super( color, intensity );
  23668. this.type = 'PointLight';
  23669. this.distance = distance;
  23670. this.decay = decay; // for physically correct lights, should be 2.
  23671. this.shadow = new PointLightShadow();
  23672. }
  23673. get power() {
  23674. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23675. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23676. return this.intensity * 4 * Math.PI;
  23677. }
  23678. set power( power ) {
  23679. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23680. this.intensity = power / ( 4 * Math.PI );
  23681. }
  23682. dispose() {
  23683. this.shadow.dispose();
  23684. }
  23685. copy( source ) {
  23686. super.copy( source );
  23687. this.distance = source.distance;
  23688. this.decay = source.decay;
  23689. this.shadow = source.shadow.clone();
  23690. return this;
  23691. }
  23692. }
  23693. PointLight.prototype.isPointLight = true;
  23694. class DirectionalLightShadow extends LightShadow {
  23695. constructor() {
  23696. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  23697. }
  23698. }
  23699. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23700. class DirectionalLight extends Light {
  23701. constructor( color, intensity ) {
  23702. super( color, intensity );
  23703. this.type = 'DirectionalLight';
  23704. this.position.copy( Object3D.DefaultUp );
  23705. this.updateMatrix();
  23706. this.target = new Object3D();
  23707. this.shadow = new DirectionalLightShadow();
  23708. }
  23709. dispose() {
  23710. this.shadow.dispose();
  23711. }
  23712. copy( source ) {
  23713. super.copy( source );
  23714. this.target = source.target.clone();
  23715. this.shadow = source.shadow.clone();
  23716. return this;
  23717. }
  23718. }
  23719. DirectionalLight.prototype.isDirectionalLight = true;
  23720. class AmbientLight extends Light {
  23721. constructor( color, intensity ) {
  23722. super( color, intensity );
  23723. this.type = 'AmbientLight';
  23724. }
  23725. }
  23726. AmbientLight.prototype.isAmbientLight = true;
  23727. class RectAreaLight extends Light {
  23728. constructor( color, intensity, width = 10, height = 10 ) {
  23729. super( color, intensity );
  23730. this.type = 'RectAreaLight';
  23731. this.width = width;
  23732. this.height = height;
  23733. }
  23734. get power() {
  23735. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23736. return this.intensity * this.width * this.height * Math.PI;
  23737. }
  23738. set power( power ) {
  23739. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23740. this.intensity = power / ( this.width * this.height * Math.PI );
  23741. }
  23742. copy( source ) {
  23743. super.copy( source );
  23744. this.width = source.width;
  23745. this.height = source.height;
  23746. return this;
  23747. }
  23748. toJSON( meta ) {
  23749. const data = super.toJSON( meta );
  23750. data.object.width = this.width;
  23751. data.object.height = this.height;
  23752. return data;
  23753. }
  23754. }
  23755. RectAreaLight.prototype.isRectAreaLight = true;
  23756. /**
  23757. * Primary reference:
  23758. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23759. *
  23760. * Secondary reference:
  23761. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23762. */
  23763. // 3-band SH defined by 9 coefficients
  23764. class SphericalHarmonics3 {
  23765. constructor() {
  23766. this.coefficients = [];
  23767. for ( let i = 0; i < 9; i ++ ) {
  23768. this.coefficients.push( new Vector3() );
  23769. }
  23770. }
  23771. set( coefficients ) {
  23772. for ( let i = 0; i < 9; i ++ ) {
  23773. this.coefficients[ i ].copy( coefficients[ i ] );
  23774. }
  23775. return this;
  23776. }
  23777. zero() {
  23778. for ( let i = 0; i < 9; i ++ ) {
  23779. this.coefficients[ i ].set( 0, 0, 0 );
  23780. }
  23781. return this;
  23782. }
  23783. // get the radiance in the direction of the normal
  23784. // target is a Vector3
  23785. getAt( normal, target ) {
  23786. // normal is assumed to be unit length
  23787. const x = normal.x, y = normal.y, z = normal.z;
  23788. const coeff = this.coefficients;
  23789. // band 0
  23790. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  23791. // band 1
  23792. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  23793. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  23794. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  23795. // band 2
  23796. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  23797. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  23798. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  23799. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  23800. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  23801. return target;
  23802. }
  23803. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23804. // target is a Vector3
  23805. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23806. getIrradianceAt( normal, target ) {
  23807. // normal is assumed to be unit length
  23808. const x = normal.x, y = normal.y, z = normal.z;
  23809. const coeff = this.coefficients;
  23810. // band 0
  23811. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  23812. // band 1
  23813. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  23814. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  23815. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  23816. // band 2
  23817. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  23818. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  23819. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  23820. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  23821. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  23822. return target;
  23823. }
  23824. add( sh ) {
  23825. for ( let i = 0; i < 9; i ++ ) {
  23826. this.coefficients[ i ].add( sh.coefficients[ i ] );
  23827. }
  23828. return this;
  23829. }
  23830. addScaledSH( sh, s ) {
  23831. for ( let i = 0; i < 9; i ++ ) {
  23832. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  23833. }
  23834. return this;
  23835. }
  23836. scale( s ) {
  23837. for ( let i = 0; i < 9; i ++ ) {
  23838. this.coefficients[ i ].multiplyScalar( s );
  23839. }
  23840. return this;
  23841. }
  23842. lerp( sh, alpha ) {
  23843. for ( let i = 0; i < 9; i ++ ) {
  23844. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  23845. }
  23846. return this;
  23847. }
  23848. equals( sh ) {
  23849. for ( let i = 0; i < 9; i ++ ) {
  23850. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  23851. return false;
  23852. }
  23853. }
  23854. return true;
  23855. }
  23856. copy( sh ) {
  23857. return this.set( sh.coefficients );
  23858. }
  23859. clone() {
  23860. return new this.constructor().copy( this );
  23861. }
  23862. fromArray( array, offset = 0 ) {
  23863. const coefficients = this.coefficients;
  23864. for ( let i = 0; i < 9; i ++ ) {
  23865. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  23866. }
  23867. return this;
  23868. }
  23869. toArray( array = [], offset = 0 ) {
  23870. const coefficients = this.coefficients;
  23871. for ( let i = 0; i < 9; i ++ ) {
  23872. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  23873. }
  23874. return array;
  23875. }
  23876. // evaluate the basis functions
  23877. // shBasis is an Array[ 9 ]
  23878. static getBasisAt( normal, shBasis ) {
  23879. // normal is assumed to be unit length
  23880. const x = normal.x, y = normal.y, z = normal.z;
  23881. // band 0
  23882. shBasis[ 0 ] = 0.282095;
  23883. // band 1
  23884. shBasis[ 1 ] = 0.488603 * y;
  23885. shBasis[ 2 ] = 0.488603 * z;
  23886. shBasis[ 3 ] = 0.488603 * x;
  23887. // band 2
  23888. shBasis[ 4 ] = 1.092548 * x * y;
  23889. shBasis[ 5 ] = 1.092548 * y * z;
  23890. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  23891. shBasis[ 7 ] = 1.092548 * x * z;
  23892. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  23893. }
  23894. }
  23895. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23896. class LightProbe extends Light {
  23897. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  23898. super( undefined, intensity );
  23899. this.sh = sh;
  23900. }
  23901. copy( source ) {
  23902. super.copy( source );
  23903. this.sh.copy( source.sh );
  23904. return this;
  23905. }
  23906. fromJSON( json ) {
  23907. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23908. this.sh.fromArray( json.sh );
  23909. return this;
  23910. }
  23911. toJSON( meta ) {
  23912. const data = super.toJSON( meta );
  23913. data.object.sh = this.sh.toArray();
  23914. return data;
  23915. }
  23916. }
  23917. LightProbe.prototype.isLightProbe = true;
  23918. class MaterialLoader extends Loader {
  23919. constructor( manager ) {
  23920. super( manager );
  23921. this.textures = {};
  23922. }
  23923. load( url, onLoad, onProgress, onError ) {
  23924. const scope = this;
  23925. const loader = new FileLoader( scope.manager );
  23926. loader.setPath( scope.path );
  23927. loader.setRequestHeader( scope.requestHeader );
  23928. loader.setWithCredentials( scope.withCredentials );
  23929. loader.load( url, function ( text ) {
  23930. try {
  23931. onLoad( scope.parse( JSON.parse( text ) ) );
  23932. } catch ( e ) {
  23933. if ( onError ) {
  23934. onError( e );
  23935. } else {
  23936. console.error( e );
  23937. }
  23938. scope.manager.itemError( url );
  23939. }
  23940. }, onProgress, onError );
  23941. }
  23942. parse( json ) {
  23943. const textures = this.textures;
  23944. function getTexture( name ) {
  23945. if ( textures[ name ] === undefined ) {
  23946. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  23947. }
  23948. return textures[ name ];
  23949. }
  23950. const material = new Materials[ json.type ]();
  23951. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  23952. if ( json.name !== undefined ) material.name = json.name;
  23953. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  23954. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  23955. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  23956. if ( json.sheenTint !== undefined ) material.sheenTint = new Color().setHex( json.sheenTint );
  23957. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  23958. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  23959. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  23960. if ( json.specularTint !== undefined && material.specularTint !== undefined ) material.specularTint.setHex( json.specularTint );
  23961. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  23962. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  23963. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  23964. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  23965. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  23966. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  23967. if ( json.attenuationTint !== undefined && material.attenuationTint !== undefined ) material.attenuationTint.setHex( json.attenuationTint );
  23968. if ( json.fog !== undefined ) material.fog = json.fog;
  23969. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  23970. if ( json.blending !== undefined ) material.blending = json.blending;
  23971. if ( json.combine !== undefined ) material.combine = json.combine;
  23972. if ( json.side !== undefined ) material.side = json.side;
  23973. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  23974. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  23975. if ( json.format !== undefined ) material.format = json.format;
  23976. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  23977. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  23978. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  23979. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  23980. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  23981. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  23982. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  23983. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  23984. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  23985. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  23986. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  23987. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  23988. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  23989. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  23990. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  23991. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  23992. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  23993. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  23994. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  23995. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  23996. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  23997. if ( json.scale !== undefined ) material.scale = json.scale;
  23998. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  23999. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24000. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24001. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24002. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24003. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24004. if ( json.visible !== undefined ) material.visible = json.visible;
  24005. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24006. if ( json.userData !== undefined ) material.userData = json.userData;
  24007. if ( json.vertexColors !== undefined ) {
  24008. if ( typeof json.vertexColors === 'number' ) {
  24009. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24010. } else {
  24011. material.vertexColors = json.vertexColors;
  24012. }
  24013. }
  24014. // Shader Material
  24015. if ( json.uniforms !== undefined ) {
  24016. for ( const name in json.uniforms ) {
  24017. const uniform = json.uniforms[ name ];
  24018. material.uniforms[ name ] = {};
  24019. switch ( uniform.type ) {
  24020. case 't':
  24021. material.uniforms[ name ].value = getTexture( uniform.value );
  24022. break;
  24023. case 'c':
  24024. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24025. break;
  24026. case 'v2':
  24027. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24028. break;
  24029. case 'v3':
  24030. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24031. break;
  24032. case 'v4':
  24033. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24034. break;
  24035. case 'm3':
  24036. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24037. break;
  24038. case 'm4':
  24039. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24040. break;
  24041. default:
  24042. material.uniforms[ name ].value = uniform.value;
  24043. }
  24044. }
  24045. }
  24046. if ( json.defines !== undefined ) material.defines = json.defines;
  24047. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24048. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24049. if ( json.extensions !== undefined ) {
  24050. for ( const key in json.extensions ) {
  24051. material.extensions[ key ] = json.extensions[ key ];
  24052. }
  24053. }
  24054. // Deprecated
  24055. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24056. // for PointsMaterial
  24057. if ( json.size !== undefined ) material.size = json.size;
  24058. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24059. // maps
  24060. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24061. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24062. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24063. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24064. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24065. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24066. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24067. if ( json.normalScale !== undefined ) {
  24068. let normalScale = json.normalScale;
  24069. if ( Array.isArray( normalScale ) === false ) {
  24070. // Blender exporter used to export a scalar. See #7459
  24071. normalScale = [ normalScale, normalScale ];
  24072. }
  24073. material.normalScale = new Vector2().fromArray( normalScale );
  24074. }
  24075. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24076. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24077. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24078. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24079. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24080. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24081. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24082. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24083. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24084. if ( json.specularTintMap !== undefined ) material.specularTintMap = getTexture( json.specularTintMap );
  24085. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24086. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24087. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24088. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24089. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24090. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24091. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24092. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24093. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24094. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24095. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24096. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24097. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24098. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24099. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24100. return material;
  24101. }
  24102. setTextures( value ) {
  24103. this.textures = value;
  24104. return this;
  24105. }
  24106. }
  24107. class LoaderUtils {
  24108. static decodeText( array ) {
  24109. if ( typeof TextDecoder !== 'undefined' ) {
  24110. return new TextDecoder().decode( array );
  24111. }
  24112. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24113. // throws a "maximum call stack size exceeded" error for large arrays.
  24114. let s = '';
  24115. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24116. // Implicitly assumes little-endian.
  24117. s += String.fromCharCode( array[ i ] );
  24118. }
  24119. try {
  24120. // merges multi-byte utf-8 characters.
  24121. return decodeURIComponent( escape( s ) );
  24122. } catch ( e ) { // see #16358
  24123. return s;
  24124. }
  24125. }
  24126. static extractUrlBase( url ) {
  24127. const index = url.lastIndexOf( '/' );
  24128. if ( index === - 1 ) return './';
  24129. return url.substr( 0, index + 1 );
  24130. }
  24131. }
  24132. class InstancedBufferGeometry extends BufferGeometry {
  24133. constructor() {
  24134. super();
  24135. this.type = 'InstancedBufferGeometry';
  24136. this.instanceCount = Infinity;
  24137. }
  24138. copy( source ) {
  24139. super.copy( source );
  24140. this.instanceCount = source.instanceCount;
  24141. return this;
  24142. }
  24143. clone() {
  24144. return new this.constructor().copy( this );
  24145. }
  24146. toJSON() {
  24147. const data = super.toJSON( this );
  24148. data.instanceCount = this.instanceCount;
  24149. data.isInstancedBufferGeometry = true;
  24150. return data;
  24151. }
  24152. }
  24153. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24154. class BufferGeometryLoader extends Loader {
  24155. constructor( manager ) {
  24156. super( manager );
  24157. }
  24158. load( url, onLoad, onProgress, onError ) {
  24159. const scope = this;
  24160. const loader = new FileLoader( scope.manager );
  24161. loader.setPath( scope.path );
  24162. loader.setRequestHeader( scope.requestHeader );
  24163. loader.setWithCredentials( scope.withCredentials );
  24164. loader.load( url, function ( text ) {
  24165. try {
  24166. onLoad( scope.parse( JSON.parse( text ) ) );
  24167. } catch ( e ) {
  24168. if ( onError ) {
  24169. onError( e );
  24170. } else {
  24171. console.error( e );
  24172. }
  24173. scope.manager.itemError( url );
  24174. }
  24175. }, onProgress, onError );
  24176. }
  24177. parse( json ) {
  24178. const interleavedBufferMap = {};
  24179. const arrayBufferMap = {};
  24180. function getInterleavedBuffer( json, uuid ) {
  24181. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24182. const interleavedBuffers = json.interleavedBuffers;
  24183. const interleavedBuffer = interleavedBuffers[ uuid ];
  24184. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24185. const array = getTypedArray( interleavedBuffer.type, buffer );
  24186. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24187. ib.uuid = interleavedBuffer.uuid;
  24188. interleavedBufferMap[ uuid ] = ib;
  24189. return ib;
  24190. }
  24191. function getArrayBuffer( json, uuid ) {
  24192. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24193. const arrayBuffers = json.arrayBuffers;
  24194. const arrayBuffer = arrayBuffers[ uuid ];
  24195. const ab = new Uint32Array( arrayBuffer ).buffer;
  24196. arrayBufferMap[ uuid ] = ab;
  24197. return ab;
  24198. }
  24199. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24200. const index = json.data.index;
  24201. if ( index !== undefined ) {
  24202. const typedArray = getTypedArray( index.type, index.array );
  24203. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24204. }
  24205. const attributes = json.data.attributes;
  24206. for ( const key in attributes ) {
  24207. const attribute = attributes[ key ];
  24208. let bufferAttribute;
  24209. if ( attribute.isInterleavedBufferAttribute ) {
  24210. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24211. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24212. } else {
  24213. const typedArray = getTypedArray( attribute.type, attribute.array );
  24214. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24215. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24216. }
  24217. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24218. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24219. if ( attribute.updateRange !== undefined ) {
  24220. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24221. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24222. }
  24223. geometry.setAttribute( key, bufferAttribute );
  24224. }
  24225. const morphAttributes = json.data.morphAttributes;
  24226. if ( morphAttributes ) {
  24227. for ( const key in morphAttributes ) {
  24228. const attributeArray = morphAttributes[ key ];
  24229. const array = [];
  24230. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24231. const attribute = attributeArray[ i ];
  24232. let bufferAttribute;
  24233. if ( attribute.isInterleavedBufferAttribute ) {
  24234. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24235. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24236. } else {
  24237. const typedArray = getTypedArray( attribute.type, attribute.array );
  24238. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24239. }
  24240. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24241. array.push( bufferAttribute );
  24242. }
  24243. geometry.morphAttributes[ key ] = array;
  24244. }
  24245. }
  24246. const morphTargetsRelative = json.data.morphTargetsRelative;
  24247. if ( morphTargetsRelative ) {
  24248. geometry.morphTargetsRelative = true;
  24249. }
  24250. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24251. if ( groups !== undefined ) {
  24252. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24253. const group = groups[ i ];
  24254. geometry.addGroup( group.start, group.count, group.materialIndex );
  24255. }
  24256. }
  24257. const boundingSphere = json.data.boundingSphere;
  24258. if ( boundingSphere !== undefined ) {
  24259. const center = new Vector3();
  24260. if ( boundingSphere.center !== undefined ) {
  24261. center.fromArray( boundingSphere.center );
  24262. }
  24263. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24264. }
  24265. if ( json.name ) geometry.name = json.name;
  24266. if ( json.userData ) geometry.userData = json.userData;
  24267. return geometry;
  24268. }
  24269. }
  24270. class ObjectLoader extends Loader {
  24271. constructor( manager ) {
  24272. super( manager );
  24273. }
  24274. load( url, onLoad, onProgress, onError ) {
  24275. const scope = this;
  24276. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24277. this.resourcePath = this.resourcePath || path;
  24278. const loader = new FileLoader( this.manager );
  24279. loader.setPath( this.path );
  24280. loader.setRequestHeader( this.requestHeader );
  24281. loader.setWithCredentials( this.withCredentials );
  24282. loader.load( url, function ( text ) {
  24283. let json = null;
  24284. try {
  24285. json = JSON.parse( text );
  24286. } catch ( error ) {
  24287. if ( onError !== undefined ) onError( error );
  24288. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24289. return;
  24290. }
  24291. const metadata = json.metadata;
  24292. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24293. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24294. return;
  24295. }
  24296. scope.parse( json, onLoad );
  24297. }, onProgress, onError );
  24298. }
  24299. async loadAsync( url, onProgress ) {
  24300. const scope = this;
  24301. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24302. this.resourcePath = this.resourcePath || path;
  24303. const loader = new FileLoader( this.manager );
  24304. loader.setPath( this.path );
  24305. loader.setRequestHeader( this.requestHeader );
  24306. loader.setWithCredentials( this.withCredentials );
  24307. const text = await loader.loadAsync( url, onProgress );
  24308. const json = JSON.parse( text );
  24309. const metadata = json.metadata;
  24310. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24311. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24312. }
  24313. return await scope.parseAsync( json );
  24314. }
  24315. parse( json, onLoad ) {
  24316. const animations = this.parseAnimations( json.animations );
  24317. const shapes = this.parseShapes( json.shapes );
  24318. const geometries = this.parseGeometries( json.geometries, shapes );
  24319. const images = this.parseImages( json.images, function () {
  24320. if ( onLoad !== undefined ) onLoad( object );
  24321. } );
  24322. const textures = this.parseTextures( json.textures, images );
  24323. const materials = this.parseMaterials( json.materials, textures );
  24324. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24325. const skeletons = this.parseSkeletons( json.skeletons, object );
  24326. this.bindSkeletons( object, skeletons );
  24327. //
  24328. if ( onLoad !== undefined ) {
  24329. let hasImages = false;
  24330. for ( const uuid in images ) {
  24331. if ( images[ uuid ] instanceof HTMLImageElement ) {
  24332. hasImages = true;
  24333. break;
  24334. }
  24335. }
  24336. if ( hasImages === false ) onLoad( object );
  24337. }
  24338. return object;
  24339. }
  24340. async parseAsync( json ) {
  24341. const animations = this.parseAnimations( json.animations );
  24342. const shapes = this.parseShapes( json.shapes );
  24343. const geometries = this.parseGeometries( json.geometries, shapes );
  24344. const images = await this.parseImagesAsync( json.images );
  24345. const textures = this.parseTextures( json.textures, images );
  24346. const materials = this.parseMaterials( json.materials, textures );
  24347. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24348. const skeletons = this.parseSkeletons( json.skeletons, object );
  24349. this.bindSkeletons( object, skeletons );
  24350. return object;
  24351. }
  24352. parseShapes( json ) {
  24353. const shapes = {};
  24354. if ( json !== undefined ) {
  24355. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24356. const shape = new Shape().fromJSON( json[ i ] );
  24357. shapes[ shape.uuid ] = shape;
  24358. }
  24359. }
  24360. return shapes;
  24361. }
  24362. parseSkeletons( json, object ) {
  24363. const skeletons = {};
  24364. const bones = {};
  24365. // generate bone lookup table
  24366. object.traverse( function ( child ) {
  24367. if ( child.isBone ) bones[ child.uuid ] = child;
  24368. } );
  24369. // create skeletons
  24370. if ( json !== undefined ) {
  24371. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24372. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24373. skeletons[ skeleton.uuid ] = skeleton;
  24374. }
  24375. }
  24376. return skeletons;
  24377. }
  24378. parseGeometries( json, shapes ) {
  24379. const geometries = {};
  24380. if ( json !== undefined ) {
  24381. const bufferGeometryLoader = new BufferGeometryLoader();
  24382. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24383. let geometry;
  24384. const data = json[ i ];
  24385. switch ( data.type ) {
  24386. case 'BufferGeometry':
  24387. case 'InstancedBufferGeometry':
  24388. geometry = bufferGeometryLoader.parse( data );
  24389. break;
  24390. case 'Geometry':
  24391. console.error( 'THREE.ObjectLoader: The legacy Geometry type is no longer supported.' );
  24392. break;
  24393. default:
  24394. if ( data.type in Geometries ) {
  24395. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24396. } else {
  24397. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24398. }
  24399. }
  24400. geometry.uuid = data.uuid;
  24401. if ( data.name !== undefined ) geometry.name = data.name;
  24402. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24403. geometries[ data.uuid ] = geometry;
  24404. }
  24405. }
  24406. return geometries;
  24407. }
  24408. parseMaterials( json, textures ) {
  24409. const cache = {}; // MultiMaterial
  24410. const materials = {};
  24411. if ( json !== undefined ) {
  24412. const loader = new MaterialLoader();
  24413. loader.setTextures( textures );
  24414. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24415. const data = json[ i ];
  24416. if ( data.type === 'MultiMaterial' ) {
  24417. // Deprecated
  24418. const array = [];
  24419. for ( let j = 0; j < data.materials.length; j ++ ) {
  24420. const material = data.materials[ j ];
  24421. if ( cache[ material.uuid ] === undefined ) {
  24422. cache[ material.uuid ] = loader.parse( material );
  24423. }
  24424. array.push( cache[ material.uuid ] );
  24425. }
  24426. materials[ data.uuid ] = array;
  24427. } else {
  24428. if ( cache[ data.uuid ] === undefined ) {
  24429. cache[ data.uuid ] = loader.parse( data );
  24430. }
  24431. materials[ data.uuid ] = cache[ data.uuid ];
  24432. }
  24433. }
  24434. }
  24435. return materials;
  24436. }
  24437. parseAnimations( json ) {
  24438. const animations = {};
  24439. if ( json !== undefined ) {
  24440. for ( let i = 0; i < json.length; i ++ ) {
  24441. const data = json[ i ];
  24442. const clip = AnimationClip.parse( data );
  24443. animations[ clip.uuid ] = clip;
  24444. }
  24445. }
  24446. return animations;
  24447. }
  24448. parseImages( json, onLoad ) {
  24449. const scope = this;
  24450. const images = {};
  24451. let loader;
  24452. function loadImage( url ) {
  24453. scope.manager.itemStart( url );
  24454. return loader.load( url, function () {
  24455. scope.manager.itemEnd( url );
  24456. }, undefined, function () {
  24457. scope.manager.itemError( url );
  24458. scope.manager.itemEnd( url );
  24459. } );
  24460. }
  24461. function deserializeImage( image ) {
  24462. if ( typeof image === 'string' ) {
  24463. const url = image;
  24464. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24465. return loadImage( path );
  24466. } else {
  24467. if ( image.data ) {
  24468. return {
  24469. data: getTypedArray( image.type, image.data ),
  24470. width: image.width,
  24471. height: image.height
  24472. };
  24473. } else {
  24474. return null;
  24475. }
  24476. }
  24477. }
  24478. if ( json !== undefined && json.length > 0 ) {
  24479. const manager = new LoadingManager( onLoad );
  24480. loader = new ImageLoader( manager );
  24481. loader.setCrossOrigin( this.crossOrigin );
  24482. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24483. const image = json[ i ];
  24484. const url = image.url;
  24485. if ( Array.isArray( url ) ) {
  24486. // load array of images e.g CubeTexture
  24487. images[ image.uuid ] = [];
  24488. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24489. const currentUrl = url[ j ];
  24490. const deserializedImage = deserializeImage( currentUrl );
  24491. if ( deserializedImage !== null ) {
  24492. if ( deserializedImage instanceof HTMLImageElement ) {
  24493. images[ image.uuid ].push( deserializedImage );
  24494. } else {
  24495. // special case: handle array of data textures for cube textures
  24496. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24497. }
  24498. }
  24499. }
  24500. } else {
  24501. // load single image
  24502. const deserializedImage = deserializeImage( image.url );
  24503. if ( deserializedImage !== null ) {
  24504. images[ image.uuid ] = deserializedImage;
  24505. }
  24506. }
  24507. }
  24508. }
  24509. return images;
  24510. }
  24511. async parseImagesAsync( json ) {
  24512. const scope = this;
  24513. const images = {};
  24514. let loader;
  24515. async function deserializeImage( image ) {
  24516. if ( typeof image === 'string' ) {
  24517. const url = image;
  24518. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24519. return await loader.loadAsync( path );
  24520. } else {
  24521. if ( image.data ) {
  24522. return {
  24523. data: getTypedArray( image.type, image.data ),
  24524. width: image.width,
  24525. height: image.height
  24526. };
  24527. } else {
  24528. return null;
  24529. }
  24530. }
  24531. }
  24532. if ( json !== undefined && json.length > 0 ) {
  24533. loader = new ImageLoader( this.manager );
  24534. loader.setCrossOrigin( this.crossOrigin );
  24535. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24536. const image = json[ i ];
  24537. const url = image.url;
  24538. if ( Array.isArray( url ) ) {
  24539. // load array of images e.g CubeTexture
  24540. images[ image.uuid ] = [];
  24541. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24542. const currentUrl = url[ j ];
  24543. const deserializedImage = await deserializeImage( currentUrl );
  24544. if ( deserializedImage !== null ) {
  24545. if ( deserializedImage instanceof HTMLImageElement ) {
  24546. images[ image.uuid ].push( deserializedImage );
  24547. } else {
  24548. // special case: handle array of data textures for cube textures
  24549. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24550. }
  24551. }
  24552. }
  24553. } else {
  24554. // load single image
  24555. const deserializedImage = await deserializeImage( image.url );
  24556. if ( deserializedImage !== null ) {
  24557. images[ image.uuid ] = deserializedImage;
  24558. }
  24559. }
  24560. }
  24561. }
  24562. return images;
  24563. }
  24564. parseTextures( json, images ) {
  24565. function parseConstant( value, type ) {
  24566. if ( typeof value === 'number' ) return value;
  24567. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24568. return type[ value ];
  24569. }
  24570. const textures = {};
  24571. if ( json !== undefined ) {
  24572. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24573. const data = json[ i ];
  24574. if ( data.image === undefined ) {
  24575. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24576. }
  24577. if ( images[ data.image ] === undefined ) {
  24578. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24579. }
  24580. let texture;
  24581. const image = images[ data.image ];
  24582. if ( Array.isArray( image ) ) {
  24583. texture = new CubeTexture( image );
  24584. if ( image.length === 6 ) texture.needsUpdate = true;
  24585. } else {
  24586. if ( image && image.data ) {
  24587. texture = new DataTexture( image.data, image.width, image.height );
  24588. } else {
  24589. texture = new Texture( image );
  24590. }
  24591. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  24592. }
  24593. texture.uuid = data.uuid;
  24594. if ( data.name !== undefined ) texture.name = data.name;
  24595. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24596. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24597. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24598. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24599. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24600. if ( data.wrap !== undefined ) {
  24601. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24602. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24603. }
  24604. if ( data.format !== undefined ) texture.format = data.format;
  24605. if ( data.type !== undefined ) texture.type = data.type;
  24606. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  24607. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24608. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24609. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24610. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24611. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24612. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24613. textures[ data.uuid ] = texture;
  24614. }
  24615. }
  24616. return textures;
  24617. }
  24618. parseObject( data, geometries, materials, textures, animations ) {
  24619. let object;
  24620. function getGeometry( name ) {
  24621. if ( geometries[ name ] === undefined ) {
  24622. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24623. }
  24624. return geometries[ name ];
  24625. }
  24626. function getMaterial( name ) {
  24627. if ( name === undefined ) return undefined;
  24628. if ( Array.isArray( name ) ) {
  24629. const array = [];
  24630. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24631. const uuid = name[ i ];
  24632. if ( materials[ uuid ] === undefined ) {
  24633. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24634. }
  24635. array.push( materials[ uuid ] );
  24636. }
  24637. return array;
  24638. }
  24639. if ( materials[ name ] === undefined ) {
  24640. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24641. }
  24642. return materials[ name ];
  24643. }
  24644. function getTexture( uuid ) {
  24645. if ( textures[ uuid ] === undefined ) {
  24646. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  24647. }
  24648. return textures[ uuid ];
  24649. }
  24650. let geometry, material;
  24651. switch ( data.type ) {
  24652. case 'Scene':
  24653. object = new Scene();
  24654. if ( data.background !== undefined ) {
  24655. if ( Number.isInteger( data.background ) ) {
  24656. object.background = new Color( data.background );
  24657. } else {
  24658. object.background = getTexture( data.background );
  24659. }
  24660. }
  24661. if ( data.environment !== undefined ) {
  24662. object.environment = getTexture( data.environment );
  24663. }
  24664. if ( data.fog !== undefined ) {
  24665. if ( data.fog.type === 'Fog' ) {
  24666. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24667. } else if ( data.fog.type === 'FogExp2' ) {
  24668. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24669. }
  24670. }
  24671. break;
  24672. case 'PerspectiveCamera':
  24673. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24674. if ( data.focus !== undefined ) object.focus = data.focus;
  24675. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24676. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24677. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24678. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24679. break;
  24680. case 'OrthographicCamera':
  24681. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24682. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24683. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24684. break;
  24685. case 'AmbientLight':
  24686. object = new AmbientLight( data.color, data.intensity );
  24687. break;
  24688. case 'DirectionalLight':
  24689. object = new DirectionalLight( data.color, data.intensity );
  24690. break;
  24691. case 'PointLight':
  24692. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24693. break;
  24694. case 'RectAreaLight':
  24695. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24696. break;
  24697. case 'SpotLight':
  24698. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24699. break;
  24700. case 'HemisphereLight':
  24701. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24702. break;
  24703. case 'LightProbe':
  24704. object = new LightProbe().fromJSON( data );
  24705. break;
  24706. case 'SkinnedMesh':
  24707. geometry = getGeometry( data.geometry );
  24708. material = getMaterial( data.material );
  24709. object = new SkinnedMesh( geometry, material );
  24710. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  24711. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  24712. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  24713. break;
  24714. case 'Mesh':
  24715. geometry = getGeometry( data.geometry );
  24716. material = getMaterial( data.material );
  24717. object = new Mesh( geometry, material );
  24718. break;
  24719. case 'InstancedMesh':
  24720. geometry = getGeometry( data.geometry );
  24721. material = getMaterial( data.material );
  24722. const count = data.count;
  24723. const instanceMatrix = data.instanceMatrix;
  24724. const instanceColor = data.instanceColor;
  24725. object = new InstancedMesh( geometry, material, count );
  24726. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  24727. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  24728. break;
  24729. case 'LOD':
  24730. object = new LOD();
  24731. break;
  24732. case 'Line':
  24733. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  24734. break;
  24735. case 'LineLoop':
  24736. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  24737. break;
  24738. case 'LineSegments':
  24739. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24740. break;
  24741. case 'PointCloud':
  24742. case 'Points':
  24743. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24744. break;
  24745. case 'Sprite':
  24746. object = new Sprite( getMaterial( data.material ) );
  24747. break;
  24748. case 'Group':
  24749. object = new Group();
  24750. break;
  24751. case 'Bone':
  24752. object = new Bone();
  24753. break;
  24754. default:
  24755. object = new Object3D();
  24756. }
  24757. object.uuid = data.uuid;
  24758. if ( data.name !== undefined ) object.name = data.name;
  24759. if ( data.matrix !== undefined ) {
  24760. object.matrix.fromArray( data.matrix );
  24761. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24762. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  24763. } else {
  24764. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24765. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24766. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24767. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24768. }
  24769. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24770. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24771. if ( data.shadow ) {
  24772. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24773. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  24774. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24775. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24776. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24777. }
  24778. if ( data.visible !== undefined ) object.visible = data.visible;
  24779. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  24780. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  24781. if ( data.userData !== undefined ) object.userData = data.userData;
  24782. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  24783. if ( data.children !== undefined ) {
  24784. const children = data.children;
  24785. for ( let i = 0; i < children.length; i ++ ) {
  24786. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  24787. }
  24788. }
  24789. if ( data.animations !== undefined ) {
  24790. const objectAnimations = data.animations;
  24791. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  24792. const uuid = objectAnimations[ i ];
  24793. object.animations.push( animations[ uuid ] );
  24794. }
  24795. }
  24796. if ( data.type === 'LOD' ) {
  24797. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  24798. const levels = data.levels;
  24799. for ( let l = 0; l < levels.length; l ++ ) {
  24800. const level = levels[ l ];
  24801. const child = object.getObjectByProperty( 'uuid', level.object );
  24802. if ( child !== undefined ) {
  24803. object.addLevel( child, level.distance );
  24804. }
  24805. }
  24806. }
  24807. return object;
  24808. }
  24809. bindSkeletons( object, skeletons ) {
  24810. if ( Object.keys( skeletons ).length === 0 ) return;
  24811. object.traverse( function ( child ) {
  24812. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  24813. const skeleton = skeletons[ child.skeleton ];
  24814. if ( skeleton === undefined ) {
  24815. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  24816. } else {
  24817. child.bind( skeleton, child.bindMatrix );
  24818. }
  24819. }
  24820. } );
  24821. }
  24822. /* DEPRECATED */
  24823. setTexturePath( value ) {
  24824. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  24825. return this.setResourcePath( value );
  24826. }
  24827. }
  24828. const TEXTURE_MAPPING = {
  24829. UVMapping: UVMapping,
  24830. CubeReflectionMapping: CubeReflectionMapping,
  24831. CubeRefractionMapping: CubeRefractionMapping,
  24832. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24833. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24834. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24835. CubeUVRefractionMapping: CubeUVRefractionMapping
  24836. };
  24837. const TEXTURE_WRAPPING = {
  24838. RepeatWrapping: RepeatWrapping,
  24839. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24840. MirroredRepeatWrapping: MirroredRepeatWrapping
  24841. };
  24842. const TEXTURE_FILTER = {
  24843. NearestFilter: NearestFilter,
  24844. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24845. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24846. LinearFilter: LinearFilter,
  24847. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24848. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24849. };
  24850. class ImageBitmapLoader extends Loader {
  24851. constructor( manager ) {
  24852. super( manager );
  24853. if ( typeof createImageBitmap === 'undefined' ) {
  24854. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  24855. }
  24856. if ( typeof fetch === 'undefined' ) {
  24857. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  24858. }
  24859. this.options = { premultiplyAlpha: 'none' };
  24860. }
  24861. setOptions( options ) {
  24862. this.options = options;
  24863. return this;
  24864. }
  24865. load( url, onLoad, onProgress, onError ) {
  24866. if ( url === undefined ) url = '';
  24867. if ( this.path !== undefined ) url = this.path + url;
  24868. url = this.manager.resolveURL( url );
  24869. const scope = this;
  24870. const cached = Cache.get( url );
  24871. if ( cached !== undefined ) {
  24872. scope.manager.itemStart( url );
  24873. setTimeout( function () {
  24874. if ( onLoad ) onLoad( cached );
  24875. scope.manager.itemEnd( url );
  24876. }, 0 );
  24877. return cached;
  24878. }
  24879. const fetchOptions = {};
  24880. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  24881. fetchOptions.headers = this.requestHeader;
  24882. fetch( url, fetchOptions ).then( function ( res ) {
  24883. return res.blob();
  24884. } ).then( function ( blob ) {
  24885. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  24886. } ).then( function ( imageBitmap ) {
  24887. Cache.add( url, imageBitmap );
  24888. if ( onLoad ) onLoad( imageBitmap );
  24889. scope.manager.itemEnd( url );
  24890. } ).catch( function ( e ) {
  24891. if ( onError ) onError( e );
  24892. scope.manager.itemError( url );
  24893. scope.manager.itemEnd( url );
  24894. } );
  24895. scope.manager.itemStart( url );
  24896. }
  24897. }
  24898. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24899. class ShapePath {
  24900. constructor() {
  24901. this.type = 'ShapePath';
  24902. this.color = new Color();
  24903. this.subPaths = [];
  24904. this.currentPath = null;
  24905. }
  24906. moveTo( x, y ) {
  24907. this.currentPath = new Path();
  24908. this.subPaths.push( this.currentPath );
  24909. this.currentPath.moveTo( x, y );
  24910. return this;
  24911. }
  24912. lineTo( x, y ) {
  24913. this.currentPath.lineTo( x, y );
  24914. return this;
  24915. }
  24916. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24917. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  24918. return this;
  24919. }
  24920. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24921. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  24922. return this;
  24923. }
  24924. splineThru( pts ) {
  24925. this.currentPath.splineThru( pts );
  24926. return this;
  24927. }
  24928. toShapes( isCCW, noHoles ) {
  24929. function toShapesNoHoles( inSubpaths ) {
  24930. const shapes = [];
  24931. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  24932. const tmpPath = inSubpaths[ i ];
  24933. const tmpShape = new Shape();
  24934. tmpShape.curves = tmpPath.curves;
  24935. shapes.push( tmpShape );
  24936. }
  24937. return shapes;
  24938. }
  24939. function isPointInsidePolygon( inPt, inPolygon ) {
  24940. const polyLen = inPolygon.length;
  24941. // inPt on polygon contour => immediate success or
  24942. // toggling of inside/outside at every single! intersection point of an edge
  24943. // with the horizontal line through inPt, left of inPt
  24944. // not counting lowerY endpoints of edges and whole edges on that line
  24945. let inside = false;
  24946. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  24947. let edgeLowPt = inPolygon[ p ];
  24948. let edgeHighPt = inPolygon[ q ];
  24949. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  24950. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  24951. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  24952. // not parallel
  24953. if ( edgeDy < 0 ) {
  24954. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  24955. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  24956. }
  24957. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  24958. if ( inPt.y === edgeLowPt.y ) {
  24959. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  24960. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24961. } else {
  24962. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  24963. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  24964. if ( perpEdge < 0 ) continue;
  24965. inside = ! inside; // true intersection left of inPt
  24966. }
  24967. } else {
  24968. // parallel or collinear
  24969. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  24970. // edge lies on the same horizontal line as inPt
  24971. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  24972. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  24973. // continue;
  24974. }
  24975. }
  24976. return inside;
  24977. }
  24978. const isClockWise = ShapeUtils.isClockWise;
  24979. const subPaths = this.subPaths;
  24980. if ( subPaths.length === 0 ) return [];
  24981. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  24982. let solid, tmpPath, tmpShape;
  24983. const shapes = [];
  24984. if ( subPaths.length === 1 ) {
  24985. tmpPath = subPaths[ 0 ];
  24986. tmpShape = new Shape();
  24987. tmpShape.curves = tmpPath.curves;
  24988. shapes.push( tmpShape );
  24989. return shapes;
  24990. }
  24991. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  24992. holesFirst = isCCW ? ! holesFirst : holesFirst;
  24993. // console.log("Holes first", holesFirst);
  24994. const betterShapeHoles = [];
  24995. const newShapes = [];
  24996. let newShapeHoles = [];
  24997. let mainIdx = 0;
  24998. let tmpPoints;
  24999. newShapes[ mainIdx ] = undefined;
  25000. newShapeHoles[ mainIdx ] = [];
  25001. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  25002. tmpPath = subPaths[ i ];
  25003. tmpPoints = tmpPath.getPoints();
  25004. solid = isClockWise( tmpPoints );
  25005. solid = isCCW ? ! solid : solid;
  25006. if ( solid ) {
  25007. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25008. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25009. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25010. if ( holesFirst ) mainIdx ++;
  25011. newShapeHoles[ mainIdx ] = [];
  25012. //console.log('cw', i);
  25013. } else {
  25014. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25015. //console.log('ccw', i);
  25016. }
  25017. }
  25018. // only Holes? -> probably all Shapes with wrong orientation
  25019. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25020. if ( newShapes.length > 1 ) {
  25021. let ambiguous = false;
  25022. const toChange = [];
  25023. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25024. betterShapeHoles[ sIdx ] = [];
  25025. }
  25026. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25027. const sho = newShapeHoles[ sIdx ];
  25028. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25029. const ho = sho[ hIdx ];
  25030. let hole_unassigned = true;
  25031. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25032. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25033. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25034. if ( hole_unassigned ) {
  25035. hole_unassigned = false;
  25036. betterShapeHoles[ s2Idx ].push( ho );
  25037. } else {
  25038. ambiguous = true;
  25039. }
  25040. }
  25041. }
  25042. if ( hole_unassigned ) {
  25043. betterShapeHoles[ sIdx ].push( ho );
  25044. }
  25045. }
  25046. }
  25047. // console.log("ambiguous: ", ambiguous);
  25048. if ( toChange.length > 0 ) {
  25049. // console.log("to change: ", toChange);
  25050. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25051. }
  25052. }
  25053. let tmpHoles;
  25054. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  25055. tmpShape = newShapes[ i ].s;
  25056. shapes.push( tmpShape );
  25057. tmpHoles = newShapeHoles[ i ];
  25058. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25059. tmpShape.holes.push( tmpHoles[ j ].h );
  25060. }
  25061. }
  25062. //console.log("shape", shapes);
  25063. return shapes;
  25064. }
  25065. }
  25066. class Font {
  25067. constructor( data ) {
  25068. this.type = 'Font';
  25069. this.data = data;
  25070. }
  25071. generateShapes( text, size = 100 ) {
  25072. const shapes = [];
  25073. const paths = createPaths( text, size, this.data );
  25074. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  25075. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25076. }
  25077. return shapes;
  25078. }
  25079. }
  25080. function createPaths( text, size, data ) {
  25081. const chars = Array.from( text );
  25082. const scale = size / data.resolution;
  25083. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  25084. const paths = [];
  25085. let offsetX = 0, offsetY = 0;
  25086. for ( let i = 0; i < chars.length; i ++ ) {
  25087. const char = chars[ i ];
  25088. if ( char === '\n' ) {
  25089. offsetX = 0;
  25090. offsetY -= line_height;
  25091. } else {
  25092. const ret = createPath( char, scale, offsetX, offsetY, data );
  25093. offsetX += ret.offsetX;
  25094. paths.push( ret.path );
  25095. }
  25096. }
  25097. return paths;
  25098. }
  25099. function createPath( char, scale, offsetX, offsetY, data ) {
  25100. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  25101. if ( ! glyph ) {
  25102. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  25103. return;
  25104. }
  25105. const path = new ShapePath();
  25106. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25107. if ( glyph.o ) {
  25108. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25109. for ( let i = 0, l = outline.length; i < l; ) {
  25110. const action = outline[ i ++ ];
  25111. switch ( action ) {
  25112. case 'm': // moveTo
  25113. x = outline[ i ++ ] * scale + offsetX;
  25114. y = outline[ i ++ ] * scale + offsetY;
  25115. path.moveTo( x, y );
  25116. break;
  25117. case 'l': // lineTo
  25118. x = outline[ i ++ ] * scale + offsetX;
  25119. y = outline[ i ++ ] * scale + offsetY;
  25120. path.lineTo( x, y );
  25121. break;
  25122. case 'q': // quadraticCurveTo
  25123. cpx = outline[ i ++ ] * scale + offsetX;
  25124. cpy = outline[ i ++ ] * scale + offsetY;
  25125. cpx1 = outline[ i ++ ] * scale + offsetX;
  25126. cpy1 = outline[ i ++ ] * scale + offsetY;
  25127. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25128. break;
  25129. case 'b': // bezierCurveTo
  25130. cpx = outline[ i ++ ] * scale + offsetX;
  25131. cpy = outline[ i ++ ] * scale + offsetY;
  25132. cpx1 = outline[ i ++ ] * scale + offsetX;
  25133. cpy1 = outline[ i ++ ] * scale + offsetY;
  25134. cpx2 = outline[ i ++ ] * scale + offsetX;
  25135. cpy2 = outline[ i ++ ] * scale + offsetY;
  25136. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  25137. break;
  25138. }
  25139. }
  25140. }
  25141. return { offsetX: glyph.ha * scale, path: path };
  25142. }
  25143. Font.prototype.isFont = true;
  25144. class FontLoader extends Loader {
  25145. constructor( manager ) {
  25146. super( manager );
  25147. }
  25148. load( url, onLoad, onProgress, onError ) {
  25149. const scope = this;
  25150. const loader = new FileLoader( this.manager );
  25151. loader.setPath( this.path );
  25152. loader.setRequestHeader( this.requestHeader );
  25153. loader.setWithCredentials( scope.withCredentials );
  25154. loader.load( url, function ( text ) {
  25155. let json;
  25156. try {
  25157. json = JSON.parse( text );
  25158. } catch ( e ) {
  25159. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  25160. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  25161. }
  25162. const font = scope.parse( json );
  25163. if ( onLoad ) onLoad( font );
  25164. }, onProgress, onError );
  25165. }
  25166. parse( json ) {
  25167. return new Font( json );
  25168. }
  25169. }
  25170. let _context;
  25171. const AudioContext = {
  25172. getContext: function () {
  25173. if ( _context === undefined ) {
  25174. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25175. }
  25176. return _context;
  25177. },
  25178. setContext: function ( value ) {
  25179. _context = value;
  25180. }
  25181. };
  25182. class AudioLoader extends Loader {
  25183. constructor( manager ) {
  25184. super( manager );
  25185. }
  25186. load( url, onLoad, onProgress, onError ) {
  25187. const scope = this;
  25188. const loader = new FileLoader( this.manager );
  25189. loader.setResponseType( 'arraybuffer' );
  25190. loader.setPath( this.path );
  25191. loader.setRequestHeader( this.requestHeader );
  25192. loader.setWithCredentials( this.withCredentials );
  25193. loader.load( url, function ( buffer ) {
  25194. try {
  25195. // Create a copy of the buffer. The `decodeAudioData` method
  25196. // detaches the buffer when complete, preventing reuse.
  25197. const bufferCopy = buffer.slice( 0 );
  25198. const context = AudioContext.getContext();
  25199. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25200. onLoad( audioBuffer );
  25201. } );
  25202. } catch ( e ) {
  25203. if ( onError ) {
  25204. onError( e );
  25205. } else {
  25206. console.error( e );
  25207. }
  25208. scope.manager.itemError( url );
  25209. }
  25210. }, onProgress, onError );
  25211. }
  25212. }
  25213. class HemisphereLightProbe extends LightProbe {
  25214. constructor( skyColor, groundColor, intensity = 1 ) {
  25215. super( undefined, intensity );
  25216. const color1 = new Color().set( skyColor );
  25217. const color2 = new Color().set( groundColor );
  25218. const sky = new Vector3( color1.r, color1.g, color1.b );
  25219. const ground = new Vector3( color2.r, color2.g, color2.b );
  25220. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25221. const c0 = Math.sqrt( Math.PI );
  25222. const c1 = c0 * Math.sqrt( 0.75 );
  25223. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25224. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25225. }
  25226. }
  25227. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  25228. class AmbientLightProbe extends LightProbe {
  25229. constructor( color, intensity = 1 ) {
  25230. super( undefined, intensity );
  25231. const color1 = new Color().set( color );
  25232. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25233. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25234. }
  25235. }
  25236. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  25237. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25238. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25239. class StereoCamera {
  25240. constructor() {
  25241. this.type = 'StereoCamera';
  25242. this.aspect = 1;
  25243. this.eyeSep = 0.064;
  25244. this.cameraL = new PerspectiveCamera();
  25245. this.cameraL.layers.enable( 1 );
  25246. this.cameraL.matrixAutoUpdate = false;
  25247. this.cameraR = new PerspectiveCamera();
  25248. this.cameraR.layers.enable( 2 );
  25249. this.cameraR.matrixAutoUpdate = false;
  25250. this._cache = {
  25251. focus: null,
  25252. fov: null,
  25253. aspect: null,
  25254. near: null,
  25255. far: null,
  25256. zoom: null,
  25257. eyeSep: null
  25258. };
  25259. }
  25260. update( camera ) {
  25261. const cache = this._cache;
  25262. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25263. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25264. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25265. if ( needsUpdate ) {
  25266. cache.focus = camera.focus;
  25267. cache.fov = camera.fov;
  25268. cache.aspect = camera.aspect * this.aspect;
  25269. cache.near = camera.near;
  25270. cache.far = camera.far;
  25271. cache.zoom = camera.zoom;
  25272. cache.eyeSep = this.eyeSep;
  25273. // Off-axis stereoscopic effect based on
  25274. // http://paulbourke.net/stereographics/stereorender/
  25275. const projectionMatrix = camera.projectionMatrix.clone();
  25276. const eyeSepHalf = cache.eyeSep / 2;
  25277. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25278. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25279. let xmin, xmax;
  25280. // translate xOffset
  25281. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25282. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25283. // for left eye
  25284. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25285. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25286. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25287. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25288. this.cameraL.projectionMatrix.copy( projectionMatrix );
  25289. // for right eye
  25290. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25291. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25292. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25293. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25294. this.cameraR.projectionMatrix.copy( projectionMatrix );
  25295. }
  25296. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25297. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25298. }
  25299. }
  25300. class Clock {
  25301. constructor( autoStart = true ) {
  25302. this.autoStart = autoStart;
  25303. this.startTime = 0;
  25304. this.oldTime = 0;
  25305. this.elapsedTime = 0;
  25306. this.running = false;
  25307. }
  25308. start() {
  25309. this.startTime = now();
  25310. this.oldTime = this.startTime;
  25311. this.elapsedTime = 0;
  25312. this.running = true;
  25313. }
  25314. stop() {
  25315. this.getElapsedTime();
  25316. this.running = false;
  25317. this.autoStart = false;
  25318. }
  25319. getElapsedTime() {
  25320. this.getDelta();
  25321. return this.elapsedTime;
  25322. }
  25323. getDelta() {
  25324. let diff = 0;
  25325. if ( this.autoStart && ! this.running ) {
  25326. this.start();
  25327. return 0;
  25328. }
  25329. if ( this.running ) {
  25330. const newTime = now();
  25331. diff = ( newTime - this.oldTime ) / 1000;
  25332. this.oldTime = newTime;
  25333. this.elapsedTime += diff;
  25334. }
  25335. return diff;
  25336. }
  25337. }
  25338. function now() {
  25339. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25340. }
  25341. const _position$1 = /*@__PURE__*/ new Vector3();
  25342. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25343. const _scale$1 = /*@__PURE__*/ new Vector3();
  25344. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25345. class AudioListener extends Object3D {
  25346. constructor() {
  25347. super();
  25348. this.type = 'AudioListener';
  25349. this.context = AudioContext.getContext();
  25350. this.gain = this.context.createGain();
  25351. this.gain.connect( this.context.destination );
  25352. this.filter = null;
  25353. this.timeDelta = 0;
  25354. // private
  25355. this._clock = new Clock();
  25356. }
  25357. getInput() {
  25358. return this.gain;
  25359. }
  25360. removeFilter() {
  25361. if ( this.filter !== null ) {
  25362. this.gain.disconnect( this.filter );
  25363. this.filter.disconnect( this.context.destination );
  25364. this.gain.connect( this.context.destination );
  25365. this.filter = null;
  25366. }
  25367. return this;
  25368. }
  25369. getFilter() {
  25370. return this.filter;
  25371. }
  25372. setFilter( value ) {
  25373. if ( this.filter !== null ) {
  25374. this.gain.disconnect( this.filter );
  25375. this.filter.disconnect( this.context.destination );
  25376. } else {
  25377. this.gain.disconnect( this.context.destination );
  25378. }
  25379. this.filter = value;
  25380. this.gain.connect( this.filter );
  25381. this.filter.connect( this.context.destination );
  25382. return this;
  25383. }
  25384. getMasterVolume() {
  25385. return this.gain.gain.value;
  25386. }
  25387. setMasterVolume( value ) {
  25388. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25389. return this;
  25390. }
  25391. updateMatrixWorld( force ) {
  25392. super.updateMatrixWorld( force );
  25393. const listener = this.context.listener;
  25394. const up = this.up;
  25395. this.timeDelta = this._clock.getDelta();
  25396. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25397. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  25398. if ( listener.positionX ) {
  25399. // code path for Chrome (see #14393)
  25400. const endTime = this.context.currentTime + this.timeDelta;
  25401. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25402. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25403. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25404. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25405. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25406. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25407. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25408. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25409. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25410. } else {
  25411. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25412. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25413. }
  25414. }
  25415. }
  25416. class Audio extends Object3D {
  25417. constructor( listener ) {
  25418. super();
  25419. this.type = 'Audio';
  25420. this.listener = listener;
  25421. this.context = listener.context;
  25422. this.gain = this.context.createGain();
  25423. this.gain.connect( listener.getInput() );
  25424. this.autoplay = false;
  25425. this.buffer = null;
  25426. this.detune = 0;
  25427. this.loop = false;
  25428. this.loopStart = 0;
  25429. this.loopEnd = 0;
  25430. this.offset = 0;
  25431. this.duration = undefined;
  25432. this.playbackRate = 1;
  25433. this.isPlaying = false;
  25434. this.hasPlaybackControl = true;
  25435. this.source = null;
  25436. this.sourceType = 'empty';
  25437. this._startedAt = 0;
  25438. this._progress = 0;
  25439. this._connected = false;
  25440. this.filters = [];
  25441. }
  25442. getOutput() {
  25443. return this.gain;
  25444. }
  25445. setNodeSource( audioNode ) {
  25446. this.hasPlaybackControl = false;
  25447. this.sourceType = 'audioNode';
  25448. this.source = audioNode;
  25449. this.connect();
  25450. return this;
  25451. }
  25452. setMediaElementSource( mediaElement ) {
  25453. this.hasPlaybackControl = false;
  25454. this.sourceType = 'mediaNode';
  25455. this.source = this.context.createMediaElementSource( mediaElement );
  25456. this.connect();
  25457. return this;
  25458. }
  25459. setMediaStreamSource( mediaStream ) {
  25460. this.hasPlaybackControl = false;
  25461. this.sourceType = 'mediaStreamNode';
  25462. this.source = this.context.createMediaStreamSource( mediaStream );
  25463. this.connect();
  25464. return this;
  25465. }
  25466. setBuffer( audioBuffer ) {
  25467. this.buffer = audioBuffer;
  25468. this.sourceType = 'buffer';
  25469. if ( this.autoplay ) this.play();
  25470. return this;
  25471. }
  25472. play( delay = 0 ) {
  25473. if ( this.isPlaying === true ) {
  25474. console.warn( 'THREE.Audio: Audio is already playing.' );
  25475. return;
  25476. }
  25477. if ( this.hasPlaybackControl === false ) {
  25478. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25479. return;
  25480. }
  25481. this._startedAt = this.context.currentTime + delay;
  25482. const source = this.context.createBufferSource();
  25483. source.buffer = this.buffer;
  25484. source.loop = this.loop;
  25485. source.loopStart = this.loopStart;
  25486. source.loopEnd = this.loopEnd;
  25487. source.onended = this.onEnded.bind( this );
  25488. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25489. this.isPlaying = true;
  25490. this.source = source;
  25491. this.setDetune( this.detune );
  25492. this.setPlaybackRate( this.playbackRate );
  25493. return this.connect();
  25494. }
  25495. pause() {
  25496. if ( this.hasPlaybackControl === false ) {
  25497. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25498. return;
  25499. }
  25500. if ( this.isPlaying === true ) {
  25501. // update current progress
  25502. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25503. if ( this.loop === true ) {
  25504. // ensure _progress does not exceed duration with looped audios
  25505. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25506. }
  25507. this.source.stop();
  25508. this.source.onended = null;
  25509. this.isPlaying = false;
  25510. }
  25511. return this;
  25512. }
  25513. stop() {
  25514. if ( this.hasPlaybackControl === false ) {
  25515. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25516. return;
  25517. }
  25518. this._progress = 0;
  25519. this.source.stop();
  25520. this.source.onended = null;
  25521. this.isPlaying = false;
  25522. return this;
  25523. }
  25524. connect() {
  25525. if ( this.filters.length > 0 ) {
  25526. this.source.connect( this.filters[ 0 ] );
  25527. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25528. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25529. }
  25530. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25531. } else {
  25532. this.source.connect( this.getOutput() );
  25533. }
  25534. this._connected = true;
  25535. return this;
  25536. }
  25537. disconnect() {
  25538. if ( this.filters.length > 0 ) {
  25539. this.source.disconnect( this.filters[ 0 ] );
  25540. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25541. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25542. }
  25543. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25544. } else {
  25545. this.source.disconnect( this.getOutput() );
  25546. }
  25547. this._connected = false;
  25548. return this;
  25549. }
  25550. getFilters() {
  25551. return this.filters;
  25552. }
  25553. setFilters( value ) {
  25554. if ( ! value ) value = [];
  25555. if ( this._connected === true ) {
  25556. this.disconnect();
  25557. this.filters = value.slice();
  25558. this.connect();
  25559. } else {
  25560. this.filters = value.slice();
  25561. }
  25562. return this;
  25563. }
  25564. setDetune( value ) {
  25565. this.detune = value;
  25566. if ( this.source.detune === undefined ) return; // only set detune when available
  25567. if ( this.isPlaying === true ) {
  25568. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25569. }
  25570. return this;
  25571. }
  25572. getDetune() {
  25573. return this.detune;
  25574. }
  25575. getFilter() {
  25576. return this.getFilters()[ 0 ];
  25577. }
  25578. setFilter( filter ) {
  25579. return this.setFilters( filter ? [ filter ] : [] );
  25580. }
  25581. setPlaybackRate( value ) {
  25582. if ( this.hasPlaybackControl === false ) {
  25583. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25584. return;
  25585. }
  25586. this.playbackRate = value;
  25587. if ( this.isPlaying === true ) {
  25588. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25589. }
  25590. return this;
  25591. }
  25592. getPlaybackRate() {
  25593. return this.playbackRate;
  25594. }
  25595. onEnded() {
  25596. this.isPlaying = false;
  25597. }
  25598. getLoop() {
  25599. if ( this.hasPlaybackControl === false ) {
  25600. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25601. return false;
  25602. }
  25603. return this.loop;
  25604. }
  25605. setLoop( value ) {
  25606. if ( this.hasPlaybackControl === false ) {
  25607. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25608. return;
  25609. }
  25610. this.loop = value;
  25611. if ( this.isPlaying === true ) {
  25612. this.source.loop = this.loop;
  25613. }
  25614. return this;
  25615. }
  25616. setLoopStart( value ) {
  25617. this.loopStart = value;
  25618. return this;
  25619. }
  25620. setLoopEnd( value ) {
  25621. this.loopEnd = value;
  25622. return this;
  25623. }
  25624. getVolume() {
  25625. return this.gain.gain.value;
  25626. }
  25627. setVolume( value ) {
  25628. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25629. return this;
  25630. }
  25631. }
  25632. const _position = /*@__PURE__*/ new Vector3();
  25633. const _quaternion = /*@__PURE__*/ new Quaternion();
  25634. const _scale = /*@__PURE__*/ new Vector3();
  25635. const _orientation = /*@__PURE__*/ new Vector3();
  25636. class PositionalAudio extends Audio {
  25637. constructor( listener ) {
  25638. super( listener );
  25639. this.panner = this.context.createPanner();
  25640. this.panner.panningModel = 'HRTF';
  25641. this.panner.connect( this.gain );
  25642. }
  25643. getOutput() {
  25644. return this.panner;
  25645. }
  25646. getRefDistance() {
  25647. return this.panner.refDistance;
  25648. }
  25649. setRefDistance( value ) {
  25650. this.panner.refDistance = value;
  25651. return this;
  25652. }
  25653. getRolloffFactor() {
  25654. return this.panner.rolloffFactor;
  25655. }
  25656. setRolloffFactor( value ) {
  25657. this.panner.rolloffFactor = value;
  25658. return this;
  25659. }
  25660. getDistanceModel() {
  25661. return this.panner.distanceModel;
  25662. }
  25663. setDistanceModel( value ) {
  25664. this.panner.distanceModel = value;
  25665. return this;
  25666. }
  25667. getMaxDistance() {
  25668. return this.panner.maxDistance;
  25669. }
  25670. setMaxDistance( value ) {
  25671. this.panner.maxDistance = value;
  25672. return this;
  25673. }
  25674. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25675. this.panner.coneInnerAngle = coneInnerAngle;
  25676. this.panner.coneOuterAngle = coneOuterAngle;
  25677. this.panner.coneOuterGain = coneOuterGain;
  25678. return this;
  25679. }
  25680. updateMatrixWorld( force ) {
  25681. super.updateMatrixWorld( force );
  25682. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25683. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25684. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25685. const panner = this.panner;
  25686. if ( panner.positionX ) {
  25687. // code path for Chrome and Firefox (see #14393)
  25688. const endTime = this.context.currentTime + this.listener.timeDelta;
  25689. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25690. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25691. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25692. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25693. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25694. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25695. } else {
  25696. panner.setPosition( _position.x, _position.y, _position.z );
  25697. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25698. }
  25699. }
  25700. }
  25701. class AudioAnalyser {
  25702. constructor( audio, fftSize = 2048 ) {
  25703. this.analyser = audio.context.createAnalyser();
  25704. this.analyser.fftSize = fftSize;
  25705. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25706. audio.getOutput().connect( this.analyser );
  25707. }
  25708. getFrequencyData() {
  25709. this.analyser.getByteFrequencyData( this.data );
  25710. return this.data;
  25711. }
  25712. getAverageFrequency() {
  25713. let value = 0;
  25714. const data = this.getFrequencyData();
  25715. for ( let i = 0; i < data.length; i ++ ) {
  25716. value += data[ i ];
  25717. }
  25718. return value / data.length;
  25719. }
  25720. }
  25721. class PropertyMixer {
  25722. constructor( binding, typeName, valueSize ) {
  25723. this.binding = binding;
  25724. this.valueSize = valueSize;
  25725. let mixFunction,
  25726. mixFunctionAdditive,
  25727. setIdentity;
  25728. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25729. //
  25730. // interpolators can use .buffer as their .result
  25731. // the data then goes to 'incoming'
  25732. //
  25733. // 'accu0' and 'accu1' are used frame-interleaved for
  25734. // the cumulative result and are compared to detect
  25735. // changes
  25736. //
  25737. // 'orig' stores the original state of the property
  25738. //
  25739. // 'add' is used for additive cumulative results
  25740. //
  25741. // 'work' is optional and is only present for quaternion types. It is used
  25742. // to store intermediate quaternion multiplication results
  25743. switch ( typeName ) {
  25744. case 'quaternion':
  25745. mixFunction = this._slerp;
  25746. mixFunctionAdditive = this._slerpAdditive;
  25747. setIdentity = this._setAdditiveIdentityQuaternion;
  25748. this.buffer = new Float64Array( valueSize * 6 );
  25749. this._workIndex = 5;
  25750. break;
  25751. case 'string':
  25752. case 'bool':
  25753. mixFunction = this._select;
  25754. // Use the regular mix function and for additive on these types,
  25755. // additive is not relevant for non-numeric types
  25756. mixFunctionAdditive = this._select;
  25757. setIdentity = this._setAdditiveIdentityOther;
  25758. this.buffer = new Array( valueSize * 5 );
  25759. break;
  25760. default:
  25761. mixFunction = this._lerp;
  25762. mixFunctionAdditive = this._lerpAdditive;
  25763. setIdentity = this._setAdditiveIdentityNumeric;
  25764. this.buffer = new Float64Array( valueSize * 5 );
  25765. }
  25766. this._mixBufferRegion = mixFunction;
  25767. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25768. this._setIdentity = setIdentity;
  25769. this._origIndex = 3;
  25770. this._addIndex = 4;
  25771. this.cumulativeWeight = 0;
  25772. this.cumulativeWeightAdditive = 0;
  25773. this.useCount = 0;
  25774. this.referenceCount = 0;
  25775. }
  25776. // accumulate data in the 'incoming' region into 'accu<i>'
  25777. accumulate( accuIndex, weight ) {
  25778. // note: happily accumulating nothing when weight = 0, the caller knows
  25779. // the weight and shouldn't have made the call in the first place
  25780. const buffer = this.buffer,
  25781. stride = this.valueSize,
  25782. offset = accuIndex * stride + stride;
  25783. let currentWeight = this.cumulativeWeight;
  25784. if ( currentWeight === 0 ) {
  25785. // accuN := incoming * weight
  25786. for ( let i = 0; i !== stride; ++ i ) {
  25787. buffer[ offset + i ] = buffer[ i ];
  25788. }
  25789. currentWeight = weight;
  25790. } else {
  25791. // accuN := accuN + incoming * weight
  25792. currentWeight += weight;
  25793. const mix = weight / currentWeight;
  25794. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25795. }
  25796. this.cumulativeWeight = currentWeight;
  25797. }
  25798. // accumulate data in the 'incoming' region into 'add'
  25799. accumulateAdditive( weight ) {
  25800. const buffer = this.buffer,
  25801. stride = this.valueSize,
  25802. offset = stride * this._addIndex;
  25803. if ( this.cumulativeWeightAdditive === 0 ) {
  25804. // add = identity
  25805. this._setIdentity();
  25806. }
  25807. // add := add + incoming * weight
  25808. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25809. this.cumulativeWeightAdditive += weight;
  25810. }
  25811. // apply the state of 'accu<i>' to the binding when accus differ
  25812. apply( accuIndex ) {
  25813. const stride = this.valueSize,
  25814. buffer = this.buffer,
  25815. offset = accuIndex * stride + stride,
  25816. weight = this.cumulativeWeight,
  25817. weightAdditive = this.cumulativeWeightAdditive,
  25818. binding = this.binding;
  25819. this.cumulativeWeight = 0;
  25820. this.cumulativeWeightAdditive = 0;
  25821. if ( weight < 1 ) {
  25822. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25823. const originalValueOffset = stride * this._origIndex;
  25824. this._mixBufferRegion(
  25825. buffer, offset, originalValueOffset, 1 - weight, stride );
  25826. }
  25827. if ( weightAdditive > 0 ) {
  25828. // accuN := accuN + additive accuN
  25829. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25830. }
  25831. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25832. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25833. // value has changed -> update scene graph
  25834. binding.setValue( buffer, offset );
  25835. break;
  25836. }
  25837. }
  25838. }
  25839. // remember the state of the bound property and copy it to both accus
  25840. saveOriginalState() {
  25841. const binding = this.binding;
  25842. const buffer = this.buffer,
  25843. stride = this.valueSize,
  25844. originalValueOffset = stride * this._origIndex;
  25845. binding.getValue( buffer, originalValueOffset );
  25846. // accu[0..1] := orig -- initially detect changes against the original
  25847. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25848. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25849. }
  25850. // Add to identity for additive
  25851. this._setIdentity();
  25852. this.cumulativeWeight = 0;
  25853. this.cumulativeWeightAdditive = 0;
  25854. }
  25855. // apply the state previously taken via 'saveOriginalState' to the binding
  25856. restoreOriginalState() {
  25857. const originalValueOffset = this.valueSize * 3;
  25858. this.binding.setValue( this.buffer, originalValueOffset );
  25859. }
  25860. _setAdditiveIdentityNumeric() {
  25861. const startIndex = this._addIndex * this.valueSize;
  25862. const endIndex = startIndex + this.valueSize;
  25863. for ( let i = startIndex; i < endIndex; i ++ ) {
  25864. this.buffer[ i ] = 0;
  25865. }
  25866. }
  25867. _setAdditiveIdentityQuaternion() {
  25868. this._setAdditiveIdentityNumeric();
  25869. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  25870. }
  25871. _setAdditiveIdentityOther() {
  25872. const startIndex = this._origIndex * this.valueSize;
  25873. const targetIndex = this._addIndex * this.valueSize;
  25874. for ( let i = 0; i < this.valueSize; i ++ ) {
  25875. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  25876. }
  25877. }
  25878. // mix functions
  25879. _select( buffer, dstOffset, srcOffset, t, stride ) {
  25880. if ( t >= 0.5 ) {
  25881. for ( let i = 0; i !== stride; ++ i ) {
  25882. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  25883. }
  25884. }
  25885. }
  25886. _slerp( buffer, dstOffset, srcOffset, t ) {
  25887. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  25888. }
  25889. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25890. const workOffset = this._workIndex * stride;
  25891. // Store result in intermediate buffer offset
  25892. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  25893. // Slerp to the intermediate result
  25894. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  25895. }
  25896. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  25897. const s = 1 - t;
  25898. for ( let i = 0; i !== stride; ++ i ) {
  25899. const j = dstOffset + i;
  25900. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  25901. }
  25902. }
  25903. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25904. for ( let i = 0; i !== stride; ++ i ) {
  25905. const j = dstOffset + i;
  25906. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  25907. }
  25908. }
  25909. }
  25910. // Characters [].:/ are reserved for track binding syntax.
  25911. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25912. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  25913. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25914. // only latin characters, and the unicode \p{L} is not yet supported. So
  25915. // instead, we exclude reserved characters and match everything else.
  25916. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25917. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  25918. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25919. // be matched to parse the rest of the track name.
  25920. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  25921. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25922. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  25923. // Object on target node, and accessor. May not contain reserved
  25924. // characters. Accessor may contain any character except closing bracket.
  25925. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  25926. // Property and accessor. May not contain reserved characters. Accessor may
  25927. // contain any non-bracket characters.
  25928. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  25929. const _trackRe = new RegExp( ''
  25930. + '^'
  25931. + _directoryRe
  25932. + _nodeRe
  25933. + _objectRe
  25934. + _propertyRe
  25935. + '$'
  25936. );
  25937. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  25938. class Composite {
  25939. constructor( targetGroup, path, optionalParsedPath ) {
  25940. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  25941. this._targetGroup = targetGroup;
  25942. this._bindings = targetGroup.subscribe_( path, parsedPath );
  25943. }
  25944. getValue( array, offset ) {
  25945. this.bind(); // bind all binding
  25946. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25947. binding = this._bindings[ firstValidIndex ];
  25948. // and only call .getValue on the first
  25949. if ( binding !== undefined ) binding.getValue( array, offset );
  25950. }
  25951. setValue( array, offset ) {
  25952. const bindings = this._bindings;
  25953. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25954. bindings[ i ].setValue( array, offset );
  25955. }
  25956. }
  25957. bind() {
  25958. const bindings = this._bindings;
  25959. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25960. bindings[ i ].bind();
  25961. }
  25962. }
  25963. unbind() {
  25964. const bindings = this._bindings;
  25965. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25966. bindings[ i ].unbind();
  25967. }
  25968. }
  25969. }
  25970. // Note: This class uses a State pattern on a per-method basis:
  25971. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25972. // prototype version of these methods with one that represents
  25973. // the bound state. When the property is not found, the methods
  25974. // become no-ops.
  25975. class PropertyBinding {
  25976. constructor( rootNode, path, parsedPath ) {
  25977. this.path = path;
  25978. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  25979. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  25980. this.rootNode = rootNode;
  25981. // initial state of these methods that calls 'bind'
  25982. this.getValue = this._getValue_unbound;
  25983. this.setValue = this._setValue_unbound;
  25984. }
  25985. static create( root, path, parsedPath ) {
  25986. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  25987. return new PropertyBinding( root, path, parsedPath );
  25988. } else {
  25989. return new PropertyBinding.Composite( root, path, parsedPath );
  25990. }
  25991. }
  25992. /**
  25993. * Replaces spaces with underscores and removes unsupported characters from
  25994. * node names, to ensure compatibility with parseTrackName().
  25995. *
  25996. * @param {string} name Node name to be sanitized.
  25997. * @return {string}
  25998. */
  25999. static sanitizeNodeName( name ) {
  26000. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26001. }
  26002. static parseTrackName( trackName ) {
  26003. const matches = _trackRe.exec( trackName );
  26004. if ( ! matches ) {
  26005. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26006. }
  26007. const results = {
  26008. // directoryName: matches[ 1 ], // (tschw) currently unused
  26009. nodeName: matches[ 2 ],
  26010. objectName: matches[ 3 ],
  26011. objectIndex: matches[ 4 ],
  26012. propertyName: matches[ 5 ], // required
  26013. propertyIndex: matches[ 6 ]
  26014. };
  26015. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26016. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26017. const objectName = results.nodeName.substring( lastDot + 1 );
  26018. // Object names must be checked against an allowlist. Otherwise, there
  26019. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26020. // 'bar' could be the objectName, or part of a nodeName (which can
  26021. // include '.' characters).
  26022. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26023. results.nodeName = results.nodeName.substring( 0, lastDot );
  26024. results.objectName = objectName;
  26025. }
  26026. }
  26027. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26028. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26029. }
  26030. return results;
  26031. }
  26032. static findNode( root, nodeName ) {
  26033. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26034. return root;
  26035. }
  26036. // search into skeleton bones.
  26037. if ( root.skeleton ) {
  26038. const bone = root.skeleton.getBoneByName( nodeName );
  26039. if ( bone !== undefined ) {
  26040. return bone;
  26041. }
  26042. }
  26043. // search into node subtree.
  26044. if ( root.children ) {
  26045. const searchNodeSubtree = function ( children ) {
  26046. for ( let i = 0; i < children.length; i ++ ) {
  26047. const childNode = children[ i ];
  26048. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26049. return childNode;
  26050. }
  26051. const result = searchNodeSubtree( childNode.children );
  26052. if ( result ) return result;
  26053. }
  26054. return null;
  26055. };
  26056. const subTreeNode = searchNodeSubtree( root.children );
  26057. if ( subTreeNode ) {
  26058. return subTreeNode;
  26059. }
  26060. }
  26061. return null;
  26062. }
  26063. // these are used to "bind" a nonexistent property
  26064. _getValue_unavailable() {}
  26065. _setValue_unavailable() {}
  26066. // Getters
  26067. _getValue_direct( buffer, offset ) {
  26068. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26069. }
  26070. _getValue_array( buffer, offset ) {
  26071. const source = this.resolvedProperty;
  26072. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26073. buffer[ offset ++ ] = source[ i ];
  26074. }
  26075. }
  26076. _getValue_arrayElement( buffer, offset ) {
  26077. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26078. }
  26079. _getValue_toArray( buffer, offset ) {
  26080. this.resolvedProperty.toArray( buffer, offset );
  26081. }
  26082. // Direct
  26083. _setValue_direct( buffer, offset ) {
  26084. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26085. }
  26086. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26087. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26088. this.targetObject.needsUpdate = true;
  26089. }
  26090. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26091. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26092. this.targetObject.matrixWorldNeedsUpdate = true;
  26093. }
  26094. // EntireArray
  26095. _setValue_array( buffer, offset ) {
  26096. const dest = this.resolvedProperty;
  26097. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26098. dest[ i ] = buffer[ offset ++ ];
  26099. }
  26100. }
  26101. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26102. const dest = this.resolvedProperty;
  26103. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26104. dest[ i ] = buffer[ offset ++ ];
  26105. }
  26106. this.targetObject.needsUpdate = true;
  26107. }
  26108. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26109. const dest = this.resolvedProperty;
  26110. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26111. dest[ i ] = buffer[ offset ++ ];
  26112. }
  26113. this.targetObject.matrixWorldNeedsUpdate = true;
  26114. }
  26115. // ArrayElement
  26116. _setValue_arrayElement( buffer, offset ) {
  26117. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26118. }
  26119. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26120. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26121. this.targetObject.needsUpdate = true;
  26122. }
  26123. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26124. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26125. this.targetObject.matrixWorldNeedsUpdate = true;
  26126. }
  26127. // HasToFromArray
  26128. _setValue_fromArray( buffer, offset ) {
  26129. this.resolvedProperty.fromArray( buffer, offset );
  26130. }
  26131. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26132. this.resolvedProperty.fromArray( buffer, offset );
  26133. this.targetObject.needsUpdate = true;
  26134. }
  26135. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26136. this.resolvedProperty.fromArray( buffer, offset );
  26137. this.targetObject.matrixWorldNeedsUpdate = true;
  26138. }
  26139. _getValue_unbound( targetArray, offset ) {
  26140. this.bind();
  26141. this.getValue( targetArray, offset );
  26142. }
  26143. _setValue_unbound( sourceArray, offset ) {
  26144. this.bind();
  26145. this.setValue( sourceArray, offset );
  26146. }
  26147. // create getter / setter pair for a property in the scene graph
  26148. bind() {
  26149. let targetObject = this.node;
  26150. const parsedPath = this.parsedPath;
  26151. const objectName = parsedPath.objectName;
  26152. const propertyName = parsedPath.propertyName;
  26153. let propertyIndex = parsedPath.propertyIndex;
  26154. if ( ! targetObject ) {
  26155. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26156. this.node = targetObject;
  26157. }
  26158. // set fail state so we can just 'return' on error
  26159. this.getValue = this._getValue_unavailable;
  26160. this.setValue = this._setValue_unavailable;
  26161. // ensure there is a value node
  26162. if ( ! targetObject ) {
  26163. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26164. return;
  26165. }
  26166. if ( objectName ) {
  26167. let objectIndex = parsedPath.objectIndex;
  26168. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26169. switch ( objectName ) {
  26170. case 'materials':
  26171. if ( ! targetObject.material ) {
  26172. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26173. return;
  26174. }
  26175. if ( ! targetObject.material.materials ) {
  26176. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26177. return;
  26178. }
  26179. targetObject = targetObject.material.materials;
  26180. break;
  26181. case 'bones':
  26182. if ( ! targetObject.skeleton ) {
  26183. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26184. return;
  26185. }
  26186. // potential future optimization: skip this if propertyIndex is already an integer
  26187. // and convert the integer string to a true integer.
  26188. targetObject = targetObject.skeleton.bones;
  26189. // support resolving morphTarget names into indices.
  26190. for ( let i = 0; i < targetObject.length; i ++ ) {
  26191. if ( targetObject[ i ].name === objectIndex ) {
  26192. objectIndex = i;
  26193. break;
  26194. }
  26195. }
  26196. break;
  26197. default:
  26198. if ( targetObject[ objectName ] === undefined ) {
  26199. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26200. return;
  26201. }
  26202. targetObject = targetObject[ objectName ];
  26203. }
  26204. if ( objectIndex !== undefined ) {
  26205. if ( targetObject[ objectIndex ] === undefined ) {
  26206. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26207. return;
  26208. }
  26209. targetObject = targetObject[ objectIndex ];
  26210. }
  26211. }
  26212. // resolve property
  26213. const nodeProperty = targetObject[ propertyName ];
  26214. if ( nodeProperty === undefined ) {
  26215. const nodeName = parsedPath.nodeName;
  26216. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26217. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26218. return;
  26219. }
  26220. // determine versioning scheme
  26221. let versioning = this.Versioning.None;
  26222. this.targetObject = targetObject;
  26223. if ( targetObject.needsUpdate !== undefined ) { // material
  26224. versioning = this.Versioning.NeedsUpdate;
  26225. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26226. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26227. }
  26228. // determine how the property gets bound
  26229. let bindingType = this.BindingType.Direct;
  26230. if ( propertyIndex !== undefined ) {
  26231. // access a sub element of the property array (only primitives are supported right now)
  26232. if ( propertyName === 'morphTargetInfluences' ) {
  26233. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26234. // support resolving morphTarget names into indices.
  26235. if ( ! targetObject.geometry ) {
  26236. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26237. return;
  26238. }
  26239. if ( targetObject.geometry.isBufferGeometry ) {
  26240. if ( ! targetObject.geometry.morphAttributes ) {
  26241. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26242. return;
  26243. }
  26244. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26245. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26246. }
  26247. } else {
  26248. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  26249. return;
  26250. }
  26251. }
  26252. bindingType = this.BindingType.ArrayElement;
  26253. this.resolvedProperty = nodeProperty;
  26254. this.propertyIndex = propertyIndex;
  26255. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26256. // must use copy for Object3D.Euler/Quaternion
  26257. bindingType = this.BindingType.HasFromToArray;
  26258. this.resolvedProperty = nodeProperty;
  26259. } else if ( Array.isArray( nodeProperty ) ) {
  26260. bindingType = this.BindingType.EntireArray;
  26261. this.resolvedProperty = nodeProperty;
  26262. } else {
  26263. this.propertyName = propertyName;
  26264. }
  26265. // select getter / setter
  26266. this.getValue = this.GetterByBindingType[ bindingType ];
  26267. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26268. }
  26269. unbind() {
  26270. this.node = null;
  26271. // back to the prototype version of getValue / setValue
  26272. // note: avoiding to mutate the shape of 'this' via 'delete'
  26273. this.getValue = this._getValue_unbound;
  26274. this.setValue = this._setValue_unbound;
  26275. }
  26276. }
  26277. PropertyBinding.Composite = Composite;
  26278. PropertyBinding.prototype.BindingType = {
  26279. Direct: 0,
  26280. EntireArray: 1,
  26281. ArrayElement: 2,
  26282. HasFromToArray: 3
  26283. };
  26284. PropertyBinding.prototype.Versioning = {
  26285. None: 0,
  26286. NeedsUpdate: 1,
  26287. MatrixWorldNeedsUpdate: 2
  26288. };
  26289. PropertyBinding.prototype.GetterByBindingType = [
  26290. PropertyBinding.prototype._getValue_direct,
  26291. PropertyBinding.prototype._getValue_array,
  26292. PropertyBinding.prototype._getValue_arrayElement,
  26293. PropertyBinding.prototype._getValue_toArray,
  26294. ];
  26295. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26296. [
  26297. // Direct
  26298. PropertyBinding.prototype._setValue_direct,
  26299. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26300. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26301. ], [
  26302. // EntireArray
  26303. PropertyBinding.prototype._setValue_array,
  26304. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26305. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26306. ], [
  26307. // ArrayElement
  26308. PropertyBinding.prototype._setValue_arrayElement,
  26309. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26310. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26311. ], [
  26312. // HasToFromArray
  26313. PropertyBinding.prototype._setValue_fromArray,
  26314. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26315. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26316. ]
  26317. ];
  26318. /**
  26319. *
  26320. * A group of objects that receives a shared animation state.
  26321. *
  26322. * Usage:
  26323. *
  26324. * - Add objects you would otherwise pass as 'root' to the
  26325. * constructor or the .clipAction method of AnimationMixer.
  26326. *
  26327. * - Instead pass this object as 'root'.
  26328. *
  26329. * - You can also add and remove objects later when the mixer
  26330. * is running.
  26331. *
  26332. * Note:
  26333. *
  26334. * Objects of this class appear as one object to the mixer,
  26335. * so cache control of the individual objects must be done
  26336. * on the group.
  26337. *
  26338. * Limitation:
  26339. *
  26340. * - The animated properties must be compatible among the
  26341. * all objects in the group.
  26342. *
  26343. * - A single property can either be controlled through a
  26344. * target group or directly, but not both.
  26345. */
  26346. class AnimationObjectGroup {
  26347. constructor() {
  26348. this.uuid = generateUUID();
  26349. // cached objects followed by the active ones
  26350. this._objects = Array.prototype.slice.call( arguments );
  26351. this.nCachedObjects_ = 0; // threshold
  26352. // note: read by PropertyBinding.Composite
  26353. const indices = {};
  26354. this._indicesByUUID = indices; // for bookkeeping
  26355. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26356. indices[ arguments[ i ].uuid ] = i;
  26357. }
  26358. this._paths = []; // inside: string
  26359. this._parsedPaths = []; // inside: { we don't care, here }
  26360. this._bindings = []; // inside: Array< PropertyBinding >
  26361. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26362. const scope = this;
  26363. this.stats = {
  26364. objects: {
  26365. get total() {
  26366. return scope._objects.length;
  26367. },
  26368. get inUse() {
  26369. return this.total - scope.nCachedObjects_;
  26370. }
  26371. },
  26372. get bindingsPerObject() {
  26373. return scope._bindings.length;
  26374. }
  26375. };
  26376. }
  26377. add() {
  26378. const objects = this._objects,
  26379. indicesByUUID = this._indicesByUUID,
  26380. paths = this._paths,
  26381. parsedPaths = this._parsedPaths,
  26382. bindings = this._bindings,
  26383. nBindings = bindings.length;
  26384. let knownObject = undefined,
  26385. nObjects = objects.length,
  26386. nCachedObjects = this.nCachedObjects_;
  26387. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26388. const object = arguments[ i ],
  26389. uuid = object.uuid;
  26390. let index = indicesByUUID[ uuid ];
  26391. if ( index === undefined ) {
  26392. // unknown object -> add it to the ACTIVE region
  26393. index = nObjects ++;
  26394. indicesByUUID[ uuid ] = index;
  26395. objects.push( object );
  26396. // accounting is done, now do the same for all bindings
  26397. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26398. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26399. }
  26400. } else if ( index < nCachedObjects ) {
  26401. knownObject = objects[ index ];
  26402. // move existing object to the ACTIVE region
  26403. const firstActiveIndex = -- nCachedObjects,
  26404. lastCachedObject = objects[ firstActiveIndex ];
  26405. indicesByUUID[ lastCachedObject.uuid ] = index;
  26406. objects[ index ] = lastCachedObject;
  26407. indicesByUUID[ uuid ] = firstActiveIndex;
  26408. objects[ firstActiveIndex ] = object;
  26409. // accounting is done, now do the same for all bindings
  26410. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26411. const bindingsForPath = bindings[ j ],
  26412. lastCached = bindingsForPath[ firstActiveIndex ];
  26413. let binding = bindingsForPath[ index ];
  26414. bindingsForPath[ index ] = lastCached;
  26415. if ( binding === undefined ) {
  26416. // since we do not bother to create new bindings
  26417. // for objects that are cached, the binding may
  26418. // or may not exist
  26419. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26420. }
  26421. bindingsForPath[ firstActiveIndex ] = binding;
  26422. }
  26423. } else if ( objects[ index ] !== knownObject ) {
  26424. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26425. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26426. } // else the object is already where we want it to be
  26427. } // for arguments
  26428. this.nCachedObjects_ = nCachedObjects;
  26429. }
  26430. remove() {
  26431. const objects = this._objects,
  26432. indicesByUUID = this._indicesByUUID,
  26433. bindings = this._bindings,
  26434. nBindings = bindings.length;
  26435. let nCachedObjects = this.nCachedObjects_;
  26436. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26437. const object = arguments[ i ],
  26438. uuid = object.uuid,
  26439. index = indicesByUUID[ uuid ];
  26440. if ( index !== undefined && index >= nCachedObjects ) {
  26441. // move existing object into the CACHED region
  26442. const lastCachedIndex = nCachedObjects ++,
  26443. firstActiveObject = objects[ lastCachedIndex ];
  26444. indicesByUUID[ firstActiveObject.uuid ] = index;
  26445. objects[ index ] = firstActiveObject;
  26446. indicesByUUID[ uuid ] = lastCachedIndex;
  26447. objects[ lastCachedIndex ] = object;
  26448. // accounting is done, now do the same for all bindings
  26449. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26450. const bindingsForPath = bindings[ j ],
  26451. firstActive = bindingsForPath[ lastCachedIndex ],
  26452. binding = bindingsForPath[ index ];
  26453. bindingsForPath[ index ] = firstActive;
  26454. bindingsForPath[ lastCachedIndex ] = binding;
  26455. }
  26456. }
  26457. } // for arguments
  26458. this.nCachedObjects_ = nCachedObjects;
  26459. }
  26460. // remove & forget
  26461. uncache() {
  26462. const objects = this._objects,
  26463. indicesByUUID = this._indicesByUUID,
  26464. bindings = this._bindings,
  26465. nBindings = bindings.length;
  26466. let nCachedObjects = this.nCachedObjects_,
  26467. nObjects = objects.length;
  26468. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26469. const object = arguments[ i ],
  26470. uuid = object.uuid,
  26471. index = indicesByUUID[ uuid ];
  26472. if ( index !== undefined ) {
  26473. delete indicesByUUID[ uuid ];
  26474. if ( index < nCachedObjects ) {
  26475. // object is cached, shrink the CACHED region
  26476. const firstActiveIndex = -- nCachedObjects,
  26477. lastCachedObject = objects[ firstActiveIndex ],
  26478. lastIndex = -- nObjects,
  26479. lastObject = objects[ lastIndex ];
  26480. // last cached object takes this object's place
  26481. indicesByUUID[ lastCachedObject.uuid ] = index;
  26482. objects[ index ] = lastCachedObject;
  26483. // last object goes to the activated slot and pop
  26484. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26485. objects[ firstActiveIndex ] = lastObject;
  26486. objects.pop();
  26487. // accounting is done, now do the same for all bindings
  26488. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26489. const bindingsForPath = bindings[ j ],
  26490. lastCached = bindingsForPath[ firstActiveIndex ],
  26491. last = bindingsForPath[ lastIndex ];
  26492. bindingsForPath[ index ] = lastCached;
  26493. bindingsForPath[ firstActiveIndex ] = last;
  26494. bindingsForPath.pop();
  26495. }
  26496. } else {
  26497. // object is active, just swap with the last and pop
  26498. const lastIndex = -- nObjects,
  26499. lastObject = objects[ lastIndex ];
  26500. if ( lastIndex > 0 ) {
  26501. indicesByUUID[ lastObject.uuid ] = index;
  26502. }
  26503. objects[ index ] = lastObject;
  26504. objects.pop();
  26505. // accounting is done, now do the same for all bindings
  26506. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26507. const bindingsForPath = bindings[ j ];
  26508. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26509. bindingsForPath.pop();
  26510. }
  26511. } // cached or active
  26512. } // if object is known
  26513. } // for arguments
  26514. this.nCachedObjects_ = nCachedObjects;
  26515. }
  26516. // Internal interface used by befriended PropertyBinding.Composite:
  26517. subscribe_( path, parsedPath ) {
  26518. // returns an array of bindings for the given path that is changed
  26519. // according to the contained objects in the group
  26520. const indicesByPath = this._bindingsIndicesByPath;
  26521. let index = indicesByPath[ path ];
  26522. const bindings = this._bindings;
  26523. if ( index !== undefined ) return bindings[ index ];
  26524. const paths = this._paths,
  26525. parsedPaths = this._parsedPaths,
  26526. objects = this._objects,
  26527. nObjects = objects.length,
  26528. nCachedObjects = this.nCachedObjects_,
  26529. bindingsForPath = new Array( nObjects );
  26530. index = bindings.length;
  26531. indicesByPath[ path ] = index;
  26532. paths.push( path );
  26533. parsedPaths.push( parsedPath );
  26534. bindings.push( bindingsForPath );
  26535. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26536. const object = objects[ i ];
  26537. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26538. }
  26539. return bindingsForPath;
  26540. }
  26541. unsubscribe_( path ) {
  26542. // tells the group to forget about a property path and no longer
  26543. // update the array previously obtained with 'subscribe_'
  26544. const indicesByPath = this._bindingsIndicesByPath,
  26545. index = indicesByPath[ path ];
  26546. if ( index !== undefined ) {
  26547. const paths = this._paths,
  26548. parsedPaths = this._parsedPaths,
  26549. bindings = this._bindings,
  26550. lastBindingsIndex = bindings.length - 1,
  26551. lastBindings = bindings[ lastBindingsIndex ],
  26552. lastBindingsPath = path[ lastBindingsIndex ];
  26553. indicesByPath[ lastBindingsPath ] = index;
  26554. bindings[ index ] = lastBindings;
  26555. bindings.pop();
  26556. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26557. parsedPaths.pop();
  26558. paths[ index ] = paths[ lastBindingsIndex ];
  26559. paths.pop();
  26560. }
  26561. }
  26562. }
  26563. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26564. class AnimationAction {
  26565. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26566. this._mixer = mixer;
  26567. this._clip = clip;
  26568. this._localRoot = localRoot;
  26569. this.blendMode = blendMode;
  26570. const tracks = clip.tracks,
  26571. nTracks = tracks.length,
  26572. interpolants = new Array( nTracks );
  26573. const interpolantSettings = {
  26574. endingStart: ZeroCurvatureEnding,
  26575. endingEnd: ZeroCurvatureEnding
  26576. };
  26577. for ( let i = 0; i !== nTracks; ++ i ) {
  26578. const interpolant = tracks[ i ].createInterpolant( null );
  26579. interpolants[ i ] = interpolant;
  26580. interpolant.settings = interpolantSettings;
  26581. }
  26582. this._interpolantSettings = interpolantSettings;
  26583. this._interpolants = interpolants; // bound by the mixer
  26584. // inside: PropertyMixer (managed by the mixer)
  26585. this._propertyBindings = new Array( nTracks );
  26586. this._cacheIndex = null; // for the memory manager
  26587. this._byClipCacheIndex = null; // for the memory manager
  26588. this._timeScaleInterpolant = null;
  26589. this._weightInterpolant = null;
  26590. this.loop = LoopRepeat;
  26591. this._loopCount = - 1;
  26592. // global mixer time when the action is to be started
  26593. // it's set back to 'null' upon start of the action
  26594. this._startTime = null;
  26595. // scaled local time of the action
  26596. // gets clamped or wrapped to 0..clip.duration according to loop
  26597. this.time = 0;
  26598. this.timeScale = 1;
  26599. this._effectiveTimeScale = 1;
  26600. this.weight = 1;
  26601. this._effectiveWeight = 1;
  26602. this.repetitions = Infinity; // no. of repetitions when looping
  26603. this.paused = false; // true -> zero effective time scale
  26604. this.enabled = true; // false -> zero effective weight
  26605. this.clampWhenFinished = false;// keep feeding the last frame?
  26606. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26607. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26608. }
  26609. // State & Scheduling
  26610. play() {
  26611. this._mixer._activateAction( this );
  26612. return this;
  26613. }
  26614. stop() {
  26615. this._mixer._deactivateAction( this );
  26616. return this.reset();
  26617. }
  26618. reset() {
  26619. this.paused = false;
  26620. this.enabled = true;
  26621. this.time = 0; // restart clip
  26622. this._loopCount = - 1;// forget previous loops
  26623. this._startTime = null;// forget scheduling
  26624. return this.stopFading().stopWarping();
  26625. }
  26626. isRunning() {
  26627. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26628. this._startTime === null && this._mixer._isActiveAction( this );
  26629. }
  26630. // return true when play has been called
  26631. isScheduled() {
  26632. return this._mixer._isActiveAction( this );
  26633. }
  26634. startAt( time ) {
  26635. this._startTime = time;
  26636. return this;
  26637. }
  26638. setLoop( mode, repetitions ) {
  26639. this.loop = mode;
  26640. this.repetitions = repetitions;
  26641. return this;
  26642. }
  26643. // Weight
  26644. // set the weight stopping any scheduled fading
  26645. // although .enabled = false yields an effective weight of zero, this
  26646. // method does *not* change .enabled, because it would be confusing
  26647. setEffectiveWeight( weight ) {
  26648. this.weight = weight;
  26649. // note: same logic as when updated at runtime
  26650. this._effectiveWeight = this.enabled ? weight : 0;
  26651. return this.stopFading();
  26652. }
  26653. // return the weight considering fading and .enabled
  26654. getEffectiveWeight() {
  26655. return this._effectiveWeight;
  26656. }
  26657. fadeIn( duration ) {
  26658. return this._scheduleFading( duration, 0, 1 );
  26659. }
  26660. fadeOut( duration ) {
  26661. return this._scheduleFading( duration, 1, 0 );
  26662. }
  26663. crossFadeFrom( fadeOutAction, duration, warp ) {
  26664. fadeOutAction.fadeOut( duration );
  26665. this.fadeIn( duration );
  26666. if ( warp ) {
  26667. const fadeInDuration = this._clip.duration,
  26668. fadeOutDuration = fadeOutAction._clip.duration,
  26669. startEndRatio = fadeOutDuration / fadeInDuration,
  26670. endStartRatio = fadeInDuration / fadeOutDuration;
  26671. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26672. this.warp( endStartRatio, 1.0, duration );
  26673. }
  26674. return this;
  26675. }
  26676. crossFadeTo( fadeInAction, duration, warp ) {
  26677. return fadeInAction.crossFadeFrom( this, duration, warp );
  26678. }
  26679. stopFading() {
  26680. const weightInterpolant = this._weightInterpolant;
  26681. if ( weightInterpolant !== null ) {
  26682. this._weightInterpolant = null;
  26683. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26684. }
  26685. return this;
  26686. }
  26687. // Time Scale Control
  26688. // set the time scale stopping any scheduled warping
  26689. // although .paused = true yields an effective time scale of zero, this
  26690. // method does *not* change .paused, because it would be confusing
  26691. setEffectiveTimeScale( timeScale ) {
  26692. this.timeScale = timeScale;
  26693. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26694. return this.stopWarping();
  26695. }
  26696. // return the time scale considering warping and .paused
  26697. getEffectiveTimeScale() {
  26698. return this._effectiveTimeScale;
  26699. }
  26700. setDuration( duration ) {
  26701. this.timeScale = this._clip.duration / duration;
  26702. return this.stopWarping();
  26703. }
  26704. syncWith( action ) {
  26705. this.time = action.time;
  26706. this.timeScale = action.timeScale;
  26707. return this.stopWarping();
  26708. }
  26709. halt( duration ) {
  26710. return this.warp( this._effectiveTimeScale, 0, duration );
  26711. }
  26712. warp( startTimeScale, endTimeScale, duration ) {
  26713. const mixer = this._mixer,
  26714. now = mixer.time,
  26715. timeScale = this.timeScale;
  26716. let interpolant = this._timeScaleInterpolant;
  26717. if ( interpolant === null ) {
  26718. interpolant = mixer._lendControlInterpolant();
  26719. this._timeScaleInterpolant = interpolant;
  26720. }
  26721. const times = interpolant.parameterPositions,
  26722. values = interpolant.sampleValues;
  26723. times[ 0 ] = now;
  26724. times[ 1 ] = now + duration;
  26725. values[ 0 ] = startTimeScale / timeScale;
  26726. values[ 1 ] = endTimeScale / timeScale;
  26727. return this;
  26728. }
  26729. stopWarping() {
  26730. const timeScaleInterpolant = this._timeScaleInterpolant;
  26731. if ( timeScaleInterpolant !== null ) {
  26732. this._timeScaleInterpolant = null;
  26733. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26734. }
  26735. return this;
  26736. }
  26737. // Object Accessors
  26738. getMixer() {
  26739. return this._mixer;
  26740. }
  26741. getClip() {
  26742. return this._clip;
  26743. }
  26744. getRoot() {
  26745. return this._localRoot || this._mixer._root;
  26746. }
  26747. // Interna
  26748. _update( time, deltaTime, timeDirection, accuIndex ) {
  26749. // called by the mixer
  26750. if ( ! this.enabled ) {
  26751. // call ._updateWeight() to update ._effectiveWeight
  26752. this._updateWeight( time );
  26753. return;
  26754. }
  26755. const startTime = this._startTime;
  26756. if ( startTime !== null ) {
  26757. // check for scheduled start of action
  26758. const timeRunning = ( time - startTime ) * timeDirection;
  26759. if ( timeRunning < 0 || timeDirection === 0 ) {
  26760. return; // yet to come / don't decide when delta = 0
  26761. }
  26762. // start
  26763. this._startTime = null; // unschedule
  26764. deltaTime = timeDirection * timeRunning;
  26765. }
  26766. // apply time scale and advance time
  26767. deltaTime *= this._updateTimeScale( time );
  26768. const clipTime = this._updateTime( deltaTime );
  26769. // note: _updateTime may disable the action resulting in
  26770. // an effective weight of 0
  26771. const weight = this._updateWeight( time );
  26772. if ( weight > 0 ) {
  26773. const interpolants = this._interpolants;
  26774. const propertyMixers = this._propertyBindings;
  26775. switch ( this.blendMode ) {
  26776. case AdditiveAnimationBlendMode:
  26777. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26778. interpolants[ j ].evaluate( clipTime );
  26779. propertyMixers[ j ].accumulateAdditive( weight );
  26780. }
  26781. break;
  26782. case NormalAnimationBlendMode:
  26783. default:
  26784. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26785. interpolants[ j ].evaluate( clipTime );
  26786. propertyMixers[ j ].accumulate( accuIndex, weight );
  26787. }
  26788. }
  26789. }
  26790. }
  26791. _updateWeight( time ) {
  26792. let weight = 0;
  26793. if ( this.enabled ) {
  26794. weight = this.weight;
  26795. const interpolant = this._weightInterpolant;
  26796. if ( interpolant !== null ) {
  26797. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26798. weight *= interpolantValue;
  26799. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26800. this.stopFading();
  26801. if ( interpolantValue === 0 ) {
  26802. // faded out, disable
  26803. this.enabled = false;
  26804. }
  26805. }
  26806. }
  26807. }
  26808. this._effectiveWeight = weight;
  26809. return weight;
  26810. }
  26811. _updateTimeScale( time ) {
  26812. let timeScale = 0;
  26813. if ( ! this.paused ) {
  26814. timeScale = this.timeScale;
  26815. const interpolant = this._timeScaleInterpolant;
  26816. if ( interpolant !== null ) {
  26817. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26818. timeScale *= interpolantValue;
  26819. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26820. this.stopWarping();
  26821. if ( timeScale === 0 ) {
  26822. // motion has halted, pause
  26823. this.paused = true;
  26824. } else {
  26825. // warp done - apply final time scale
  26826. this.timeScale = timeScale;
  26827. }
  26828. }
  26829. }
  26830. }
  26831. this._effectiveTimeScale = timeScale;
  26832. return timeScale;
  26833. }
  26834. _updateTime( deltaTime ) {
  26835. const duration = this._clip.duration;
  26836. const loop = this.loop;
  26837. let time = this.time + deltaTime;
  26838. let loopCount = this._loopCount;
  26839. const pingPong = ( loop === LoopPingPong );
  26840. if ( deltaTime === 0 ) {
  26841. if ( loopCount === - 1 ) return time;
  26842. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26843. }
  26844. if ( loop === LoopOnce ) {
  26845. if ( loopCount === - 1 ) {
  26846. // just started
  26847. this._loopCount = 0;
  26848. this._setEndings( true, true, false );
  26849. }
  26850. handle_stop: {
  26851. if ( time >= duration ) {
  26852. time = duration;
  26853. } else if ( time < 0 ) {
  26854. time = 0;
  26855. } else {
  26856. this.time = time;
  26857. break handle_stop;
  26858. }
  26859. if ( this.clampWhenFinished ) this.paused = true;
  26860. else this.enabled = false;
  26861. this.time = time;
  26862. this._mixer.dispatchEvent( {
  26863. type: 'finished', action: this,
  26864. direction: deltaTime < 0 ? - 1 : 1
  26865. } );
  26866. }
  26867. } else { // repetitive Repeat or PingPong
  26868. if ( loopCount === - 1 ) {
  26869. // just started
  26870. if ( deltaTime >= 0 ) {
  26871. loopCount = 0;
  26872. this._setEndings( true, this.repetitions === 0, pingPong );
  26873. } else {
  26874. // when looping in reverse direction, the initial
  26875. // transition through zero counts as a repetition,
  26876. // so leave loopCount at -1
  26877. this._setEndings( this.repetitions === 0, true, pingPong );
  26878. }
  26879. }
  26880. if ( time >= duration || time < 0 ) {
  26881. // wrap around
  26882. const loopDelta = Math.floor( time / duration ); // signed
  26883. time -= duration * loopDelta;
  26884. loopCount += Math.abs( loopDelta );
  26885. const pending = this.repetitions - loopCount;
  26886. if ( pending <= 0 ) {
  26887. // have to stop (switch state, clamp time, fire event)
  26888. if ( this.clampWhenFinished ) this.paused = true;
  26889. else this.enabled = false;
  26890. time = deltaTime > 0 ? duration : 0;
  26891. this.time = time;
  26892. this._mixer.dispatchEvent( {
  26893. type: 'finished', action: this,
  26894. direction: deltaTime > 0 ? 1 : - 1
  26895. } );
  26896. } else {
  26897. // keep running
  26898. if ( pending === 1 ) {
  26899. // entering the last round
  26900. const atStart = deltaTime < 0;
  26901. this._setEndings( atStart, ! atStart, pingPong );
  26902. } else {
  26903. this._setEndings( false, false, pingPong );
  26904. }
  26905. this._loopCount = loopCount;
  26906. this.time = time;
  26907. this._mixer.dispatchEvent( {
  26908. type: 'loop', action: this, loopDelta: loopDelta
  26909. } );
  26910. }
  26911. } else {
  26912. this.time = time;
  26913. }
  26914. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  26915. // invert time for the "pong round"
  26916. return duration - time;
  26917. }
  26918. }
  26919. return time;
  26920. }
  26921. _setEndings( atStart, atEnd, pingPong ) {
  26922. const settings = this._interpolantSettings;
  26923. if ( pingPong ) {
  26924. settings.endingStart = ZeroSlopeEnding;
  26925. settings.endingEnd = ZeroSlopeEnding;
  26926. } else {
  26927. // assuming for LoopOnce atStart == atEnd == true
  26928. if ( atStart ) {
  26929. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26930. } else {
  26931. settings.endingStart = WrapAroundEnding;
  26932. }
  26933. if ( atEnd ) {
  26934. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26935. } else {
  26936. settings.endingEnd = WrapAroundEnding;
  26937. }
  26938. }
  26939. }
  26940. _scheduleFading( duration, weightNow, weightThen ) {
  26941. const mixer = this._mixer, now = mixer.time;
  26942. let interpolant = this._weightInterpolant;
  26943. if ( interpolant === null ) {
  26944. interpolant = mixer._lendControlInterpolant();
  26945. this._weightInterpolant = interpolant;
  26946. }
  26947. const times = interpolant.parameterPositions,
  26948. values = interpolant.sampleValues;
  26949. times[ 0 ] = now;
  26950. values[ 0 ] = weightNow;
  26951. times[ 1 ] = now + duration;
  26952. values[ 1 ] = weightThen;
  26953. return this;
  26954. }
  26955. }
  26956. class AnimationMixer extends EventDispatcher {
  26957. constructor( root ) {
  26958. super();
  26959. this._root = root;
  26960. this._initMemoryManager();
  26961. this._accuIndex = 0;
  26962. this.time = 0;
  26963. this.timeScale = 1.0;
  26964. }
  26965. _bindAction( action, prototypeAction ) {
  26966. const root = action._localRoot || this._root,
  26967. tracks = action._clip.tracks,
  26968. nTracks = tracks.length,
  26969. bindings = action._propertyBindings,
  26970. interpolants = action._interpolants,
  26971. rootUuid = root.uuid,
  26972. bindingsByRoot = this._bindingsByRootAndName;
  26973. let bindingsByName = bindingsByRoot[ rootUuid ];
  26974. if ( bindingsByName === undefined ) {
  26975. bindingsByName = {};
  26976. bindingsByRoot[ rootUuid ] = bindingsByName;
  26977. }
  26978. for ( let i = 0; i !== nTracks; ++ i ) {
  26979. const track = tracks[ i ],
  26980. trackName = track.name;
  26981. let binding = bindingsByName[ trackName ];
  26982. if ( binding !== undefined ) {
  26983. bindings[ i ] = binding;
  26984. } else {
  26985. binding = bindings[ i ];
  26986. if ( binding !== undefined ) {
  26987. // existing binding, make sure the cache knows
  26988. if ( binding._cacheIndex === null ) {
  26989. ++ binding.referenceCount;
  26990. this._addInactiveBinding( binding, rootUuid, trackName );
  26991. }
  26992. continue;
  26993. }
  26994. const path = prototypeAction && prototypeAction.
  26995. _propertyBindings[ i ].binding.parsedPath;
  26996. binding = new PropertyMixer(
  26997. PropertyBinding.create( root, trackName, path ),
  26998. track.ValueTypeName, track.getValueSize() );
  26999. ++ binding.referenceCount;
  27000. this._addInactiveBinding( binding, rootUuid, trackName );
  27001. bindings[ i ] = binding;
  27002. }
  27003. interpolants[ i ].resultBuffer = binding.buffer;
  27004. }
  27005. }
  27006. _activateAction( action ) {
  27007. if ( ! this._isActiveAction( action ) ) {
  27008. if ( action._cacheIndex === null ) {
  27009. // this action has been forgotten by the cache, but the user
  27010. // appears to be still using it -> rebind
  27011. const rootUuid = ( action._localRoot || this._root ).uuid,
  27012. clipUuid = action._clip.uuid,
  27013. actionsForClip = this._actionsByClip[ clipUuid ];
  27014. this._bindAction( action,
  27015. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27016. this._addInactiveAction( action, clipUuid, rootUuid );
  27017. }
  27018. const bindings = action._propertyBindings;
  27019. // increment reference counts / sort out state
  27020. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27021. const binding = bindings[ i ];
  27022. if ( binding.useCount ++ === 0 ) {
  27023. this._lendBinding( binding );
  27024. binding.saveOriginalState();
  27025. }
  27026. }
  27027. this._lendAction( action );
  27028. }
  27029. }
  27030. _deactivateAction( action ) {
  27031. if ( this._isActiveAction( action ) ) {
  27032. const bindings = action._propertyBindings;
  27033. // decrement reference counts / sort out state
  27034. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27035. const binding = bindings[ i ];
  27036. if ( -- binding.useCount === 0 ) {
  27037. binding.restoreOriginalState();
  27038. this._takeBackBinding( binding );
  27039. }
  27040. }
  27041. this._takeBackAction( action );
  27042. }
  27043. }
  27044. // Memory manager
  27045. _initMemoryManager() {
  27046. this._actions = []; // 'nActiveActions' followed by inactive ones
  27047. this._nActiveActions = 0;
  27048. this._actionsByClip = {};
  27049. // inside:
  27050. // {
  27051. // knownActions: Array< AnimationAction > - used as prototypes
  27052. // actionByRoot: AnimationAction - lookup
  27053. // }
  27054. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27055. this._nActiveBindings = 0;
  27056. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27057. this._controlInterpolants = []; // same game as above
  27058. this._nActiveControlInterpolants = 0;
  27059. const scope = this;
  27060. this.stats = {
  27061. actions: {
  27062. get total() {
  27063. return scope._actions.length;
  27064. },
  27065. get inUse() {
  27066. return scope._nActiveActions;
  27067. }
  27068. },
  27069. bindings: {
  27070. get total() {
  27071. return scope._bindings.length;
  27072. },
  27073. get inUse() {
  27074. return scope._nActiveBindings;
  27075. }
  27076. },
  27077. controlInterpolants: {
  27078. get total() {
  27079. return scope._controlInterpolants.length;
  27080. },
  27081. get inUse() {
  27082. return scope._nActiveControlInterpolants;
  27083. }
  27084. }
  27085. };
  27086. }
  27087. // Memory management for AnimationAction objects
  27088. _isActiveAction( action ) {
  27089. const index = action._cacheIndex;
  27090. return index !== null && index < this._nActiveActions;
  27091. }
  27092. _addInactiveAction( action, clipUuid, rootUuid ) {
  27093. const actions = this._actions,
  27094. actionsByClip = this._actionsByClip;
  27095. let actionsForClip = actionsByClip[ clipUuid ];
  27096. if ( actionsForClip === undefined ) {
  27097. actionsForClip = {
  27098. knownActions: [ action ],
  27099. actionByRoot: {}
  27100. };
  27101. action._byClipCacheIndex = 0;
  27102. actionsByClip[ clipUuid ] = actionsForClip;
  27103. } else {
  27104. const knownActions = actionsForClip.knownActions;
  27105. action._byClipCacheIndex = knownActions.length;
  27106. knownActions.push( action );
  27107. }
  27108. action._cacheIndex = actions.length;
  27109. actions.push( action );
  27110. actionsForClip.actionByRoot[ rootUuid ] = action;
  27111. }
  27112. _removeInactiveAction( action ) {
  27113. const actions = this._actions,
  27114. lastInactiveAction = actions[ actions.length - 1 ],
  27115. cacheIndex = action._cacheIndex;
  27116. lastInactiveAction._cacheIndex = cacheIndex;
  27117. actions[ cacheIndex ] = lastInactiveAction;
  27118. actions.pop();
  27119. action._cacheIndex = null;
  27120. const clipUuid = action._clip.uuid,
  27121. actionsByClip = this._actionsByClip,
  27122. actionsForClip = actionsByClip[ clipUuid ],
  27123. knownActionsForClip = actionsForClip.knownActions,
  27124. lastKnownAction =
  27125. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27126. byClipCacheIndex = action._byClipCacheIndex;
  27127. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27128. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27129. knownActionsForClip.pop();
  27130. action._byClipCacheIndex = null;
  27131. const actionByRoot = actionsForClip.actionByRoot,
  27132. rootUuid = ( action._localRoot || this._root ).uuid;
  27133. delete actionByRoot[ rootUuid ];
  27134. if ( knownActionsForClip.length === 0 ) {
  27135. delete actionsByClip[ clipUuid ];
  27136. }
  27137. this._removeInactiveBindingsForAction( action );
  27138. }
  27139. _removeInactiveBindingsForAction( action ) {
  27140. const bindings = action._propertyBindings;
  27141. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27142. const binding = bindings[ i ];
  27143. if ( -- binding.referenceCount === 0 ) {
  27144. this._removeInactiveBinding( binding );
  27145. }
  27146. }
  27147. }
  27148. _lendAction( action ) {
  27149. // [ active actions | inactive actions ]
  27150. // [ active actions >| inactive actions ]
  27151. // s a
  27152. // <-swap->
  27153. // a s
  27154. const actions = this._actions,
  27155. prevIndex = action._cacheIndex,
  27156. lastActiveIndex = this._nActiveActions ++,
  27157. firstInactiveAction = actions[ lastActiveIndex ];
  27158. action._cacheIndex = lastActiveIndex;
  27159. actions[ lastActiveIndex ] = action;
  27160. firstInactiveAction._cacheIndex = prevIndex;
  27161. actions[ prevIndex ] = firstInactiveAction;
  27162. }
  27163. _takeBackAction( action ) {
  27164. // [ active actions | inactive actions ]
  27165. // [ active actions |< inactive actions ]
  27166. // a s
  27167. // <-swap->
  27168. // s a
  27169. const actions = this._actions,
  27170. prevIndex = action._cacheIndex,
  27171. firstInactiveIndex = -- this._nActiveActions,
  27172. lastActiveAction = actions[ firstInactiveIndex ];
  27173. action._cacheIndex = firstInactiveIndex;
  27174. actions[ firstInactiveIndex ] = action;
  27175. lastActiveAction._cacheIndex = prevIndex;
  27176. actions[ prevIndex ] = lastActiveAction;
  27177. }
  27178. // Memory management for PropertyMixer objects
  27179. _addInactiveBinding( binding, rootUuid, trackName ) {
  27180. const bindingsByRoot = this._bindingsByRootAndName,
  27181. bindings = this._bindings;
  27182. let bindingByName = bindingsByRoot[ rootUuid ];
  27183. if ( bindingByName === undefined ) {
  27184. bindingByName = {};
  27185. bindingsByRoot[ rootUuid ] = bindingByName;
  27186. }
  27187. bindingByName[ trackName ] = binding;
  27188. binding._cacheIndex = bindings.length;
  27189. bindings.push( binding );
  27190. }
  27191. _removeInactiveBinding( binding ) {
  27192. const bindings = this._bindings,
  27193. propBinding = binding.binding,
  27194. rootUuid = propBinding.rootNode.uuid,
  27195. trackName = propBinding.path,
  27196. bindingsByRoot = this._bindingsByRootAndName,
  27197. bindingByName = bindingsByRoot[ rootUuid ],
  27198. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27199. cacheIndex = binding._cacheIndex;
  27200. lastInactiveBinding._cacheIndex = cacheIndex;
  27201. bindings[ cacheIndex ] = lastInactiveBinding;
  27202. bindings.pop();
  27203. delete bindingByName[ trackName ];
  27204. if ( Object.keys( bindingByName ).length === 0 ) {
  27205. delete bindingsByRoot[ rootUuid ];
  27206. }
  27207. }
  27208. _lendBinding( binding ) {
  27209. const bindings = this._bindings,
  27210. prevIndex = binding._cacheIndex,
  27211. lastActiveIndex = this._nActiveBindings ++,
  27212. firstInactiveBinding = bindings[ lastActiveIndex ];
  27213. binding._cacheIndex = lastActiveIndex;
  27214. bindings[ lastActiveIndex ] = binding;
  27215. firstInactiveBinding._cacheIndex = prevIndex;
  27216. bindings[ prevIndex ] = firstInactiveBinding;
  27217. }
  27218. _takeBackBinding( binding ) {
  27219. const bindings = this._bindings,
  27220. prevIndex = binding._cacheIndex,
  27221. firstInactiveIndex = -- this._nActiveBindings,
  27222. lastActiveBinding = bindings[ firstInactiveIndex ];
  27223. binding._cacheIndex = firstInactiveIndex;
  27224. bindings[ firstInactiveIndex ] = binding;
  27225. lastActiveBinding._cacheIndex = prevIndex;
  27226. bindings[ prevIndex ] = lastActiveBinding;
  27227. }
  27228. // Memory management of Interpolants for weight and time scale
  27229. _lendControlInterpolant() {
  27230. const interpolants = this._controlInterpolants,
  27231. lastActiveIndex = this._nActiveControlInterpolants ++;
  27232. let interpolant = interpolants[ lastActiveIndex ];
  27233. if ( interpolant === undefined ) {
  27234. interpolant = new LinearInterpolant(
  27235. new Float32Array( 2 ), new Float32Array( 2 ),
  27236. 1, this._controlInterpolantsResultBuffer );
  27237. interpolant.__cacheIndex = lastActiveIndex;
  27238. interpolants[ lastActiveIndex ] = interpolant;
  27239. }
  27240. return interpolant;
  27241. }
  27242. _takeBackControlInterpolant( interpolant ) {
  27243. const interpolants = this._controlInterpolants,
  27244. prevIndex = interpolant.__cacheIndex,
  27245. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27246. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27247. interpolant.__cacheIndex = firstInactiveIndex;
  27248. interpolants[ firstInactiveIndex ] = interpolant;
  27249. lastActiveInterpolant.__cacheIndex = prevIndex;
  27250. interpolants[ prevIndex ] = lastActiveInterpolant;
  27251. }
  27252. // return an action for a clip optionally using a custom root target
  27253. // object (this method allocates a lot of dynamic memory in case a
  27254. // previously unknown clip/root combination is specified)
  27255. clipAction( clip, optionalRoot, blendMode ) {
  27256. const root = optionalRoot || this._root,
  27257. rootUuid = root.uuid;
  27258. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27259. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27260. const actionsForClip = this._actionsByClip[ clipUuid ];
  27261. let prototypeAction = null;
  27262. if ( blendMode === undefined ) {
  27263. if ( clipObject !== null ) {
  27264. blendMode = clipObject.blendMode;
  27265. } else {
  27266. blendMode = NormalAnimationBlendMode;
  27267. }
  27268. }
  27269. if ( actionsForClip !== undefined ) {
  27270. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27271. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27272. return existingAction;
  27273. }
  27274. // we know the clip, so we don't have to parse all
  27275. // the bindings again but can just copy
  27276. prototypeAction = actionsForClip.knownActions[ 0 ];
  27277. // also, take the clip from the prototype action
  27278. if ( clipObject === null )
  27279. clipObject = prototypeAction._clip;
  27280. }
  27281. // clip must be known when specified via string
  27282. if ( clipObject === null ) return null;
  27283. // allocate all resources required to run it
  27284. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27285. this._bindAction( newAction, prototypeAction );
  27286. // and make the action known to the memory manager
  27287. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27288. return newAction;
  27289. }
  27290. // get an existing action
  27291. existingAction( clip, optionalRoot ) {
  27292. const root = optionalRoot || this._root,
  27293. rootUuid = root.uuid,
  27294. clipObject = typeof clip === 'string' ?
  27295. AnimationClip.findByName( root, clip ) : clip,
  27296. clipUuid = clipObject ? clipObject.uuid : clip,
  27297. actionsForClip = this._actionsByClip[ clipUuid ];
  27298. if ( actionsForClip !== undefined ) {
  27299. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27300. }
  27301. return null;
  27302. }
  27303. // deactivates all previously scheduled actions
  27304. stopAllAction() {
  27305. const actions = this._actions,
  27306. nActions = this._nActiveActions;
  27307. for ( let i = nActions - 1; i >= 0; -- i ) {
  27308. actions[ i ].stop();
  27309. }
  27310. return this;
  27311. }
  27312. // advance the time and update apply the animation
  27313. update( deltaTime ) {
  27314. deltaTime *= this.timeScale;
  27315. const actions = this._actions,
  27316. nActions = this._nActiveActions,
  27317. time = this.time += deltaTime,
  27318. timeDirection = Math.sign( deltaTime ),
  27319. accuIndex = this._accuIndex ^= 1;
  27320. // run active actions
  27321. for ( let i = 0; i !== nActions; ++ i ) {
  27322. const action = actions[ i ];
  27323. action._update( time, deltaTime, timeDirection, accuIndex );
  27324. }
  27325. // update scene graph
  27326. const bindings = this._bindings,
  27327. nBindings = this._nActiveBindings;
  27328. for ( let i = 0; i !== nBindings; ++ i ) {
  27329. bindings[ i ].apply( accuIndex );
  27330. }
  27331. return this;
  27332. }
  27333. // Allows you to seek to a specific time in an animation.
  27334. setTime( timeInSeconds ) {
  27335. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27336. for ( let i = 0; i < this._actions.length; i ++ ) {
  27337. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27338. }
  27339. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27340. }
  27341. // return this mixer's root target object
  27342. getRoot() {
  27343. return this._root;
  27344. }
  27345. // free all resources specific to a particular clip
  27346. uncacheClip( clip ) {
  27347. const actions = this._actions,
  27348. clipUuid = clip.uuid,
  27349. actionsByClip = this._actionsByClip,
  27350. actionsForClip = actionsByClip[ clipUuid ];
  27351. if ( actionsForClip !== undefined ) {
  27352. // note: just calling _removeInactiveAction would mess up the
  27353. // iteration state and also require updating the state we can
  27354. // just throw away
  27355. const actionsToRemove = actionsForClip.knownActions;
  27356. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27357. const action = actionsToRemove[ i ];
  27358. this._deactivateAction( action );
  27359. const cacheIndex = action._cacheIndex,
  27360. lastInactiveAction = actions[ actions.length - 1 ];
  27361. action._cacheIndex = null;
  27362. action._byClipCacheIndex = null;
  27363. lastInactiveAction._cacheIndex = cacheIndex;
  27364. actions[ cacheIndex ] = lastInactiveAction;
  27365. actions.pop();
  27366. this._removeInactiveBindingsForAction( action );
  27367. }
  27368. delete actionsByClip[ clipUuid ];
  27369. }
  27370. }
  27371. // free all resources specific to a particular root target object
  27372. uncacheRoot( root ) {
  27373. const rootUuid = root.uuid,
  27374. actionsByClip = this._actionsByClip;
  27375. for ( const clipUuid in actionsByClip ) {
  27376. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27377. action = actionByRoot[ rootUuid ];
  27378. if ( action !== undefined ) {
  27379. this._deactivateAction( action );
  27380. this._removeInactiveAction( action );
  27381. }
  27382. }
  27383. const bindingsByRoot = this._bindingsByRootAndName,
  27384. bindingByName = bindingsByRoot[ rootUuid ];
  27385. if ( bindingByName !== undefined ) {
  27386. for ( const trackName in bindingByName ) {
  27387. const binding = bindingByName[ trackName ];
  27388. binding.restoreOriginalState();
  27389. this._removeInactiveBinding( binding );
  27390. }
  27391. }
  27392. }
  27393. // remove a targeted clip from the cache
  27394. uncacheAction( clip, optionalRoot ) {
  27395. const action = this.existingAction( clip, optionalRoot );
  27396. if ( action !== null ) {
  27397. this._deactivateAction( action );
  27398. this._removeInactiveAction( action );
  27399. }
  27400. }
  27401. }
  27402. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  27403. class Uniform {
  27404. constructor( value ) {
  27405. if ( typeof value === 'string' ) {
  27406. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27407. value = arguments[ 1 ];
  27408. }
  27409. this.value = value;
  27410. }
  27411. clone() {
  27412. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27413. }
  27414. }
  27415. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27416. constructor( array, stride, meshPerAttribute = 1 ) {
  27417. super( array, stride );
  27418. this.meshPerAttribute = meshPerAttribute;
  27419. }
  27420. copy( source ) {
  27421. super.copy( source );
  27422. this.meshPerAttribute = source.meshPerAttribute;
  27423. return this;
  27424. }
  27425. clone( data ) {
  27426. const ib = super.clone( data );
  27427. ib.meshPerAttribute = this.meshPerAttribute;
  27428. return ib;
  27429. }
  27430. toJSON( data ) {
  27431. const json = super.toJSON( data );
  27432. json.isInstancedInterleavedBuffer = true;
  27433. json.meshPerAttribute = this.meshPerAttribute;
  27434. return json;
  27435. }
  27436. }
  27437. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  27438. class GLBufferAttribute {
  27439. constructor( buffer, type, itemSize, elementSize, count ) {
  27440. this.buffer = buffer;
  27441. this.type = type;
  27442. this.itemSize = itemSize;
  27443. this.elementSize = elementSize;
  27444. this.count = count;
  27445. this.version = 0;
  27446. }
  27447. set needsUpdate( value ) {
  27448. if ( value === true ) this.version ++;
  27449. }
  27450. setBuffer( buffer ) {
  27451. this.buffer = buffer;
  27452. return this;
  27453. }
  27454. setType( type, elementSize ) {
  27455. this.type = type;
  27456. this.elementSize = elementSize;
  27457. return this;
  27458. }
  27459. setItemSize( itemSize ) {
  27460. this.itemSize = itemSize;
  27461. return this;
  27462. }
  27463. setCount( count ) {
  27464. this.count = count;
  27465. return this;
  27466. }
  27467. }
  27468. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  27469. class Raycaster {
  27470. constructor( origin, direction, near = 0, far = Infinity ) {
  27471. this.ray = new Ray( origin, direction );
  27472. // direction is assumed to be normalized (for accurate distance calculations)
  27473. this.near = near;
  27474. this.far = far;
  27475. this.camera = null;
  27476. this.layers = new Layers();
  27477. this.params = {
  27478. Mesh: {},
  27479. Line: { threshold: 1 },
  27480. LOD: {},
  27481. Points: { threshold: 1 },
  27482. Sprite: {}
  27483. };
  27484. }
  27485. set( origin, direction ) {
  27486. // direction is assumed to be normalized (for accurate distance calculations)
  27487. this.ray.set( origin, direction );
  27488. }
  27489. setFromCamera( coords, camera ) {
  27490. if ( camera && camera.isPerspectiveCamera ) {
  27491. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27492. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27493. this.camera = camera;
  27494. } else if ( camera && camera.isOrthographicCamera ) {
  27495. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27496. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27497. this.camera = camera;
  27498. } else {
  27499. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27500. }
  27501. }
  27502. intersectObject( object, recursive = false, intersects = [] ) {
  27503. intersectObject( object, this, intersects, recursive );
  27504. intersects.sort( ascSort );
  27505. return intersects;
  27506. }
  27507. intersectObjects( objects, recursive = false, intersects = [] ) {
  27508. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27509. intersectObject( objects[ i ], this, intersects, recursive );
  27510. }
  27511. intersects.sort( ascSort );
  27512. return intersects;
  27513. }
  27514. }
  27515. function ascSort( a, b ) {
  27516. return a.distance - b.distance;
  27517. }
  27518. function intersectObject( object, raycaster, intersects, recursive ) {
  27519. if ( object.layers.test( raycaster.layers ) ) {
  27520. object.raycast( raycaster, intersects );
  27521. }
  27522. if ( recursive === true ) {
  27523. const children = object.children;
  27524. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27525. intersectObject( children[ i ], raycaster, intersects, true );
  27526. }
  27527. }
  27528. }
  27529. /**
  27530. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27531. *
  27532. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27533. * The azimuthal angle (theta) is measured from the positive z-axis.
  27534. */
  27535. class Spherical {
  27536. constructor( radius = 1, phi = 0, theta = 0 ) {
  27537. this.radius = radius;
  27538. this.phi = phi; // polar angle
  27539. this.theta = theta; // azimuthal angle
  27540. return this;
  27541. }
  27542. set( radius, phi, theta ) {
  27543. this.radius = radius;
  27544. this.phi = phi;
  27545. this.theta = theta;
  27546. return this;
  27547. }
  27548. copy( other ) {
  27549. this.radius = other.radius;
  27550. this.phi = other.phi;
  27551. this.theta = other.theta;
  27552. return this;
  27553. }
  27554. // restrict phi to be betwee EPS and PI-EPS
  27555. makeSafe() {
  27556. const EPS = 0.000001;
  27557. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27558. return this;
  27559. }
  27560. setFromVector3( v ) {
  27561. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27562. }
  27563. setFromCartesianCoords( x, y, z ) {
  27564. this.radius = Math.sqrt( x * x + y * y + z * z );
  27565. if ( this.radius === 0 ) {
  27566. this.theta = 0;
  27567. this.phi = 0;
  27568. } else {
  27569. this.theta = Math.atan2( x, z );
  27570. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  27571. }
  27572. return this;
  27573. }
  27574. clone() {
  27575. return new this.constructor().copy( this );
  27576. }
  27577. }
  27578. /**
  27579. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27580. */
  27581. class Cylindrical {
  27582. constructor( radius = 1, theta = 0, y = 0 ) {
  27583. this.radius = radius; // distance from the origin to a point in the x-z plane
  27584. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27585. this.y = y; // height above the x-z plane
  27586. return this;
  27587. }
  27588. set( radius, theta, y ) {
  27589. this.radius = radius;
  27590. this.theta = theta;
  27591. this.y = y;
  27592. return this;
  27593. }
  27594. copy( other ) {
  27595. this.radius = other.radius;
  27596. this.theta = other.theta;
  27597. this.y = other.y;
  27598. return this;
  27599. }
  27600. setFromVector3( v ) {
  27601. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27602. }
  27603. setFromCartesianCoords( x, y, z ) {
  27604. this.radius = Math.sqrt( x * x + z * z );
  27605. this.theta = Math.atan2( x, z );
  27606. this.y = y;
  27607. return this;
  27608. }
  27609. clone() {
  27610. return new this.constructor().copy( this );
  27611. }
  27612. }
  27613. const _vector$4 = /*@__PURE__*/ new Vector2();
  27614. class Box2 {
  27615. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  27616. this.min = min;
  27617. this.max = max;
  27618. }
  27619. set( min, max ) {
  27620. this.min.copy( min );
  27621. this.max.copy( max );
  27622. return this;
  27623. }
  27624. setFromPoints( points ) {
  27625. this.makeEmpty();
  27626. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27627. this.expandByPoint( points[ i ] );
  27628. }
  27629. return this;
  27630. }
  27631. setFromCenterAndSize( center, size ) {
  27632. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  27633. this.min.copy( center ).sub( halfSize );
  27634. this.max.copy( center ).add( halfSize );
  27635. return this;
  27636. }
  27637. clone() {
  27638. return new this.constructor().copy( this );
  27639. }
  27640. copy( box ) {
  27641. this.min.copy( box.min );
  27642. this.max.copy( box.max );
  27643. return this;
  27644. }
  27645. makeEmpty() {
  27646. this.min.x = this.min.y = + Infinity;
  27647. this.max.x = this.max.y = - Infinity;
  27648. return this;
  27649. }
  27650. isEmpty() {
  27651. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27652. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27653. }
  27654. getCenter( target ) {
  27655. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27656. }
  27657. getSize( target ) {
  27658. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27659. }
  27660. expandByPoint( point ) {
  27661. this.min.min( point );
  27662. this.max.max( point );
  27663. return this;
  27664. }
  27665. expandByVector( vector ) {
  27666. this.min.sub( vector );
  27667. this.max.add( vector );
  27668. return this;
  27669. }
  27670. expandByScalar( scalar ) {
  27671. this.min.addScalar( - scalar );
  27672. this.max.addScalar( scalar );
  27673. return this;
  27674. }
  27675. containsPoint( point ) {
  27676. return point.x < this.min.x || point.x > this.max.x ||
  27677. point.y < this.min.y || point.y > this.max.y ? false : true;
  27678. }
  27679. containsBox( box ) {
  27680. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  27681. this.min.y <= box.min.y && box.max.y <= this.max.y;
  27682. }
  27683. getParameter( point, target ) {
  27684. // This can potentially have a divide by zero if the box
  27685. // has a size dimension of 0.
  27686. return target.set(
  27687. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  27688. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  27689. );
  27690. }
  27691. intersectsBox( box ) {
  27692. // using 4 splitting planes to rule out intersections
  27693. return box.max.x < this.min.x || box.min.x > this.max.x ||
  27694. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27695. }
  27696. clampPoint( point, target ) {
  27697. return target.copy( point ).clamp( this.min, this.max );
  27698. }
  27699. distanceToPoint( point ) {
  27700. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  27701. return clampedPoint.sub( point ).length();
  27702. }
  27703. intersect( box ) {
  27704. this.min.max( box.min );
  27705. this.max.min( box.max );
  27706. return this;
  27707. }
  27708. union( box ) {
  27709. this.min.min( box.min );
  27710. this.max.max( box.max );
  27711. return this;
  27712. }
  27713. translate( offset ) {
  27714. this.min.add( offset );
  27715. this.max.add( offset );
  27716. return this;
  27717. }
  27718. equals( box ) {
  27719. return box.min.equals( this.min ) && box.max.equals( this.max );
  27720. }
  27721. }
  27722. Box2.prototype.isBox2 = true;
  27723. const _startP = /*@__PURE__*/ new Vector3();
  27724. const _startEnd = /*@__PURE__*/ new Vector3();
  27725. class Line3 {
  27726. constructor( start = new Vector3(), end = new Vector3() ) {
  27727. this.start = start;
  27728. this.end = end;
  27729. }
  27730. set( start, end ) {
  27731. this.start.copy( start );
  27732. this.end.copy( end );
  27733. return this;
  27734. }
  27735. copy( line ) {
  27736. this.start.copy( line.start );
  27737. this.end.copy( line.end );
  27738. return this;
  27739. }
  27740. getCenter( target ) {
  27741. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  27742. }
  27743. delta( target ) {
  27744. return target.subVectors( this.end, this.start );
  27745. }
  27746. distanceSq() {
  27747. return this.start.distanceToSquared( this.end );
  27748. }
  27749. distance() {
  27750. return this.start.distanceTo( this.end );
  27751. }
  27752. at( t, target ) {
  27753. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27754. }
  27755. closestPointToPointParameter( point, clampToLine ) {
  27756. _startP.subVectors( point, this.start );
  27757. _startEnd.subVectors( this.end, this.start );
  27758. const startEnd2 = _startEnd.dot( _startEnd );
  27759. const startEnd_startP = _startEnd.dot( _startP );
  27760. let t = startEnd_startP / startEnd2;
  27761. if ( clampToLine ) {
  27762. t = clamp( t, 0, 1 );
  27763. }
  27764. return t;
  27765. }
  27766. closestPointToPoint( point, clampToLine, target ) {
  27767. const t = this.closestPointToPointParameter( point, clampToLine );
  27768. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27769. }
  27770. applyMatrix4( matrix ) {
  27771. this.start.applyMatrix4( matrix );
  27772. this.end.applyMatrix4( matrix );
  27773. return this;
  27774. }
  27775. equals( line ) {
  27776. return line.start.equals( this.start ) && line.end.equals( this.end );
  27777. }
  27778. clone() {
  27779. return new this.constructor().copy( this );
  27780. }
  27781. }
  27782. class ImmediateRenderObject extends Object3D {
  27783. constructor( material ) {
  27784. super();
  27785. this.material = material;
  27786. this.render = function ( /* renderCallback */ ) {};
  27787. this.hasPositions = false;
  27788. this.hasNormals = false;
  27789. this.hasColors = false;
  27790. this.hasUvs = false;
  27791. this.positionArray = null;
  27792. this.normalArray = null;
  27793. this.colorArray = null;
  27794. this.uvArray = null;
  27795. this.count = 0;
  27796. }
  27797. }
  27798. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27799. const _vector$3 = /*@__PURE__*/ new Vector3();
  27800. class SpotLightHelper extends Object3D {
  27801. constructor( light, color ) {
  27802. super();
  27803. this.light = light;
  27804. this.light.updateMatrixWorld();
  27805. this.matrix = light.matrixWorld;
  27806. this.matrixAutoUpdate = false;
  27807. this.color = color;
  27808. const geometry = new BufferGeometry();
  27809. const positions = [
  27810. 0, 0, 0, 0, 0, 1,
  27811. 0, 0, 0, 1, 0, 1,
  27812. 0, 0, 0, - 1, 0, 1,
  27813. 0, 0, 0, 0, 1, 1,
  27814. 0, 0, 0, 0, - 1, 1
  27815. ];
  27816. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  27817. const p1 = ( i / l ) * Math.PI * 2;
  27818. const p2 = ( j / l ) * Math.PI * 2;
  27819. positions.push(
  27820. Math.cos( p1 ), Math.sin( p1 ), 1,
  27821. Math.cos( p2 ), Math.sin( p2 ), 1
  27822. );
  27823. }
  27824. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27825. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27826. this.cone = new LineSegments( geometry, material );
  27827. this.add( this.cone );
  27828. this.update();
  27829. }
  27830. dispose() {
  27831. this.cone.geometry.dispose();
  27832. this.cone.material.dispose();
  27833. }
  27834. update() {
  27835. this.light.updateMatrixWorld();
  27836. const coneLength = this.light.distance ? this.light.distance : 1000;
  27837. const coneWidth = coneLength * Math.tan( this.light.angle );
  27838. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  27839. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  27840. this.cone.lookAt( _vector$3 );
  27841. if ( this.color !== undefined ) {
  27842. this.cone.material.color.set( this.color );
  27843. } else {
  27844. this.cone.material.color.copy( this.light.color );
  27845. }
  27846. }
  27847. }
  27848. const _vector$2 = /*@__PURE__*/ new Vector3();
  27849. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  27850. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  27851. class SkeletonHelper extends LineSegments {
  27852. constructor( object ) {
  27853. const bones = getBoneList( object );
  27854. const geometry = new BufferGeometry();
  27855. const vertices = [];
  27856. const colors = [];
  27857. const color1 = new Color( 0, 0, 1 );
  27858. const color2 = new Color( 0, 1, 0 );
  27859. for ( let i = 0; i < bones.length; i ++ ) {
  27860. const bone = bones[ i ];
  27861. if ( bone.parent && bone.parent.isBone ) {
  27862. vertices.push( 0, 0, 0 );
  27863. vertices.push( 0, 0, 0 );
  27864. colors.push( color1.r, color1.g, color1.b );
  27865. colors.push( color2.r, color2.g, color2.b );
  27866. }
  27867. }
  27868. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27869. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27870. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  27871. super( geometry, material );
  27872. this.type = 'SkeletonHelper';
  27873. this.isSkeletonHelper = true;
  27874. this.root = object;
  27875. this.bones = bones;
  27876. this.matrix = object.matrixWorld;
  27877. this.matrixAutoUpdate = false;
  27878. }
  27879. updateMatrixWorld( force ) {
  27880. const bones = this.bones;
  27881. const geometry = this.geometry;
  27882. const position = geometry.getAttribute( 'position' );
  27883. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  27884. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  27885. const bone = bones[ i ];
  27886. if ( bone.parent && bone.parent.isBone ) {
  27887. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  27888. _vector$2.setFromMatrixPosition( _boneMatrix );
  27889. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  27890. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  27891. _vector$2.setFromMatrixPosition( _boneMatrix );
  27892. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  27893. j += 2;
  27894. }
  27895. }
  27896. geometry.getAttribute( 'position' ).needsUpdate = true;
  27897. super.updateMatrixWorld( force );
  27898. }
  27899. }
  27900. function getBoneList( object ) {
  27901. const boneList = [];
  27902. if ( object && object.isBone ) {
  27903. boneList.push( object );
  27904. }
  27905. for ( let i = 0; i < object.children.length; i ++ ) {
  27906. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  27907. }
  27908. return boneList;
  27909. }
  27910. class PointLightHelper extends Mesh {
  27911. constructor( light, sphereSize, color ) {
  27912. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  27913. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27914. super( geometry, material );
  27915. this.light = light;
  27916. this.light.updateMatrixWorld();
  27917. this.color = color;
  27918. this.type = 'PointLightHelper';
  27919. this.matrix = this.light.matrixWorld;
  27920. this.matrixAutoUpdate = false;
  27921. this.update();
  27922. /*
  27923. // TODO: delete this comment?
  27924. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27925. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27926. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27927. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27928. const d = light.distance;
  27929. if ( d === 0.0 ) {
  27930. this.lightDistance.visible = false;
  27931. } else {
  27932. this.lightDistance.scale.set( d, d, d );
  27933. }
  27934. this.add( this.lightDistance );
  27935. */
  27936. }
  27937. dispose() {
  27938. this.geometry.dispose();
  27939. this.material.dispose();
  27940. }
  27941. update() {
  27942. if ( this.color !== undefined ) {
  27943. this.material.color.set( this.color );
  27944. } else {
  27945. this.material.color.copy( this.light.color );
  27946. }
  27947. /*
  27948. const d = this.light.distance;
  27949. if ( d === 0.0 ) {
  27950. this.lightDistance.visible = false;
  27951. } else {
  27952. this.lightDistance.visible = true;
  27953. this.lightDistance.scale.set( d, d, d );
  27954. }
  27955. */
  27956. }
  27957. }
  27958. const _vector$1 = /*@__PURE__*/ new Vector3();
  27959. const _color1 = /*@__PURE__*/ new Color();
  27960. const _color2 = /*@__PURE__*/ new Color();
  27961. class HemisphereLightHelper extends Object3D {
  27962. constructor( light, size, color ) {
  27963. super();
  27964. this.light = light;
  27965. this.light.updateMatrixWorld();
  27966. this.matrix = light.matrixWorld;
  27967. this.matrixAutoUpdate = false;
  27968. this.color = color;
  27969. const geometry = new OctahedronGeometry( size );
  27970. geometry.rotateY( Math.PI * 0.5 );
  27971. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27972. if ( this.color === undefined ) this.material.vertexColors = true;
  27973. const position = geometry.getAttribute( 'position' );
  27974. const colors = new Float32Array( position.count * 3 );
  27975. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  27976. this.add( new Mesh( geometry, this.material ) );
  27977. this.update();
  27978. }
  27979. dispose() {
  27980. this.children[ 0 ].geometry.dispose();
  27981. this.children[ 0 ].material.dispose();
  27982. }
  27983. update() {
  27984. const mesh = this.children[ 0 ];
  27985. if ( this.color !== undefined ) {
  27986. this.material.color.set( this.color );
  27987. } else {
  27988. const colors = mesh.geometry.getAttribute( 'color' );
  27989. _color1.copy( this.light.color );
  27990. _color2.copy( this.light.groundColor );
  27991. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  27992. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  27993. colors.setXYZ( i, color.r, color.g, color.b );
  27994. }
  27995. colors.needsUpdate = true;
  27996. }
  27997. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  27998. }
  27999. }
  28000. class GridHelper extends LineSegments {
  28001. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28002. color1 = new Color( color1 );
  28003. color2 = new Color( color2 );
  28004. const center = divisions / 2;
  28005. const step = size / divisions;
  28006. const halfSize = size / 2;
  28007. const vertices = [], colors = [];
  28008. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28009. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28010. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28011. const color = i === center ? color1 : color2;
  28012. color.toArray( colors, j ); j += 3;
  28013. color.toArray( colors, j ); j += 3;
  28014. color.toArray( colors, j ); j += 3;
  28015. color.toArray( colors, j ); j += 3;
  28016. }
  28017. const geometry = new BufferGeometry();
  28018. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28019. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28020. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28021. super( geometry, material );
  28022. this.type = 'GridHelper';
  28023. }
  28024. }
  28025. class PolarGridHelper extends LineSegments {
  28026. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28027. color1 = new Color( color1 );
  28028. color2 = new Color( color2 );
  28029. const vertices = [];
  28030. const colors = [];
  28031. // create the radials
  28032. for ( let i = 0; i <= radials; i ++ ) {
  28033. const v = ( i / radials ) * ( Math.PI * 2 );
  28034. const x = Math.sin( v ) * radius;
  28035. const z = Math.cos( v ) * radius;
  28036. vertices.push( 0, 0, 0 );
  28037. vertices.push( x, 0, z );
  28038. const color = ( i & 1 ) ? color1 : color2;
  28039. colors.push( color.r, color.g, color.b );
  28040. colors.push( color.r, color.g, color.b );
  28041. }
  28042. // create the circles
  28043. for ( let i = 0; i <= circles; i ++ ) {
  28044. const color = ( i & 1 ) ? color1 : color2;
  28045. const r = radius - ( radius / circles * i );
  28046. for ( let j = 0; j < divisions; j ++ ) {
  28047. // first vertex
  28048. let v = ( j / divisions ) * ( Math.PI * 2 );
  28049. let x = Math.sin( v ) * r;
  28050. let z = Math.cos( v ) * r;
  28051. vertices.push( x, 0, z );
  28052. colors.push( color.r, color.g, color.b );
  28053. // second vertex
  28054. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28055. x = Math.sin( v ) * r;
  28056. z = Math.cos( v ) * r;
  28057. vertices.push( x, 0, z );
  28058. colors.push( color.r, color.g, color.b );
  28059. }
  28060. }
  28061. const geometry = new BufferGeometry();
  28062. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28063. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28064. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28065. super( geometry, material );
  28066. this.type = 'PolarGridHelper';
  28067. }
  28068. }
  28069. const _v1 = /*@__PURE__*/ new Vector3();
  28070. const _v2 = /*@__PURE__*/ new Vector3();
  28071. const _v3 = /*@__PURE__*/ new Vector3();
  28072. class DirectionalLightHelper extends Object3D {
  28073. constructor( light, size, color ) {
  28074. super();
  28075. this.light = light;
  28076. this.light.updateMatrixWorld();
  28077. this.matrix = light.matrixWorld;
  28078. this.matrixAutoUpdate = false;
  28079. this.color = color;
  28080. if ( size === undefined ) size = 1;
  28081. let geometry = new BufferGeometry();
  28082. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28083. - size, size, 0,
  28084. size, size, 0,
  28085. size, - size, 0,
  28086. - size, - size, 0,
  28087. - size, size, 0
  28088. ], 3 ) );
  28089. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28090. this.lightPlane = new Line( geometry, material );
  28091. this.add( this.lightPlane );
  28092. geometry = new BufferGeometry();
  28093. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28094. this.targetLine = new Line( geometry, material );
  28095. this.add( this.targetLine );
  28096. this.update();
  28097. }
  28098. dispose() {
  28099. this.lightPlane.geometry.dispose();
  28100. this.lightPlane.material.dispose();
  28101. this.targetLine.geometry.dispose();
  28102. this.targetLine.material.dispose();
  28103. }
  28104. update() {
  28105. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28106. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28107. _v3.subVectors( _v2, _v1 );
  28108. this.lightPlane.lookAt( _v2 );
  28109. if ( this.color !== undefined ) {
  28110. this.lightPlane.material.color.set( this.color );
  28111. this.targetLine.material.color.set( this.color );
  28112. } else {
  28113. this.lightPlane.material.color.copy( this.light.color );
  28114. this.targetLine.material.color.copy( this.light.color );
  28115. }
  28116. this.targetLine.lookAt( _v2 );
  28117. this.targetLine.scale.z = _v3.length();
  28118. }
  28119. }
  28120. const _vector = /*@__PURE__*/ new Vector3();
  28121. const _camera = /*@__PURE__*/ new Camera();
  28122. /**
  28123. * - shows frustum, line of sight and up of the camera
  28124. * - suitable for fast updates
  28125. * - based on frustum visualization in lightgl.js shadowmap example
  28126. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28127. */
  28128. class CameraHelper extends LineSegments {
  28129. constructor( camera ) {
  28130. const geometry = new BufferGeometry();
  28131. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28132. const vertices = [];
  28133. const colors = [];
  28134. const pointMap = {};
  28135. // colors
  28136. const colorFrustum = new Color( 0xffaa00 );
  28137. const colorCone = new Color( 0xff0000 );
  28138. const colorUp = new Color( 0x00aaff );
  28139. const colorTarget = new Color( 0xffffff );
  28140. const colorCross = new Color( 0x333333 );
  28141. // near
  28142. addLine( 'n1', 'n2', colorFrustum );
  28143. addLine( 'n2', 'n4', colorFrustum );
  28144. addLine( 'n4', 'n3', colorFrustum );
  28145. addLine( 'n3', 'n1', colorFrustum );
  28146. // far
  28147. addLine( 'f1', 'f2', colorFrustum );
  28148. addLine( 'f2', 'f4', colorFrustum );
  28149. addLine( 'f4', 'f3', colorFrustum );
  28150. addLine( 'f3', 'f1', colorFrustum );
  28151. // sides
  28152. addLine( 'n1', 'f1', colorFrustum );
  28153. addLine( 'n2', 'f2', colorFrustum );
  28154. addLine( 'n3', 'f3', colorFrustum );
  28155. addLine( 'n4', 'f4', colorFrustum );
  28156. // cone
  28157. addLine( 'p', 'n1', colorCone );
  28158. addLine( 'p', 'n2', colorCone );
  28159. addLine( 'p', 'n3', colorCone );
  28160. addLine( 'p', 'n4', colorCone );
  28161. // up
  28162. addLine( 'u1', 'u2', colorUp );
  28163. addLine( 'u2', 'u3', colorUp );
  28164. addLine( 'u3', 'u1', colorUp );
  28165. // target
  28166. addLine( 'c', 't', colorTarget );
  28167. addLine( 'p', 'c', colorCross );
  28168. // cross
  28169. addLine( 'cn1', 'cn2', colorCross );
  28170. addLine( 'cn3', 'cn4', colorCross );
  28171. addLine( 'cf1', 'cf2', colorCross );
  28172. addLine( 'cf3', 'cf4', colorCross );
  28173. function addLine( a, b, color ) {
  28174. addPoint( a, color );
  28175. addPoint( b, color );
  28176. }
  28177. function addPoint( id, color ) {
  28178. vertices.push( 0, 0, 0 );
  28179. colors.push( color.r, color.g, color.b );
  28180. if ( pointMap[ id ] === undefined ) {
  28181. pointMap[ id ] = [];
  28182. }
  28183. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28184. }
  28185. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28186. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28187. super( geometry, material );
  28188. this.type = 'CameraHelper';
  28189. this.camera = camera;
  28190. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28191. this.matrix = camera.matrixWorld;
  28192. this.matrixAutoUpdate = false;
  28193. this.pointMap = pointMap;
  28194. this.update();
  28195. }
  28196. update() {
  28197. const geometry = this.geometry;
  28198. const pointMap = this.pointMap;
  28199. const w = 1, h = 1;
  28200. // we need just camera projection matrix inverse
  28201. // world matrix must be identity
  28202. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28203. // center / target
  28204. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28205. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28206. // near
  28207. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28208. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28209. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28210. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28211. // far
  28212. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28213. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28214. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28215. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28216. // up
  28217. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28218. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28219. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28220. // cross
  28221. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28222. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28223. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28224. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28225. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28226. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28227. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28228. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28229. geometry.getAttribute( 'position' ).needsUpdate = true;
  28230. }
  28231. dispose() {
  28232. this.geometry.dispose();
  28233. this.material.dispose();
  28234. }
  28235. }
  28236. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28237. _vector.set( x, y, z ).unproject( camera );
  28238. const points = pointMap[ point ];
  28239. if ( points !== undefined ) {
  28240. const position = geometry.getAttribute( 'position' );
  28241. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28242. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28243. }
  28244. }
  28245. }
  28246. const _box = /*@__PURE__*/ new Box3();
  28247. class BoxHelper extends LineSegments {
  28248. constructor( object, color = 0xffff00 ) {
  28249. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  28250. const positions = new Float32Array( 8 * 3 );
  28251. const geometry = new BufferGeometry();
  28252. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28253. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28254. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28255. this.object = object;
  28256. this.type = 'BoxHelper';
  28257. this.matrixAutoUpdate = false;
  28258. this.update();
  28259. }
  28260. update( object ) {
  28261. if ( object !== undefined ) {
  28262. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28263. }
  28264. if ( this.object !== undefined ) {
  28265. _box.setFromObject( this.object );
  28266. }
  28267. if ( _box.isEmpty() ) return;
  28268. const min = _box.min;
  28269. const max = _box.max;
  28270. /*
  28271. 5____4
  28272. 1/___0/|
  28273. | 6__|_7
  28274. 2/___3/
  28275. 0: max.x, max.y, max.z
  28276. 1: min.x, max.y, max.z
  28277. 2: min.x, min.y, max.z
  28278. 3: max.x, min.y, max.z
  28279. 4: max.x, max.y, min.z
  28280. 5: min.x, max.y, min.z
  28281. 6: min.x, min.y, min.z
  28282. 7: max.x, min.y, min.z
  28283. */
  28284. const position = this.geometry.attributes.position;
  28285. const array = position.array;
  28286. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28287. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28288. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28289. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28290. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28291. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28292. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28293. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28294. position.needsUpdate = true;
  28295. this.geometry.computeBoundingSphere();
  28296. }
  28297. setFromObject( object ) {
  28298. this.object = object;
  28299. this.update();
  28300. return this;
  28301. }
  28302. copy( source ) {
  28303. LineSegments.prototype.copy.call( this, source );
  28304. this.object = source.object;
  28305. return this;
  28306. }
  28307. }
  28308. class Box3Helper extends LineSegments {
  28309. constructor( box, color = 0xffff00 ) {
  28310. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  28311. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  28312. const geometry = new BufferGeometry();
  28313. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28314. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28315. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28316. this.box = box;
  28317. this.type = 'Box3Helper';
  28318. this.geometry.computeBoundingSphere();
  28319. }
  28320. updateMatrixWorld( force ) {
  28321. const box = this.box;
  28322. if ( box.isEmpty() ) return;
  28323. box.getCenter( this.position );
  28324. box.getSize( this.scale );
  28325. this.scale.multiplyScalar( 0.5 );
  28326. super.updateMatrixWorld( force );
  28327. }
  28328. }
  28329. class PlaneHelper extends Line {
  28330. constructor( plane, size = 1, hex = 0xffff00 ) {
  28331. const color = hex;
  28332. const positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  28333. const geometry = new BufferGeometry();
  28334. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28335. geometry.computeBoundingSphere();
  28336. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28337. this.type = 'PlaneHelper';
  28338. this.plane = plane;
  28339. this.size = size;
  28340. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  28341. const geometry2 = new BufferGeometry();
  28342. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28343. geometry2.computeBoundingSphere();
  28344. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28345. }
  28346. updateMatrixWorld( force ) {
  28347. let scale = - this.plane.constant;
  28348. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  28349. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  28350. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28351. this.lookAt( this.plane.normal );
  28352. super.updateMatrixWorld( force );
  28353. }
  28354. }
  28355. const _axis = /*@__PURE__*/ new Vector3();
  28356. let _lineGeometry, _coneGeometry;
  28357. class ArrowHelper extends Object3D {
  28358. // dir is assumed to be normalized
  28359. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28360. super();
  28361. this.type = 'ArrowHelper';
  28362. if ( _lineGeometry === undefined ) {
  28363. _lineGeometry = new BufferGeometry();
  28364. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28365. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  28366. _coneGeometry.translate( 0, - 0.5, 0 );
  28367. }
  28368. this.position.copy( origin );
  28369. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28370. this.line.matrixAutoUpdate = false;
  28371. this.add( this.line );
  28372. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28373. this.cone.matrixAutoUpdate = false;
  28374. this.add( this.cone );
  28375. this.setDirection( dir );
  28376. this.setLength( length, headLength, headWidth );
  28377. }
  28378. setDirection( dir ) {
  28379. // dir is assumed to be normalized
  28380. if ( dir.y > 0.99999 ) {
  28381. this.quaternion.set( 0, 0, 0, 1 );
  28382. } else if ( dir.y < - 0.99999 ) {
  28383. this.quaternion.set( 1, 0, 0, 0 );
  28384. } else {
  28385. _axis.set( dir.z, 0, - dir.x ).normalize();
  28386. const radians = Math.acos( dir.y );
  28387. this.quaternion.setFromAxisAngle( _axis, radians );
  28388. }
  28389. }
  28390. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28391. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28392. this.line.updateMatrix();
  28393. this.cone.scale.set( headWidth, headLength, headWidth );
  28394. this.cone.position.y = length;
  28395. this.cone.updateMatrix();
  28396. }
  28397. setColor( color ) {
  28398. this.line.material.color.set( color );
  28399. this.cone.material.color.set( color );
  28400. }
  28401. copy( source ) {
  28402. super.copy( source, false );
  28403. this.line.copy( source.line );
  28404. this.cone.copy( source.cone );
  28405. return this;
  28406. }
  28407. }
  28408. class AxesHelper extends LineSegments {
  28409. constructor( size = 1 ) {
  28410. const vertices = [
  28411. 0, 0, 0, size, 0, 0,
  28412. 0, 0, 0, 0, size, 0,
  28413. 0, 0, 0, 0, 0, size
  28414. ];
  28415. const colors = [
  28416. 1, 0, 0, 1, 0.6, 0,
  28417. 0, 1, 0, 0.6, 1, 0,
  28418. 0, 0, 1, 0, 0.6, 1
  28419. ];
  28420. const geometry = new BufferGeometry();
  28421. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28422. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28423. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28424. super( geometry, material );
  28425. this.type = 'AxesHelper';
  28426. }
  28427. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  28428. const color = new Color();
  28429. const array = this.geometry.attributes.color.array;
  28430. color.set( xAxisColor );
  28431. color.toArray( array, 0 );
  28432. color.toArray( array, 3 );
  28433. color.set( yAxisColor );
  28434. color.toArray( array, 6 );
  28435. color.toArray( array, 9 );
  28436. color.set( zAxisColor );
  28437. color.toArray( array, 12 );
  28438. color.toArray( array, 15 );
  28439. this.geometry.attributes.color.needsUpdate = true;
  28440. return this;
  28441. }
  28442. dispose() {
  28443. this.geometry.dispose();
  28444. this.material.dispose();
  28445. }
  28446. }
  28447. const _floatView = new Float32Array( 1 );
  28448. const _int32View = new Int32Array( _floatView.buffer );
  28449. class DataUtils {
  28450. // Converts float32 to float16 (stored as uint16 value).
  28451. static toHalfFloat( val ) {
  28452. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28453. /* This method is faster than the OpenEXR implementation (very often
  28454. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28455. * by James Tursa?s half-precision code. */
  28456. _floatView[ 0 ] = val;
  28457. const x = _int32View[ 0 ];
  28458. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  28459. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  28460. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  28461. /* If zero, or denormal, or exponent underflows too much for a denormal
  28462. * half, return signed zero. */
  28463. if ( e < 103 ) return bits;
  28464. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28465. if ( e > 142 ) {
  28466. bits |= 0x7c00;
  28467. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28468. * not Inf, so make sure we set one mantissa bit too. */
  28469. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  28470. return bits;
  28471. }
  28472. /* If exponent underflows but not too much, return a denormal */
  28473. if ( e < 113 ) {
  28474. m |= 0x0800;
  28475. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28476. * to 1, which is OK. */
  28477. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  28478. return bits;
  28479. }
  28480. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  28481. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28482. * the exponent, which is OK. */
  28483. bits += m & 1;
  28484. return bits;
  28485. }
  28486. }
  28487. const LineStrip = 0;
  28488. const LinePieces = 1;
  28489. const NoColors = 0;
  28490. const FaceColors = 1;
  28491. const VertexColors = 2;
  28492. function MeshFaceMaterial( materials ) {
  28493. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  28494. return materials;
  28495. }
  28496. function MultiMaterial( materials = [] ) {
  28497. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  28498. materials.isMultiMaterial = true;
  28499. materials.materials = materials;
  28500. materials.clone = function () {
  28501. return materials.slice();
  28502. };
  28503. return materials;
  28504. }
  28505. function PointCloud( geometry, material ) {
  28506. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  28507. return new Points( geometry, material );
  28508. }
  28509. function Particle( material ) {
  28510. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  28511. return new Sprite( material );
  28512. }
  28513. function ParticleSystem( geometry, material ) {
  28514. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  28515. return new Points( geometry, material );
  28516. }
  28517. function PointCloudMaterial( parameters ) {
  28518. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  28519. return new PointsMaterial( parameters );
  28520. }
  28521. function ParticleBasicMaterial( parameters ) {
  28522. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  28523. return new PointsMaterial( parameters );
  28524. }
  28525. function ParticleSystemMaterial( parameters ) {
  28526. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  28527. return new PointsMaterial( parameters );
  28528. }
  28529. function Vertex( x, y, z ) {
  28530. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  28531. return new Vector3( x, y, z );
  28532. }
  28533. //
  28534. function DynamicBufferAttribute( array, itemSize ) {
  28535. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  28536. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  28537. }
  28538. function Int8Attribute( array, itemSize ) {
  28539. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  28540. return new Int8BufferAttribute( array, itemSize );
  28541. }
  28542. function Uint8Attribute( array, itemSize ) {
  28543. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  28544. return new Uint8BufferAttribute( array, itemSize );
  28545. }
  28546. function Uint8ClampedAttribute( array, itemSize ) {
  28547. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  28548. return new Uint8ClampedBufferAttribute( array, itemSize );
  28549. }
  28550. function Int16Attribute( array, itemSize ) {
  28551. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  28552. return new Int16BufferAttribute( array, itemSize );
  28553. }
  28554. function Uint16Attribute( array, itemSize ) {
  28555. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  28556. return new Uint16BufferAttribute( array, itemSize );
  28557. }
  28558. function Int32Attribute( array, itemSize ) {
  28559. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  28560. return new Int32BufferAttribute( array, itemSize );
  28561. }
  28562. function Uint32Attribute( array, itemSize ) {
  28563. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  28564. return new Uint32BufferAttribute( array, itemSize );
  28565. }
  28566. function Float32Attribute( array, itemSize ) {
  28567. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  28568. return new Float32BufferAttribute( array, itemSize );
  28569. }
  28570. function Float64Attribute( array, itemSize ) {
  28571. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  28572. return new Float64BufferAttribute( array, itemSize );
  28573. }
  28574. //
  28575. Curve.create = function ( construct, getPoint ) {
  28576. console.log( 'THREE.Curve.create() has been deprecated' );
  28577. construct.prototype = Object.create( Curve.prototype );
  28578. construct.prototype.constructor = construct;
  28579. construct.prototype.getPoint = getPoint;
  28580. return construct;
  28581. };
  28582. //
  28583. Path.prototype.fromPoints = function ( points ) {
  28584. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  28585. return this.setFromPoints( points );
  28586. };
  28587. //
  28588. function AxisHelper( size ) {
  28589. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  28590. return new AxesHelper( size );
  28591. }
  28592. function BoundingBoxHelper( object, color ) {
  28593. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  28594. return new BoxHelper( object, color );
  28595. }
  28596. function EdgesHelper( object, hex ) {
  28597. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  28598. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28599. }
  28600. GridHelper.prototype.setColors = function () {
  28601. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  28602. };
  28603. SkeletonHelper.prototype.update = function () {
  28604. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  28605. };
  28606. function WireframeHelper( object, hex ) {
  28607. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  28608. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28609. }
  28610. //
  28611. Loader.prototype.extractUrlBase = function ( url ) {
  28612. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  28613. return LoaderUtils.extractUrlBase( url );
  28614. };
  28615. Loader.Handlers = {
  28616. add: function ( /* regex, loader */ ) {
  28617. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  28618. },
  28619. get: function ( /* file */ ) {
  28620. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  28621. }
  28622. };
  28623. function XHRLoader( manager ) {
  28624. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  28625. return new FileLoader( manager );
  28626. }
  28627. function BinaryTextureLoader( manager ) {
  28628. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  28629. return new DataTextureLoader( manager );
  28630. }
  28631. //
  28632. Box2.prototype.center = function ( optionalTarget ) {
  28633. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  28634. return this.getCenter( optionalTarget );
  28635. };
  28636. Box2.prototype.empty = function () {
  28637. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  28638. return this.isEmpty();
  28639. };
  28640. Box2.prototype.isIntersectionBox = function ( box ) {
  28641. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28642. return this.intersectsBox( box );
  28643. };
  28644. Box2.prototype.size = function ( optionalTarget ) {
  28645. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  28646. return this.getSize( optionalTarget );
  28647. };
  28648. //
  28649. Box3.prototype.center = function ( optionalTarget ) {
  28650. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  28651. return this.getCenter( optionalTarget );
  28652. };
  28653. Box3.prototype.empty = function () {
  28654. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  28655. return this.isEmpty();
  28656. };
  28657. Box3.prototype.isIntersectionBox = function ( box ) {
  28658. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28659. return this.intersectsBox( box );
  28660. };
  28661. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  28662. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28663. return this.intersectsSphere( sphere );
  28664. };
  28665. Box3.prototype.size = function ( optionalTarget ) {
  28666. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  28667. return this.getSize( optionalTarget );
  28668. };
  28669. //
  28670. Sphere.prototype.empty = function () {
  28671. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  28672. return this.isEmpty();
  28673. };
  28674. //
  28675. Frustum.prototype.setFromMatrix = function ( m ) {
  28676. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  28677. return this.setFromProjectionMatrix( m );
  28678. };
  28679. //
  28680. Line3.prototype.center = function ( optionalTarget ) {
  28681. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  28682. return this.getCenter( optionalTarget );
  28683. };
  28684. //
  28685. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  28686. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28687. return this.toArray( array, offset );
  28688. };
  28689. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  28690. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  28691. return vector.applyMatrix3( this );
  28692. };
  28693. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  28694. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  28695. };
  28696. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  28697. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  28698. return attribute.applyMatrix3( this );
  28699. };
  28700. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28701. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  28702. };
  28703. Matrix3.prototype.getInverse = function ( matrix ) {
  28704. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28705. return this.copy( matrix ).invert();
  28706. };
  28707. //
  28708. Matrix4.prototype.extractPosition = function ( m ) {
  28709. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  28710. return this.copyPosition( m );
  28711. };
  28712. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  28713. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28714. return this.toArray( array, offset );
  28715. };
  28716. Matrix4.prototype.getPosition = function () {
  28717. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  28718. return new Vector3().setFromMatrixColumn( this, 3 );
  28719. };
  28720. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  28721. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  28722. return this.makeRotationFromQuaternion( q );
  28723. };
  28724. Matrix4.prototype.multiplyToArray = function () {
  28725. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  28726. };
  28727. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  28728. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28729. return vector.applyMatrix4( this );
  28730. };
  28731. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  28732. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28733. return vector.applyMatrix4( this );
  28734. };
  28735. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  28736. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  28737. };
  28738. Matrix4.prototype.rotateAxis = function ( v ) {
  28739. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  28740. v.transformDirection( this );
  28741. };
  28742. Matrix4.prototype.crossVector = function ( vector ) {
  28743. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28744. return vector.applyMatrix4( this );
  28745. };
  28746. Matrix4.prototype.translate = function () {
  28747. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  28748. };
  28749. Matrix4.prototype.rotateX = function () {
  28750. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  28751. };
  28752. Matrix4.prototype.rotateY = function () {
  28753. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  28754. };
  28755. Matrix4.prototype.rotateZ = function () {
  28756. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  28757. };
  28758. Matrix4.prototype.rotateByAxis = function () {
  28759. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  28760. };
  28761. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  28762. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  28763. return attribute.applyMatrix4( this );
  28764. };
  28765. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28766. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  28767. };
  28768. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  28769. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  28770. return this.makePerspective( left, right, top, bottom, near, far );
  28771. };
  28772. Matrix4.prototype.getInverse = function ( matrix ) {
  28773. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28774. return this.copy( matrix ).invert();
  28775. };
  28776. //
  28777. Plane.prototype.isIntersectionLine = function ( line ) {
  28778. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  28779. return this.intersectsLine( line );
  28780. };
  28781. //
  28782. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  28783. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  28784. return vector.applyQuaternion( this );
  28785. };
  28786. Quaternion.prototype.inverse = function ( ) {
  28787. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  28788. return this.invert();
  28789. };
  28790. //
  28791. Ray.prototype.isIntersectionBox = function ( box ) {
  28792. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28793. return this.intersectsBox( box );
  28794. };
  28795. Ray.prototype.isIntersectionPlane = function ( plane ) {
  28796. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  28797. return this.intersectsPlane( plane );
  28798. };
  28799. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  28800. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28801. return this.intersectsSphere( sphere );
  28802. };
  28803. //
  28804. Triangle.prototype.area = function () {
  28805. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  28806. return this.getArea();
  28807. };
  28808. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  28809. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28810. return this.getBarycoord( point, target );
  28811. };
  28812. Triangle.prototype.midpoint = function ( target ) {
  28813. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  28814. return this.getMidpoint( target );
  28815. };
  28816. Triangle.prototypenormal = function ( target ) {
  28817. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28818. return this.getNormal( target );
  28819. };
  28820. Triangle.prototype.plane = function ( target ) {
  28821. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  28822. return this.getPlane( target );
  28823. };
  28824. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  28825. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28826. return Triangle.getBarycoord( point, a, b, c, target );
  28827. };
  28828. Triangle.normal = function ( a, b, c, target ) {
  28829. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28830. return Triangle.getNormal( a, b, c, target );
  28831. };
  28832. //
  28833. Shape.prototype.extractAllPoints = function ( divisions ) {
  28834. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  28835. return this.extractPoints( divisions );
  28836. };
  28837. Shape.prototype.extrude = function ( options ) {
  28838. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  28839. return new ExtrudeGeometry( this, options );
  28840. };
  28841. Shape.prototype.makeGeometry = function ( options ) {
  28842. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  28843. return new ShapeGeometry( this, options );
  28844. };
  28845. //
  28846. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  28847. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28848. return this.fromBufferAttribute( attribute, index, offset );
  28849. };
  28850. Vector2.prototype.distanceToManhattan = function ( v ) {
  28851. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28852. return this.manhattanDistanceTo( v );
  28853. };
  28854. Vector2.prototype.lengthManhattan = function () {
  28855. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  28856. return this.manhattanLength();
  28857. };
  28858. //
  28859. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28860. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  28861. };
  28862. Vector3.prototype.setEulerFromQuaternion = function () {
  28863. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  28864. };
  28865. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  28866. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  28867. return this.setFromMatrixPosition( m );
  28868. };
  28869. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  28870. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  28871. return this.setFromMatrixScale( m );
  28872. };
  28873. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  28874. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  28875. return this.setFromMatrixColumn( matrix, index );
  28876. };
  28877. Vector3.prototype.applyProjection = function ( m ) {
  28878. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  28879. return this.applyMatrix4( m );
  28880. };
  28881. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  28882. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28883. return this.fromBufferAttribute( attribute, index, offset );
  28884. };
  28885. Vector3.prototype.distanceToManhattan = function ( v ) {
  28886. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28887. return this.manhattanDistanceTo( v );
  28888. };
  28889. Vector3.prototype.lengthManhattan = function () {
  28890. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  28891. return this.manhattanLength();
  28892. };
  28893. //
  28894. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  28895. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28896. return this.fromBufferAttribute( attribute, index, offset );
  28897. };
  28898. Vector4.prototype.lengthManhattan = function () {
  28899. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  28900. return this.manhattanLength();
  28901. };
  28902. //
  28903. Object3D.prototype.getChildByName = function ( name ) {
  28904. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  28905. return this.getObjectByName( name );
  28906. };
  28907. Object3D.prototype.renderDepth = function () {
  28908. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  28909. };
  28910. Object3D.prototype.translate = function ( distance, axis ) {
  28911. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  28912. return this.translateOnAxis( axis, distance );
  28913. };
  28914. Object3D.prototype.getWorldRotation = function () {
  28915. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  28916. };
  28917. Object3D.prototype.applyMatrix = function ( matrix ) {
  28918. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  28919. return this.applyMatrix4( matrix );
  28920. };
  28921. Object.defineProperties( Object3D.prototype, {
  28922. eulerOrder: {
  28923. get: function () {
  28924. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28925. return this.rotation.order;
  28926. },
  28927. set: function ( value ) {
  28928. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28929. this.rotation.order = value;
  28930. }
  28931. },
  28932. useQuaternion: {
  28933. get: function () {
  28934. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28935. },
  28936. set: function () {
  28937. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28938. }
  28939. }
  28940. } );
  28941. Mesh.prototype.setDrawMode = function () {
  28942. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28943. };
  28944. Object.defineProperties( Mesh.prototype, {
  28945. drawMode: {
  28946. get: function () {
  28947. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  28948. return TrianglesDrawMode;
  28949. },
  28950. set: function () {
  28951. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28952. }
  28953. }
  28954. } );
  28955. SkinnedMesh.prototype.initBones = function () {
  28956. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  28957. };
  28958. //
  28959. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  28960. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  28961. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  28962. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  28963. this.setFocalLength( focalLength );
  28964. };
  28965. //
  28966. Object.defineProperties( Light.prototype, {
  28967. onlyShadow: {
  28968. set: function () {
  28969. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  28970. }
  28971. },
  28972. shadowCameraFov: {
  28973. set: function ( value ) {
  28974. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  28975. this.shadow.camera.fov = value;
  28976. }
  28977. },
  28978. shadowCameraLeft: {
  28979. set: function ( value ) {
  28980. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  28981. this.shadow.camera.left = value;
  28982. }
  28983. },
  28984. shadowCameraRight: {
  28985. set: function ( value ) {
  28986. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  28987. this.shadow.camera.right = value;
  28988. }
  28989. },
  28990. shadowCameraTop: {
  28991. set: function ( value ) {
  28992. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  28993. this.shadow.camera.top = value;
  28994. }
  28995. },
  28996. shadowCameraBottom: {
  28997. set: function ( value ) {
  28998. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  28999. this.shadow.camera.bottom = value;
  29000. }
  29001. },
  29002. shadowCameraNear: {
  29003. set: function ( value ) {
  29004. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29005. this.shadow.camera.near = value;
  29006. }
  29007. },
  29008. shadowCameraFar: {
  29009. set: function ( value ) {
  29010. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29011. this.shadow.camera.far = value;
  29012. }
  29013. },
  29014. shadowCameraVisible: {
  29015. set: function () {
  29016. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29017. }
  29018. },
  29019. shadowBias: {
  29020. set: function ( value ) {
  29021. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29022. this.shadow.bias = value;
  29023. }
  29024. },
  29025. shadowDarkness: {
  29026. set: function () {
  29027. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29028. }
  29029. },
  29030. shadowMapWidth: {
  29031. set: function ( value ) {
  29032. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29033. this.shadow.mapSize.width = value;
  29034. }
  29035. },
  29036. shadowMapHeight: {
  29037. set: function ( value ) {
  29038. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29039. this.shadow.mapSize.height = value;
  29040. }
  29041. }
  29042. } );
  29043. //
  29044. Object.defineProperties( BufferAttribute.prototype, {
  29045. length: {
  29046. get: function () {
  29047. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29048. return this.array.length;
  29049. }
  29050. },
  29051. dynamic: {
  29052. get: function () {
  29053. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29054. return this.usage === DynamicDrawUsage;
  29055. },
  29056. set: function ( /* value */ ) {
  29057. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29058. this.setUsage( DynamicDrawUsage );
  29059. }
  29060. }
  29061. } );
  29062. BufferAttribute.prototype.setDynamic = function ( value ) {
  29063. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29064. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29065. return this;
  29066. };
  29067. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  29068. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  29069. },
  29070. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  29071. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29072. };
  29073. //
  29074. BufferGeometry.prototype.addIndex = function ( index ) {
  29075. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29076. this.setIndex( index );
  29077. };
  29078. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  29079. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  29080. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  29081. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  29082. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  29083. }
  29084. if ( name === 'index' ) {
  29085. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  29086. this.setIndex( attribute );
  29087. return this;
  29088. }
  29089. return this.setAttribute( name, attribute );
  29090. };
  29091. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  29092. if ( indexOffset !== undefined ) {
  29093. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29094. }
  29095. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29096. this.addGroup( start, count );
  29097. };
  29098. BufferGeometry.prototype.clearDrawCalls = function () {
  29099. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29100. this.clearGroups();
  29101. };
  29102. BufferGeometry.prototype.computeOffsets = function () {
  29103. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29104. };
  29105. BufferGeometry.prototype.removeAttribute = function ( name ) {
  29106. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  29107. return this.deleteAttribute( name );
  29108. };
  29109. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  29110. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  29111. return this.applyMatrix4( matrix );
  29112. };
  29113. Object.defineProperties( BufferGeometry.prototype, {
  29114. drawcalls: {
  29115. get: function () {
  29116. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29117. return this.groups;
  29118. }
  29119. },
  29120. offsets: {
  29121. get: function () {
  29122. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29123. return this.groups;
  29124. }
  29125. }
  29126. } );
  29127. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  29128. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29129. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29130. return this;
  29131. };
  29132. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  29133. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29134. };
  29135. //
  29136. ExtrudeGeometry.prototype.getArrays = function () {
  29137. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  29138. };
  29139. ExtrudeGeometry.prototype.addShapeList = function () {
  29140. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  29141. };
  29142. ExtrudeGeometry.prototype.addShape = function () {
  29143. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  29144. };
  29145. //
  29146. Scene.prototype.dispose = function () {
  29147. console.error( 'THREE.Scene: .dispose() has been removed.' );
  29148. };
  29149. //
  29150. Uniform.prototype.onUpdate = function () {
  29151. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29152. return this;
  29153. };
  29154. //
  29155. Object.defineProperties( Material.prototype, {
  29156. wrapAround: {
  29157. get: function () {
  29158. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29159. },
  29160. set: function () {
  29161. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29162. }
  29163. },
  29164. overdraw: {
  29165. get: function () {
  29166. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29167. },
  29168. set: function () {
  29169. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29170. }
  29171. },
  29172. wrapRGB: {
  29173. get: function () {
  29174. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  29175. return new Color();
  29176. }
  29177. },
  29178. shading: {
  29179. get: function () {
  29180. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29181. },
  29182. set: function ( value ) {
  29183. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29184. this.flatShading = ( value === FlatShading );
  29185. }
  29186. },
  29187. stencilMask: {
  29188. get: function () {
  29189. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29190. return this.stencilFuncMask;
  29191. },
  29192. set: function ( value ) {
  29193. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29194. this.stencilFuncMask = value;
  29195. }
  29196. },
  29197. vertexTangents: {
  29198. get: function () {
  29199. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29200. },
  29201. set: function () {
  29202. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29203. }
  29204. },
  29205. } );
  29206. Object.defineProperties( ShaderMaterial.prototype, {
  29207. derivatives: {
  29208. get: function () {
  29209. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29210. return this.extensions.derivatives;
  29211. },
  29212. set: function ( value ) {
  29213. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29214. this.extensions.derivatives = value;
  29215. }
  29216. }
  29217. } );
  29218. //
  29219. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  29220. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  29221. this.setRenderTarget( renderTarget );
  29222. this.clear( color, depth, stencil );
  29223. };
  29224. WebGLRenderer.prototype.animate = function ( callback ) {
  29225. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  29226. this.setAnimationLoop( callback );
  29227. };
  29228. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  29229. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  29230. return this.getRenderTarget();
  29231. };
  29232. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  29233. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  29234. return this.capabilities.getMaxAnisotropy();
  29235. };
  29236. WebGLRenderer.prototype.getPrecision = function () {
  29237. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  29238. return this.capabilities.precision;
  29239. };
  29240. WebGLRenderer.prototype.resetGLState = function () {
  29241. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  29242. return this.state.reset();
  29243. };
  29244. WebGLRenderer.prototype.supportsFloatTextures = function () {
  29245. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29246. return this.extensions.get( 'OES_texture_float' );
  29247. };
  29248. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  29249. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29250. return this.extensions.get( 'OES_texture_half_float' );
  29251. };
  29252. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  29253. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29254. return this.extensions.get( 'OES_standard_derivatives' );
  29255. };
  29256. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  29257. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29258. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29259. };
  29260. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  29261. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29262. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29263. };
  29264. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  29265. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29266. return this.extensions.get( 'EXT_blend_minmax' );
  29267. };
  29268. WebGLRenderer.prototype.supportsVertexTextures = function () {
  29269. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29270. return this.capabilities.vertexTextures;
  29271. };
  29272. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  29273. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29274. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29275. };
  29276. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  29277. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29278. this.setScissorTest( boolean );
  29279. };
  29280. WebGLRenderer.prototype.initMaterial = function () {
  29281. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29282. };
  29283. WebGLRenderer.prototype.addPrePlugin = function () {
  29284. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29285. };
  29286. WebGLRenderer.prototype.addPostPlugin = function () {
  29287. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  29288. };
  29289. WebGLRenderer.prototype.updateShadowMap = function () {
  29290. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29291. };
  29292. WebGLRenderer.prototype.setFaceCulling = function () {
  29293. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  29294. };
  29295. WebGLRenderer.prototype.allocTextureUnit = function () {
  29296. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  29297. };
  29298. WebGLRenderer.prototype.setTexture = function () {
  29299. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  29300. };
  29301. WebGLRenderer.prototype.setTexture2D = function () {
  29302. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  29303. };
  29304. WebGLRenderer.prototype.setTextureCube = function () {
  29305. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  29306. };
  29307. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29308. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  29309. return this.getActiveMipmapLevel();
  29310. };
  29311. Object.defineProperties( WebGLRenderer.prototype, {
  29312. shadowMapEnabled: {
  29313. get: function () {
  29314. return this.shadowMap.enabled;
  29315. },
  29316. set: function ( value ) {
  29317. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29318. this.shadowMap.enabled = value;
  29319. }
  29320. },
  29321. shadowMapType: {
  29322. get: function () {
  29323. return this.shadowMap.type;
  29324. },
  29325. set: function ( value ) {
  29326. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29327. this.shadowMap.type = value;
  29328. }
  29329. },
  29330. shadowMapCullFace: {
  29331. get: function () {
  29332. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29333. return undefined;
  29334. },
  29335. set: function ( /* value */ ) {
  29336. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29337. }
  29338. },
  29339. context: {
  29340. get: function () {
  29341. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  29342. return this.getContext();
  29343. }
  29344. },
  29345. vr: {
  29346. get: function () {
  29347. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  29348. return this.xr;
  29349. }
  29350. },
  29351. gammaInput: {
  29352. get: function () {
  29353. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29354. return false;
  29355. },
  29356. set: function () {
  29357. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29358. }
  29359. },
  29360. gammaOutput: {
  29361. get: function () {
  29362. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29363. return false;
  29364. },
  29365. set: function ( value ) {
  29366. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29367. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  29368. }
  29369. },
  29370. toneMappingWhitePoint: {
  29371. get: function () {
  29372. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29373. return 1.0;
  29374. },
  29375. set: function () {
  29376. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29377. }
  29378. },
  29379. } );
  29380. Object.defineProperties( WebGLShadowMap.prototype, {
  29381. cullFace: {
  29382. get: function () {
  29383. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29384. return undefined;
  29385. },
  29386. set: function ( /* cullFace */ ) {
  29387. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29388. }
  29389. },
  29390. renderReverseSided: {
  29391. get: function () {
  29392. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29393. return undefined;
  29394. },
  29395. set: function () {
  29396. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29397. }
  29398. },
  29399. renderSingleSided: {
  29400. get: function () {
  29401. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29402. return undefined;
  29403. },
  29404. set: function () {
  29405. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29406. }
  29407. }
  29408. } );
  29409. function WebGLRenderTargetCube( width, height, options ) {
  29410. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  29411. return new WebGLCubeRenderTarget( width, options );
  29412. }
  29413. //
  29414. Object.defineProperties( WebGLRenderTarget.prototype, {
  29415. wrapS: {
  29416. get: function () {
  29417. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29418. return this.texture.wrapS;
  29419. },
  29420. set: function ( value ) {
  29421. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29422. this.texture.wrapS = value;
  29423. }
  29424. },
  29425. wrapT: {
  29426. get: function () {
  29427. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29428. return this.texture.wrapT;
  29429. },
  29430. set: function ( value ) {
  29431. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29432. this.texture.wrapT = value;
  29433. }
  29434. },
  29435. magFilter: {
  29436. get: function () {
  29437. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29438. return this.texture.magFilter;
  29439. },
  29440. set: function ( value ) {
  29441. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29442. this.texture.magFilter = value;
  29443. }
  29444. },
  29445. minFilter: {
  29446. get: function () {
  29447. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29448. return this.texture.minFilter;
  29449. },
  29450. set: function ( value ) {
  29451. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29452. this.texture.minFilter = value;
  29453. }
  29454. },
  29455. anisotropy: {
  29456. get: function () {
  29457. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29458. return this.texture.anisotropy;
  29459. },
  29460. set: function ( value ) {
  29461. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29462. this.texture.anisotropy = value;
  29463. }
  29464. },
  29465. offset: {
  29466. get: function () {
  29467. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29468. return this.texture.offset;
  29469. },
  29470. set: function ( value ) {
  29471. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29472. this.texture.offset = value;
  29473. }
  29474. },
  29475. repeat: {
  29476. get: function () {
  29477. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29478. return this.texture.repeat;
  29479. },
  29480. set: function ( value ) {
  29481. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29482. this.texture.repeat = value;
  29483. }
  29484. },
  29485. format: {
  29486. get: function () {
  29487. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29488. return this.texture.format;
  29489. },
  29490. set: function ( value ) {
  29491. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29492. this.texture.format = value;
  29493. }
  29494. },
  29495. type: {
  29496. get: function () {
  29497. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29498. return this.texture.type;
  29499. },
  29500. set: function ( value ) {
  29501. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29502. this.texture.type = value;
  29503. }
  29504. },
  29505. generateMipmaps: {
  29506. get: function () {
  29507. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29508. return this.texture.generateMipmaps;
  29509. },
  29510. set: function ( value ) {
  29511. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29512. this.texture.generateMipmaps = value;
  29513. }
  29514. }
  29515. } );
  29516. //
  29517. Audio.prototype.load = function ( file ) {
  29518. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29519. const scope = this;
  29520. const audioLoader = new AudioLoader();
  29521. audioLoader.load( file, function ( buffer ) {
  29522. scope.setBuffer( buffer );
  29523. } );
  29524. return this;
  29525. };
  29526. AudioAnalyser.prototype.getData = function () {
  29527. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29528. return this.getFrequencyData();
  29529. };
  29530. //
  29531. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  29532. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  29533. return this.update( renderer, scene );
  29534. };
  29535. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  29536. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  29537. return this.renderTarget.clear( renderer, color, depth, stencil );
  29538. };
  29539. ImageUtils.crossOrigin = undefined;
  29540. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  29541. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29542. const loader = new TextureLoader();
  29543. loader.setCrossOrigin( this.crossOrigin );
  29544. const texture = loader.load( url, onLoad, undefined, onError );
  29545. if ( mapping ) texture.mapping = mapping;
  29546. return texture;
  29547. };
  29548. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  29549. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29550. const loader = new CubeTextureLoader();
  29551. loader.setCrossOrigin( this.crossOrigin );
  29552. const texture = loader.load( urls, onLoad, undefined, onError );
  29553. if ( mapping ) texture.mapping = mapping;
  29554. return texture;
  29555. };
  29556. ImageUtils.loadCompressedTexture = function () {
  29557. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29558. };
  29559. ImageUtils.loadCompressedTextureCube = function () {
  29560. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29561. };
  29562. //
  29563. function CanvasRenderer() {
  29564. console.error( 'THREE.CanvasRenderer has been removed' );
  29565. }
  29566. //
  29567. function JSONLoader() {
  29568. console.error( 'THREE.JSONLoader has been removed.' );
  29569. }
  29570. //
  29571. const SceneUtils = {
  29572. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  29573. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29574. },
  29575. detach: function ( /* child, parent, scene */ ) {
  29576. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29577. },
  29578. attach: function ( /* child, scene, parent */ ) {
  29579. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29580. }
  29581. };
  29582. //
  29583. function LensFlare() {
  29584. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  29585. }
  29586. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29587. /* eslint-disable no-undef */
  29588. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29589. revision: REVISION,
  29590. } } ) );
  29591. /* eslint-enable no-undef */
  29592. }
  29593. if ( typeof window !== 'undefined' ) {
  29594. if ( window.__THREE__ ) {
  29595. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29596. } else {
  29597. window.__THREE__ = REVISION;
  29598. }
  29599. }
  29600. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, 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, BoxGeometry as BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleGeometry as CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeGeometry as ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry as CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry as DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry as ExtrudeBufferGeometry, ExtrudeGeometry, FaceColors, FileLoader, FlatShading, Float16BufferAttribute, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GammaEncoding, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry as IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry as LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, 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, MathUtils as Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilte