Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

52057 righe
1.2 MiB

  1. /******/ (() => { // webpackBootstrap
  2. /******/ var __webpack_modules__ = ({
  3. /***/ "../../Users/chop/Desktop/chamran/Three/texture/text.png":
  4. /*!***************************************************************!*\
  5. !*** ../../Users/chop/Desktop/chamran/Three/texture/text.png ***!
  6. \***************************************************************/
  7. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8. "use strict";
  9. __webpack_require__.r(__webpack_exports__);
  10. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  11. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  12. /* harmony export */ });
  13. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "2fc205c5dd2bec64ca543627f54923a0.png");
  14. /***/ }),
  15. /***/ "./node_modules/three-dragcontrols/lib/index.module.js":
  16. /*!*************************************************************!*\
  17. !*** ./node_modules/three-dragcontrols/lib/index.module.js ***!
  18. \*************************************************************/
  19. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  20. "use strict";
  21. __webpack_require__.r(__webpack_exports__);
  22. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  23. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  24. /* harmony export */ });
  25. /* harmony import */ var three__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! three */ "./node_modules/three/build/three.module.js");
  26. /*
  27. * @author zz85 / https://github.com/zz85
  28. * @author mrdoob / http://mrdoob.com
  29. * Running this will allow you to drag three.js objects around the screen.
  30. */
  31. function DragControls(_objects, _camera, _domElement) {
  32. if (_objects.isCamera) {
  33. console.warn('THREE.DragControls: Constructor now expects ( objects, camera, domElement )');
  34. var temp = _objects;
  35. _objects = _camera;
  36. _camera = temp;
  37. }
  38. var _plane = new three__WEBPACK_IMPORTED_MODULE_0__.Plane();
  39. var _raycaster = new three__WEBPACK_IMPORTED_MODULE_0__.Raycaster();
  40. var _mouse = new three__WEBPACK_IMPORTED_MODULE_0__.Vector2();
  41. var _offset = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();
  42. var _intersection = new three__WEBPACK_IMPORTED_MODULE_0__.Vector3();
  43. var _selected = null,
  44. _hovered = null;
  45. //
  46. var scope = this;
  47. function activate() {
  48. _domElement.addEventListener('mousemove', onDocumentMouseMove, false);
  49. _domElement.addEventListener('mousedown', onDocumentMouseDown, false);
  50. _domElement.addEventListener('mouseup', onDocumentMouseCancel, false);
  51. _domElement.addEventListener('mouseleave', onDocumentMouseCancel, false);
  52. _domElement.addEventListener('touchmove', onDocumentTouchMove, false);
  53. _domElement.addEventListener('touchstart', onDocumentTouchStart, false);
  54. _domElement.addEventListener('touchend', onDocumentTouchEnd, false);
  55. }
  56. function deactivate() {
  57. _domElement.removeEventListener('mousemove', onDocumentMouseMove, false);
  58. _domElement.removeEventListener('mousedown', onDocumentMouseDown, false);
  59. _domElement.removeEventListener('mouseup', onDocumentMouseCancel, false);
  60. _domElement.removeEventListener('mouseleave', onDocumentMouseCancel, false);
  61. _domElement.removeEventListener('touchmove', onDocumentTouchMove, false);
  62. _domElement.removeEventListener('touchstart', onDocumentTouchStart, false);
  63. _domElement.removeEventListener('touchend', onDocumentTouchEnd, false);
  64. }
  65. function dispose() {
  66. deactivate();
  67. }
  68. function onDocumentMouseMove(event) {
  69. event.preventDefault();
  70. var rect = _domElement.getBoundingClientRect();
  71. _mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  72. _mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  73. _raycaster.setFromCamera(_mouse, _camera);
  74. if (_selected && scope.enabled) {
  75. if (_raycaster.ray.intersectPlane(_plane, _intersection)) {
  76. _selected.position.copy(_intersection.sub(_offset));
  77. }
  78. scope.dispatchEvent({
  79. type: 'drag',
  80. object: _selected
  81. });
  82. return;
  83. }
  84. _raycaster.setFromCamera(_mouse, _camera);
  85. var intersects = _raycaster.intersectObjects(_objects);
  86. if (intersects.length > 0) {
  87. var object = intersects[0].object;
  88. _plane.setFromNormalAndCoplanarPoint(_camera.getWorldDirection(_plane.normal), object.position);
  89. if (_hovered !== object) {
  90. scope.dispatchEvent({
  91. type: 'hoveron',
  92. object: object
  93. });
  94. _domElement.style.cursor = 'pointer';
  95. _hovered = object;
  96. }
  97. } else {
  98. if (_hovered !== null) {
  99. scope.dispatchEvent({
  100. type: 'hoveroff',
  101. object: _hovered
  102. });
  103. _domElement.style.cursor = 'auto';
  104. _hovered = null;
  105. }
  106. }
  107. }
  108. function onDocumentMouseDown(event) {
  109. event.preventDefault();
  110. _raycaster.setFromCamera(_mouse, _camera);
  111. var intersects = _raycaster.intersectObjects(_objects);
  112. if (intersects.length > 0) {
  113. _selected = intersects[0].object;
  114. if (_raycaster.ray.intersectPlane(_plane, _intersection)) {
  115. _offset.copy(_intersection).sub(_selected.position);
  116. }
  117. _domElement.style.cursor = 'move';
  118. scope.dispatchEvent({
  119. type: 'dragstart',
  120. object: _selected
  121. });
  122. }
  123. }
  124. function onDocumentMouseCancel(event) {
  125. event.preventDefault();
  126. if (_selected) {
  127. scope.dispatchEvent({
  128. type: 'dragend',
  129. object: _selected
  130. });
  131. _selected = null;
  132. }
  133. _domElement.style.cursor = 'auto';
  134. }
  135. function onDocumentTouchMove(event) {
  136. event.preventDefault();
  137. event = event.changedTouches[0];
  138. var rect = _domElement.getBoundingClientRect();
  139. _mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  140. _mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  141. _raycaster.setFromCamera(_mouse, _camera);
  142. if (_selected && scope.enabled) {
  143. if (_raycaster.ray.intersectPlane(_plane, _intersection)) {
  144. _selected.position.copy(_intersection.sub(_offset));
  145. }
  146. scope.dispatchEvent({
  147. type: 'drag',
  148. object: _selected
  149. });
  150. return;
  151. }
  152. }
  153. function onDocumentTouchStart(event) {
  154. event.preventDefault();
  155. event = event.changedTouches[0];
  156. var rect = _domElement.getBoundingClientRect();
  157. _mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  158. _mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  159. _raycaster.setFromCamera(_mouse, _camera);
  160. var intersects = _raycaster.intersectObjects(_objects);
  161. if (intersects.length > 0) {
  162. _selected = intersects[0].object;
  163. _plane.setFromNormalAndCoplanarPoint(_camera.getWorldDirection(_plane.normal), _selected.position);
  164. if (_raycaster.ray.intersectPlane(_plane, _intersection)) {
  165. _offset.copy(_intersection).sub(_selected.position);
  166. }
  167. _domElement.style.cursor = 'move';
  168. scope.dispatchEvent({
  169. type: 'dragstart',
  170. object: _selected
  171. });
  172. }
  173. }
  174. function onDocumentTouchEnd(event) {
  175. event.preventDefault();
  176. if (_selected) {
  177. scope.dispatchEvent({
  178. type: 'dragend',
  179. object: _selected
  180. });
  181. _selected = null;
  182. }
  183. _domElement.style.cursor = 'auto';
  184. }
  185. activate();
  186. // API
  187. this.enabled = true;
  188. this.activate = activate;
  189. this.deactivate = deactivate;
  190. this.dispose = dispose;
  191. // Backward compatibility
  192. this.setObjects = function() {
  193. console.error('THREE.DragControls: setObjects() has been removed.');
  194. };
  195. this.on = function(type, listener) {
  196. console.warn('THREE.DragControls: on() has been deprecated. Use addEventListener() instead.');
  197. scope.addEventListener(type, listener);
  198. };
  199. this.off = function(type, listener) {
  200. console.warn('THREE.DragControls: off() has been deprecated. Use removeEventListener() instead.');
  201. scope.removeEventListener(type, listener);
  202. };
  203. this.notify = function(type) {
  204. console.error('THREE.DragControls: notify() has been deprecated. Use dispatchEvent() instead.');
  205. scope.dispatchEvent({
  206. type: type
  207. });
  208. };
  209. }
  210. DragControls.prototype = Object.create(three__WEBPACK_IMPORTED_MODULE_0__.EventDispatcher.prototype);
  211. DragControls.prototype.constructor = DragControls;
  212. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (DragControls);
  213. /***/ }),
  214. /***/ "./node_modules/three-orbitcontrols/OrbitControls.js":
  215. /*!***********************************************************!*\
  216. !*** ./node_modules/three-orbitcontrols/OrbitControls.js ***!
  217. \***********************************************************/
  218. /***/ ((module, exports, __webpack_require__) => {
  219. /* three-orbitcontrols addendum */ var THREE = __webpack_require__(/*! three */ "./node_modules/three/build/three.module.js");
  220. /**
  221. * @author qiao / https://github.com/qiao
  222. * @author mrdoob / http://mrdoob.com
  223. * @author alteredq / http://alteredqualia.com/
  224. * @author WestLangley / http://github.com/WestLangley
  225. * @author erich666 / http://erichaines.com
  226. * @author ScieCode / http://github.com/sciecode
  227. */
  228. // This set of controls performs orbiting, dollying (zooming), and panning.
  229. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  230. //
  231. // Orbit - left mouse / touch: one-finger move
  232. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  233. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  234. THREE.OrbitControls = function ( object, domElement ) {
  235. if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' );
  236. if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
  237. this.object = object;
  238. this.domElement = domElement;
  239. // Set to false to disable this control
  240. this.enabled = true;
  241. // "target" sets the location of focus, where the object orbits around
  242. this.target = new THREE.Vector3();
  243. // How far you can dolly in and out ( PerspectiveCamera only )
  244. this.minDistance = 0;
  245. this.maxDistance = Infinity;
  246. // How far you can zoom in and out ( OrthographicCamera only )
  247. this.minZoom = 0;
  248. this.maxZoom = Infinity;
  249. // How far you can orbit vertically, upper and lower limits.
  250. // Range is 0 to Math.PI radians.
  251. this.minPolarAngle = 0; // radians
  252. this.maxPolarAngle = Math.PI; // radians
  253. // How far you can orbit horizontally, upper and lower limits.
  254. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  255. this.minAzimuthAngle = - Infinity; // radians
  256. this.maxAzimuthAngle = Infinity; // radians
  257. // Set to true to enable damping (inertia)
  258. // If damping is enabled, you must call controls.update() in your animation loop
  259. this.enableDamping = false;
  260. this.dampingFactor = 0.05;
  261. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  262. // Set to false to disable zooming
  263. this.enableZoom = true;
  264. this.zoomSpeed = 1.0;
  265. // Set to false to disable rotating
  266. this.enableRotate = true;
  267. this.rotateSpeed = 1.0;
  268. // Set to false to disable panning
  269. this.enablePan = true;
  270. this.panSpeed = 1.0;
  271. this.screenSpacePanning = false; // if true, pan in screen-space
  272. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  273. // Set to true to automatically rotate around the target
  274. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  275. this.autoRotate = false;
  276. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  277. // Set to false to disable use of the keys
  278. this.enableKeys = true;
  279. // The four arrow keys
  280. this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };
  281. // Mouse buttons
  282. this.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN };
  283. // Touch fingers
  284. this.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN };
  285. // for reset
  286. this.target0 = this.target.clone();
  287. this.position0 = this.object.position.clone();
  288. this.zoom0 = this.object.zoom;
  289. //
  290. // public methods
  291. //
  292. this.getPolarAngle = function () {
  293. return spherical.phi;
  294. };
  295. this.getAzimuthalAngle = function () {
  296. return spherical.theta;
  297. };
  298. this.saveState = function () {
  299. scope.target0.copy( scope.target );
  300. scope.position0.copy( scope.object.position );
  301. scope.zoom0 = scope.object.zoom;
  302. };
  303. this.reset = function () {
  304. scope.target.copy( scope.target0 );
  305. scope.object.position.copy( scope.position0 );
  306. scope.object.zoom = scope.zoom0;
  307. scope.object.updateProjectionMatrix();
  308. scope.dispatchEvent( changeEvent );
  309. scope.update();
  310. state = STATE.NONE;
  311. };
  312. // this method is exposed, but perhaps it would be better if we can make it private...
  313. this.update = function () {
  314. var offset = new THREE.Vector3();
  315. // so camera.up is the orbit axis
  316. var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) );
  317. var quatInverse = quat.clone().inverse();
  318. var lastPosition = new THREE.Vector3();
  319. var lastQuaternion = new THREE.Quaternion();
  320. return function update() {
  321. var position = scope.object.position;
  322. offset.copy( position ).sub( scope.target );
  323. // rotate offset to "y-axis-is-up" space
  324. offset.applyQuaternion( quat );
  325. // angle from z-axis around y-axis
  326. spherical.setFromVector3( offset );
  327. if ( scope.autoRotate && state === STATE.NONE ) {
  328. rotateLeft( getAutoRotationAngle() );
  329. }
  330. if ( scope.enableDamping ) {
  331. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  332. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  333. } else {
  334. spherical.theta += sphericalDelta.theta;
  335. spherical.phi += sphericalDelta.phi;
  336. }
  337. // restrict theta to be between desired limits
  338. spherical.theta = Math.max( scope.minAzimuthAngle, Math.min( scope.maxAzimuthAngle, spherical.theta ) );
  339. // restrict phi to be between desired limits
  340. spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
  341. spherical.makeSafe();
  342. spherical.radius *= scale;
  343. // restrict radius to be between desired limits
  344. spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );
  345. // move target to panned location
  346. if ( scope.enableDamping === true ) {
  347. scope.target.addScaledVector( panOffset, scope.dampingFactor );
  348. } else {
  349. scope.target.add( panOffset );
  350. }
  351. offset.setFromSpherical( spherical );
  352. // rotate offset back to "camera-up-vector-is-up" space
  353. offset.applyQuaternion( quatInverse );
  354. position.copy( scope.target ).add( offset );
  355. scope.object.lookAt( scope.target );
  356. if ( scope.enableDamping === true ) {
  357. sphericalDelta.theta *= ( 1 - scope.dampingFactor );
  358. sphericalDelta.phi *= ( 1 - scope.dampingFactor );
  359. panOffset.multiplyScalar( 1 - scope.dampingFactor );
  360. } else {
  361. sphericalDelta.set( 0, 0, 0 );
  362. panOffset.set( 0, 0, 0 );
  363. }
  364. scale = 1;
  365. // update condition is:
  366. // min(camera displacement, camera rotation in radians)^2 > EPS
  367. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  368. if ( zoomChanged ||
  369. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  370. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
  371. scope.dispatchEvent( changeEvent );
  372. lastPosition.copy( scope.object.position );
  373. lastQuaternion.copy( scope.object.quaternion );
  374. zoomChanged = false;
  375. return true;
  376. }
  377. return false;
  378. };
  379. }();
  380. this.dispose = function () {
  381. scope.domElement.removeEventListener( 'contextmenu', onContextMenu, false );
  382. scope.domElement.removeEventListener( 'mousedown', onMouseDown, false );
  383. scope.domElement.removeEventListener( 'wheel', onMouseWheel, false );
  384. scope.domElement.removeEventListener( 'touchstart', onTouchStart, false );
  385. scope.domElement.removeEventListener( 'touchend', onTouchEnd, false );
  386. scope.domElement.removeEventListener( 'touchmove', onTouchMove, false );
  387. document.removeEventListener( 'mousemove', onMouseMove, false );
  388. document.removeEventListener( 'mouseup', onMouseUp, false );
  389. scope.domElement.removeEventListener( 'keydown', onKeyDown, false );
  390. //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  391. };
  392. //
  393. // internals
  394. //
  395. var scope = this;
  396. var changeEvent = { type: 'change' };
  397. var startEvent = { type: 'start' };
  398. var endEvent = { type: 'end' };
  399. var STATE = {
  400. NONE: - 1,
  401. ROTATE: 0,
  402. DOLLY: 1,
  403. PAN: 2,
  404. TOUCH_ROTATE: 3,
  405. TOUCH_PAN: 4,
  406. TOUCH_DOLLY_PAN: 5,
  407. TOUCH_DOLLY_ROTATE: 6
  408. };
  409. var state = STATE.NONE;
  410. var EPS = 0.000001;
  411. // current position in spherical coordinates
  412. var spherical = new THREE.Spherical();
  413. var sphericalDelta = new THREE.Spherical();
  414. var scale = 1;
  415. var panOffset = new THREE.Vector3();
  416. var zoomChanged = false;
  417. var rotateStart = new THREE.Vector2();
  418. var rotateEnd = new THREE.Vector2();
  419. var rotateDelta = new THREE.Vector2();
  420. var panStart = new THREE.Vector2();
  421. var panEnd = new THREE.Vector2();
  422. var panDelta = new THREE.Vector2();
  423. var dollyStart = new THREE.Vector2();
  424. var dollyEnd = new THREE.Vector2();
  425. var dollyDelta = new THREE.Vector2();
  426. function getAutoRotationAngle() {
  427. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  428. }
  429. function getZoomScale() {
  430. return Math.pow( 0.95, scope.zoomSpeed );
  431. }
  432. function rotateLeft( angle ) {
  433. sphericalDelta.theta -= angle;
  434. }
  435. function rotateUp( angle ) {
  436. sphericalDelta.phi -= angle;
  437. }
  438. var panLeft = function () {
  439. var v = new THREE.Vector3();
  440. return function panLeft( distance, objectMatrix ) {
  441. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  442. v.multiplyScalar( - distance );
  443. panOffset.add( v );
  444. };
  445. }();
  446. var panUp = function () {
  447. var v = new THREE.Vector3();
  448. return function panUp( distance, objectMatrix ) {
  449. if ( scope.screenSpacePanning === true ) {
  450. v.setFromMatrixColumn( objectMatrix, 1 );
  451. } else {
  452. v.setFromMatrixColumn( objectMatrix, 0 );
  453. v.crossVectors( scope.object.up, v );
  454. }
  455. v.multiplyScalar( distance );
  456. panOffset.add( v );
  457. };
  458. }();
  459. // deltaX and deltaY are in pixels; right and down are positive
  460. var pan = function () {
  461. var offset = new THREE.Vector3();
  462. return function pan( deltaX, deltaY ) {
  463. var element = scope.domElement;
  464. if ( scope.object.isPerspectiveCamera ) {
  465. // perspective
  466. var position = scope.object.position;
  467. offset.copy( position ).sub( scope.target );
  468. var targetDistance = offset.length();
  469. // half of the fov is center to top of screen
  470. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  471. // we use only clientHeight here so aspect ratio does not distort speed
  472. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  473. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  474. } else if ( scope.object.isOrthographicCamera ) {
  475. // orthographic
  476. panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
  477. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
  478. } else {
  479. // camera neither orthographic nor perspective
  480. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  481. scope.enablePan = false;
  482. }
  483. };
  484. }();
  485. function dollyIn( dollyScale ) {
  486. if ( scope.object.isPerspectiveCamera ) {
  487. scale /= dollyScale;
  488. } else if ( scope.object.isOrthographicCamera ) {
  489. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
  490. scope.object.updateProjectionMatrix();
  491. zoomChanged = true;
  492. } else {
  493. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  494. scope.enableZoom = false;
  495. }
  496. }
  497. function dollyOut( dollyScale ) {
  498. if ( scope.object.isPerspectiveCamera ) {
  499. scale *= dollyScale;
  500. } else if ( scope.object.isOrthographicCamera ) {
  501. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
  502. scope.object.updateProjectionMatrix();
  503. zoomChanged = true;
  504. } else {
  505. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  506. scope.enableZoom = false;
  507. }
  508. }
  509. //
  510. // event callbacks - update the object state
  511. //
  512. function handleMouseDownRotate( event ) {
  513. rotateStart.set( event.clientX, event.clientY );
  514. }
  515. function handleMouseDownDolly( event ) {
  516. dollyStart.set( event.clientX, event.clientY );
  517. }
  518. function handleMouseDownPan( event ) {
  519. panStart.set( event.clientX, event.clientY );
  520. }
  521. function handleMouseMoveRotate( event ) {
  522. rotateEnd.set( event.clientX, event.clientY );
  523. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  524. var element = scope.domElement;
  525. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  526. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  527. rotateStart.copy( rotateEnd );
  528. scope.update();
  529. }
  530. function handleMouseMoveDolly( event ) {
  531. dollyEnd.set( event.clientX, event.clientY );
  532. dollyDelta.subVectors( dollyEnd, dollyStart );
  533. if ( dollyDelta.y > 0 ) {
  534. dollyIn( getZoomScale() );
  535. } else if ( dollyDelta.y < 0 ) {
  536. dollyOut( getZoomScale() );
  537. }
  538. dollyStart.copy( dollyEnd );
  539. scope.update();
  540. }
  541. function handleMouseMovePan( event ) {
  542. panEnd.set( event.clientX, event.clientY );
  543. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  544. pan( panDelta.x, panDelta.y );
  545. panStart.copy( panEnd );
  546. scope.update();
  547. }
  548. function handleMouseUp( /*event*/ ) {
  549. // no-op
  550. }
  551. function handleMouseWheel( event ) {
  552. if ( event.deltaY < 0 ) {
  553. dollyOut( getZoomScale() );
  554. } else if ( event.deltaY > 0 ) {
  555. dollyIn( getZoomScale() );
  556. }
  557. scope.update();
  558. }
  559. function handleKeyDown( event ) {
  560. var needsUpdate = false;
  561. switch ( event.keyCode ) {
  562. case scope.keys.UP:
  563. pan( 0, scope.keyPanSpeed );
  564. needsUpdate = true;
  565. break;
  566. case scope.keys.BOTTOM:
  567. pan( 0, - scope.keyPanSpeed );
  568. needsUpdate = true;
  569. break;
  570. case scope.keys.LEFT:
  571. pan( scope.keyPanSpeed, 0 );
  572. needsUpdate = true;
  573. break;
  574. case scope.keys.RIGHT:
  575. pan( - scope.keyPanSpeed, 0 );
  576. needsUpdate = true;
  577. break;
  578. }
  579. if ( needsUpdate ) {
  580. // prevent the browser from scrolling on cursor keys
  581. event.preventDefault();
  582. scope.update();
  583. }
  584. }
  585. function handleTouchStartRotate( event ) {
  586. if ( event.touches.length == 1 ) {
  587. rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  588. } else {
  589. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  590. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  591. rotateStart.set( x, y );
  592. }
  593. }
  594. function handleTouchStartPan( event ) {
  595. if ( event.touches.length == 1 ) {
  596. panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  597. } else {
  598. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  599. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  600. panStart.set( x, y );
  601. }
  602. }
  603. function handleTouchStartDolly( event ) {
  604. var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  605. var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  606. var distance = Math.sqrt( dx * dx + dy * dy );
  607. dollyStart.set( 0, distance );
  608. }
  609. function handleTouchStartDollyPan( event ) {
  610. if ( scope.enableZoom ) handleTouchStartDolly( event );
  611. if ( scope.enablePan ) handleTouchStartPan( event );
  612. }
  613. function handleTouchStartDollyRotate( event ) {
  614. if ( scope.enableZoom ) handleTouchStartDolly( event );
  615. if ( scope.enableRotate ) handleTouchStartRotate( event );
  616. }
  617. function handleTouchMoveRotate( event ) {
  618. if ( event.touches.length == 1 ) {
  619. rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  620. } else {
  621. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  622. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  623. rotateEnd.set( x, y );
  624. }
  625. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  626. var element = scope.domElement;
  627. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  628. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  629. rotateStart.copy( rotateEnd );
  630. }
  631. function handleTouchMovePan( event ) {
  632. if ( event.touches.length == 1 ) {
  633. panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  634. } else {
  635. var x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  636. var y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  637. panEnd.set( x, y );
  638. }
  639. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  640. pan( panDelta.x, panDelta.y );
  641. panStart.copy( panEnd );
  642. }
  643. function handleTouchMoveDolly( event ) {
  644. var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  645. var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  646. var distance = Math.sqrt( dx * dx + dy * dy );
  647. dollyEnd.set( 0, distance );
  648. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  649. dollyIn( dollyDelta.y );
  650. dollyStart.copy( dollyEnd );
  651. }
  652. function handleTouchMoveDollyPan( event ) {
  653. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  654. if ( scope.enablePan ) handleTouchMovePan( event );
  655. }
  656. function handleTouchMoveDollyRotate( event ) {
  657. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  658. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  659. }
  660. function handleTouchEnd( /*event*/ ) {
  661. // no-op
  662. }
  663. //
  664. // event handlers - FSM: listen for events and reset state
  665. //
  666. function onMouseDown( event ) {
  667. if ( scope.enabled === false ) return;
  668. // Prevent the browser from scrolling.
  669. event.preventDefault();
  670. // Manually set the focus since calling preventDefault above
  671. // prevents the browser from setting it automatically.
  672. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  673. switch ( event.button ) {
  674. case 0:
  675. switch ( scope.mouseButtons.LEFT ) {
  676. case THREE.MOUSE.ROTATE:
  677. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  678. if ( scope.enablePan === false ) return;
  679. handleMouseDownPan( event );
  680. state = STATE.PAN;
  681. } else {
  682. if ( scope.enableRotate === false ) return;
  683. handleMouseDownRotate( event );
  684. state = STATE.ROTATE;
  685. }
  686. break;
  687. case THREE.MOUSE.PAN:
  688. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  689. if ( scope.enableRotate === false ) return;
  690. handleMouseDownRotate( event );
  691. state = STATE.ROTATE;
  692. } else {
  693. if ( scope.enablePan === false ) return;
  694. handleMouseDownPan( event );
  695. state = STATE.PAN;
  696. }
  697. break;
  698. default:
  699. state = STATE.NONE;
  700. }
  701. break;
  702. case 1:
  703. switch ( scope.mouseButtons.MIDDLE ) {
  704. case THREE.MOUSE.DOLLY:
  705. if ( scope.enableZoom === false ) return;
  706. handleMouseDownDolly( event );
  707. state = STATE.DOLLY;
  708. break;
  709. default:
  710. state = STATE.NONE;
  711. }
  712. break;
  713. case 2:
  714. switch ( scope.mouseButtons.RIGHT ) {
  715. case THREE.MOUSE.ROTATE:
  716. if ( scope.enableRotate === false ) return;
  717. handleMouseDownRotate( event );
  718. state = STATE.ROTATE;
  719. break;
  720. case THREE.MOUSE.PAN:
  721. if ( scope.enablePan === false ) return;
  722. handleMouseDownPan( event );
  723. state = STATE.PAN;
  724. break;
  725. default:
  726. state = STATE.NONE;
  727. }
  728. break;
  729. }
  730. if ( state !== STATE.NONE ) {
  731. document.addEventListener( 'mousemove', onMouseMove, false );
  732. document.addEventListener( 'mouseup', onMouseUp, false );
  733. scope.dispatchEvent( startEvent );
  734. }
  735. }
  736. function onMouseMove( event ) {
  737. if ( scope.enabled === false ) return;
  738. event.preventDefault();
  739. switch ( state ) {
  740. case STATE.ROTATE:
  741. if ( scope.enableRotate === false ) return;
  742. handleMouseMoveRotate( event );
  743. break;
  744. case STATE.DOLLY:
  745. if ( scope.enableZoom === false ) return;
  746. handleMouseMoveDolly( event );
  747. break;
  748. case STATE.PAN:
  749. if ( scope.enablePan === false ) return;
  750. handleMouseMovePan( event );
  751. break;
  752. }
  753. }
  754. function onMouseUp( event ) {
  755. if ( scope.enabled === false ) return;
  756. handleMouseUp( event );
  757. document.removeEventListener( 'mousemove', onMouseMove, false );
  758. document.removeEventListener( 'mouseup', onMouseUp, false );
  759. scope.dispatchEvent( endEvent );
  760. state = STATE.NONE;
  761. }
  762. function onMouseWheel( event ) {
  763. if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return;
  764. event.preventDefault();
  765. event.stopPropagation();
  766. scope.dispatchEvent( startEvent );
  767. handleMouseWheel( event );
  768. scope.dispatchEvent( endEvent );
  769. }
  770. function onKeyDown( event ) {
  771. if ( scope.enabled === false || scope.enableKeys === false || scope.enablePan === false ) return;
  772. handleKeyDown( event );
  773. }
  774. function onTouchStart( event ) {
  775. if ( scope.enabled === false ) return;
  776. event.preventDefault();
  777. switch ( event.touches.length ) {
  778. case 1:
  779. switch ( scope.touches.ONE ) {
  780. case THREE.TOUCH.ROTATE:
  781. if ( scope.enableRotate === false ) return;
  782. handleTouchStartRotate( event );
  783. state = STATE.TOUCH_ROTATE;
  784. break;
  785. case THREE.TOUCH.PAN:
  786. if ( scope.enablePan === false ) return;
  787. handleTouchStartPan( event );
  788. state = STATE.TOUCH_PAN;
  789. break;
  790. default:
  791. state = STATE.NONE;
  792. }
  793. break;
  794. case 2:
  795. switch ( scope.touches.TWO ) {
  796. case THREE.TOUCH.DOLLY_PAN:
  797. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  798. handleTouchStartDollyPan( event );
  799. state = STATE.TOUCH_DOLLY_PAN;
  800. break;
  801. case THREE.TOUCH.DOLLY_ROTATE:
  802. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  803. handleTouchStartDollyRotate( event );
  804. state = STATE.TOUCH_DOLLY_ROTATE;
  805. break;
  806. default:
  807. state = STATE.NONE;
  808. }
  809. break;
  810. default:
  811. state = STATE.NONE;
  812. }
  813. if ( state !== STATE.NONE ) {
  814. scope.dispatchEvent( startEvent );
  815. }
  816. }
  817. function onTouchMove( event ) {
  818. if ( scope.enabled === false ) return;
  819. event.preventDefault();
  820. event.stopPropagation();
  821. switch ( state ) {
  822. case STATE.TOUCH_ROTATE:
  823. if ( scope.enableRotate === false ) return;
  824. handleTouchMoveRotate( event );
  825. scope.update();
  826. break;
  827. case STATE.TOUCH_PAN:
  828. if ( scope.enablePan === false ) return;
  829. handleTouchMovePan( event );
  830. scope.update();
  831. break;
  832. case STATE.TOUCH_DOLLY_PAN:
  833. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  834. handleTouchMoveDollyPan( event );
  835. scope.update();
  836. break;
  837. case STATE.TOUCH_DOLLY_ROTATE:
  838. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  839. handleTouchMoveDollyRotate( event );
  840. scope.update();
  841. break;
  842. default:
  843. state = STATE.NONE;
  844. }
  845. }
  846. function onTouchEnd( event ) {
  847. if ( scope.enabled === false ) return;
  848. handleTouchEnd( event );
  849. scope.dispatchEvent( endEvent );
  850. state = STATE.NONE;
  851. }
  852. function onContextMenu( event ) {
  853. if ( scope.enabled === false ) return;
  854. event.preventDefault();
  855. }
  856. //
  857. scope.domElement.addEventListener( 'contextmenu', onContextMenu, false );
  858. scope.domElement.addEventListener( 'mousedown', onMouseDown, false );
  859. scope.domElement.addEventListener( 'wheel', onMouseWheel, false );
  860. scope.domElement.addEventListener( 'touchstart', onTouchStart, false );
  861. scope.domElement.addEventListener( 'touchend', onTouchEnd, false );
  862. scope.domElement.addEventListener( 'touchmove', onTouchMove, false );
  863. scope.domElement.addEventListener( 'keydown', onKeyDown, false );
  864. // make sure element can receive keys.
  865. if ( scope.domElement.tabIndex === - 1 ) {
  866. scope.domElement.tabIndex = 0;
  867. }
  868. // force an update at start
  869. this.update();
  870. };
  871. THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype );
  872. THREE.OrbitControls.prototype.constructor = THREE.OrbitControls;
  873. // This set of controls performs orbiting, dollying (zooming), and panning.
  874. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  875. // This is very similar to OrbitControls, another set of touch behavior
  876. //
  877. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  878. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  879. // Pan - left mouse, or arrow keys / touch: one-finger move
  880. THREE.MapControls = function ( object, domElement ) {
  881. THREE.OrbitControls.call( this, object, domElement );
  882. this.mouseButtons.LEFT = THREE.MOUSE.PAN;
  883. this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE;
  884. this.touches.ONE = THREE.TOUCH.PAN;
  885. this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE;
  886. };
  887. THREE.MapControls.prototype = Object.create( THREE.EventDispatcher.prototype );
  888. THREE.MapControls.prototype.constructor = THREE.MapControls;
  889. /* three-orbitcontrols addendum */ module.exports = exports["default"] = THREE.OrbitControls;
  890. /***/ }),
  891. /***/ "./node_modules/three/build/three.module.js":
  892. /*!**************************************************!*\
  893. !*** ./node_modules/three/build/three.module.js ***!
  894. \**************************************************/
  895. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  896. "use strict";
  897. __webpack_require__.r(__webpack_exports__);
  898. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  899. /* harmony export */ "ACESFilmicToneMapping": () => (/* binding */ ACESFilmicToneMapping),
  900. /* harmony export */ "AddEquation": () => (/* binding */ AddEquation),
  901. /* harmony export */ "AddOperation": () => (/* binding */ AddOperation),
  902. /* harmony export */ "AdditiveAnimationBlendMode": () => (/* binding */ AdditiveAnimationBlendMode),
  903. /* harmony export */ "AdditiveBlending": () => (/* binding */ AdditiveBlending),
  904. /* harmony export */ "AlphaFormat": () => (/* binding */ AlphaFormat),
  905. /* harmony export */ "AlwaysDepth": () => (/* binding */ AlwaysDepth),
  906. /* harmony export */ "AlwaysStencilFunc": () => (/* binding */ AlwaysStencilFunc),
  907. /* harmony export */ "AmbientLight": () => (/* binding */ AmbientLight),
  908. /* harmony export */ "AmbientLightProbe": () => (/* binding */ AmbientLightProbe),
  909. /* harmony export */ "AnimationClip": () => (/* binding */ AnimationClip),
  910. /* harmony export */ "AnimationLoader": () => (/* binding */ AnimationLoader),
  911. /* harmony export */ "AnimationMixer": () => (/* binding */ AnimationMixer),
  912. /* harmony export */ "AnimationObjectGroup": () => (/* binding */ AnimationObjectGroup),
  913. /* harmony export */ "AnimationUtils": () => (/* binding */ AnimationUtils),
  914. /* harmony export */ "ArcCurve": () => (/* binding */ ArcCurve),
  915. /* harmony export */ "ArrayCamera": () => (/* binding */ ArrayCamera),
  916. /* harmony export */ "ArrowHelper": () => (/* binding */ ArrowHelper),
  917. /* harmony export */ "Audio": () => (/* binding */ Audio),
  918. /* harmony export */ "AudioAnalyser": () => (/* binding */ AudioAnalyser),
  919. /* harmony export */ "AudioContext": () => (/* binding */ AudioContext),
  920. /* harmony export */ "AudioListener": () => (/* binding */ AudioListener),
  921. /* harmony export */ "AudioLoader": () => (/* binding */ AudioLoader),
  922. /* harmony export */ "AxesHelper": () => (/* binding */ AxesHelper),
  923. /* harmony export */ "AxisHelper": () => (/* binding */ AxisHelper),
  924. /* harmony export */ "BackSide": () => (/* binding */ BackSide),
  925. /* harmony export */ "BasicDepthPacking": () => (/* binding */ BasicDepthPacking),
  926. /* harmony export */ "BasicShadowMap": () => (/* binding */ BasicShadowMap),
  927. /* harmony export */ "BinaryTextureLoader": () => (/* binding */ BinaryTextureLoader),
  928. /* harmony export */ "Bone": () => (/* binding */ Bone),
  929. /* harmony export */ "BooleanKeyframeTrack": () => (/* binding */ BooleanKeyframeTrack),
  930. /* harmony export */ "BoundingBoxHelper": () => (/* binding */ BoundingBoxHelper),
  931. /* harmony export */ "Box2": () => (/* binding */ Box2),
  932. /* harmony export */ "Box3": () => (/* binding */ Box3),
  933. /* harmony export */ "Box3Helper": () => (/* binding */ Box3Helper),
  934. /* harmony export */ "BoxBufferGeometry": () => (/* binding */ BoxGeometry),
  935. /* harmony export */ "BoxGeometry": () => (/* binding */ BoxGeometry),
  936. /* harmony export */ "BoxHelper": () => (/* binding */ BoxHelper),
  937. /* harmony export */ "BufferAttribute": () => (/* binding */ BufferAttribute),
  938. /* harmony export */ "BufferGeometry": () => (/* binding */ BufferGeometry),
  939. /* harmony export */ "BufferGeometryLoader": () => (/* binding */ BufferGeometryLoader),
  940. /* harmony export */ "ByteType": () => (/* binding */ ByteType),
  941. /* harmony export */ "Cache": () => (/* binding */ Cache),
  942. /* harmony export */ "Camera": () => (/* binding */ Camera),
  943. /* harmony export */ "CameraHelper": () => (/* binding */ CameraHelper),
  944. /* harmony export */ "CanvasRenderer": () => (/* binding */ CanvasRenderer),
  945. /* harmony export */ "CanvasTexture": () => (/* binding */ CanvasTexture),
  946. /* harmony export */ "CatmullRomCurve3": () => (/* binding */ CatmullRomCurve3),
  947. /* harmony export */ "CineonToneMapping": () => (/* binding */ CineonToneMapping),
  948. /* harmony export */ "CircleBufferGeometry": () => (/* binding */ CircleGeometry),
  949. /* harmony export */ "CircleGeometry": () => (/* binding */ CircleGeometry),
  950. /* harmony export */ "ClampToEdgeWrapping": () => (/* binding */ ClampToEdgeWrapping),
  951. /* harmony export */ "Clock": () => (/* binding */ Clock),
  952. /* harmony export */ "Color": () => (/* binding */ Color),
  953. /* harmony export */ "ColorKeyframeTrack": () => (/* binding */ ColorKeyframeTrack),
  954. /* harmony export */ "CompressedTexture": () => (/* binding */ CompressedTexture),
  955. /* harmony export */ "CompressedTextureLoader": () => (/* binding */ CompressedTextureLoader),
  956. /* harmony export */ "ConeBufferGeometry": () => (/* binding */ ConeGeometry),
  957. /* harmony export */ "ConeGeometry": () => (/* binding */ ConeGeometry),
  958. /* harmony export */ "CubeCamera": () => (/* binding */ CubeCamera),
  959. /* harmony export */ "CubeReflectionMapping": () => (/* binding */ CubeReflectionMapping),
  960. /* harmony export */ "CubeRefractionMapping": () => (/* binding */ CubeRefractionMapping),
  961. /* harmony export */ "CubeTexture": () => (/* binding */ CubeTexture),
  962. /* harmony export */ "CubeTextureLoader": () => (/* binding */ CubeTextureLoader),
  963. /* harmony export */ "CubeUVReflectionMapping": () => (/* binding */ CubeUVReflectionMapping),
  964. /* harmony export */ "CubeUVRefractionMapping": () => (/* binding */ CubeUVRefractionMapping),
  965. /* harmony export */ "CubicBezierCurve": () => (/* binding */ CubicBezierCurve),
  966. /* harmony export */ "CubicBezierCurve3": () => (/* binding */ CubicBezierCurve3),
  967. /* harmony export */ "CubicInterpolant": () => (/* binding */ CubicInterpolant),
  968. /* harmony export */ "CullFaceBack": () => (/* binding */ CullFaceBack),
  969. /* harmony export */ "CullFaceFront": () => (/* binding */ CullFaceFront),
  970. /* harmony export */ "CullFaceFrontBack": () => (/* binding */ CullFaceFrontBack),
  971. /* harmony export */ "CullFaceNone": () => (/* binding */ CullFaceNone),
  972. /* harmony export */ "Curve": () => (/* binding */ Curve),
  973. /* harmony export */ "CurvePath": () => (/* binding */ CurvePath),
  974. /* harmony export */ "CustomBlending": () => (/* binding */ CustomBlending),
  975. /* harmony export */ "CustomToneMapping": () => (/* binding */ CustomToneMapping),
  976. /* harmony export */ "CylinderBufferGeometry": () => (/* binding */ CylinderGeometry),
  977. /* harmony export */ "CylinderGeometry": () => (/* binding */ CylinderGeometry),
  978. /* harmony export */ "Cylindrical": () => (/* binding */ Cylindrical),
  979. /* harmony export */ "DataTexture": () => (/* binding */ DataTexture),
  980. /* harmony export */ "DataTexture2DArray": () => (/* binding */ DataTexture2DArray),
  981. /* harmony export */ "DataTexture3D": () => (/* binding */ DataTexture3D),
  982. /* harmony export */ "DataTextureLoader": () => (/* binding */ DataTextureLoader),
  983. /* harmony export */ "DataUtils": () => (/* binding */ DataUtils),
  984. /* harmony export */ "DecrementStencilOp": () => (/* binding */ DecrementStencilOp),
  985. /* harmony export */ "DecrementWrapStencilOp": () => (/* binding */ DecrementWrapStencilOp),
  986. /* harmony export */ "DefaultLoadingManager": () => (/* binding */ DefaultLoadingManager),
  987. /* harmony export */ "DepthFormat": () => (/* binding */ DepthFormat),
  988. /* harmony export */ "DepthStencilFormat": () => (/* binding */ DepthStencilFormat),
  989. /* harmony export */ "DepthTexture": () => (/* binding */ DepthTexture),
  990. /* harmony export */ "DirectionalLight": () => (/* binding */ DirectionalLight),
  991. /* harmony export */ "DirectionalLightHelper": () => (/* binding */ DirectionalLightHelper),
  992. /* harmony export */ "DiscreteInterpolant": () => (/* binding */ DiscreteInterpolant),
  993. /* harmony export */ "DodecahedronBufferGeometry": () => (/* binding */ DodecahedronGeometry),
  994. /* harmony export */ "DodecahedronGeometry": () => (/* binding */ DodecahedronGeometry),
  995. /* harmony export */ "DoubleSide": () => (/* binding */ DoubleSide),
  996. /* harmony export */ "DstAlphaFactor": () => (/* binding */ DstAlphaFactor),
  997. /* harmony export */ "DstColorFactor": () => (/* binding */ DstColorFactor),
  998. /* harmony export */ "DynamicBufferAttribute": () => (/* binding */ DynamicBufferAttribute),
  999. /* harmony export */ "DynamicCopyUsage": () => (/* binding */ DynamicCopyUsage),
  1000. /* harmony export */ "DynamicDrawUsage": () => (/* binding */ DynamicDrawUsage),
  1001. /* harmony export */ "DynamicReadUsage": () => (/* binding */ DynamicReadUsage),
  1002. /* harmony export */ "EdgesGeometry": () => (/* binding */ EdgesGeometry),
  1003. /* harmony export */ "EdgesHelper": () => (/* binding */ EdgesHelper),
  1004. /* harmony export */ "EllipseCurve": () => (/* binding */ EllipseCurve),
  1005. /* harmony export */ "EqualDepth": () => (/* binding */ EqualDepth),
  1006. /* harmony export */ "EqualStencilFunc": () => (/* binding */ EqualStencilFunc),
  1007. /* harmony export */ "EquirectangularReflectionMapping": () => (/* binding */ EquirectangularReflectionMapping),
  1008. /* harmony export */ "EquirectangularRefractionMapping": () => (/* binding */ EquirectangularRefractionMapping),
  1009. /* harmony export */ "Euler": () => (/* binding */ Euler),
  1010. /* harmony export */ "EventDispatcher": () => (/* binding */ EventDispatcher),
  1011. /* harmony export */ "ExtrudeBufferGeometry": () => (/* binding */ ExtrudeGeometry),
  1012. /* harmony export */ "ExtrudeGeometry": () => (/* binding */ ExtrudeGeometry),
  1013. /* harmony export */ "FaceColors": () => (/* binding */ FaceColors),
  1014. /* harmony export */ "FileLoader": () => (/* binding */ FileLoader),
  1015. /* harmony export */ "FlatShading": () => (/* binding */ FlatShading),
  1016. /* harmony export */ "Float16BufferAttribute": () => (/* binding */ Float16BufferAttribute),
  1017. /* harmony export */ "Float32Attribute": () => (/* binding */ Float32Attribute),
  1018. /* harmony export */ "Float32BufferAttribute": () => (/* binding */ Float32BufferAttribute),
  1019. /* harmony export */ "Float64Attribute": () => (/* binding */ Float64Attribute),
  1020. /* harmony export */ "Float64BufferAttribute": () => (/* binding */ Float64BufferAttribute),
  1021. /* harmony export */ "FloatType": () => (/* binding */ FloatType),
  1022. /* harmony export */ "Fog": () => (/* binding */ Fog),
  1023. /* harmony export */ "FogExp2": () => (/* binding */ FogExp2),
  1024. /* harmony export */ "Font": () => (/* binding */ Font),
  1025. /* harmony export */ "FontLoader": () => (/* binding */ FontLoader),
  1026. /* harmony export */ "FrontSide": () => (/* binding */ FrontSide),
  1027. /* harmony export */ "Frustum": () => (/* binding */ Frustum),
  1028. /* harmony export */ "GLBufferAttribute": () => (/* binding */ GLBufferAttribute),
  1029. /* harmony export */ "GLSL1": () => (/* binding */ GLSL1),
  1030. /* harmony export */ "GLSL3": () => (/* binding */ GLSL3),
  1031. /* harmony export */ "GammaEncoding": () => (/* binding */ GammaEncoding),
  1032. /* harmony export */ "GreaterDepth": () => (/* binding */ GreaterDepth),
  1033. /* harmony export */ "GreaterEqualDepth": () => (/* binding */ GreaterEqualDepth),
  1034. /* harmony export */ "GreaterEqualStencilFunc": () => (/* binding */ GreaterEqualStencilFunc),
  1035. /* harmony export */ "GreaterStencilFunc": () => (/* binding */ GreaterStencilFunc),
  1036. /* harmony export */ "GridHelper": () => (/* binding */ GridHelper),
  1037. /* harmony export */ "Group": () => (/* binding */ Group),
  1038. /* harmony export */ "HalfFloatType": () => (/* binding */ HalfFloatType),
  1039. /* harmony export */ "HemisphereLight": () => (/* binding */ HemisphereLight),
  1040. /* harmony export */ "HemisphereLightHelper": () => (/* binding */ HemisphereLightHelper),
  1041. /* harmony export */ "HemisphereLightProbe": () => (/* binding */ HemisphereLightProbe),
  1042. /* harmony export */ "IcosahedronBufferGeometry": () => (/* binding */ IcosahedronGeometry),
  1043. /* harmony export */ "IcosahedronGeometry": () => (/* binding */ IcosahedronGeometry),
  1044. /* harmony export */ "ImageBitmapLoader": () => (/* binding */ ImageBitmapLoader),
  1045. /* harmony export */ "ImageLoader": () => (/* binding */ ImageLoader),
  1046. /* harmony export */ "ImageUtils": () => (/* binding */ ImageUtils),
  1047. /* harmony export */ "ImmediateRenderObject": () => (/* binding */ ImmediateRenderObject),
  1048. /* harmony export */ "IncrementStencilOp": () => (/* binding */ IncrementStencilOp),
  1049. /* harmony export */ "IncrementWrapStencilOp": () => (/* binding */ IncrementWrapStencilOp),
  1050. /* harmony export */ "InstancedBufferAttribute": () => (/* binding */ InstancedBufferAttribute),
  1051. /* harmony export */ "InstancedBufferGeometry": () => (/* binding */ InstancedBufferGeometry),
  1052. /* harmony export */ "InstancedInterleavedBuffer": () => (/* binding */ InstancedInterleavedBuffer),
  1053. /* harmony export */ "InstancedMesh": () => (/* binding */ InstancedMesh),
  1054. /* harmony export */ "Int16Attribute": () => (/* binding */ Int16Attribute),
  1055. /* harmony export */ "Int16BufferAttribute": () => (/* binding */ Int16BufferAttribute),
  1056. /* harmony export */ "Int32Attribute": () => (/* binding */ Int32Attribute),
  1057. /* harmony export */ "Int32BufferAttribute": () => (/* binding */ Int32BufferAttribute),
  1058. /* harmony export */ "Int8Attribute": () => (/* binding */ Int8Attribute),
  1059. /* harmony export */ "Int8BufferAttribute": () => (/* binding */ Int8BufferAttribute),
  1060. /* harmony export */ "IntType": () => (/* binding */ IntType),
  1061. /* harmony export */ "InterleavedBuffer": () => (/* binding */ InterleavedBuffer),
  1062. /* harmony export */ "InterleavedBufferAttribute": () => (/* binding */ InterleavedBufferAttribute),
  1063. /* harmony export */ "Interpolant": () => (/* binding */ Interpolant),
  1064. /* harmony export */ "InterpolateDiscrete": () => (/* binding */ InterpolateDiscrete),
  1065. /* harmony export */ "InterpolateLinear": () => (/* binding */ InterpolateLinear),
  1066. /* harmony export */ "InterpolateSmooth": () => (/* binding */ InterpolateSmooth),
  1067. /* harmony export */ "InvertStencilOp": () => (/* binding */ InvertStencilOp),
  1068. /* harmony export */ "JSONLoader": () => (/* binding */ JSONLoader),
  1069. /* harmony export */ "KeepStencilOp": () => (/* binding */ KeepStencilOp),
  1070. /* harmony export */ "KeyframeTrack": () => (/* binding */ KeyframeTrack),
  1071. /* harmony export */ "LOD": () => (/* binding */ LOD),
  1072. /* harmony export */ "LatheBufferGeometry": () => (/* binding */ LatheGeometry),
  1073. /* harmony export */ "LatheGeometry": () => (/* binding */ LatheGeometry),
  1074. /* harmony export */ "Layers": () => (/* binding */ Layers),
  1075. /* harmony export */ "LensFlare": () => (/* binding */ LensFlare),
  1076. /* harmony export */ "LessDepth": () => (/* binding */ LessDepth),
  1077. /* harmony export */ "LessEqualDepth": () => (/* binding */ LessEqualDepth),
  1078. /* harmony export */ "LessEqualStencilFunc": () => (/* binding */ LessEqualStencilFunc),
  1079. /* harmony export */ "LessStencilFunc": () => (/* binding */ LessStencilFunc),
  1080. /* harmony export */ "Light": () => (/* binding */ Light),
  1081. /* harmony export */ "LightProbe": () => (/* binding */ LightProbe),
  1082. /* harmony export */ "Line": () => (/* binding */ Line),
  1083. /* harmony export */ "Line3": () => (/* binding */ Line3),
  1084. /* harmony export */ "LineBasicMaterial": () => (/* binding */ LineBasicMaterial),
  1085. /* harmony export */ "LineCurve": () => (/* binding */ LineCurve),
  1086. /* harmony export */ "LineCurve3": () => (/* binding */ LineCurve3),
  1087. /* harmony export */ "LineDashedMaterial": () => (/* binding */ LineDashedMaterial),
  1088. /* harmony export */ "LineLoop": () => (/* binding */ LineLoop),
  1089. /* harmony export */ "LinePieces": () => (/* binding */ LinePieces),
  1090. /* harmony export */ "LineSegments": () => (/* binding */ LineSegments),
  1091. /* harmony export */ "LineStrip": () => (/* binding */ LineStrip),
  1092. /* harmony export */ "LinearEncoding": () => (/* binding */ LinearEncoding),
  1093. /* harmony export */ "LinearFilter": () => (/* binding */ LinearFilter),
  1094. /* harmony export */ "LinearInterpolant": () => (/* binding */ LinearInterpolant),
  1095. /* harmony export */ "LinearMipMapLinearFilter": () => (/* binding */ LinearMipMapLinearFilter),
  1096. /* harmony export */ "LinearMipMapNearestFilter": () => (/* binding */ LinearMipMapNearestFilter),
  1097. /* harmony export */ "LinearMipmapLinearFilter": () => (/* binding */ LinearMipmapLinearFilter),
  1098. /* harmony export */ "LinearMipmapNearestFilter": () => (/* binding */ LinearMipmapNearestFilter),
  1099. /* harmony export */ "LinearToneMapping": () => (/* binding */ LinearToneMapping),
  1100. /* harmony export */ "Loader": () => (/* binding */ Loader),
  1101. /* harmony export */ "LoaderUtils": () => (/* binding */ LoaderUtils),
  1102. /* harmony export */ "LoadingManager": () => (/* binding */ LoadingManager),
  1103. /* harmony export */ "LogLuvEncoding": () => (/* binding */ LogLuvEncoding),
  1104. /* harmony export */ "LoopOnce": () => (/* binding */ LoopOnce),
  1105. /* harmony export */ "LoopPingPong": () => (/* binding */ LoopPingPong),
  1106. /* harmony export */ "LoopRepeat": () => (/* binding */ LoopRepeat),
  1107. /* harmony export */ "LuminanceAlphaFormat": () => (/* binding */ LuminanceAlphaFormat),
  1108. /* harmony export */ "LuminanceFormat": () => (/* binding */ LuminanceFormat),
  1109. /* harmony export */ "MOUSE": () => (/* binding */ MOUSE),
  1110. /* harmony export */ "Material": () => (/* binding */ Material),
  1111. /* harmony export */ "MaterialLoader": () => (/* binding */ MaterialLoader),
  1112. /* harmony export */ "Math": () => (/* binding */ MathUtils),
  1113. /* harmony export */ "MathUtils": () => (/* binding */ MathUtils),
  1114. /* harmony export */ "Matrix3": () => (/* binding */ Matrix3),
  1115. /* harmony export */ "Matrix4": () => (/* binding */ Matrix4),
  1116. /* harmony export */ "MaxEquation": () => (/* binding */ MaxEquation),
  1117. /* harmony export */ "Mesh": () => (/* binding */ Mesh),
  1118. /* harmony export */ "MeshBasicMaterial": () => (/* binding */ MeshBasicMaterial),
  1119. /* harmony export */ "MeshDepthMaterial": () => (/* binding */ MeshDepthMaterial),
  1120. /* harmony export */ "MeshDistanceMaterial": () => (/* binding */ MeshDistanceMaterial),
  1121. /* harmony export */ "MeshFaceMaterial": () => (/* binding */ MeshFaceMaterial),
  1122. /* harmony export */ "MeshLambertMaterial": () => (/* binding */ MeshLambertMaterial),
  1123. /* harmony export */ "MeshMatcapMaterial": () => (/* binding */ MeshMatcapMaterial),
  1124. /* harmony export */ "MeshNormalMaterial": () => (/* binding */ MeshNormalMaterial),
  1125. /* harmony export */ "MeshPhongMaterial": () => (/* binding */ MeshPhongMaterial),
  1126. /* harmony export */ "MeshPhysicalMaterial": () => (/* binding */ MeshPhysicalMaterial),
  1127. /* harmony export */ "MeshStandardMaterial": () => (/* binding */ MeshStandardMaterial),
  1128. /* harmony export */ "MeshToonMaterial": () => (/* binding */ MeshToonMaterial),
  1129. /* harmony export */ "MinEquation": () => (/* binding */ MinEquation),
  1130. /* harmony export */ "MirroredRepeatWrapping": () => (/* binding */ MirroredRepeatWrapping),
  1131. /* harmony export */ "MixOperation": () => (/* binding */ MixOperation),
  1132. /* harmony export */ "MultiMaterial": () => (/* binding */ MultiMaterial),
  1133. /* harmony export */ "MultiplyBlending": () => (/* binding */ MultiplyBlending),
  1134. /* harmony export */ "MultiplyOperation": () => (/* binding */ MultiplyOperation),
  1135. /* harmony export */ "NearestFilter": () => (/* binding */ NearestFilter),
  1136. /* harmony export */ "NearestMipMapLinearFilter": () => (/* binding */ NearestMipMapLinearFilter),
  1137. /* harmony export */ "NearestMipMapNearestFilter": () => (/* binding */ NearestMipMapNearestFilter),
  1138. /* harmony export */ "NearestMipmapLinearFilter": () => (/* binding */ NearestMipmapLinearFilter),
  1139. /* harmony export */ "NearestMipmapNearestFilter": () => (/* binding */ NearestMipmapNearestFilter),
  1140. /* harmony export */ "NeverDepth": () => (/* binding */ NeverDepth),
  1141. /* harmony export */ "NeverStencilFunc": () => (/* binding */ NeverStencilFunc),
  1142. /* harmony export */ "NoBlending": () => (/* binding */ NoBlending),
  1143. /* harmony export */ "NoColors": () => (/* binding */ NoColors),
  1144. /* harmony export */ "NoToneMapping": () => (/* binding */ NoToneMapping),
  1145. /* harmony export */ "NormalAnimationBlendMode": () => (/* binding */ NormalAnimationBlendMode),
  1146. /* harmony export */ "NormalBlending": () => (/* binding */ NormalBlending),
  1147. /* harmony export */ "NotEqualDepth": () => (/* binding */ NotEqualDepth),
  1148. /* harmony export */ "NotEqualStencilFunc": () => (/* binding */ NotEqualStencilFunc),
  1149. /* harmony export */ "NumberKeyframeTrack": () => (/* binding */ NumberKeyframeTrack),
  1150. /* harmony export */ "Object3D": () => (/* binding */ Object3D),
  1151. /* harmony export */ "ObjectLoader": () => (/* binding */ ObjectLoader),
  1152. /* harmony export */ "ObjectSpaceNormalMap": () => (/* binding */ ObjectSpaceNormalMap),
  1153. /* harmony export */ "OctahedronBufferGeometry": () => (/* binding */ OctahedronGeometry),
  1154. /* harmony export */ "OctahedronGeometry": () => (/* binding */ OctahedronGeometry),
  1155. /* harmony export */ "OneFactor": () => (/* binding */ OneFactor),
  1156. /* harmony export */ "OneMinusDstAlphaFactor": () => (/* binding */ OneMinusDstAlphaFactor),
  1157. /* harmony export */ "OneMinusDstColorFactor": () => (/* binding */ OneMinusDstColorFactor),
  1158. /* harmony export */ "OneMinusSrcAlphaFactor": () => (/* binding */ OneMinusSrcAlphaFactor),
  1159. /* harmony export */ "OneMinusSrcColorFactor": () => (/* binding */ OneMinusSrcColorFactor),
  1160. /* harmony export */ "OrthographicCamera": () => (/* binding */ OrthographicCamera),
  1161. /* harmony export */ "PCFShadowMap": () => (/* binding */ PCFShadowMap),
  1162. /* harmony export */ "PCFSoftShadowMap": () => (/* binding */ PCFSoftShadowMap),
  1163. /* harmony export */ "PMREMGenerator": () => (/* binding */ PMREMGenerator),
  1164. /* harmony export */ "ParametricBufferGeometry": () => (/* binding */ ParametricGeometry),
  1165. /* harmony export */ "ParametricGeometry": () => (/* binding */ ParametricGeometry),
  1166. /* harmony export */ "Particle": () => (/* binding */ Particle),
  1167. /* harmony export */ "ParticleBasicMaterial": () => (/* binding */ ParticleBasicMaterial),
  1168. /* harmony export */ "ParticleSystem": () => (/* binding */ ParticleSystem),
  1169. /* harmony export */ "ParticleSystemMaterial": () => (/* binding */ ParticleSystemMaterial),
  1170. /* harmony export */ "Path": () => (/* binding */ Path),
  1171. /* harmony export */ "PerspectiveCamera": () => (/* binding */ PerspectiveCamera),
  1172. /* harmony export */ "Plane": () => (/* binding */ Plane),
  1173. /* harmony export */ "PlaneBufferGeometry": () => (/* binding */ PlaneGeometry),
  1174. /* harmony export */ "PlaneGeometry": () => (/* binding */ PlaneGeometry),
  1175. /* harmony export */ "PlaneHelper": () => (/* binding */ PlaneHelper),
  1176. /* harmony export */ "PointCloud": () => (/* binding */ PointCloud),
  1177. /* harmony export */ "PointCloudMaterial": () => (/* binding */ PointCloudMaterial),
  1178. /* harmony export */ "PointLight": () => (/* binding */ PointLight),
  1179. /* harmony export */ "PointLightHelper": () => (/* binding */ PointLightHelper),
  1180. /* harmony export */ "Points": () => (/* binding */ Points),
  1181. /* harmony export */ "PointsMaterial": () => (/* binding */ PointsMaterial),
  1182. /* harmony export */ "PolarGridHelper": () => (/* binding */ PolarGridHelper),
  1183. /* harmony export */ "PolyhedronBufferGeometry": () => (/* binding */ PolyhedronGeometry),
  1184. /* harmony export */ "PolyhedronGeometry": () => (/* binding */ PolyhedronGeometry),
  1185. /* harmony export */ "PositionalAudio": () => (/* binding */ PositionalAudio),
  1186. /* harmony export */ "PropertyBinding": () => (/* binding */ PropertyBinding),
  1187. /* harmony export */ "PropertyMixer": () => (/* binding */ PropertyMixer),
  1188. /* harmony export */ "QuadraticBezierCurve": () => (/* binding */ QuadraticBezierCurve),
  1189. /* harmony export */ "QuadraticBezierCurve3": () => (/* binding */ QuadraticBezierCurve3),
  1190. /* harmony export */ "Quaternion": () => (/* binding */ Quaternion),
  1191. /* harmony export */ "QuaternionKeyframeTrack": () => (/* binding */ QuaternionKeyframeTrack),
  1192. /* harmony export */ "QuaternionLinearInterpolant": () => (/* binding */ QuaternionLinearInterpolant),
  1193. /* harmony export */ "REVISION": () => (/* binding */ REVISION),
  1194. /* harmony export */ "RGBADepthPacking": () => (/* binding */ RGBADepthPacking),
  1195. /* harmony export */ "RGBAFormat": () => (/* binding */ RGBAFormat),
  1196. /* harmony export */ "RGBAIntegerFormat": () => (/* binding */ RGBAIntegerFormat),
  1197. /* harmony export */ "RGBA_ASTC_10x10_Format": () => (/* binding */ RGBA_ASTC_10x10_Format),
  1198. /* harmony export */ "RGBA_ASTC_10x5_Format": () => (/* binding */ RGBA_ASTC_10x5_Format),
  1199. /* harmony export */ "RGBA_ASTC_10x6_Format": () => (/* binding */ RGBA_ASTC_10x6_Format),
  1200. /* harmony export */ "RGBA_ASTC_10x8_Format": () => (/* binding */ RGBA_ASTC_10x8_Format),
  1201. /* harmony export */ "RGBA_ASTC_12x10_Format": () => (/* binding */ RGBA_ASTC_12x10_Format),
  1202. /* harmony export */ "RGBA_ASTC_12x12_Format": () => (/* binding */ RGBA_ASTC_12x12_Format),
  1203. /* harmony export */ "RGBA_ASTC_4x4_Format": () => (/* binding */ RGBA_ASTC_4x4_Format),
  1204. /* harmony export */ "RGBA_ASTC_5x4_Format": () => (/* binding */ RGBA_ASTC_5x4_Format),
  1205. /* harmony export */ "RGBA_ASTC_5x5_Format": () => (/* binding */ RGBA_ASTC_5x5_Format),
  1206. /* harmony export */ "RGBA_ASTC_6x5_Format": () => (/* binding */ RGBA_ASTC_6x5_Format),
  1207. /* harmony export */ "RGBA_ASTC_6x6_Format": () => (/* binding */ RGBA_ASTC_6x6_Format),
  1208. /* harmony export */ "RGBA_ASTC_8x5_Format": () => (/* binding */ RGBA_ASTC_8x5_Format),
  1209. /* harmony export */ "RGBA_ASTC_8x6_Format": () => (/* binding */ RGBA_ASTC_8x6_Format),
  1210. /* harmony export */ "RGBA_ASTC_8x8_Format": () => (/* binding */ RGBA_ASTC_8x8_Format),
  1211. /* harmony export */ "RGBA_BPTC_Format": () => (/* binding */ RGBA_BPTC_Format),
  1212. /* harmony export */ "RGBA_ETC2_EAC_Format": () => (/* binding */ RGBA_ETC2_EAC_Format),
  1213. /* harmony export */ "RGBA_PVRTC_2BPPV1_Format": () => (/* binding */ RGBA_PVRTC_2BPPV1_Format),
  1214. /* harmony export */ "RGBA_PVRTC_4BPPV1_Format": () => (/* binding */ RGBA_PVRTC_4BPPV1_Format),
  1215. /* harmony export */ "RGBA_S3TC_DXT1_Format": () => (/* binding */ RGBA_S3TC_DXT1_Format),
  1216. /* harmony export */ "RGBA_S3TC_DXT3_Format": () => (/* binding */ RGBA_S3TC_DXT3_Format),
  1217. /* harmony export */ "RGBA_S3TC_DXT5_Format": () => (/* binding */ RGBA_S3TC_DXT5_Format),
  1218. /* harmony export */ "RGBDEncoding": () => (/* binding */ RGBDEncoding),
  1219. /* harmony export */ "RGBEEncoding": () => (/* binding */ RGBEEncoding),
  1220. /* harmony export */ "RGBEFormat": () => (/* binding */ RGBEFormat),
  1221. /* harmony export */ "RGBFormat": () => (/* binding */ RGBFormat),
  1222. /* harmony export */ "RGBIntegerFormat": () => (/* binding */ RGBIntegerFormat),
  1223. /* harmony export */ "RGBM16Encoding": () => (/* binding */ RGBM16Encoding),
  1224. /* harmony export */ "RGBM7Encoding": () => (/* binding */ RGBM7Encoding),
  1225. /* harmony export */ "RGB_ETC1_Format": () => (/* binding */ RGB_ETC1_Format),
  1226. /* harmony export */ "RGB_ETC2_Format": () => (/* binding */ RGB_ETC2_Format),
  1227. /* harmony export */ "RGB_PVRTC_2BPPV1_Format": () => (/* binding */ RGB_PVRTC_2BPPV1_Format),
  1228. /* harmony export */ "RGB_PVRTC_4BPPV1_Format": () => (/* binding */ RGB_PVRTC_4BPPV1_Format),
  1229. /* harmony export */ "RGB_S3TC_DXT1_Format": () => (/* binding */ RGB_S3TC_DXT1_Format),
  1230. /* harmony export */ "RGFormat": () => (/* binding */ RGFormat),
  1231. /* harmony export */ "RGIntegerFormat": () => (/* binding */ RGIntegerFormat),
  1232. /* harmony export */ "RawShaderMaterial": () => (/* binding */ RawShaderMaterial),
  1233. /* harmony export */ "Ray": () => (/* binding */ Ray),
  1234. /* harmony export */ "Raycaster": () => (/* binding */ Raycaster),
  1235. /* harmony export */ "RectAreaLight": () => (/* binding */ RectAreaLight),
  1236. /* harmony export */ "RedFormat": () => (/* binding */ RedFormat),
  1237. /* harmony export */ "RedIntegerFormat": () => (/* binding */ RedIntegerFormat),
  1238. /* harmony export */ "ReinhardToneMapping": () => (/* binding */ ReinhardToneMapping),
  1239. /* harmony export */ "RepeatWrapping": () => (/* binding */ RepeatWrapping),
  1240. /* harmony export */ "ReplaceStencilOp": () => (/* binding */ ReplaceStencilOp),
  1241. /* harmony export */ "ReverseSubtractEquation": () => (/* binding */ ReverseSubtractEquation),
  1242. /* harmony export */ "RingBufferGeometry": () => (/* binding */ RingGeometry),
  1243. /* harmony export */ "RingGeometry": () => (/* binding */ RingGeometry),
  1244. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x10_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x10_Format),
  1245. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x5_Format),
  1246. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x6_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x6_Format),
  1247. /* harmony export */ "SRGB8_ALPHA8_ASTC_10x8_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_10x8_Format),
  1248. /* harmony export */ "SRGB8_ALPHA8_ASTC_12x10_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_12x10_Format),
  1249. /* harmony export */ "SRGB8_ALPHA8_ASTC_12x12_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_12x12_Format),
  1250. /* harmony export */ "SRGB8_ALPHA8_ASTC_4x4_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_4x4_Format),
  1251. /* harmony export */ "SRGB8_ALPHA8_ASTC_5x4_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_5x4_Format),
  1252. /* harmony export */ "SRGB8_ALPHA8_ASTC_5x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_5x5_Format),
  1253. /* harmony export */ "SRGB8_ALPHA8_ASTC_6x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_6x5_Format),
  1254. /* harmony export */ "SRGB8_ALPHA8_ASTC_6x6_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_6x6_Format),
  1255. /* harmony export */ "SRGB8_ALPHA8_ASTC_8x5_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_8x5_Format),
  1256. /* harmony export */ "SRGB8_ALPHA8_ASTC_8x6_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_8x6_Format),
  1257. /* harmony export */ "SRGB8_ALPHA8_ASTC_8x8_Format": () => (/* binding */ SRGB8_ALPHA8_ASTC_8x8_Format),
  1258. /* harmony export */ "Scene": () => (/* binding */ Scene),
  1259. /* harmony export */ "SceneUtils": () => (/* binding */ SceneUtils),
  1260. /* harmony export */ "ShaderChunk": () => (/* binding */ ShaderChunk),
  1261. /* harmony export */ "ShaderLib": () => (/* binding */ ShaderLib),
  1262. /* harmony export */ "ShaderMaterial": () => (/* binding */ ShaderMaterial),
  1263. /* harmony export */ "ShadowMaterial": () => (/* binding */ ShadowMaterial),
  1264. /* harmony export */ "Shape": () => (/* binding */ Shape),
  1265. /* harmony export */ "ShapeBufferGeometry": () => (/* binding */ ShapeGeometry),
  1266. /* harmony export */ "ShapeGeometry": () => (/* binding */ ShapeGeometry),
  1267. /* harmony export */ "ShapePath": () => (/* binding */ ShapePath),
  1268. /* harmony export */ "ShapeUtils": () => (/* binding */ ShapeUtils),
  1269. /* harmony export */ "ShortType": () => (/* binding */ ShortType),
  1270. /* harmony export */ "Skeleton": () => (/* binding */ Skeleton),
  1271. /* harmony export */ "SkeletonHelper": () => (/* binding */ SkeletonHelper),
  1272. /* harmony export */ "SkinnedMesh": () => (/* binding */ SkinnedMesh),
  1273. /* harmony export */ "SmoothShading": () => (/* binding */ SmoothShading),
  1274. /* harmony export */ "Sphere": () => (/* binding */ Sphere),
  1275. /* harmony export */ "SphereBufferGeometry": () => (/* binding */ SphereGeometry),
  1276. /* harmony export */ "SphereGeometry": () => (/* binding */ SphereGeometry),
  1277. /* harmony export */ "Spherical": () => (/* binding */ Spherical),
  1278. /* harmony export */ "SphericalHarmonics3": () => (/* binding */ SphericalHarmonics3),
  1279. /* harmony export */ "SplineCurve": () => (/* binding */ SplineCurve),
  1280. /* harmony export */ "SpotLight": () => (/* binding */ SpotLight),
  1281. /* harmony export */ "SpotLightHelper": () => (/* binding */ SpotLightHelper),
  1282. /* harmony export */ "Sprite": () => (/* binding */ Sprite),
  1283. /* harmony export */ "SpriteMaterial": () => (/* binding */ SpriteMaterial),
  1284. /* harmony export */ "SrcAlphaFactor": () => (/* binding */ SrcAlphaFactor),
  1285. /* harmony export */ "SrcAlphaSaturateFactor": () => (/* binding */ SrcAlphaSaturateFactor),
  1286. /* harmony export */ "SrcColorFactor": () => (/* binding */ SrcColorFactor),
  1287. /* harmony export */ "StaticCopyUsage": () => (/* binding */ StaticCopyUsage),
  1288. /* harmony export */ "StaticDrawUsage": () => (/* binding */ StaticDrawUsage),
  1289. /* harmony export */ "StaticReadUsage": () => (/* binding */ StaticReadUsage),
  1290. /* harmony export */ "StereoCamera": () => (/* binding */ StereoCamera),
  1291. /* harmony export */ "StreamCopyUsage": () => (/* binding */ StreamCopyUsage),
  1292. /* harmony export */ "StreamDrawUsage": () => (/* binding */ StreamDrawUsage),
  1293. /* harmony export */ "StreamReadUsage": () => (/* binding */ StreamReadUsage),
  1294. /* harmony export */ "StringKeyframeTrack": () => (/* binding */ StringKeyframeTrack),
  1295. /* harmony export */ "SubtractEquation": () => (/* binding */ SubtractEquation),
  1296. /* harmony export */ "SubtractiveBlending": () => (/* binding */ SubtractiveBlending),
  1297. /* harmony export */ "TOUCH": () => (/* binding */ TOUCH),
  1298. /* harmony export */ "TangentSpaceNormalMap": () => (/* binding */ TangentSpaceNormalMap),
  1299. /* harmony export */ "TetrahedronBufferGeometry": () => (/* binding */ TetrahedronGeometry),
  1300. /* harmony export */ "TetrahedronGeometry": () => (/* binding */ TetrahedronGeometry),
  1301. /* harmony export */ "TextBufferGeometry": () => (/* binding */ TextGeometry),
  1302. /* harmony export */ "TextGeometry": () => (/* binding */ TextGeometry),
  1303. /* harmony export */ "Texture": () => (/* binding */ Texture),
  1304. /* harmony export */ "TextureLoader": () => (/* binding */ TextureLoader),
  1305. /* harmony export */ "TorusBufferGeometry": () => (/* binding */ TorusGeometry),
  1306. /* harmony export */ "TorusGeometry": () => (/* binding */ TorusGeometry),
  1307. /* harmony export */ "TorusKnotBufferGeometry": () => (/* binding */ TorusKnotGeometry),
  1308. /* harmony export */ "TorusKnotGeometry": () => (/* binding */ TorusKnotGeometry),
  1309. /* harmony export */ "Triangle": () => (/* binding */ Triangle),
  1310. /* harmony export */ "TriangleFanDrawMode": () => (/* binding */ TriangleFanDrawMode),
  1311. /* harmony export */ "TriangleStripDrawMode": () => (/* binding */ TriangleStripDrawMode),
  1312. /* harmony export */ "TrianglesDrawMode": () => (/* binding */ TrianglesDrawMode),
  1313. /* harmony export */ "TubeBufferGeometry": () => (/* binding */ TubeGeometry),
  1314. /* harmony export */ "TubeGeometry": () => (/* binding */ TubeGeometry),
  1315. /* harmony export */ "UVMapping": () => (/* binding */ UVMapping),
  1316. /* harmony export */ "Uint16Attribute": () => (/* binding */ Uint16Attribute),
  1317. /* harmony export */ "Uint16BufferAttribute": () => (/* binding */ Uint16BufferAttribute),
  1318. /* harmony export */ "Uint32Attribute": () => (/* binding */ Uint32Attribute),
  1319. /* harmony export */ "Uint32BufferAttribute": () => (/* binding */ Uint32BufferAttribute),
  1320. /* harmony export */ "Uint8Attribute": () => (/* binding */ Uint8Attribute),
  1321. /* harmony export */ "Uint8BufferAttribute": () => (/* binding */ Uint8BufferAttribute),
  1322. /* harmony export */ "Uint8ClampedAttribute": () => (/* binding */ Uint8ClampedAttribute),
  1323. /* harmony export */ "Uint8ClampedBufferAttribute": () => (/* binding */ Uint8ClampedBufferAttribute),
  1324. /* harmony export */ "Uniform": () => (/* binding */ Uniform),
  1325. /* harmony export */ "UniformsLib": () => (/* binding */ UniformsLib),
  1326. /* harmony export */ "UniformsUtils": () => (/* binding */ UniformsUtils),
  1327. /* harmony export */ "UnsignedByteType": () => (/* binding */ UnsignedByteType),
  1328. /* harmony export */ "UnsignedInt248Type": () => (/* binding */ UnsignedInt248Type),
  1329. /* harmony export */ "UnsignedIntType": () => (/* binding */ UnsignedIntType),
  1330. /* harmony export */ "UnsignedShort4444Type": () => (/* binding */ UnsignedShort4444Type),
  1331. /* harmony export */ "UnsignedShort5551Type": () => (/* binding */ UnsignedShort5551Type),
  1332. /* harmony export */ "UnsignedShort565Type": () => (/* binding */ UnsignedShort565Type),
  1333. /* harmony export */ "UnsignedShortType": () => (/* binding */ UnsignedShortType),
  1334. /* harmony export */ "VSMShadowMap": () => (/* binding */ VSMShadowMap),
  1335. /* harmony export */ "Vector2": () => (/* binding */ Vector2),
  1336. /* harmony export */ "Vector3": () => (/* binding */ Vector3),
  1337. /* harmony export */ "Vector4": () => (/* binding */ Vector4),
  1338. /* harmony export */ "VectorKeyframeTrack": () => (/* binding */ VectorKeyframeTrack),
  1339. /* harmony export */ "Vertex": () => (/* binding */ Vertex),
  1340. /* harmony export */ "VertexColors": () => (/* binding */ VertexColors),
  1341. /* harmony export */ "VideoTexture": () => (/* binding */ VideoTexture),
  1342. /* harmony export */ "WebGL1Renderer": () => (/* binding */ WebGL1Renderer),
  1343. /* harmony export */ "WebGLCubeRenderTarget": () => (/* binding */ WebGLCubeRenderTarget),
  1344. /* harmony export */ "WebGLMultipleRenderTargets": () => (/* binding */ WebGLMultipleRenderTargets),
  1345. /* harmony export */ "WebGLMultisampleRenderTarget": () => (/* binding */ WebGLMultisampleRenderTarget),
  1346. /* harmony export */ "WebGLRenderTarget": () => (/* binding */ WebGLRenderTarget),
  1347. /* harmony export */ "WebGLRenderTargetCube": () => (/* binding */ WebGLRenderTargetCube),
  1348. /* harmony export */ "WebGLRenderer": () => (/* binding */ WebGLRenderer),
  1349. /* harmony export */ "WebGLUtils": () => (/* binding */ WebGLUtils),
  1350. /* harmony export */ "WireframeGeometry": () => (/* binding */ WireframeGeometry),
  1351. /* harmony export */ "WireframeHelper": () => (/* binding */ WireframeHelper),
  1352. /* harmony export */ "WrapAroundEnding": () => (/* binding */ WrapAroundEnding),
  1353. /* harmony export */ "XHRLoader": () => (/* binding */ XHRLoader),
  1354. /* harmony export */ "ZeroCurvatureEnding": () => (/* binding */ ZeroCurvatureEnding),
  1355. /* harmony export */ "ZeroFactor": () => (/* binding */ ZeroFactor),
  1356. /* harmony export */ "ZeroSlopeEnding": () => (/* binding */ ZeroSlopeEnding),
  1357. /* harmony export */ "ZeroStencilOp": () => (/* binding */ ZeroStencilOp),
  1358. /* harmony export */ "sRGBEncoding": () => (/* binding */ sRGBEncoding)
  1359. /* harmony export */ });
  1360. /**
  1361. * @license
  1362. * Copyright 2010-2021 Three.js Authors
  1363. * SPDX-License-Identifier: MIT
  1364. */
  1365. const REVISION = '132';
  1366. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  1367. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  1368. const CullFaceNone = 0;
  1369. const CullFaceBack = 1;
  1370. const CullFaceFront = 2;
  1371. const CullFaceFrontBack = 3;
  1372. const BasicShadowMap = 0;
  1373. const PCFShadowMap = 1;
  1374. const PCFSoftShadowMap = 2;
  1375. const VSMShadowMap = 3;
  1376. const FrontSide = 0;
  1377. const BackSide = 1;
  1378. const DoubleSide = 2;
  1379. const FlatShading = 1;
  1380. const SmoothShading = 2;
  1381. const NoBlending = 0;
  1382. const NormalBlending = 1;
  1383. const AdditiveBlending = 2;
  1384. const SubtractiveBlending = 3;
  1385. const MultiplyBlending = 4;
  1386. const CustomBlending = 5;
  1387. const AddEquation = 100;
  1388. const SubtractEquation = 101;
  1389. const ReverseSubtractEquation = 102;
  1390. const MinEquation = 103;
  1391. const MaxEquation = 104;
  1392. const ZeroFactor = 200;
  1393. const OneFactor = 201;
  1394. const SrcColorFactor = 202;
  1395. const OneMinusSrcColorFactor = 203;
  1396. const SrcAlphaFactor = 204;
  1397. const OneMinusSrcAlphaFactor = 205;
  1398. const DstAlphaFactor = 206;
  1399. const OneMinusDstAlphaFactor = 207;
  1400. const DstColorFactor = 208;
  1401. const OneMinusDstColorFactor = 209;
  1402. const SrcAlphaSaturateFactor = 210;
  1403. const NeverDepth = 0;
  1404. const AlwaysDepth = 1;
  1405. const LessDepth = 2;
  1406. const LessEqualDepth = 3;
  1407. const EqualDepth = 4;
  1408. const GreaterEqualDepth = 5;
  1409. const GreaterDepth = 6;
  1410. const NotEqualDepth = 7;
  1411. const MultiplyOperation = 0;
  1412. const MixOperation = 1;
  1413. const AddOperation = 2;
  1414. const NoToneMapping = 0;
  1415. const LinearToneMapping = 1;
  1416. const ReinhardToneMapping = 2;
  1417. const CineonToneMapping = 3;
  1418. const ACESFilmicToneMapping = 4;
  1419. const CustomToneMapping = 5;
  1420. const UVMapping = 300;
  1421. const CubeReflectionMapping = 301;
  1422. const CubeRefractionMapping = 302;
  1423. const EquirectangularReflectionMapping = 303;
  1424. const EquirectangularRefractionMapping = 304;
  1425. const CubeUVReflectionMapping = 306;
  1426. const CubeUVRefractionMapping = 307;
  1427. const RepeatWrapping = 1000;
  1428. const ClampToEdgeWrapping = 1001;
  1429. const MirroredRepeatWrapping = 1002;
  1430. const NearestFilter = 1003;
  1431. const NearestMipmapNearestFilter = 1004;
  1432. const NearestMipMapNearestFilter = 1004;
  1433. const NearestMipmapLinearFilter = 1005;
  1434. const NearestMipMapLinearFilter = 1005;
  1435. const LinearFilter = 1006;
  1436. const LinearMipmapNearestFilter = 1007;
  1437. const LinearMipMapNearestFilter = 1007;
  1438. const LinearMipmapLinearFilter = 1008;
  1439. const LinearMipMapLinearFilter = 1008;
  1440. const UnsignedByteType = 1009;
  1441. const ByteType = 1010;
  1442. const ShortType = 1011;
  1443. const UnsignedShortType = 1012;
  1444. const IntType = 1013;
  1445. const UnsignedIntType = 1014;
  1446. const FloatType = 1015;
  1447. const HalfFloatType = 1016;
  1448. const UnsignedShort4444Type = 1017;
  1449. const UnsignedShort5551Type = 1018;
  1450. const UnsignedShort565Type = 1019;
  1451. const UnsignedInt248Type = 1020;
  1452. const AlphaFormat = 1021;
  1453. const RGBFormat = 1022;
  1454. const RGBAFormat = 1023;
  1455. const LuminanceFormat = 1024;
  1456. const LuminanceAlphaFormat = 1025;
  1457. const RGBEFormat = RGBAFormat;
  1458. const DepthFormat = 1026;
  1459. const DepthStencilFormat = 1027;
  1460. const RedFormat = 1028;
  1461. const RedIntegerFormat = 1029;
  1462. const RGFormat = 1030;
  1463. const RGIntegerFormat = 1031;
  1464. const RGBIntegerFormat = 1032;
  1465. const RGBAIntegerFormat = 1033;
  1466. const RGB_S3TC_DXT1_Format = 33776;
  1467. const RGBA_S3TC_DXT1_Format = 33777;
  1468. const RGBA_S3TC_DXT3_Format = 33778;
  1469. const RGBA_S3TC_DXT5_Format = 33779;
  1470. const RGB_PVRTC_4BPPV1_Format = 35840;
  1471. const RGB_PVRTC_2BPPV1_Format = 35841;
  1472. const RGBA_PVRTC_4BPPV1_Format = 35842;
  1473. const RGBA_PVRTC_2BPPV1_Format = 35843;
  1474. const RGB_ETC1_Format = 36196;
  1475. const RGB_ETC2_Format = 37492;
  1476. const RGBA_ETC2_EAC_Format = 37496;
  1477. const RGBA_ASTC_4x4_Format = 37808;
  1478. const RGBA_ASTC_5x4_Format = 37809;
  1479. const RGBA_ASTC_5x5_Format = 37810;
  1480. const RGBA_ASTC_6x5_Format = 37811;
  1481. const RGBA_ASTC_6x6_Format = 37812;
  1482. const RGBA_ASTC_8x5_Format = 37813;
  1483. const RGBA_ASTC_8x6_Format = 37814;
  1484. const RGBA_ASTC_8x8_Format = 37815;
  1485. const RGBA_ASTC_10x5_Format = 37816;
  1486. const RGBA_ASTC_10x6_Format = 37817;
  1487. const RGBA_ASTC_10x8_Format = 37818;
  1488. const RGBA_ASTC_10x10_Format = 37819;
  1489. const RGBA_ASTC_12x10_Format = 37820;
  1490. const RGBA_ASTC_12x12_Format = 37821;
  1491. const RGBA_BPTC_Format = 36492;
  1492. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  1493. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  1494. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  1495. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  1496. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  1497. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  1498. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  1499. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  1500. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  1501. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  1502. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  1503. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  1504. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  1505. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  1506. const LoopOnce = 2200;
  1507. const LoopRepeat = 2201;
  1508. const LoopPingPong = 2202;
  1509. const InterpolateDiscrete = 2300;
  1510. const InterpolateLinear = 2301;
  1511. const InterpolateSmooth = 2302;
  1512. const ZeroCurvatureEnding = 2400;
  1513. const ZeroSlopeEnding = 2401;
  1514. const WrapAroundEnding = 2402;
  1515. const NormalAnimationBlendMode = 2500;
  1516. const AdditiveAnimationBlendMode = 2501;
  1517. const TrianglesDrawMode = 0;
  1518. const TriangleStripDrawMode = 1;
  1519. const TriangleFanDrawMode = 2;
  1520. const LinearEncoding = 3000;
  1521. const sRGBEncoding = 3001;
  1522. const GammaEncoding = 3007;
  1523. const RGBEEncoding = 3002;
  1524. const LogLuvEncoding = 3003;
  1525. const RGBM7Encoding = 3004;
  1526. const RGBM16Encoding = 3005;
  1527. const RGBDEncoding = 3006;
  1528. const BasicDepthPacking = 3200;
  1529. const RGBADepthPacking = 3201;
  1530. const TangentSpaceNormalMap = 0;
  1531. const ObjectSpaceNormalMap = 1;
  1532. const ZeroStencilOp = 0;
  1533. const KeepStencilOp = 7680;
  1534. const ReplaceStencilOp = 7681;
  1535. const IncrementStencilOp = 7682;
  1536. const DecrementStencilOp = 7683;
  1537. const IncrementWrapStencilOp = 34055;
  1538. const DecrementWrapStencilOp = 34056;
  1539. const InvertStencilOp = 5386;
  1540. const NeverStencilFunc = 512;
  1541. const LessStencilFunc = 513;
  1542. const EqualStencilFunc = 514;
  1543. const LessEqualStencilFunc = 515;
  1544. const GreaterStencilFunc = 516;
  1545. const NotEqualStencilFunc = 517;
  1546. const GreaterEqualStencilFunc = 518;
  1547. const AlwaysStencilFunc = 519;
  1548. const StaticDrawUsage = 35044;
  1549. const DynamicDrawUsage = 35048;
  1550. const StreamDrawUsage = 35040;
  1551. const StaticReadUsage = 35045;
  1552. const DynamicReadUsage = 35049;
  1553. const StreamReadUsage = 35041;
  1554. const StaticCopyUsage = 35046;
  1555. const DynamicCopyUsage = 35050;
  1556. const StreamCopyUsage = 35042;
  1557. const GLSL1 = '100';
  1558. const GLSL3 = '300 es';
  1559. /**
  1560. * https://github.com/mrdoob/eventdispatcher.js/
  1561. */
  1562. class EventDispatcher {
  1563. addEventListener( type, listener ) {
  1564. if ( this._listeners === undefined ) this._listeners = {};
  1565. const listeners = this._listeners;
  1566. if ( listeners[ type ] === undefined ) {
  1567. listeners[ type ] = [];
  1568. }
  1569. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1570. listeners[ type ].push( listener );
  1571. }
  1572. }
  1573. hasEventListener( type, listener ) {
  1574. if ( this._listeners === undefined ) return false;
  1575. const listeners = this._listeners;
  1576. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  1577. }
  1578. removeEventListener( type, listener ) {
  1579. if ( this._listeners === undefined ) return;
  1580. const listeners = this._listeners;
  1581. const listenerArray = listeners[ type ];
  1582. if ( listenerArray !== undefined ) {
  1583. const index = listenerArray.indexOf( listener );
  1584. if ( index !== - 1 ) {
  1585. listenerArray.splice( index, 1 );
  1586. }
  1587. }
  1588. }
  1589. dispatchEvent( event ) {
  1590. if ( this._listeners === undefined ) return;
  1591. const listeners = this._listeners;
  1592. const listenerArray = listeners[ event.type ];
  1593. if ( listenerArray !== undefined ) {
  1594. event.target = this;
  1595. // Make a copy, in case listeners are removed while iterating.
  1596. const array = listenerArray.slice( 0 );
  1597. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1598. array[ i ].call( this, event );
  1599. }
  1600. event.target = null;
  1601. }
  1602. }
  1603. }
  1604. const _lut = [];
  1605. for ( let i = 0; i < 256; i ++ ) {
  1606. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  1607. }
  1608. let _seed = 1234567;
  1609. const DEG2RAD = Math.PI / 180;
  1610. const RAD2DEG = 180 / Math.PI;
  1611. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1612. function generateUUID() {
  1613. const d0 = Math.random() * 0xffffffff | 0;
  1614. const d1 = Math.random() * 0xffffffff | 0;
  1615. const d2 = Math.random() * 0xffffffff | 0;
  1616. const d3 = Math.random() * 0xffffffff | 0;
  1617. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1618. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1619. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1620. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1621. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  1622. return uuid.toUpperCase();
  1623. }
  1624. function clamp( value, min, max ) {
  1625. return Math.max( min, Math.min( max, value ) );
  1626. }
  1627. // compute euclidian modulo of m % n
  1628. // https://en.wikipedia.org/wiki/Modulo_operation
  1629. function euclideanModulo( n, m ) {
  1630. return ( ( n % m ) + m ) % m;
  1631. }
  1632. // Linear mapping from range <a1, a2> to range <b1, b2>
  1633. function mapLinear( x, a1, a2, b1, b2 ) {
  1634. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1635. }
  1636. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1637. function inverseLerp( x, y, value ) {
  1638. if ( x !== y ) {
  1639. return ( value - x ) / ( y - x );
  1640. } else {
  1641. return 0;
  1642. }
  1643. }
  1644. // https://en.wikipedia.org/wiki/Linear_interpolation
  1645. function lerp( x, y, t ) {
  1646. return ( 1 - t ) * x + t * y;
  1647. }
  1648. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  1649. function damp( x, y, lambda, dt ) {
  1650. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1651. }
  1652. // https://www.desmos.com/calculator/vcsjnyz7x4
  1653. function pingpong( x, length = 1 ) {
  1654. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1655. }
  1656. // http://en.wikipedia.org/wiki/Smoothstep
  1657. function smoothstep( x, min, max ) {
  1658. if ( x <= min ) return 0;
  1659. if ( x >= max ) return 1;
  1660. x = ( x - min ) / ( max - min );
  1661. return x * x * ( 3 - 2 * x );
  1662. }
  1663. function smootherstep( x, min, max ) {
  1664. if ( x <= min ) return 0;
  1665. if ( x >= max ) return 1;
  1666. x = ( x - min ) / ( max - min );
  1667. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1668. }
  1669. // Random integer from <low, high> interval
  1670. function randInt( low, high ) {
  1671. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1672. }
  1673. // Random float from <low, high> interval
  1674. function randFloat( low, high ) {
  1675. return low + Math.random() * ( high - low );
  1676. }
  1677. // Random float from <-range/2, range/2> interval
  1678. function randFloatSpread( range ) {
  1679. return range * ( 0.5 - Math.random() );
  1680. }
  1681. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  1682. function seededRandom( s ) {
  1683. if ( s !== undefined ) _seed = s % 2147483647;
  1684. // Park-Miller algorithm
  1685. _seed = _seed * 16807 % 2147483647;
  1686. return ( _seed - 1 ) / 2147483646;
  1687. }
  1688. function degToRad( degrees ) {
  1689. return degrees * DEG2RAD;
  1690. }
  1691. function radToDeg( radians ) {
  1692. return radians * RAD2DEG;
  1693. }
  1694. function isPowerOfTwo( value ) {
  1695. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1696. }
  1697. function ceilPowerOfTwo( value ) {
  1698. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1699. }
  1700. function floorPowerOfTwo( value ) {
  1701. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1702. }
  1703. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1704. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  1705. // rotations are applied to the axes in the order specified by 'order'
  1706. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  1707. // angles are in radians
  1708. const cos = Math.cos;
  1709. const sin = Math.sin;
  1710. const c2 = cos( b / 2 );
  1711. const s2 = sin( b / 2 );
  1712. const c13 = cos( ( a + c ) / 2 );
  1713. const s13 = sin( ( a + c ) / 2 );
  1714. const c1_3 = cos( ( a - c ) / 2 );
  1715. const s1_3 = sin( ( a - c ) / 2 );
  1716. const c3_1 = cos( ( c - a ) / 2 );
  1717. const s3_1 = sin( ( c - a ) / 2 );
  1718. switch ( order ) {
  1719. case 'XYX':
  1720. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1721. break;
  1722. case 'YZY':
  1723. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1724. break;
  1725. case 'ZXZ':
  1726. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1727. break;
  1728. case 'XZX':
  1729. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1730. break;
  1731. case 'YXY':
  1732. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1733. break;
  1734. case 'ZYZ':
  1735. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1736. break;
  1737. default:
  1738. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1739. }
  1740. }
  1741. var MathUtils = /*#__PURE__*/Object.freeze({
  1742. __proto__: null,
  1743. DEG2RAD: DEG2RAD,
  1744. RAD2DEG: RAD2DEG,
  1745. generateUUID: generateUUID,
  1746. clamp: clamp,
  1747. euclideanModulo: euclideanModulo,
  1748. mapLinear: mapLinear,
  1749. inverseLerp: inverseLerp,
  1750. lerp: lerp,
  1751. damp: damp,
  1752. pingpong: pingpong,
  1753. smoothstep: smoothstep,
  1754. smootherstep: smootherstep,
  1755. randInt: randInt,
  1756. randFloat: randFloat,
  1757. randFloatSpread: randFloatSpread,
  1758. seededRandom: seededRandom,
  1759. degToRad: degToRad,
  1760. radToDeg: radToDeg,
  1761. isPowerOfTwo: isPowerOfTwo,
  1762. ceilPowerOfTwo: ceilPowerOfTwo,
  1763. floorPowerOfTwo: floorPowerOfTwo,
  1764. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  1765. });
  1766. class Vector2 {
  1767. constructor( x = 0, y = 0 ) {
  1768. this.x = x;
  1769. this.y = y;
  1770. }
  1771. get width() {
  1772. return this.x;
  1773. }
  1774. set width( value ) {
  1775. this.x = value;
  1776. }
  1777. get height() {
  1778. return this.y;
  1779. }
  1780. set height( value ) {
  1781. this.y = value;
  1782. }
  1783. set( x, y ) {
  1784. this.x = x;
  1785. this.y = y;
  1786. return this;
  1787. }
  1788. setScalar( scalar ) {
  1789. this.x = scalar;
  1790. this.y = scalar;
  1791. return this;
  1792. }
  1793. setX( x ) {
  1794. this.x = x;
  1795. return this;
  1796. }
  1797. setY( y ) {
  1798. this.y = y;
  1799. return this;
  1800. }
  1801. setComponent( index, value ) {
  1802. switch ( index ) {
  1803. case 0: this.x = value; break;
  1804. case 1: this.y = value; break;
  1805. default: throw new Error( 'index is out of range: ' + index );
  1806. }
  1807. return this;
  1808. }
  1809. getComponent( index ) {
  1810. switch ( index ) {
  1811. case 0: return this.x;
  1812. case 1: return this.y;
  1813. default: throw new Error( 'index is out of range: ' + index );
  1814. }
  1815. }
  1816. clone() {
  1817. return new this.constructor( this.x, this.y );
  1818. }
  1819. copy( v ) {
  1820. this.x = v.x;
  1821. this.y = v.y;
  1822. return this;
  1823. }
  1824. add( v, w ) {
  1825. if ( w !== undefined ) {
  1826. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1827. return this.addVectors( v, w );
  1828. }
  1829. this.x += v.x;
  1830. this.y += v.y;
  1831. return this;
  1832. }
  1833. addScalar( s ) {
  1834. this.x += s;
  1835. this.y += s;
  1836. return this;
  1837. }
  1838. addVectors( a, b ) {
  1839. this.x = a.x + b.x;
  1840. this.y = a.y + b.y;
  1841. return this;
  1842. }
  1843. addScaledVector( v, s ) {
  1844. this.x += v.x * s;
  1845. this.y += v.y * s;
  1846. return this;
  1847. }
  1848. sub( v, w ) {
  1849. if ( w !== undefined ) {
  1850. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1851. return this.subVectors( v, w );
  1852. }
  1853. this.x -= v.x;
  1854. this.y -= v.y;
  1855. return this;
  1856. }
  1857. subScalar( s ) {
  1858. this.x -= s;
  1859. this.y -= s;
  1860. return this;
  1861. }
  1862. subVectors( a, b ) {
  1863. this.x = a.x - b.x;
  1864. this.y = a.y - b.y;
  1865. return this;
  1866. }
  1867. multiply( v ) {
  1868. this.x *= v.x;
  1869. this.y *= v.y;
  1870. return this;
  1871. }
  1872. multiplyScalar( scalar ) {
  1873. this.x *= scalar;
  1874. this.y *= scalar;
  1875. return this;
  1876. }
  1877. divide( v ) {
  1878. this.x /= v.x;
  1879. this.y /= v.y;
  1880. return this;
  1881. }
  1882. divideScalar( scalar ) {
  1883. return this.multiplyScalar( 1 / scalar );
  1884. }
  1885. applyMatrix3( m ) {
  1886. const x = this.x, y = this.y;
  1887. const e = m.elements;
  1888. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  1889. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  1890. return this;
  1891. }
  1892. min( v ) {
  1893. this.x = Math.min( this.x, v.x );
  1894. this.y = Math.min( this.y, v.y );
  1895. return this;
  1896. }
  1897. max( v ) {
  1898. this.x = Math.max( this.x, v.x );
  1899. this.y = Math.max( this.y, v.y );
  1900. return this;
  1901. }
  1902. clamp( min, max ) {
  1903. // assumes min < max, componentwise
  1904. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1905. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1906. return this;
  1907. }
  1908. clampScalar( minVal, maxVal ) {
  1909. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1910. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1911. return this;
  1912. }
  1913. clampLength( min, max ) {
  1914. const length = this.length();
  1915. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1916. }
  1917. floor() {
  1918. this.x = Math.floor( this.x );
  1919. this.y = Math.floor( this.y );
  1920. return this;
  1921. }
  1922. ceil() {
  1923. this.x = Math.ceil( this.x );
  1924. this.y = Math.ceil( this.y );
  1925. return this;
  1926. }
  1927. round() {
  1928. this.x = Math.round( this.x );
  1929. this.y = Math.round( this.y );
  1930. return this;
  1931. }
  1932. roundToZero() {
  1933. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1934. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1935. return this;
  1936. }
  1937. negate() {
  1938. this.x = - this.x;
  1939. this.y = - this.y;
  1940. return this;
  1941. }
  1942. dot( v ) {
  1943. return this.x * v.x + this.y * v.y;
  1944. }
  1945. cross( v ) {
  1946. return this.x * v.y - this.y * v.x;
  1947. }
  1948. lengthSq() {
  1949. return this.x * this.x + this.y * this.y;
  1950. }
  1951. length() {
  1952. return Math.sqrt( this.x * this.x + this.y * this.y );
  1953. }
  1954. manhattanLength() {
  1955. return Math.abs( this.x ) + Math.abs( this.y );
  1956. }
  1957. normalize() {
  1958. return this.divideScalar( this.length() || 1 );
  1959. }
  1960. angle() {
  1961. // computes the angle in radians with respect to the positive x-axis
  1962. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1963. return angle;
  1964. }
  1965. distanceTo( v ) {
  1966. return Math.sqrt( this.distanceToSquared( v ) );
  1967. }
  1968. distanceToSquared( v ) {
  1969. const dx = this.x - v.x, dy = this.y - v.y;
  1970. return dx * dx + dy * dy;
  1971. }
  1972. manhattanDistanceTo( v ) {
  1973. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1974. }
  1975. setLength( length ) {
  1976. return this.normalize().multiplyScalar( length );
  1977. }
  1978. lerp( v, alpha ) {
  1979. this.x += ( v.x - this.x ) * alpha;
  1980. this.y += ( v.y - this.y ) * alpha;
  1981. return this;
  1982. }
  1983. lerpVectors( v1, v2, alpha ) {
  1984. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1985. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1986. return this;
  1987. }
  1988. equals( v ) {
  1989. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1990. }
  1991. fromArray( array, offset = 0 ) {
  1992. this.x = array[ offset ];
  1993. this.y = array[ offset + 1 ];
  1994. return this;
  1995. }
  1996. toArray( array = [], offset = 0 ) {
  1997. array[ offset ] = this.x;
  1998. array[ offset + 1 ] = this.y;
  1999. return array;
  2000. }
  2001. fromBufferAttribute( attribute, index, offset ) {
  2002. if ( offset !== undefined ) {
  2003. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  2004. }
  2005. this.x = attribute.getX( index );
  2006. this.y = attribute.getY( index );
  2007. return this;
  2008. }
  2009. rotateAround( center, angle ) {
  2010. const c = Math.cos( angle ), s = Math.sin( angle );
  2011. const x = this.x - center.x;
  2012. const y = this.y - center.y;
  2013. this.x = x * c - y * s + center.x;
  2014. this.y = x * s + y * c + center.y;
  2015. return this;
  2016. }
  2017. random() {
  2018. this.x = Math.random();
  2019. this.y = Math.random();
  2020. return this;
  2021. }
  2022. }
  2023. Vector2.prototype.isVector2 = true;
  2024. class Matrix3 {
  2025. constructor() {
  2026. this.elements = [
  2027. 1, 0, 0,
  2028. 0, 1, 0,
  2029. 0, 0, 1
  2030. ];
  2031. if ( arguments.length > 0 ) {
  2032. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2033. }
  2034. }
  2035. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2036. const te = this.elements;
  2037. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  2038. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  2039. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  2040. return this;
  2041. }
  2042. identity() {
  2043. this.set(
  2044. 1, 0, 0,
  2045. 0, 1, 0,
  2046. 0, 0, 1
  2047. );
  2048. return this;
  2049. }
  2050. copy( m ) {
  2051. const te = this.elements;
  2052. const me = m.elements;
  2053. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  2054. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  2055. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  2056. return this;
  2057. }
  2058. extractBasis( xAxis, yAxis, zAxis ) {
  2059. xAxis.setFromMatrix3Column( this, 0 );
  2060. yAxis.setFromMatrix3Column( this, 1 );
  2061. zAxis.setFromMatrix3Column( this, 2 );
  2062. return this;
  2063. }
  2064. setFromMatrix4( m ) {
  2065. const me = m.elements;
  2066. this.set(
  2067. me[ 0 ], me[ 4 ], me[ 8 ],
  2068. me[ 1 ], me[ 5 ], me[ 9 ],
  2069. me[ 2 ], me[ 6 ], me[ 10 ]
  2070. );
  2071. return this;
  2072. }
  2073. multiply( m ) {
  2074. return this.multiplyMatrices( this, m );
  2075. }
  2076. premultiply( m ) {
  2077. return this.multiplyMatrices( m, this );
  2078. }
  2079. multiplyMatrices( a, b ) {
  2080. const ae = a.elements;
  2081. const be = b.elements;
  2082. const te = this.elements;
  2083. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  2084. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  2085. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  2086. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  2087. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  2088. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  2089. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  2090. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  2091. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  2092. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  2093. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  2094. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  2095. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  2096. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  2097. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  2098. return this;
  2099. }
  2100. multiplyScalar( s ) {
  2101. const te = this.elements;
  2102. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2103. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2104. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2105. return this;
  2106. }
  2107. determinant() {
  2108. const te = this.elements;
  2109. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2110. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2111. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2112. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2113. }
  2114. invert() {
  2115. const te = this.elements,
  2116. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  2117. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  2118. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  2119. t11 = n33 * n22 - n32 * n23,
  2120. t12 = n32 * n13 - n33 * n12,
  2121. t13 = n23 * n12 - n22 * n13,
  2122. det = n11 * t11 + n21 * t12 + n31 * t13;
  2123. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  2124. const detInv = 1 / det;
  2125. te[ 0 ] = t11 * detInv;
  2126. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  2127. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  2128. te[ 3 ] = t12 * detInv;
  2129. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  2130. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  2131. te[ 6 ] = t13 * detInv;
  2132. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  2133. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  2134. return this;
  2135. }
  2136. transpose() {
  2137. let tmp;
  2138. const m = this.elements;
  2139. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2140. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2141. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2142. return this;
  2143. }
  2144. getNormalMatrix( matrix4 ) {
  2145. return this.setFromMatrix4( matrix4 ).invert().transpose();
  2146. }
  2147. transposeIntoArray( r ) {
  2148. const m = this.elements;
  2149. r[ 0 ] = m[ 0 ];
  2150. r[ 1 ] = m[ 3 ];
  2151. r[ 2 ] = m[ 6 ];
  2152. r[ 3 ] = m[ 1 ];
  2153. r[ 4 ] = m[ 4 ];
  2154. r[ 5 ] = m[ 7 ];
  2155. r[ 6 ] = m[ 2 ];
  2156. r[ 7 ] = m[ 5 ];
  2157. r[ 8 ] = m[ 8 ];
  2158. return this;
  2159. }
  2160. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  2161. const c = Math.cos( rotation );
  2162. const s = Math.sin( rotation );
  2163. this.set(
  2164. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  2165. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  2166. 0, 0, 1
  2167. );
  2168. return this;
  2169. }
  2170. scale( sx, sy ) {
  2171. const te = this.elements;
  2172. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  2173. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  2174. return this;
  2175. }
  2176. rotate( theta ) {
  2177. const c = Math.cos( theta );
  2178. const s = Math.sin( theta );
  2179. const te = this.elements;
  2180. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  2181. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  2182. te[ 0 ] = c * a11 + s * a21;
  2183. te[ 3 ] = c * a12 + s * a22;
  2184. te[ 6 ] = c * a13 + s * a23;
  2185. te[ 1 ] = - s * a11 + c * a21;
  2186. te[ 4 ] = - s * a12 + c * a22;
  2187. te[ 7 ] = - s * a13 + c * a23;
  2188. return this;
  2189. }
  2190. translate( tx, ty ) {
  2191. const te = this.elements;
  2192. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  2193. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  2194. return this;
  2195. }
  2196. equals( matrix ) {
  2197. const te = this.elements;
  2198. const me = matrix.elements;
  2199. for ( let i = 0; i < 9; i ++ ) {
  2200. if ( te[ i ] !== me[ i ] ) return false;
  2201. }
  2202. return true;
  2203. }
  2204. fromArray( array, offset = 0 ) {
  2205. for ( let i = 0; i < 9; i ++ ) {
  2206. this.elements[ i ] = array[ i + offset ];
  2207. }
  2208. return this;
  2209. }
  2210. toArray( array = [], offset = 0 ) {
  2211. const te = this.elements;
  2212. array[ offset ] = te[ 0 ];
  2213. array[ offset + 1 ] = te[ 1 ];
  2214. array[ offset + 2 ] = te[ 2 ];
  2215. array[ offset + 3 ] = te[ 3 ];
  2216. array[ offset + 4 ] = te[ 4 ];
  2217. array[ offset + 5 ] = te[ 5 ];
  2218. array[ offset + 6 ] = te[ 6 ];
  2219. array[ offset + 7 ] = te[ 7 ];
  2220. array[ offset + 8 ] = te[ 8 ];
  2221. return array;
  2222. }
  2223. clone() {
  2224. return new this.constructor().fromArray( this.elements );
  2225. }
  2226. }
  2227. Matrix3.prototype.isMatrix3 = true;
  2228. let _canvas;
  2229. class ImageUtils {
  2230. static getDataURL( image ) {
  2231. if ( /^data:/i.test( image.src ) ) {
  2232. return image.src;
  2233. }
  2234. if ( typeof HTMLCanvasElement == 'undefined' ) {
  2235. return image.src;
  2236. }
  2237. let canvas;
  2238. if ( image instanceof HTMLCanvasElement ) {
  2239. canvas = image;
  2240. } else {
  2241. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  2242. _canvas.width = image.width;
  2243. _canvas.height = image.height;
  2244. const context = _canvas.getContext( '2d' );
  2245. if ( image instanceof ImageData ) {
  2246. context.putImageData( image, 0, 0 );
  2247. } else {
  2248. context.drawImage( image, 0, 0, image.width, image.height );
  2249. }
  2250. canvas = _canvas;
  2251. }
  2252. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  2253. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  2254. return canvas.toDataURL( 'image/jpeg', 0.6 );
  2255. } else {
  2256. return canvas.toDataURL( 'image/png' );
  2257. }
  2258. }
  2259. }
  2260. let textureId = 0;
  2261. class Texture extends EventDispatcher {
  2262. 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 ) {
  2263. super();
  2264. Object.defineProperty( this, 'id', { value: textureId ++ } );
  2265. this.uuid = generateUUID();
  2266. this.name = '';
  2267. this.image = image;
  2268. this.mipmaps = [];
  2269. this.mapping = mapping;
  2270. this.wrapS = wrapS;
  2271. this.wrapT = wrapT;
  2272. this.magFilter = magFilter;
  2273. this.minFilter = minFilter;
  2274. this.anisotropy = anisotropy;
  2275. this.format = format;
  2276. this.internalFormat = null;
  2277. this.type = type;
  2278. this.offset = new Vector2( 0, 0 );
  2279. this.repeat = new Vector2( 1, 1 );
  2280. this.center = new Vector2( 0, 0 );
  2281. this.rotation = 0;
  2282. this.matrixAutoUpdate = true;
  2283. this.matrix = new Matrix3();
  2284. this.generateMipmaps = true;
  2285. this.premultiplyAlpha = false;
  2286. this.flipY = true;
  2287. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2288. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  2289. //
  2290. // Also changing the encoding after already used by a Material will not automatically make the Material
  2291. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  2292. this.encoding = encoding;
  2293. this.version = 0;
  2294. this.onUpdate = null;
  2295. this.isRenderTargetTexture = false;
  2296. }
  2297. updateMatrix() {
  2298. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2299. }
  2300. clone() {
  2301. return new this.constructor().copy( this );
  2302. }
  2303. copy( source ) {
  2304. this.name = source.name;
  2305. this.image = source.image;
  2306. this.mipmaps = source.mipmaps.slice( 0 );
  2307. this.mapping = source.mapping;
  2308. this.wrapS = source.wrapS;
  2309. this.wrapT = source.wrapT;
  2310. this.magFilter = source.magFilter;
  2311. this.minFilter = source.minFilter;
  2312. this.anisotropy = source.anisotropy;
  2313. this.format = source.format;
  2314. this.internalFormat = source.internalFormat;
  2315. this.type = source.type;
  2316. this.offset.copy( source.offset );
  2317. this.repeat.copy( source.repeat );
  2318. this.center.copy( source.center );
  2319. this.rotation = source.rotation;
  2320. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2321. this.matrix.copy( source.matrix );
  2322. this.generateMipmaps = source.generateMipmaps;
  2323. this.premultiplyAlpha = source.premultiplyAlpha;
  2324. this.flipY = source.flipY;
  2325. this.unpackAlignment = source.unpackAlignment;
  2326. this.encoding = source.encoding;
  2327. return this;
  2328. }
  2329. toJSON( meta ) {
  2330. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2331. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2332. return meta.textures[ this.uuid ];
  2333. }
  2334. const output = {
  2335. metadata: {
  2336. version: 4.5,
  2337. type: 'Texture',
  2338. generator: 'Texture.toJSON'
  2339. },
  2340. uuid: this.uuid,
  2341. name: this.name,
  2342. mapping: this.mapping,
  2343. repeat: [ this.repeat.x, this.repeat.y ],
  2344. offset: [ this.offset.x, this.offset.y ],
  2345. center: [ this.center.x, this.center.y ],
  2346. rotation: this.rotation,
  2347. wrap: [ this.wrapS, this.wrapT ],
  2348. format: this.format,
  2349. type: this.type,
  2350. encoding: this.encoding,
  2351. minFilter: this.minFilter,
  2352. magFilter: this.magFilter,
  2353. anisotropy: this.anisotropy,
  2354. flipY: this.flipY,
  2355. premultiplyAlpha: this.premultiplyAlpha,
  2356. unpackAlignment: this.unpackAlignment
  2357. };
  2358. if ( this.image !== undefined ) {
  2359. // TODO: Move to THREE.Image
  2360. const image = this.image;
  2361. if ( image.uuid === undefined ) {
  2362. image.uuid = generateUUID(); // UGH
  2363. }
  2364. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  2365. let url;
  2366. if ( Array.isArray( image ) ) {
  2367. // process array of images e.g. CubeTexture
  2368. url = [];
  2369. for ( let i = 0, l = image.length; i < l; i ++ ) {
  2370. // check cube texture with data textures
  2371. if ( image[ i ].isDataTexture ) {
  2372. url.push( serializeImage( image[ i ].image ) );
  2373. } else {
  2374. url.push( serializeImage( image[ i ] ) );
  2375. }
  2376. }
  2377. } else {
  2378. // process single image
  2379. url = serializeImage( image );
  2380. }
  2381. meta.images[ image.uuid ] = {
  2382. uuid: image.uuid,
  2383. url: url
  2384. };
  2385. }
  2386. output.image = image.uuid;
  2387. }
  2388. if ( ! isRootObject ) {
  2389. meta.textures[ this.uuid ] = output;
  2390. }
  2391. return output;
  2392. }
  2393. dispose() {
  2394. this.dispatchEvent( { type: 'dispose' } );
  2395. }
  2396. transformUv( uv ) {
  2397. if ( this.mapping !== UVMapping ) return uv;
  2398. uv.applyMatrix3( this.matrix );
  2399. if ( uv.x < 0 || uv.x > 1 ) {
  2400. switch ( this.wrapS ) {
  2401. case RepeatWrapping:
  2402. uv.x = uv.x - Math.floor( uv.x );
  2403. break;
  2404. case ClampToEdgeWrapping:
  2405. uv.x = uv.x < 0 ? 0 : 1;
  2406. break;
  2407. case MirroredRepeatWrapping:
  2408. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2409. uv.x = Math.ceil( uv.x ) - uv.x;
  2410. } else {
  2411. uv.x = uv.x - Math.floor( uv.x );
  2412. }
  2413. break;
  2414. }
  2415. }
  2416. if ( uv.y < 0 || uv.y > 1 ) {
  2417. switch ( this.wrapT ) {
  2418. case RepeatWrapping:
  2419. uv.y = uv.y - Math.floor( uv.y );
  2420. break;
  2421. case ClampToEdgeWrapping:
  2422. uv.y = uv.y < 0 ? 0 : 1;
  2423. break;
  2424. case MirroredRepeatWrapping:
  2425. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2426. uv.y = Math.ceil( uv.y ) - uv.y;
  2427. } else {
  2428. uv.y = uv.y - Math.floor( uv.y );
  2429. }
  2430. break;
  2431. }
  2432. }
  2433. if ( this.flipY ) {
  2434. uv.y = 1 - uv.y;
  2435. }
  2436. return uv;
  2437. }
  2438. set needsUpdate( value ) {
  2439. if ( value === true ) this.version ++;
  2440. }
  2441. }
  2442. Texture.DEFAULT_IMAGE = undefined;
  2443. Texture.DEFAULT_MAPPING = UVMapping;
  2444. Texture.prototype.isTexture = true;
  2445. function serializeImage( image ) {
  2446. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2447. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2448. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2449. // default images
  2450. return ImageUtils.getDataURL( image );
  2451. } else {
  2452. if ( image.data ) {
  2453. // images of DataTexture
  2454. return {
  2455. data: Array.prototype.slice.call( image.data ),
  2456. width: image.width,
  2457. height: image.height,
  2458. type: image.data.constructor.name
  2459. };
  2460. } else {
  2461. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  2462. return {};
  2463. }
  2464. }
  2465. }
  2466. class Vector4 {
  2467. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2468. this.x = x;
  2469. this.y = y;
  2470. this.z = z;
  2471. this.w = w;
  2472. }
  2473. get width() {
  2474. return this.z;
  2475. }
  2476. set width( value ) {
  2477. this.z = value;
  2478. }
  2479. get height() {
  2480. return this.w;
  2481. }
  2482. set height( value ) {
  2483. this.w = value;
  2484. }
  2485. set( x, y, z, w ) {
  2486. this.x = x;
  2487. this.y = y;
  2488. this.z = z;
  2489. this.w = w;
  2490. return this;
  2491. }
  2492. setScalar( scalar ) {
  2493. this.x = scalar;
  2494. this.y = scalar;
  2495. this.z = scalar;
  2496. this.w = scalar;
  2497. return this;
  2498. }
  2499. setX( x ) {
  2500. this.x = x;
  2501. return this;
  2502. }
  2503. setY( y ) {
  2504. this.y = y;
  2505. return this;
  2506. }
  2507. setZ( z ) {
  2508. this.z = z;
  2509. return this;
  2510. }
  2511. setW( w ) {
  2512. this.w = w;
  2513. return this;
  2514. }
  2515. setComponent( index, value ) {
  2516. switch ( index ) {
  2517. case 0: this.x = value; break;
  2518. case 1: this.y = value; break;
  2519. case 2: this.z = value; break;
  2520. case 3: this.w = value; break;
  2521. default: throw new Error( 'index is out of range: ' + index );
  2522. }
  2523. return this;
  2524. }
  2525. getComponent( index ) {
  2526. switch ( index ) {
  2527. case 0: return this.x;
  2528. case 1: return this.y;
  2529. case 2: return this.z;
  2530. case 3: return this.w;
  2531. default: throw new Error( 'index is out of range: ' + index );
  2532. }
  2533. }
  2534. clone() {
  2535. return new this.constructor( this.x, this.y, this.z, this.w );
  2536. }
  2537. copy( v ) {
  2538. this.x = v.x;
  2539. this.y = v.y;
  2540. this.z = v.z;
  2541. this.w = ( v.w !== undefined ) ? v.w : 1;
  2542. return this;
  2543. }
  2544. add( v, w ) {
  2545. if ( w !== undefined ) {
  2546. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2547. return this.addVectors( v, w );
  2548. }
  2549. this.x += v.x;
  2550. this.y += v.y;
  2551. this.z += v.z;
  2552. this.w += v.w;
  2553. return this;
  2554. }
  2555. addScalar( s ) {
  2556. this.x += s;
  2557. this.y += s;
  2558. this.z += s;
  2559. this.w += s;
  2560. return this;
  2561. }
  2562. addVectors( a, b ) {
  2563. this.x = a.x + b.x;
  2564. this.y = a.y + b.y;
  2565. this.z = a.z + b.z;
  2566. this.w = a.w + b.w;
  2567. return this;
  2568. }
  2569. addScaledVector( v, s ) {
  2570. this.x += v.x * s;
  2571. this.y += v.y * s;
  2572. this.z += v.z * s;
  2573. this.w += v.w * s;
  2574. return this;
  2575. }
  2576. sub( v, w ) {
  2577. if ( w !== undefined ) {
  2578. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2579. return this.subVectors( v, w );
  2580. }
  2581. this.x -= v.x;
  2582. this.y -= v.y;
  2583. this.z -= v.z;
  2584. this.w -= v.w;
  2585. return this;
  2586. }
  2587. subScalar( s ) {
  2588. this.x -= s;
  2589. this.y -= s;
  2590. this.z -= s;
  2591. this.w -= s;
  2592. return this;
  2593. }
  2594. subVectors( a, b ) {
  2595. this.x = a.x - b.x;
  2596. this.y = a.y - b.y;
  2597. this.z = a.z - b.z;
  2598. this.w = a.w - b.w;
  2599. return this;
  2600. }
  2601. multiply( v ) {
  2602. this.x *= v.x;
  2603. this.y *= v.y;
  2604. this.z *= v.z;
  2605. this.w *= v.w;
  2606. return this;
  2607. }
  2608. multiplyScalar( scalar ) {
  2609. this.x *= scalar;
  2610. this.y *= scalar;
  2611. this.z *= scalar;
  2612. this.w *= scalar;
  2613. return this;
  2614. }
  2615. applyMatrix4( m ) {
  2616. const x = this.x, y = this.y, z = this.z, w = this.w;
  2617. const e = m.elements;
  2618. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2619. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2620. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2621. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2622. return this;
  2623. }
  2624. divideScalar( scalar ) {
  2625. return this.multiplyScalar( 1 / scalar );
  2626. }
  2627. setAxisAngleFromQuaternion( q ) {
  2628. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2629. // q is assumed to be normalized
  2630. this.w = 2 * Math.acos( q.w );
  2631. const s = Math.sqrt( 1 - q.w * q.w );
  2632. if ( s < 0.0001 ) {
  2633. this.x = 1;
  2634. this.y = 0;
  2635. this.z = 0;
  2636. } else {
  2637. this.x = q.x / s;
  2638. this.y = q.y / s;
  2639. this.z = q.z / s;
  2640. }
  2641. return this;
  2642. }
  2643. setAxisAngleFromRotationMatrix( m ) {
  2644. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2645. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2646. let angle, x, y, z; // variables for result
  2647. const epsilon = 0.01, // margin to allow for rounding errors
  2648. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2649. te = m.elements,
  2650. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2651. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2652. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2653. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2654. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2655. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2656. // singularity found
  2657. // first check for identity matrix which must have +1 for all terms
  2658. // in leading diagonal and zero in other terms
  2659. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2660. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2661. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2662. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2663. // this singularity is identity matrix so angle = 0
  2664. this.set( 1, 0, 0, 0 );
  2665. return this; // zero angle, arbitrary axis
  2666. }
  2667. // otherwise this singularity is angle = 180
  2668. angle = Math.PI;
  2669. const xx = ( m11 + 1 ) / 2;
  2670. const yy = ( m22 + 1 ) / 2;
  2671. const zz = ( m33 + 1 ) / 2;
  2672. const xy = ( m12 + m21 ) / 4;
  2673. const xz = ( m13 + m31 ) / 4;
  2674. const yz = ( m23 + m32 ) / 4;
  2675. if ( ( xx > yy ) && ( xx > zz ) ) {
  2676. // m11 is the largest diagonal term
  2677. if ( xx < epsilon ) {
  2678. x = 0;
  2679. y = 0.707106781;
  2680. z = 0.707106781;
  2681. } else {
  2682. x = Math.sqrt( xx );
  2683. y = xy / x;
  2684. z = xz / x;
  2685. }
  2686. } else if ( yy > zz ) {
  2687. // m22 is the largest diagonal term
  2688. if ( yy < epsilon ) {
  2689. x = 0.707106781;
  2690. y = 0;
  2691. z = 0.707106781;
  2692. } else {
  2693. y = Math.sqrt( yy );
  2694. x = xy / y;
  2695. z = yz / y;
  2696. }
  2697. } else {
  2698. // m33 is the largest diagonal term so base result on this
  2699. if ( zz < epsilon ) {
  2700. x = 0.707106781;
  2701. y = 0.707106781;
  2702. z = 0;
  2703. } else {
  2704. z = Math.sqrt( zz );
  2705. x = xz / z;
  2706. y = yz / z;
  2707. }
  2708. }
  2709. this.set( x, y, z, angle );
  2710. return this; // return 180 deg rotation
  2711. }
  2712. // as we have reached here there are no singularities so we can handle normally
  2713. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2714. ( m13 - m31 ) * ( m13 - m31 ) +
  2715. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2716. if ( Math.abs( s ) < 0.001 ) s = 1;
  2717. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2718. // caught by singularity test above, but I've left it in just in case
  2719. this.x = ( m32 - m23 ) / s;
  2720. this.y = ( m13 - m31 ) / s;
  2721. this.z = ( m21 - m12 ) / s;
  2722. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2723. return this;
  2724. }
  2725. min( v ) {
  2726. this.x = Math.min( this.x, v.x );
  2727. this.y = Math.min( this.y, v.y );
  2728. this.z = Math.min( this.z, v.z );
  2729. this.w = Math.min( this.w, v.w );
  2730. return this;
  2731. }
  2732. max( v ) {
  2733. this.x = Math.max( this.x, v.x );
  2734. this.y = Math.max( this.y, v.y );
  2735. this.z = Math.max( this.z, v.z );
  2736. this.w = Math.max( this.w, v.w );
  2737. return this;
  2738. }
  2739. clamp( min, max ) {
  2740. // assumes min < max, componentwise
  2741. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2742. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2743. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2744. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2745. return this;
  2746. }
  2747. clampScalar( minVal, maxVal ) {
  2748. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2749. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2750. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2751. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2752. return this;
  2753. }
  2754. clampLength( min, max ) {
  2755. const length = this.length();
  2756. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2757. }
  2758. floor() {
  2759. this.x = Math.floor( this.x );
  2760. this.y = Math.floor( this.y );
  2761. this.z = Math.floor( this.z );
  2762. this.w = Math.floor( this.w );
  2763. return this;
  2764. }
  2765. ceil() {
  2766. this.x = Math.ceil( this.x );
  2767. this.y = Math.ceil( this.y );
  2768. this.z = Math.ceil( this.z );
  2769. this.w = Math.ceil( this.w );
  2770. return this;
  2771. }
  2772. round() {
  2773. this.x = Math.round( this.x );
  2774. this.y = Math.round( this.y );
  2775. this.z = Math.round( this.z );
  2776. this.w = Math.round( this.w );
  2777. return this;
  2778. }
  2779. roundToZero() {
  2780. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2781. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2782. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2783. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2784. return this;
  2785. }
  2786. negate() {
  2787. this.x = - this.x;
  2788. this.y = - this.y;
  2789. this.z = - this.z;
  2790. this.w = - this.w;
  2791. return this;
  2792. }
  2793. dot( v ) {
  2794. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2795. }
  2796. lengthSq() {
  2797. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2798. }
  2799. length() {
  2800. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2801. }
  2802. manhattanLength() {
  2803. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2804. }
  2805. normalize() {
  2806. return this.divideScalar( this.length() || 1 );
  2807. }
  2808. setLength( length ) {
  2809. return this.normalize().multiplyScalar( length );
  2810. }
  2811. lerp( v, alpha ) {
  2812. this.x += ( v.x - this.x ) * alpha;
  2813. this.y += ( v.y - this.y ) * alpha;
  2814. this.z += ( v.z - this.z ) * alpha;
  2815. this.w += ( v.w - this.w ) * alpha;
  2816. return this;
  2817. }
  2818. lerpVectors( v1, v2, alpha ) {
  2819. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2820. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2821. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2822. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2823. return this;
  2824. }
  2825. equals( v ) {
  2826. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2827. }
  2828. fromArray( array, offset = 0 ) {
  2829. this.x = array[ offset ];
  2830. this.y = array[ offset + 1 ];
  2831. this.z = array[ offset + 2 ];
  2832. this.w = array[ offset + 3 ];
  2833. return this;
  2834. }
  2835. toArray( array = [], offset = 0 ) {
  2836. array[ offset ] = this.x;
  2837. array[ offset + 1 ] = this.y;
  2838. array[ offset + 2 ] = this.z;
  2839. array[ offset + 3 ] = this.w;
  2840. return array;
  2841. }
  2842. fromBufferAttribute( attribute, index, offset ) {
  2843. if ( offset !== undefined ) {
  2844. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  2845. }
  2846. this.x = attribute.getX( index );
  2847. this.y = attribute.getY( index );
  2848. this.z = attribute.getZ( index );
  2849. this.w = attribute.getW( index );
  2850. return this;
  2851. }
  2852. random() {
  2853. this.x = Math.random();
  2854. this.y = Math.random();
  2855. this.z = Math.random();
  2856. this.w = Math.random();
  2857. return this;
  2858. }
  2859. }
  2860. Vector4.prototype.isVector4 = true;
  2861. /*
  2862. In options, we can specify:
  2863. * Texture parameters for an auto-generated target texture
  2864. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2865. */
  2866. class WebGLRenderTarget extends EventDispatcher {
  2867. constructor( width, height, options = {} ) {
  2868. super();
  2869. this.width = width;
  2870. this.height = height;
  2871. this.depth = 1;
  2872. this.scissor = new Vector4( 0, 0, width, height );
  2873. this.scissorTest = false;
  2874. this.viewport = new Vector4( 0, 0, width, height );
  2875. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2876. this.texture.isRenderTargetTexture = true;
  2877. this.texture.image = { width: width, height: height, depth: 1 };
  2878. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2879. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2880. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2881. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2882. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2883. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2884. }
  2885. setTexture( texture ) {
  2886. texture.image = {
  2887. width: this.width,
  2888. height: this.height,
  2889. depth: this.depth
  2890. };
  2891. this.texture = texture;
  2892. }
  2893. setSize( width, height, depth = 1 ) {
  2894. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2895. this.width = width;
  2896. this.height = height;
  2897. this.depth = depth;
  2898. this.texture.image.width = width;
  2899. this.texture.image.height = height;
  2900. this.texture.image.depth = depth;
  2901. this.dispose();
  2902. }
  2903. this.viewport.set( 0, 0, width, height );
  2904. this.scissor.set( 0, 0, width, height );
  2905. }
  2906. clone() {
  2907. return new this.constructor().copy( this );
  2908. }
  2909. copy( source ) {
  2910. this.width = source.width;
  2911. this.height = source.height;
  2912. this.depth = source.depth;
  2913. this.viewport.copy( source.viewport );
  2914. this.texture = source.texture.clone();
  2915. this.texture.image = { ...this.texture.image }; // See #20328.
  2916. this.depthBuffer = source.depthBuffer;
  2917. this.stencilBuffer = source.stencilBuffer;
  2918. this.depthTexture = source.depthTexture;
  2919. return this;
  2920. }
  2921. dispose() {
  2922. this.dispatchEvent( { type: 'dispose' } );
  2923. }
  2924. }
  2925. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  2926. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2927. constructor( width, height, count ) {
  2928. super( width, height );
  2929. const texture = this.texture;
  2930. this.texture = [];
  2931. for ( let i = 0; i < count; i ++ ) {
  2932. this.texture[ i ] = texture.clone();
  2933. }
  2934. }
  2935. setSize( width, height, depth = 1 ) {
  2936. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2937. this.width = width;
  2938. this.height = height;
  2939. this.depth = depth;
  2940. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2941. this.texture[ i ].image.width = width;
  2942. this.texture[ i ].image.height = height;
  2943. this.texture[ i ].image.depth = depth;
  2944. }
  2945. this.dispose();
  2946. }
  2947. this.viewport.set( 0, 0, width, height );
  2948. this.scissor.set( 0, 0, width, height );
  2949. return this;
  2950. }
  2951. copy( source ) {
  2952. this.dispose();
  2953. this.width = source.width;
  2954. this.height = source.height;
  2955. this.depth = source.depth;
  2956. this.viewport.set( 0, 0, this.width, this.height );
  2957. this.scissor.set( 0, 0, this.width, this.height );
  2958. this.depthBuffer = source.depthBuffer;
  2959. this.stencilBuffer = source.stencilBuffer;
  2960. this.depthTexture = source.depthTexture;
  2961. this.texture.length = 0;
  2962. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2963. this.texture[ i ] = source.texture[ i ].clone();
  2964. }
  2965. return this;
  2966. }
  2967. }
  2968. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  2969. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  2970. constructor( width, height, options ) {
  2971. super( width, height, options );
  2972. this.samples = 4;
  2973. }
  2974. copy( source ) {
  2975. super.copy.call( this, source );
  2976. this.samples = source.samples;
  2977. return this;
  2978. }
  2979. }
  2980. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  2981. class Quaternion {
  2982. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2983. this._x = x;
  2984. this._y = y;
  2985. this._z = z;
  2986. this._w = w;
  2987. }
  2988. static slerp( qa, qb, qm, t ) {
  2989. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  2990. return qm.slerpQuaternions( qa, qb, t );
  2991. }
  2992. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2993. // fuzz-free, array-based Quaternion SLERP operation
  2994. let x0 = src0[ srcOffset0 + 0 ],
  2995. y0 = src0[ srcOffset0 + 1 ],
  2996. z0 = src0[ srcOffset0 + 2 ],
  2997. w0 = src0[ srcOffset0 + 3 ];
  2998. const x1 = src1[ srcOffset1 + 0 ],
  2999. y1 = src1[ srcOffset1 + 1 ],
  3000. z1 = src1[ srcOffset1 + 2 ],
  3001. w1 = src1[ srcOffset1 + 3 ];
  3002. if ( t === 0 ) {
  3003. dst[ dstOffset + 0 ] = x0;
  3004. dst[ dstOffset + 1 ] = y0;
  3005. dst[ dstOffset + 2 ] = z0;
  3006. dst[ dstOffset + 3 ] = w0;
  3007. return;
  3008. }
  3009. if ( t === 1 ) {
  3010. dst[ dstOffset + 0 ] = x1;
  3011. dst[ dstOffset + 1 ] = y1;
  3012. dst[ dstOffset + 2 ] = z1;
  3013. dst[ dstOffset + 3 ] = w1;
  3014. return;
  3015. }
  3016. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3017. let s = 1 - t;
  3018. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  3019. dir = ( cos >= 0 ? 1 : - 1 ),
  3020. sqrSin = 1 - cos * cos;
  3021. // Skip the Slerp for tiny steps to avoid numeric problems:
  3022. if ( sqrSin > Number.EPSILON ) {
  3023. const sin = Math.sqrt( sqrSin ),
  3024. len = Math.atan2( sin, cos * dir );
  3025. s = Math.sin( s * len ) / sin;
  3026. t = Math.sin( t * len ) / sin;
  3027. }
  3028. const tDir = t * dir;
  3029. x0 = x0 * s + x1 * tDir;
  3030. y0 = y0 * s + y1 * tDir;
  3031. z0 = z0 * s + z1 * tDir;
  3032. w0 = w0 * s + w1 * tDir;
  3033. // Normalize in case we just did a lerp:
  3034. if ( s === 1 - t ) {
  3035. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3036. x0 *= f;
  3037. y0 *= f;
  3038. z0 *= f;
  3039. w0 *= f;
  3040. }
  3041. }
  3042. dst[ dstOffset ] = x0;
  3043. dst[ dstOffset + 1 ] = y0;
  3044. dst[ dstOffset + 2 ] = z0;
  3045. dst[ dstOffset + 3 ] = w0;
  3046. }
  3047. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3048. const x0 = src0[ srcOffset0 ];
  3049. const y0 = src0[ srcOffset0 + 1 ];
  3050. const z0 = src0[ srcOffset0 + 2 ];
  3051. const w0 = src0[ srcOffset0 + 3 ];
  3052. const x1 = src1[ srcOffset1 ];
  3053. const y1 = src1[ srcOffset1 + 1 ];
  3054. const z1 = src1[ srcOffset1 + 2 ];
  3055. const w1 = src1[ srcOffset1 + 3 ];
  3056. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3057. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3058. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3059. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3060. return dst;
  3061. }
  3062. get x() {
  3063. return this._x;
  3064. }
  3065. set x( value ) {
  3066. this._x = value;
  3067. this._onChangeCallback();
  3068. }
  3069. get y() {
  3070. return this._y;
  3071. }
  3072. set y( value ) {
  3073. this._y = value;
  3074. this._onChangeCallback();
  3075. }
  3076. get z() {
  3077. return this._z;
  3078. }
  3079. set z( value ) {
  3080. this._z = value;
  3081. this._onChangeCallback();
  3082. }
  3083. get w() {
  3084. return this._w;
  3085. }
  3086. set w( value ) {
  3087. this._w = value;
  3088. this._onChangeCallback();
  3089. }
  3090. set( x, y, z, w ) {
  3091. this._x = x;
  3092. this._y = y;
  3093. this._z = z;
  3094. this._w = w;
  3095. this._onChangeCallback();
  3096. return this;
  3097. }
  3098. clone() {
  3099. return new this.constructor( this._x, this._y, this._z, this._w );
  3100. }
  3101. copy( quaternion ) {
  3102. this._x = quaternion.x;
  3103. this._y = quaternion.y;
  3104. this._z = quaternion.z;
  3105. this._w = quaternion.w;
  3106. this._onChangeCallback();
  3107. return this;
  3108. }
  3109. setFromEuler( euler, update ) {
  3110. if ( ! ( euler && euler.isEuler ) ) {
  3111. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  3112. }
  3113. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3114. // http://www.mathworks.com/matlabcentral/fileexchange/
  3115. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3116. // content/SpinCalc.m
  3117. const cos = Math.cos;
  3118. const sin = Math.sin;
  3119. const c1 = cos( x / 2 );
  3120. const c2 = cos( y / 2 );
  3121. const c3 = cos( z / 2 );
  3122. const s1 = sin( x / 2 );
  3123. const s2 = sin( y / 2 );
  3124. const s3 = sin( z / 2 );
  3125. switch ( order ) {
  3126. case 'XYZ':
  3127. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3128. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3129. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3130. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3131. break;
  3132. case 'YXZ':
  3133. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3134. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3135. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3136. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3137. break;
  3138. case 'ZXY':
  3139. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3140. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3141. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3142. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3143. break;
  3144. case 'ZYX':
  3145. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3146. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3147. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3148. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3149. break;
  3150. case 'YZX':
  3151. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3152. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3153. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3154. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3155. break;
  3156. case 'XZY':
  3157. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3158. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3159. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3160. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3161. break;
  3162. default:
  3163. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3164. }
  3165. if ( update !== false ) this._onChangeCallback();
  3166. return this;
  3167. }
  3168. setFromAxisAngle( axis, angle ) {
  3169. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3170. // assumes axis is normalized
  3171. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3172. this._x = axis.x * s;
  3173. this._y = axis.y * s;
  3174. this._z = axis.z * s;
  3175. this._w = Math.cos( halfAngle );
  3176. this._onChangeCallback();
  3177. return this;
  3178. }
  3179. setFromRotationMatrix( m ) {
  3180. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3181. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3182. const te = m.elements,
  3183. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3184. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3185. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3186. trace = m11 + m22 + m33;
  3187. if ( trace > 0 ) {
  3188. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3189. this._w = 0.25 / s;
  3190. this._x = ( m32 - m23 ) * s;
  3191. this._y = ( m13 - m31 ) * s;
  3192. this._z = ( m21 - m12 ) * s;
  3193. } else if ( m11 > m22 && m11 > m33 ) {
  3194. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3195. this._w = ( m32 - m23 ) / s;
  3196. this._x = 0.25 * s;
  3197. this._y = ( m12 + m21 ) / s;
  3198. this._z = ( m13 + m31 ) / s;
  3199. } else if ( m22 > m33 ) {
  3200. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3201. this._w = ( m13 - m31 ) / s;
  3202. this._x = ( m12 + m21 ) / s;
  3203. this._y = 0.25 * s;
  3204. this._z = ( m23 + m32 ) / s;
  3205. } else {
  3206. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3207. this._w = ( m21 - m12 ) / s;
  3208. this._x = ( m13 + m31 ) / s;
  3209. this._y = ( m23 + m32 ) / s;
  3210. this._z = 0.25 * s;
  3211. }
  3212. this._onChangeCallback();
  3213. return this;
  3214. }
  3215. setFromUnitVectors( vFrom, vTo ) {
  3216. // assumes direction vectors vFrom and vTo are normalized
  3217. let r = vFrom.dot( vTo ) + 1;
  3218. if ( r < Number.EPSILON ) {
  3219. // vFrom and vTo point in opposite directions
  3220. r = 0;
  3221. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3222. this._x = - vFrom.y;
  3223. this._y = vFrom.x;
  3224. this._z = 0;
  3225. this._w = r;
  3226. } else {
  3227. this._x = 0;
  3228. this._y = - vFrom.z;
  3229. this._z = vFrom.y;
  3230. this._w = r;
  3231. }
  3232. } else {
  3233. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3234. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3235. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3236. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3237. this._w = r;
  3238. }
  3239. return this.normalize();
  3240. }
  3241. angleTo( q ) {
  3242. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  3243. }
  3244. rotateTowards( q, step ) {
  3245. const angle = this.angleTo( q );
  3246. if ( angle === 0 ) return this;
  3247. const t = Math.min( 1, step / angle );
  3248. this.slerp( q, t );
  3249. return this;
  3250. }
  3251. identity() {
  3252. return this.set( 0, 0, 0, 1 );
  3253. }
  3254. invert() {
  3255. // quaternion is assumed to have unit length
  3256. return this.conjugate();
  3257. }
  3258. conjugate() {
  3259. this._x *= - 1;
  3260. this._y *= - 1;
  3261. this._z *= - 1;
  3262. this._onChangeCallback();
  3263. return this;
  3264. }
  3265. dot( v ) {
  3266. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3267. }
  3268. lengthSq() {
  3269. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3270. }
  3271. length() {
  3272. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3273. }
  3274. normalize() {
  3275. let l = this.length();
  3276. if ( l === 0 ) {
  3277. this._x = 0;
  3278. this._y = 0;
  3279. this._z = 0;
  3280. this._w = 1;
  3281. } else {
  3282. l = 1 / l;
  3283. this._x = this._x * l;
  3284. this._y = this._y * l;
  3285. this._z = this._z * l;
  3286. this._w = this._w * l;
  3287. }
  3288. this._onChangeCallback();
  3289. return this;
  3290. }
  3291. multiply( q, p ) {
  3292. if ( p !== undefined ) {
  3293. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  3294. return this.multiplyQuaternions( q, p );
  3295. }
  3296. return this.multiplyQuaternions( this, q );
  3297. }
  3298. premultiply( q ) {
  3299. return this.multiplyQuaternions( q, this );
  3300. }
  3301. multiplyQuaternions( a, b ) {
  3302. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3303. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3304. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3305. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3306. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3307. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3308. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3309. this._onChangeCallback();
  3310. return this;
  3311. }
  3312. slerp( qb, t ) {
  3313. if ( t === 0 ) return this;
  3314. if ( t === 1 ) return this.copy( qb );
  3315. const x = this._x, y = this._y, z = this._z, w = this._w;
  3316. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3317. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3318. if ( cosHalfTheta < 0 ) {
  3319. this._w = - qb._w;
  3320. this._x = - qb._x;
  3321. this._y = - qb._y;
  3322. this._z = - qb._z;
  3323. cosHalfTheta = - cosHalfTheta;
  3324. } else {
  3325. this.copy( qb );
  3326. }
  3327. if ( cosHalfTheta >= 1.0 ) {
  3328. this._w = w;
  3329. this._x = x;
  3330. this._y = y;
  3331. this._z = z;
  3332. return this;
  3333. }
  3334. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3335. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3336. const s = 1 - t;
  3337. this._w = s * w + t * this._w;
  3338. this._x = s * x + t * this._x;
  3339. this._y = s * y + t * this._y;
  3340. this._z = s * z + t * this._z;
  3341. this.normalize();
  3342. this._onChangeCallback();
  3343. return this;
  3344. }
  3345. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3346. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3347. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3348. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3349. this._w = ( w * ratioA + this._w * ratioB );
  3350. this._x = ( x * ratioA + this._x * ratioB );
  3351. this._y = ( y * ratioA + this._y * ratioB );
  3352. this._z = ( z * ratioA + this._z * ratioB );
  3353. this._onChangeCallback();
  3354. return this;
  3355. }
  3356. slerpQuaternions( qa, qb, t ) {
  3357. this.copy( qa ).slerp( qb, t );
  3358. }
  3359. equals( quaternion ) {
  3360. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3361. }
  3362. fromArray( array, offset = 0 ) {
  3363. this._x = array[ offset ];
  3364. this._y = array[ offset + 1 ];
  3365. this._z = array[ offset + 2 ];
  3366. this._w = array[ offset + 3 ];
  3367. this._onChangeCallback();
  3368. return this;
  3369. }
  3370. toArray( array = [], offset = 0 ) {
  3371. array[ offset ] = this._x;
  3372. array[ offset + 1 ] = this._y;
  3373. array[ offset + 2 ] = this._z;
  3374. array[ offset + 3 ] = this._w;
  3375. return array;
  3376. }
  3377. fromBufferAttribute( attribute, index ) {
  3378. this._x = attribute.getX( index );
  3379. this._y = attribute.getY( index );
  3380. this._z = attribute.getZ( index );
  3381. this._w = attribute.getW( index );
  3382. return this;
  3383. }
  3384. _onChange( callback ) {
  3385. this._onChangeCallback = callback;
  3386. return this;
  3387. }
  3388. _onChangeCallback() {}
  3389. }
  3390. Quaternion.prototype.isQuaternion = true;
  3391. class Vector3 {
  3392. constructor( x = 0, y = 0, z = 0 ) {
  3393. this.x = x;
  3394. this.y = y;
  3395. this.z = z;
  3396. }
  3397. set( x, y, z ) {
  3398. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3399. this.x = x;
  3400. this.y = y;
  3401. this.z = z;
  3402. return this;
  3403. }
  3404. setScalar( scalar ) {
  3405. this.x = scalar;
  3406. this.y = scalar;
  3407. this.z = scalar;
  3408. return this;
  3409. }
  3410. setX( x ) {
  3411. this.x = x;
  3412. return this;
  3413. }
  3414. setY( y ) {
  3415. this.y = y;
  3416. return this;
  3417. }
  3418. setZ( z ) {
  3419. this.z = z;
  3420. return this;
  3421. }
  3422. setComponent( index, value ) {
  3423. switch ( index ) {
  3424. case 0: this.x = value; break;
  3425. case 1: this.y = value; break;
  3426. case 2: this.z = value; break;
  3427. default: throw new Error( 'index is out of range: ' + index );
  3428. }
  3429. return this;
  3430. }
  3431. getComponent( index ) {
  3432. switch ( index ) {
  3433. case 0: return this.x;
  3434. case 1: return this.y;
  3435. case 2: return this.z;
  3436. default: throw new Error( 'index is out of range: ' + index );
  3437. }
  3438. }
  3439. clone() {
  3440. return new this.constructor( this.x, this.y, this.z );
  3441. }
  3442. copy( v ) {
  3443. this.x = v.x;
  3444. this.y = v.y;
  3445. this.z = v.z;
  3446. return this;
  3447. }
  3448. add( v, w ) {
  3449. if ( w !== undefined ) {
  3450. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  3451. return this.addVectors( v, w );
  3452. }
  3453. this.x += v.x;
  3454. this.y += v.y;
  3455. this.z += v.z;
  3456. return this;
  3457. }
  3458. addScalar( s ) {
  3459. this.x += s;
  3460. this.y += s;
  3461. this.z += s;
  3462. return this;
  3463. }
  3464. addVectors( a, b ) {
  3465. this.x = a.x + b.x;
  3466. this.y = a.y + b.y;
  3467. this.z = a.z + b.z;
  3468. return this;
  3469. }
  3470. addScaledVector( v, s ) {
  3471. this.x += v.x * s;
  3472. this.y += v.y * s;
  3473. this.z += v.z * s;
  3474. return this;
  3475. }
  3476. sub( v, w ) {
  3477. if ( w !== undefined ) {
  3478. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  3479. return this.subVectors( v, w );
  3480. }
  3481. this.x -= v.x;
  3482. this.y -= v.y;
  3483. this.z -= v.z;
  3484. return this;
  3485. }
  3486. subScalar( s ) {
  3487. this.x -= s;
  3488. this.y -= s;
  3489. this.z -= s;
  3490. return this;
  3491. }
  3492. subVectors( a, b ) {
  3493. this.x = a.x - b.x;
  3494. this.y = a.y - b.y;
  3495. this.z = a.z - b.z;
  3496. return this;
  3497. }
  3498. multiply( v, w ) {
  3499. if ( w !== undefined ) {
  3500. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  3501. return this.multiplyVectors( v, w );
  3502. }
  3503. this.x *= v.x;
  3504. this.y *= v.y;
  3505. this.z *= v.z;
  3506. return this;
  3507. }
  3508. multiplyScalar( scalar ) {
  3509. this.x *= scalar;
  3510. this.y *= scalar;
  3511. this.z *= scalar;
  3512. return this;
  3513. }
  3514. multiplyVectors( a, b ) {
  3515. this.x = a.x * b.x;
  3516. this.y = a.y * b.y;
  3517. this.z = a.z * b.z;
  3518. return this;
  3519. }
  3520. applyEuler( euler ) {
  3521. if ( ! ( euler && euler.isEuler ) ) {
  3522. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  3523. }
  3524. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3525. }
  3526. applyAxisAngle( axis, angle ) {
  3527. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3528. }
  3529. applyMatrix3( m ) {
  3530. const x = this.x, y = this.y, z = this.z;
  3531. const e = m.elements;
  3532. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3533. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3534. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3535. return this;
  3536. }
  3537. applyNormalMatrix( m ) {
  3538. return this.applyMatrix3( m ).normalize();
  3539. }
  3540. applyMatrix4( m ) {
  3541. const x = this.x, y = this.y, z = this.z;
  3542. const e = m.elements;
  3543. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3544. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3545. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3546. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3547. return this;
  3548. }
  3549. applyQuaternion( q ) {
  3550. const x = this.x, y = this.y, z = this.z;
  3551. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3552. // calculate quat * vector
  3553. const ix = qw * x + qy * z - qz * y;
  3554. const iy = qw * y + qz * x - qx * z;
  3555. const iz = qw * z + qx * y - qy * x;
  3556. const iw = - qx * x - qy * y - qz * z;
  3557. // calculate result * inverse quat
  3558. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  3559. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  3560. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  3561. return this;
  3562. }
  3563. project( camera ) {
  3564. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3565. }
  3566. unproject( camera ) {
  3567. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3568. }
  3569. transformDirection( m ) {
  3570. // input: THREE.Matrix4 affine matrix
  3571. // vector interpreted as a direction
  3572. const x = this.x, y = this.y, z = this.z;
  3573. const e = m.elements;
  3574. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3575. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3576. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3577. return this.normalize();
  3578. }
  3579. divide( v ) {
  3580. this.x /= v.x;
  3581. this.y /= v.y;
  3582. this.z /= v.z;
  3583. return this;
  3584. }
  3585. divideScalar( scalar ) {
  3586. return this.multiplyScalar( 1 / scalar );
  3587. }
  3588. min( v ) {
  3589. this.x = Math.min( this.x, v.x );
  3590. this.y = Math.min( this.y, v.y );
  3591. this.z = Math.min( this.z, v.z );
  3592. return this;
  3593. }
  3594. max( v ) {
  3595. this.x = Math.max( this.x, v.x );
  3596. this.y = Math.max( this.y, v.y );
  3597. this.z = Math.max( this.z, v.z );
  3598. return this;
  3599. }
  3600. clamp( min, max ) {
  3601. // assumes min < max, componentwise
  3602. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  3603. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  3604. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  3605. return this;
  3606. }
  3607. clampScalar( minVal, maxVal ) {
  3608. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  3609. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  3610. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  3611. return this;
  3612. }
  3613. clampLength( min, max ) {
  3614. const length = this.length();
  3615. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  3616. }
  3617. floor() {
  3618. this.x = Math.floor( this.x );
  3619. this.y = Math.floor( this.y );
  3620. this.z = Math.floor( this.z );
  3621. return this;
  3622. }
  3623. ceil() {
  3624. this.x = Math.ceil( this.x );
  3625. this.y = Math.ceil( this.y );
  3626. this.z = Math.ceil( this.z );
  3627. return this;
  3628. }
  3629. round() {
  3630. this.x = Math.round( this.x );
  3631. this.y = Math.round( this.y );
  3632. this.z = Math.round( this.z );
  3633. return this;
  3634. }
  3635. roundToZero() {
  3636. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  3637. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  3638. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  3639. return this;
  3640. }
  3641. negate() {
  3642. this.x = - this.x;
  3643. this.y = - this.y;
  3644. this.z = - this.z;
  3645. return this;
  3646. }
  3647. dot( v ) {
  3648. return this.x * v.x + this.y * v.y + this.z * v.z;
  3649. }
  3650. // TODO lengthSquared?
  3651. lengthSq() {
  3652. return this.x * this.x + this.y * this.y + this.z * this.z;
  3653. }
  3654. length() {
  3655. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  3656. }
  3657. manhattanLength() {
  3658. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  3659. }
  3660. normalize() {
  3661. return this.divideScalar( this.length() || 1 );
  3662. }
  3663. setLength( length ) {
  3664. return this.normalize().multiplyScalar( length );
  3665. }
  3666. lerp( v, alpha ) {
  3667. this.x += ( v.x - this.x ) * alpha;
  3668. this.y += ( v.y - this.y ) * alpha;
  3669. this.z += ( v.z - this.z ) * alpha;
  3670. return this;
  3671. }
  3672. lerpVectors( v1, v2, alpha ) {
  3673. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3674. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3675. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3676. return this;
  3677. }
  3678. cross( v, w ) {
  3679. if ( w !== undefined ) {
  3680. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  3681. return this.crossVectors( v, w );
  3682. }
  3683. return this.crossVectors( this, v );
  3684. }
  3685. crossVectors( a, b ) {
  3686. const ax = a.x, ay = a.y, az = a.z;
  3687. const bx = b.x, by = b.y, bz = b.z;
  3688. this.x = ay * bz - az * by;
  3689. this.y = az * bx - ax * bz;
  3690. this.z = ax * by - ay * bx;
  3691. return this;
  3692. }
  3693. projectOnVector( v ) {
  3694. const denominator = v.lengthSq();
  3695. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  3696. const scalar = v.dot( this ) / denominator;
  3697. return this.copy( v ).multiplyScalar( scalar );
  3698. }
  3699. projectOnPlane( planeNormal ) {
  3700. _vector$c.copy( this ).projectOnVector( planeNormal );
  3701. return this.sub( _vector$c );
  3702. }
  3703. reflect( normal ) {
  3704. // reflect incident vector off plane orthogonal to normal
  3705. // normal is assumed to have unit length
  3706. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  3707. }
  3708. angleTo( v ) {
  3709. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  3710. if ( denominator === 0 ) return Math.PI / 2;
  3711. const theta = this.dot( v ) / denominator;
  3712. // clamp, to handle numerical problems
  3713. return Math.acos( clamp( theta, - 1, 1 ) );
  3714. }
  3715. distanceTo( v ) {
  3716. return Math.sqrt( this.distanceToSquared( v ) );
  3717. }
  3718. distanceToSquared( v ) {
  3719. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  3720. return dx * dx + dy * dy + dz * dz;
  3721. }
  3722. manhattanDistanceTo( v ) {
  3723. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  3724. }
  3725. setFromSpherical( s ) {
  3726. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  3727. }
  3728. setFromSphericalCoords( radius, phi, theta ) {
  3729. const sinPhiRadius = Math.sin( phi ) * radius;
  3730. this.x = sinPhiRadius * Math.sin( theta );
  3731. this.y = Math.cos( phi ) * radius;
  3732. this.z = sinPhiRadius * Math.cos( theta );
  3733. return this;
  3734. }
  3735. setFromCylindrical( c ) {
  3736. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  3737. }
  3738. setFromCylindricalCoords( radius, theta, y ) {
  3739. this.x = radius * Math.sin( theta );
  3740. this.y = y;
  3741. this.z = radius * Math.cos( theta );
  3742. return this;
  3743. }
  3744. setFromMatrixPosition( m ) {
  3745. const e = m.elements;
  3746. this.x = e[ 12 ];
  3747. this.y = e[ 13 ];
  3748. this.z = e[ 14 ];
  3749. return this;
  3750. }
  3751. setFromMatrixScale( m ) {
  3752. const sx = this.setFromMatrixColumn( m, 0 ).length();
  3753. const sy = this.setFromMatrixColumn( m, 1 ).length();
  3754. const sz = this.setFromMatrixColumn( m, 2 ).length();
  3755. this.x = sx;
  3756. this.y = sy;
  3757. this.z = sz;
  3758. return this;
  3759. }
  3760. setFromMatrixColumn( m, index ) {
  3761. return this.fromArray( m.elements, index * 4 );
  3762. }
  3763. setFromMatrix3Column( m, index ) {
  3764. return this.fromArray( m.elements, index * 3 );
  3765. }
  3766. equals( v ) {
  3767. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  3768. }
  3769. fromArray( array, offset = 0 ) {
  3770. this.x = array[ offset ];
  3771. this.y = array[ offset + 1 ];
  3772. this.z = array[ offset + 2 ];
  3773. return this;
  3774. }
  3775. toArray( array = [], offset = 0 ) {
  3776. array[ offset ] = this.x;
  3777. array[ offset + 1 ] = this.y;
  3778. array[ offset + 2 ] = this.z;
  3779. return array;
  3780. }
  3781. fromBufferAttribute( attribute, index, offset ) {
  3782. if ( offset !== undefined ) {
  3783. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  3784. }
  3785. this.x = attribute.getX( index );
  3786. this.y = attribute.getY( index );
  3787. this.z = attribute.getZ( index );
  3788. return this;
  3789. }
  3790. random() {
  3791. this.x = Math.random();
  3792. this.y = Math.random();
  3793. this.z = Math.random();
  3794. return this;
  3795. }
  3796. }
  3797. Vector3.prototype.isVector3 = true;
  3798. const _vector$c = /*@__PURE__*/ new Vector3();
  3799. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  3800. class Box3 {
  3801. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  3802. this.min = min;
  3803. this.max = max;
  3804. }
  3805. set( min, max ) {
  3806. this.min.copy( min );
  3807. this.max.copy( max );
  3808. return this;
  3809. }
  3810. setFromArray( array ) {
  3811. let minX = + Infinity;
  3812. let minY = + Infinity;
  3813. let minZ = + Infinity;
  3814. let maxX = - Infinity;
  3815. let maxY = - Infinity;
  3816. let maxZ = - Infinity;
  3817. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3818. const x = array[ i ];
  3819. const y = array[ i + 1 ];
  3820. const z = array[ i + 2 ];
  3821. if ( x < minX ) minX = x;
  3822. if ( y < minY ) minY = y;
  3823. if ( z < minZ ) minZ = z;
  3824. if ( x > maxX ) maxX = x;
  3825. if ( y > maxY ) maxY = y;
  3826. if ( z > maxZ ) maxZ = z;
  3827. }
  3828. this.min.set( minX, minY, minZ );
  3829. this.max.set( maxX, maxY, maxZ );
  3830. return this;
  3831. }
  3832. setFromBufferAttribute( attribute ) {
  3833. let minX = + Infinity;
  3834. let minY = + Infinity;
  3835. let minZ = + Infinity;
  3836. let maxX = - Infinity;
  3837. let maxY = - Infinity;
  3838. let maxZ = - Infinity;
  3839. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3840. const x = attribute.getX( i );
  3841. const y = attribute.getY( i );
  3842. const z = attribute.getZ( i );
  3843. if ( x < minX ) minX = x;
  3844. if ( y < minY ) minY = y;
  3845. if ( z < minZ ) minZ = z;
  3846. if ( x > maxX ) maxX = x;
  3847. if ( y > maxY ) maxY = y;
  3848. if ( z > maxZ ) maxZ = z;
  3849. }
  3850. this.min.set( minX, minY, minZ );
  3851. this.max.set( maxX, maxY, maxZ );
  3852. return this;
  3853. }
  3854. setFromPoints( points ) {
  3855. this.makeEmpty();
  3856. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3857. this.expandByPoint( points[ i ] );
  3858. }
  3859. return this;
  3860. }
  3861. setFromCenterAndSize( center, size ) {
  3862. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3863. this.min.copy( center ).sub( halfSize );
  3864. this.max.copy( center ).add( halfSize );
  3865. return this;
  3866. }
  3867. setFromObject( object ) {
  3868. this.makeEmpty();
  3869. return this.expandByObject( object );
  3870. }
  3871. clone() {
  3872. return new this.constructor().copy( this );
  3873. }
  3874. copy( box ) {
  3875. this.min.copy( box.min );
  3876. this.max.copy( box.max );
  3877. return this;
  3878. }
  3879. makeEmpty() {
  3880. this.min.x = this.min.y = this.min.z = + Infinity;
  3881. this.max.x = this.max.y = this.max.z = - Infinity;
  3882. return this;
  3883. }
  3884. isEmpty() {
  3885. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3886. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3887. }
  3888. getCenter( target ) {
  3889. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3890. }
  3891. getSize( target ) {
  3892. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3893. }
  3894. expandByPoint( point ) {
  3895. this.min.min( point );
  3896. this.max.max( point );
  3897. return this;
  3898. }
  3899. expandByVector( vector ) {
  3900. this.min.sub( vector );
  3901. this.max.add( vector );
  3902. return this;
  3903. }
  3904. expandByScalar( scalar ) {
  3905. this.min.addScalar( - scalar );
  3906. this.max.addScalar( scalar );
  3907. return this;
  3908. }
  3909. expandByObject( object ) {
  3910. // Computes the world-axis-aligned bounding box of an object (including its children),
  3911. // accounting for both the object's, and children's, world transforms
  3912. object.updateWorldMatrix( false, false );
  3913. const geometry = object.geometry;
  3914. if ( geometry !== undefined ) {
  3915. if ( geometry.boundingBox === null ) {
  3916. geometry.computeBoundingBox();
  3917. }
  3918. _box$3.copy( geometry.boundingBox );
  3919. _box$3.applyMatrix4( object.matrixWorld );
  3920. this.union( _box$3 );
  3921. }
  3922. const children = object.children;
  3923. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3924. this.expandByObject( children[ i ] );
  3925. }
  3926. return this;
  3927. }
  3928. containsPoint( point ) {
  3929. return point.x < this.min.x || point.x > this.max.x ||
  3930. point.y < this.min.y || point.y > this.max.y ||
  3931. point.z < this.min.z || point.z > this.max.z ? false : true;
  3932. }
  3933. containsBox( box ) {
  3934. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3935. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3936. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3937. }
  3938. getParameter( point, target ) {
  3939. // This can potentially have a divide by zero if the box
  3940. // has a size dimension of 0.
  3941. return target.set(
  3942. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3943. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3944. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3945. );
  3946. }
  3947. intersectsBox( box ) {
  3948. // using 6 splitting planes to rule out intersections.
  3949. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3950. box.max.y < this.min.y || box.min.y > this.max.y ||
  3951. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3952. }
  3953. intersectsSphere( sphere ) {
  3954. // Find the point on the AABB closest to the sphere center.
  3955. this.clampPoint( sphere.center, _vector$b );
  3956. // If that point is inside the sphere, the AABB and sphere intersect.
  3957. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3958. }
  3959. intersectsPlane( plane ) {
  3960. // We compute the minimum and maximum dot product values. If those values
  3961. // are on the same side (back or front) of the plane, then there is no intersection.
  3962. let min, max;
  3963. if ( plane.normal.x > 0 ) {
  3964. min = plane.normal.x * this.min.x;
  3965. max = plane.normal.x * this.max.x;
  3966. } else {
  3967. min = plane.normal.x * this.max.x;
  3968. max = plane.normal.x * this.min.x;
  3969. }
  3970. if ( plane.normal.y > 0 ) {
  3971. min += plane.normal.y * this.min.y;
  3972. max += plane.normal.y * this.max.y;
  3973. } else {
  3974. min += plane.normal.y * this.max.y;
  3975. max += plane.normal.y * this.min.y;
  3976. }
  3977. if ( plane.normal.z > 0 ) {
  3978. min += plane.normal.z * this.min.z;
  3979. max += plane.normal.z * this.max.z;
  3980. } else {
  3981. min += plane.normal.z * this.max.z;
  3982. max += plane.normal.z * this.min.z;
  3983. }
  3984. return ( min <= - plane.constant && max >= - plane.constant );
  3985. }
  3986. intersectsTriangle( triangle ) {
  3987. if ( this.isEmpty() ) {
  3988. return false;
  3989. }
  3990. // compute box center and extents
  3991. this.getCenter( _center );
  3992. _extents.subVectors( this.max, _center );
  3993. // translate triangle to aabb origin
  3994. _v0$2.subVectors( triangle.a, _center );
  3995. _v1$7.subVectors( triangle.b, _center );
  3996. _v2$3.subVectors( triangle.c, _center );
  3997. // compute edge vectors for triangle
  3998. _f0.subVectors( _v1$7, _v0$2 );
  3999. _f1.subVectors( _v2$3, _v1$7 );
  4000. _f2.subVectors( _v0$2, _v2$3 );
  4001. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  4002. // 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
  4003. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  4004. let axes = [
  4005. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  4006. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  4007. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  4008. ];
  4009. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  4010. return false;
  4011. }
  4012. // test 3 face normals from the aabb
  4013. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  4014. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  4015. return false;
  4016. }
  4017. // finally testing the face normal of the triangle
  4018. // use already existing triangle edge vectors here
  4019. _triangleNormal.crossVectors( _f0, _f1 );
  4020. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  4021. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  4022. }
  4023. clampPoint( point, target ) {
  4024. return target.copy( point ).clamp( this.min, this.max );
  4025. }
  4026. distanceToPoint( point ) {
  4027. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  4028. return clampedPoint.sub( point ).length();
  4029. }
  4030. getBoundingSphere( target ) {
  4031. this.getCenter( target.center );
  4032. target.radius = this.getSize( _vector$b ).length() * 0.5;
  4033. return target;
  4034. }
  4035. intersect( box ) {
  4036. this.min.max( box.min );
  4037. this.max.min( box.max );
  4038. // 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.
  4039. if ( this.isEmpty() ) this.makeEmpty();
  4040. return this;
  4041. }
  4042. union( box ) {
  4043. this.min.min( box.min );
  4044. this.max.max( box.max );
  4045. return this;
  4046. }
  4047. applyMatrix4( matrix ) {
  4048. // transform of empty box is an empty box.
  4049. if ( this.isEmpty() ) return this;
  4050. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4051. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  4052. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  4053. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  4054. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  4055. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  4056. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  4057. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  4058. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  4059. this.setFromPoints( _points );
  4060. return this;
  4061. }
  4062. translate( offset ) {
  4063. this.min.add( offset );
  4064. this.max.add( offset );
  4065. return this;
  4066. }
  4067. equals( box ) {
  4068. return box.min.equals( this.min ) && box.max.equals( this.max );
  4069. }
  4070. }
  4071. Box3.prototype.isBox3 = true;
  4072. const _points = [
  4073. /*@__PURE__*/ new Vector3(),
  4074. /*@__PURE__*/ new Vector3(),
  4075. /*@__PURE__*/ new Vector3(),
  4076. /*@__PURE__*/ new Vector3(),
  4077. /*@__PURE__*/ new Vector3(),
  4078. /*@__PURE__*/ new Vector3(),
  4079. /*@__PURE__*/ new Vector3(),
  4080. /*@__PURE__*/ new Vector3()
  4081. ];
  4082. const _vector$b = /*@__PURE__*/ new Vector3();
  4083. const _box$3 = /*@__PURE__*/ new Box3();
  4084. // triangle centered vertices
  4085. const _v0$2 = /*@__PURE__*/ new Vector3();
  4086. const _v1$7 = /*@__PURE__*/ new Vector3();
  4087. const _v2$3 = /*@__PURE__*/ new Vector3();
  4088. // triangle edge vectors
  4089. const _f0 = /*@__PURE__*/ new Vector3();
  4090. const _f1 = /*@__PURE__*/ new Vector3();
  4091. const _f2 = /*@__PURE__*/ new Vector3();
  4092. const _center = /*@__PURE__*/ new Vector3();
  4093. const _extents = /*@__PURE__*/ new Vector3();
  4094. const _triangleNormal = /*@__PURE__*/ new Vector3();
  4095. const _testAxis = /*@__PURE__*/ new Vector3();
  4096. function satForAxes( axes, v0, v1, v2, extents ) {
  4097. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  4098. _testAxis.fromArray( axes, i );
  4099. // project the aabb onto the seperating axis
  4100. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  4101. // project all 3 vertices of the triangle onto the seperating axis
  4102. const p0 = v0.dot( _testAxis );
  4103. const p1 = v1.dot( _testAxis );
  4104. const p2 = v2.dot( _testAxis );
  4105. // actual test, basically see if either of the most extreme of the triangle points intersects r
  4106. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  4107. // points of the projected triangle are outside the projected half-length of the aabb
  4108. // the axis is seperating and we can exit
  4109. return false;
  4110. }
  4111. }
  4112. return true;
  4113. }
  4114. const _box$2 = /*@__PURE__*/ new Box3();
  4115. const _v1$6 = /*@__PURE__*/ new Vector3();
  4116. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  4117. const _toPoint = /*@__PURE__*/ new Vector3();
  4118. class Sphere {
  4119. constructor( center = new Vector3(), radius = - 1 ) {
  4120. this.center = center;
  4121. this.radius = radius;
  4122. }
  4123. set( center, radius ) {
  4124. this.center.copy( center );
  4125. this.radius = radius;
  4126. return this;
  4127. }
  4128. setFromPoints( points, optionalCenter ) {
  4129. const center = this.center;
  4130. if ( optionalCenter !== undefined ) {
  4131. center.copy( optionalCenter );
  4132. } else {
  4133. _box$2.setFromPoints( points ).getCenter( center );
  4134. }
  4135. let maxRadiusSq = 0;
  4136. for ( let i = 0, il = points.length; i < il; i ++ ) {
  4137. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  4138. }
  4139. this.radius = Math.sqrt( maxRadiusSq );
  4140. return this;
  4141. }
  4142. copy( sphere ) {
  4143. this.center.copy( sphere.center );
  4144. this.radius = sphere.radius;
  4145. return this;
  4146. }
  4147. isEmpty() {
  4148. return ( this.radius < 0 );
  4149. }
  4150. makeEmpty() {
  4151. this.center.set( 0, 0, 0 );
  4152. this.radius = - 1;
  4153. return this;
  4154. }
  4155. containsPoint( point ) {
  4156. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  4157. }
  4158. distanceToPoint( point ) {
  4159. return ( point.distanceTo( this.center ) - this.radius );
  4160. }
  4161. intersectsSphere( sphere ) {
  4162. const radiusSum = this.radius + sphere.radius;
  4163. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  4164. }
  4165. intersectsBox( box ) {
  4166. return box.intersectsSphere( this );
  4167. }
  4168. intersectsPlane( plane ) {
  4169. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  4170. }
  4171. clampPoint( point, target ) {
  4172. const deltaLengthSq = this.center.distanceToSquared( point );
  4173. target.copy( point );
  4174. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  4175. target.sub( this.center ).normalize();
  4176. target.multiplyScalar( this.radius ).add( this.center );
  4177. }
  4178. return target;
  4179. }
  4180. getBoundingBox( target ) {
  4181. if ( this.isEmpty() ) {
  4182. // Empty sphere produces empty bounding box
  4183. target.makeEmpty();
  4184. return target;
  4185. }
  4186. target.set( this.center, this.center );
  4187. target.expandByScalar( this.radius );
  4188. return target;
  4189. }
  4190. applyMatrix4( matrix ) {
  4191. this.center.applyMatrix4( matrix );
  4192. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  4193. return this;
  4194. }
  4195. translate( offset ) {
  4196. this.center.add( offset );
  4197. return this;
  4198. }
  4199. expandByPoint( point ) {
  4200. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  4201. _toPoint.subVectors( point, this.center );
  4202. const lengthSq = _toPoint.lengthSq();
  4203. if ( lengthSq > ( this.radius * this.radius ) ) {
  4204. const length = Math.sqrt( lengthSq );
  4205. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  4206. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  4207. // and the other half to position. This gives a tighter enclosure, instead of if
  4208. // the whole missing distance were just added to radius.
  4209. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  4210. this.radius += missingRadiusHalf;
  4211. }
  4212. return this;
  4213. }
  4214. union( sphere ) {
  4215. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  4216. // To enclose another sphere into this sphere, we only need to enclose two points:
  4217. // 1) Enclose the farthest point on the other sphere into this sphere.
  4218. // 2) Enclose the opposite point of the farthest point into this sphere.
  4219. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  4220. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  4221. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  4222. return this;
  4223. }
  4224. equals( sphere ) {
  4225. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  4226. }
  4227. clone() {
  4228. return new this.constructor().copy( this );
  4229. }
  4230. }
  4231. const _vector$a = /*@__PURE__*/ new Vector3();
  4232. const _segCenter = /*@__PURE__*/ new Vector3();
  4233. const _segDir = /*@__PURE__*/ new Vector3();
  4234. const _diff = /*@__PURE__*/ new Vector3();
  4235. const _edge1 = /*@__PURE__*/ new Vector3();
  4236. const _edge2 = /*@__PURE__*/ new Vector3();
  4237. const _normal$1 = /*@__PURE__*/ new Vector3();
  4238. class Ray {
  4239. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  4240. this.origin = origin;
  4241. this.direction = direction;
  4242. }
  4243. set( origin, direction ) {
  4244. this.origin.copy( origin );
  4245. this.direction.copy( direction );
  4246. return this;
  4247. }
  4248. copy( ray ) {
  4249. this.origin.copy( ray.origin );
  4250. this.direction.copy( ray.direction );
  4251. return this;
  4252. }
  4253. at( t, target ) {
  4254. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  4255. }
  4256. lookAt( v ) {
  4257. this.direction.copy( v ).sub( this.origin ).normalize();
  4258. return this;
  4259. }
  4260. recast( t ) {
  4261. this.origin.copy( this.at( t, _vector$a ) );
  4262. return this;
  4263. }
  4264. closestPointToPoint( point, target ) {
  4265. target.subVectors( point, this.origin );
  4266. const directionDistance = target.dot( this.direction );
  4267. if ( directionDistance < 0 ) {
  4268. return target.copy( this.origin );
  4269. }
  4270. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  4271. }
  4272. distanceToPoint( point ) {
  4273. return Math.sqrt( this.distanceSqToPoint( point ) );
  4274. }
  4275. distanceSqToPoint( point ) {
  4276. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  4277. // point behind the ray
  4278. if ( directionDistance < 0 ) {
  4279. return this.origin.distanceToSquared( point );
  4280. }
  4281. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  4282. return _vector$a.distanceToSquared( point );
  4283. }
  4284. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  4285. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  4286. // It returns the min distance between the ray and the segment
  4287. // defined by v0 and v1
  4288. // It can also set two optional targets :
  4289. // - The closest point on the ray
  4290. // - The closest point on the segment
  4291. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  4292. _segDir.copy( v1 ).sub( v0 ).normalize();
  4293. _diff.copy( this.origin ).sub( _segCenter );
  4294. const segExtent = v0.distanceTo( v1 ) * 0.5;
  4295. const a01 = - this.direction.dot( _segDir );
  4296. const b0 = _diff.dot( this.direction );
  4297. const b1 = - _diff.dot( _segDir );
  4298. const c = _diff.lengthSq();
  4299. const det = Math.abs( 1 - a01 * a01 );
  4300. let s0, s1, sqrDist, extDet;
  4301. if ( det > 0 ) {
  4302. // The ray and segment are not parallel.
  4303. s0 = a01 * b1 - b0;
  4304. s1 = a01 * b0 - b1;
  4305. extDet = segExtent * det;
  4306. if ( s0 >= 0 ) {
  4307. if ( s1 >= - extDet ) {
  4308. if ( s1 <= extDet ) {
  4309. // region 0
  4310. // Minimum at interior points of ray and segment.
  4311. const invDet = 1 / det;
  4312. s0 *= invDet;
  4313. s1 *= invDet;
  4314. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  4315. } else {
  4316. // region 1
  4317. s1 = segExtent;
  4318. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4319. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4320. }
  4321. } else {
  4322. // region 5
  4323. s1 = - segExtent;
  4324. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4325. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4326. }
  4327. } else {
  4328. if ( s1 <= - extDet ) {
  4329. // region 4
  4330. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  4331. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4332. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4333. } else if ( s1 <= extDet ) {
  4334. // region 3
  4335. s0 = 0;
  4336. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4337. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  4338. } else {
  4339. // region 2
  4340. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  4341. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4342. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4343. }
  4344. }
  4345. } else {
  4346. // Ray and segment are parallel.
  4347. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  4348. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4349. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4350. }
  4351. if ( optionalPointOnRay ) {
  4352. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  4353. }
  4354. if ( optionalPointOnSegment ) {
  4355. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  4356. }
  4357. return sqrDist;
  4358. }
  4359. intersectSphere( sphere, target ) {
  4360. _vector$a.subVectors( sphere.center, this.origin );
  4361. const tca = _vector$a.dot( this.direction );
  4362. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  4363. const radius2 = sphere.radius * sphere.radius;
  4364. if ( d2 > radius2 ) return null;
  4365. const thc = Math.sqrt( radius2 - d2 );
  4366. // t0 = first intersect point - entrance on front of sphere
  4367. const t0 = tca - thc;
  4368. // t1 = second intersect point - exit point on back of sphere
  4369. const t1 = tca + thc;
  4370. // test to see if both t0 and t1 are behind the ray - if so, return null
  4371. if ( t0 < 0 && t1 < 0 ) return null;
  4372. // test to see if t0 is behind the ray:
  4373. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  4374. // in order to always return an intersect point that is in front of the ray.
  4375. if ( t0 < 0 ) return this.at( t1, target );
  4376. // else t0 is in front of the ray, so return the first collision point scaled by t0
  4377. return this.at( t0, target );
  4378. }
  4379. intersectsSphere( sphere ) {
  4380. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  4381. }
  4382. distanceToPlane( plane ) {
  4383. const denominator = plane.normal.dot( this.direction );
  4384. if ( denominator === 0 ) {
  4385. // line is coplanar, return origin
  4386. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  4387. return 0;
  4388. }
  4389. // Null is preferable to undefined since undefined means.... it is undefined
  4390. return null;
  4391. }
  4392. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  4393. // Return if the ray never intersects the plane
  4394. return t >= 0 ? t : null;
  4395. }
  4396. intersectPlane( plane, target ) {
  4397. const t = this.distanceToPlane( plane );
  4398. if ( t === null ) {
  4399. return null;
  4400. }
  4401. return this.at( t, target );
  4402. }
  4403. intersectsPlane( plane ) {
  4404. // check if the ray lies on the plane first
  4405. const distToPoint = plane.distanceToPoint( this.origin );
  4406. if ( distToPoint === 0 ) {
  4407. return true;
  4408. }
  4409. const denominator = plane.normal.dot( this.direction );
  4410. if ( denominator * distToPoint < 0 ) {
  4411. return true;
  4412. }
  4413. // ray origin is behind the plane (and is pointing behind it)
  4414. return false;
  4415. }
  4416. intersectBox( box, target ) {
  4417. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  4418. const invdirx = 1 / this.direction.x,
  4419. invdiry = 1 / this.direction.y,
  4420. invdirz = 1 / this.direction.z;
  4421. const origin = this.origin;
  4422. if ( invdirx >= 0 ) {
  4423. tmin = ( box.min.x - origin.x ) * invdirx;
  4424. tmax = ( box.max.x - origin.x ) * invdirx;
  4425. } else {
  4426. tmin = ( box.max.x - origin.x ) * invdirx;
  4427. tmax = ( box.min.x - origin.x ) * invdirx;
  4428. }
  4429. if ( invdiry >= 0 ) {
  4430. tymin = ( box.min.y - origin.y ) * invdiry;
  4431. tymax = ( box.max.y - origin.y ) * invdiry;
  4432. } else {
  4433. tymin = ( box.max.y - origin.y ) * invdiry;
  4434. tymax = ( box.min.y - origin.y ) * invdiry;
  4435. }
  4436. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  4437. // These lines also handle the case where tmin or tmax is NaN
  4438. // (result of 0 * Infinity). x !== x returns true if x is NaN
  4439. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  4440. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  4441. if ( invdirz >= 0 ) {
  4442. tzmin = ( box.min.z - origin.z ) * invdirz;
  4443. tzmax = ( box.max.z - origin.z ) * invdirz;
  4444. } else {
  4445. tzmin = ( box.max.z - origin.z ) * invdirz;
  4446. tzmax = ( box.min.z - origin.z ) * invdirz;
  4447. }
  4448. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  4449. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  4450. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  4451. //return point closest to the ray (positive side)
  4452. if ( tmax < 0 ) return null;
  4453. return this.at( tmin >= 0 ? tmin : tmax, target );
  4454. }
  4455. intersectsBox( box ) {
  4456. return this.intersectBox( box, _vector$a ) !== null;
  4457. }
  4458. intersectTriangle( a, b, c, backfaceCulling, target ) {
  4459. // Compute the offset origin, edges, and normal.
  4460. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  4461. _edge1.subVectors( b, a );
  4462. _edge2.subVectors( c, a );
  4463. _normal$1.crossVectors( _edge1, _edge2 );
  4464. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  4465. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  4466. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  4467. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  4468. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  4469. let DdN = this.direction.dot( _normal$1 );
  4470. let sign;
  4471. if ( DdN > 0 ) {
  4472. if ( backfaceCulling ) return null;
  4473. sign = 1;
  4474. } else if ( DdN < 0 ) {
  4475. sign = - 1;
  4476. DdN = - DdN;
  4477. } else {
  4478. return null;
  4479. }
  4480. _diff.subVectors( this.origin, a );
  4481. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  4482. // b1 < 0, no intersection
  4483. if ( DdQxE2 < 0 ) {
  4484. return null;
  4485. }
  4486. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  4487. // b2 < 0, no intersection
  4488. if ( DdE1xQ < 0 ) {
  4489. return null;
  4490. }
  4491. // b1+b2 > 1, no intersection
  4492. if ( DdQxE2 + DdE1xQ > DdN ) {
  4493. return null;
  4494. }
  4495. // Line intersects triangle, check if ray does.
  4496. const QdN = - sign * _diff.dot( _normal$1 );
  4497. // t < 0, no intersection
  4498. if ( QdN < 0 ) {
  4499. return null;
  4500. }
  4501. // Ray intersects triangle.
  4502. return this.at( QdN / DdN, target );
  4503. }
  4504. applyMatrix4( matrix4 ) {
  4505. this.origin.applyMatrix4( matrix4 );
  4506. this.direction.transformDirection( matrix4 );
  4507. return this;
  4508. }
  4509. equals( ray ) {
  4510. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  4511. }
  4512. clone() {
  4513. return new this.constructor().copy( this );
  4514. }
  4515. }
  4516. class Matrix4 {
  4517. constructor() {
  4518. this.elements = [
  4519. 1, 0, 0, 0,
  4520. 0, 1, 0, 0,
  4521. 0, 0, 1, 0,
  4522. 0, 0, 0, 1
  4523. ];
  4524. if ( arguments.length > 0 ) {
  4525. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  4526. }
  4527. }
  4528. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4529. const te = this.elements;
  4530. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  4531. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  4532. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  4533. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  4534. return this;
  4535. }
  4536. identity() {
  4537. this.set(
  4538. 1, 0, 0, 0,
  4539. 0, 1, 0, 0,
  4540. 0, 0, 1, 0,
  4541. 0, 0, 0, 1
  4542. );
  4543. return this;
  4544. }
  4545. clone() {
  4546. return new Matrix4().fromArray( this.elements );
  4547. }
  4548. copy( m ) {
  4549. const te = this.elements;
  4550. const me = m.elements;
  4551. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  4552. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  4553. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  4554. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  4555. return this;
  4556. }
  4557. copyPosition( m ) {
  4558. const te = this.elements, me = m.elements;
  4559. te[ 12 ] = me[ 12 ];
  4560. te[ 13 ] = me[ 13 ];
  4561. te[ 14 ] = me[ 14 ];
  4562. return this;
  4563. }
  4564. setFromMatrix3( m ) {
  4565. const me = m.elements;
  4566. this.set(
  4567. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  4568. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  4569. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  4570. 0, 0, 0, 1
  4571. );
  4572. return this;
  4573. }
  4574. extractBasis( xAxis, yAxis, zAxis ) {
  4575. xAxis.setFromMatrixColumn( this, 0 );
  4576. yAxis.setFromMatrixColumn( this, 1 );
  4577. zAxis.setFromMatrixColumn( this, 2 );
  4578. return this;
  4579. }
  4580. makeBasis( xAxis, yAxis, zAxis ) {
  4581. this.set(
  4582. xAxis.x, yAxis.x, zAxis.x, 0,
  4583. xAxis.y, yAxis.y, zAxis.y, 0,
  4584. xAxis.z, yAxis.z, zAxis.z, 0,
  4585. 0, 0, 0, 1
  4586. );
  4587. return this;
  4588. }
  4589. extractRotation( m ) {
  4590. // this method does not support reflection matrices
  4591. const te = this.elements;
  4592. const me = m.elements;
  4593. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  4594. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  4595. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  4596. te[ 0 ] = me[ 0 ] * scaleX;
  4597. te[ 1 ] = me[ 1 ] * scaleX;
  4598. te[ 2 ] = me[ 2 ] * scaleX;
  4599. te[ 3 ] = 0;
  4600. te[ 4 ] = me[ 4 ] * scaleY;
  4601. te[ 5 ] = me[ 5 ] * scaleY;
  4602. te[ 6 ] = me[ 6 ] * scaleY;
  4603. te[ 7 ] = 0;
  4604. te[ 8 ] = me[ 8 ] * scaleZ;
  4605. te[ 9 ] = me[ 9 ] * scaleZ;
  4606. te[ 10 ] = me[ 10 ] * scaleZ;
  4607. te[ 11 ] = 0;
  4608. te[ 12 ] = 0;
  4609. te[ 13 ] = 0;
  4610. te[ 14 ] = 0;
  4611. te[ 15 ] = 1;
  4612. return this;
  4613. }
  4614. makeRotationFromEuler( euler ) {
  4615. if ( ! ( euler && euler.isEuler ) ) {
  4616. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  4617. }
  4618. const te = this.elements;
  4619. const x = euler.x, y = euler.y, z = euler.z;
  4620. const a = Math.cos( x ), b = Math.sin( x );
  4621. const c = Math.cos( y ), d = Math.sin( y );
  4622. const e = Math.cos( z ), f = Math.sin( z );
  4623. if ( euler.order === 'XYZ' ) {
  4624. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4625. te[ 0 ] = c * e;
  4626. te[ 4 ] = - c * f;
  4627. te[ 8 ] = d;
  4628. te[ 1 ] = af + be * d;
  4629. te[ 5 ] = ae - bf * d;
  4630. te[ 9 ] = - b * c;
  4631. te[ 2 ] = bf - ae * d;
  4632. te[ 6 ] = be + af * d;
  4633. te[ 10 ] = a * c;
  4634. } else if ( euler.order === 'YXZ' ) {
  4635. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4636. te[ 0 ] = ce + df * b;
  4637. te[ 4 ] = de * b - cf;
  4638. te[ 8 ] = a * d;
  4639. te[ 1 ] = a * f;
  4640. te[ 5 ] = a * e;
  4641. te[ 9 ] = - b;
  4642. te[ 2 ] = cf * b - de;
  4643. te[ 6 ] = df + ce * b;
  4644. te[ 10 ] = a * c;
  4645. } else if ( euler.order === 'ZXY' ) {
  4646. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4647. te[ 0 ] = ce - df * b;
  4648. te[ 4 ] = - a * f;
  4649. te[ 8 ] = de + cf * b;
  4650. te[ 1 ] = cf + de * b;
  4651. te[ 5 ] = a * e;
  4652. te[ 9 ] = df - ce * b;
  4653. te[ 2 ] = - a * d;
  4654. te[ 6 ] = b;
  4655. te[ 10 ] = a * c;
  4656. } else if ( euler.order === 'ZYX' ) {
  4657. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4658. te[ 0 ] = c * e;
  4659. te[ 4 ] = be * d - af;
  4660. te[ 8 ] = ae * d + bf;
  4661. te[ 1 ] = c * f;
  4662. te[ 5 ] = bf * d + ae;
  4663. te[ 9 ] = af * d - be;
  4664. te[ 2 ] = - d;
  4665. te[ 6 ] = b * c;
  4666. te[ 10 ] = a * c;
  4667. } else if ( euler.order === 'YZX' ) {
  4668. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4669. te[ 0 ] = c * e;
  4670. te[ 4 ] = bd - ac * f;
  4671. te[ 8 ] = bc * f + ad;
  4672. te[ 1 ] = f;
  4673. te[ 5 ] = a * e;
  4674. te[ 9 ] = - b * e;
  4675. te[ 2 ] = - d * e;
  4676. te[ 6 ] = ad * f + bc;
  4677. te[ 10 ] = ac - bd * f;
  4678. } else if ( euler.order === 'XZY' ) {
  4679. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4680. te[ 0 ] = c * e;
  4681. te[ 4 ] = - f;
  4682. te[ 8 ] = d * e;
  4683. te[ 1 ] = ac * f + bd;
  4684. te[ 5 ] = a * e;
  4685. te[ 9 ] = ad * f - bc;
  4686. te[ 2 ] = bc * f - ad;
  4687. te[ 6 ] = b * e;
  4688. te[ 10 ] = bd * f + ac;
  4689. }
  4690. // bottom row
  4691. te[ 3 ] = 0;
  4692. te[ 7 ] = 0;
  4693. te[ 11 ] = 0;
  4694. // last column
  4695. te[ 12 ] = 0;
  4696. te[ 13 ] = 0;
  4697. te[ 14 ] = 0;
  4698. te[ 15 ] = 1;
  4699. return this;
  4700. }
  4701. makeRotationFromQuaternion( q ) {
  4702. return this.compose( _zero, q, _one );
  4703. }
  4704. lookAt( eye, target, up ) {
  4705. const te = this.elements;
  4706. _z.subVectors( eye, target );
  4707. if ( _z.lengthSq() === 0 ) {
  4708. // eye and target are in the same position
  4709. _z.z = 1;
  4710. }
  4711. _z.normalize();
  4712. _x.crossVectors( up, _z );
  4713. if ( _x.lengthSq() === 0 ) {
  4714. // up and z are parallel
  4715. if ( Math.abs( up.z ) === 1 ) {
  4716. _z.x += 0.0001;
  4717. } else {
  4718. _z.z += 0.0001;
  4719. }
  4720. _z.normalize();
  4721. _x.crossVectors( up, _z );
  4722. }
  4723. _x.normalize();
  4724. _y.crossVectors( _z, _x );
  4725. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  4726. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  4727. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  4728. return this;
  4729. }
  4730. multiply( m, n ) {
  4731. if ( n !== undefined ) {
  4732. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  4733. return this.multiplyMatrices( m, n );
  4734. }
  4735. return this.multiplyMatrices( this, m );
  4736. }
  4737. premultiply( m ) {
  4738. return this.multiplyMatrices( m, this );
  4739. }
  4740. multiplyMatrices( a, b ) {
  4741. const ae = a.elements;
  4742. const be = b.elements;
  4743. const te = this.elements;
  4744. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  4745. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  4746. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4747. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4748. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4749. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4750. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4751. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4752. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4753. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4754. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4755. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4756. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4757. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4758. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4759. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4760. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4761. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4762. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4763. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4764. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4765. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4766. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4767. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4768. return this;
  4769. }
  4770. multiplyScalar( s ) {
  4771. const te = this.elements;
  4772. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4773. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4774. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4775. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4776. return this;
  4777. }
  4778. determinant() {
  4779. const te = this.elements;
  4780. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4781. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4782. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4783. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4784. //TODO: make this more efficient
  4785. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4786. return (
  4787. n41 * (
  4788. + n14 * n23 * n32
  4789. - n13 * n24 * n32
  4790. - n14 * n22 * n33
  4791. + n12 * n24 * n33
  4792. + n13 * n22 * n34
  4793. - n12 * n23 * n34
  4794. ) +
  4795. n42 * (
  4796. + n11 * n23 * n34
  4797. - n11 * n24 * n33
  4798. + n14 * n21 * n33
  4799. - n13 * n21 * n34
  4800. + n13 * n24 * n31
  4801. - n14 * n23 * n31
  4802. ) +
  4803. n43 * (
  4804. + n11 * n24 * n32
  4805. - n11 * n22 * n34
  4806. - n14 * n21 * n32
  4807. + n12 * n21 * n34
  4808. + n14 * n22 * n31
  4809. - n12 * n24 * n31
  4810. ) +
  4811. n44 * (
  4812. - n13 * n22 * n31
  4813. - n11 * n23 * n32
  4814. + n11 * n22 * n33
  4815. + n13 * n21 * n32
  4816. - n12 * n21 * n33
  4817. + n12 * n23 * n31
  4818. )
  4819. );
  4820. }
  4821. transpose() {
  4822. const te = this.elements;
  4823. let tmp;
  4824. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4825. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4826. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4827. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4828. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4829. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4830. return this;
  4831. }
  4832. setPosition( x, y, z ) {
  4833. const te = this.elements;
  4834. if ( x.isVector3 ) {
  4835. te[ 12 ] = x.x;
  4836. te[ 13 ] = x.y;
  4837. te[ 14 ] = x.z;
  4838. } else {
  4839. te[ 12 ] = x;
  4840. te[ 13 ] = y;
  4841. te[ 14 ] = z;
  4842. }
  4843. return this;
  4844. }
  4845. invert() {
  4846. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4847. const te = this.elements,
  4848. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4849. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4850. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4851. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4852. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4853. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4854. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4855. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4856. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4857. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4858. const detInv = 1 / det;
  4859. te[ 0 ] = t11 * detInv;
  4860. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4861. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4862. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4863. te[ 4 ] = t12 * detInv;
  4864. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4865. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4866. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4867. te[ 8 ] = t13 * detInv;
  4868. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4869. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4870. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4871. te[ 12 ] = t14 * detInv;
  4872. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4873. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4874. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4875. return this;
  4876. }
  4877. scale( v ) {
  4878. const te = this.elements;
  4879. const x = v.x, y = v.y, z = v.z;
  4880. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4881. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4882. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4883. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4884. return this;
  4885. }
  4886. getMaxScaleOnAxis() {
  4887. const te = this.elements;
  4888. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4889. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4890. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4891. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4892. }
  4893. makeTranslation( x, y, z ) {
  4894. this.set(
  4895. 1, 0, 0, x,
  4896. 0, 1, 0, y,
  4897. 0, 0, 1, z,
  4898. 0, 0, 0, 1
  4899. );
  4900. return this;
  4901. }
  4902. makeRotationX( theta ) {
  4903. const c = Math.cos( theta ), s = Math.sin( theta );
  4904. this.set(
  4905. 1, 0, 0, 0,
  4906. 0, c, - s, 0,
  4907. 0, s, c, 0,
  4908. 0, 0, 0, 1
  4909. );
  4910. return this;
  4911. }
  4912. makeRotationY( theta ) {
  4913. const c = Math.cos( theta ), s = Math.sin( theta );
  4914. this.set(
  4915. c, 0, s, 0,
  4916. 0, 1, 0, 0,
  4917. - s, 0, c, 0,
  4918. 0, 0, 0, 1
  4919. );
  4920. return this;
  4921. }
  4922. makeRotationZ( theta ) {
  4923. const c = Math.cos( theta ), s = Math.sin( theta );
  4924. this.set(
  4925. c, - s, 0, 0,
  4926. s, c, 0, 0,
  4927. 0, 0, 1, 0,
  4928. 0, 0, 0, 1
  4929. );
  4930. return this;
  4931. }
  4932. makeRotationAxis( axis, angle ) {
  4933. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4934. const c = Math.cos( angle );
  4935. const s = Math.sin( angle );
  4936. const t = 1 - c;
  4937. const x = axis.x, y = axis.y, z = axis.z;
  4938. const tx = t * x, ty = t * y;
  4939. this.set(
  4940. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4941. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4942. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4943. 0, 0, 0, 1
  4944. );
  4945. return this;
  4946. }
  4947. makeScale( x, y, z ) {
  4948. this.set(
  4949. x, 0, 0, 0,
  4950. 0, y, 0, 0,
  4951. 0, 0, z, 0,
  4952. 0, 0, 0, 1
  4953. );
  4954. return this;
  4955. }
  4956. makeShear( xy, xz, yx, yz, zx, zy ) {
  4957. this.set(
  4958. 1, yx, zx, 0,
  4959. xy, 1, zy, 0,
  4960. xz, yz, 1, 0,
  4961. 0, 0, 0, 1
  4962. );
  4963. return this;
  4964. }
  4965. compose( position, quaternion, scale ) {
  4966. const te = this.elements;
  4967. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4968. const x2 = x + x, y2 = y + y, z2 = z + z;
  4969. const xx = x * x2, xy = x * y2, xz = x * z2;
  4970. const yy = y * y2, yz = y * z2, zz = z * z2;
  4971. const wx = w * x2, wy = w * y2, wz = w * z2;
  4972. const sx = scale.x, sy = scale.y, sz = scale.z;
  4973. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4974. te[ 1 ] = ( xy + wz ) * sx;
  4975. te[ 2 ] = ( xz - wy ) * sx;
  4976. te[ 3 ] = 0;
  4977. te[ 4 ] = ( xy - wz ) * sy;
  4978. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4979. te[ 6 ] = ( yz + wx ) * sy;
  4980. te[ 7 ] = 0;
  4981. te[ 8 ] = ( xz + wy ) * sz;
  4982. te[ 9 ] = ( yz - wx ) * sz;
  4983. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4984. te[ 11 ] = 0;
  4985. te[ 12 ] = position.x;
  4986. te[ 13 ] = position.y;
  4987. te[ 14 ] = position.z;
  4988. te[ 15 ] = 1;
  4989. return this;
  4990. }
  4991. decompose( position, quaternion, scale ) {
  4992. const te = this.elements;
  4993. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4994. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4995. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4996. // if determine is negative, we need to invert one scale
  4997. const det = this.determinant();
  4998. if ( det < 0 ) sx = - sx;
  4999. position.x = te[ 12 ];
  5000. position.y = te[ 13 ];
  5001. position.z = te[ 14 ];
  5002. // scale the rotation part
  5003. _m1$2.copy( this );
  5004. const invSX = 1 / sx;
  5005. const invSY = 1 / sy;
  5006. const invSZ = 1 / sz;
  5007. _m1$2.elements[ 0 ] *= invSX;
  5008. _m1$2.elements[ 1 ] *= invSX;
  5009. _m1$2.elements[ 2 ] *= invSX;
  5010. _m1$2.elements[ 4 ] *= invSY;
  5011. _m1$2.elements[ 5 ] *= invSY;
  5012. _m1$2.elements[ 6 ] *= invSY;
  5013. _m1$2.elements[ 8 ] *= invSZ;
  5014. _m1$2.elements[ 9 ] *= invSZ;
  5015. _m1$2.elements[ 10 ] *= invSZ;
  5016. quaternion.setFromRotationMatrix( _m1$2 );
  5017. scale.x = sx;
  5018. scale.y = sy;
  5019. scale.z = sz;
  5020. return this;
  5021. }
  5022. makePerspective( left, right, top, bottom, near, far ) {
  5023. if ( far === undefined ) {
  5024. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  5025. }
  5026. const te = this.elements;
  5027. const x = 2 * near / ( right - left );
  5028. const y = 2 * near / ( top - bottom );
  5029. const a = ( right + left ) / ( right - left );
  5030. const b = ( top + bottom ) / ( top - bottom );
  5031. const c = - ( far + near ) / ( far - near );
  5032. const d = - 2 * far * near / ( far - near );
  5033. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  5034. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  5035. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  5036. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  5037. return this;
  5038. }
  5039. makeOrthographic( left, right, top, bottom, near, far ) {
  5040. const te = this.elements;
  5041. const w = 1.0 / ( right - left );
  5042. const h = 1.0 / ( top - bottom );
  5043. const p = 1.0 / ( far - near );
  5044. const x = ( right + left ) * w;
  5045. const y = ( top + bottom ) * h;
  5046. const z = ( far + near ) * p;
  5047. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  5048. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  5049. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  5050. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  5051. return this;
  5052. }
  5053. equals( matrix ) {
  5054. const te = this.elements;
  5055. const me = matrix.elements;
  5056. for ( let i = 0; i < 16; i ++ ) {
  5057. if ( te[ i ] !== me[ i ] ) return false;
  5058. }
  5059. return true;
  5060. }
  5061. fromArray( array, offset = 0 ) {
  5062. for ( let i = 0; i < 16; i ++ ) {
  5063. this.elements[ i ] = array[ i + offset ];
  5064. }
  5065. return this;
  5066. }
  5067. toArray( array = [], offset = 0 ) {
  5068. const te = this.elements;
  5069. array[ offset ] = te[ 0 ];
  5070. array[ offset + 1 ] = te[ 1 ];
  5071. array[ offset + 2 ] = te[ 2 ];
  5072. array[ offset + 3 ] = te[ 3 ];
  5073. array[ offset + 4 ] = te[ 4 ];
  5074. array[ offset + 5 ] = te[ 5 ];
  5075. array[ offset + 6 ] = te[ 6 ];
  5076. array[ offset + 7 ] = te[ 7 ];
  5077. array[ offset + 8 ] = te[ 8 ];
  5078. array[ offset + 9 ] = te[ 9 ];
  5079. array[ offset + 10 ] = te[ 10 ];
  5080. array[ offset + 11 ] = te[ 11 ];
  5081. array[ offset + 12 ] = te[ 12 ];
  5082. array[ offset + 13 ] = te[ 13 ];
  5083. array[ offset + 14 ] = te[ 14 ];
  5084. array[ offset + 15 ] = te[ 15 ];
  5085. return array;
  5086. }
  5087. }
  5088. Matrix4.prototype.isMatrix4 = true;
  5089. const _v1$5 = /*@__PURE__*/ new Vector3();
  5090. const _m1$2 = /*@__PURE__*/ new Matrix4();
  5091. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  5092. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  5093. const _x = /*@__PURE__*/ new Vector3();
  5094. const _y = /*@__PURE__*/ new Vector3();
  5095. const _z = /*@__PURE__*/ new Vector3();
  5096. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  5097. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  5098. class Euler {
  5099. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  5100. this._x = x;
  5101. this._y = y;
  5102. this._z = z;
  5103. this._order = order;
  5104. }
  5105. get x() {
  5106. return this._x;
  5107. }
  5108. set x( value ) {
  5109. this._x = value;
  5110. this._onChangeCallback();
  5111. }
  5112. get y() {
  5113. return this._y;
  5114. }
  5115. set y( value ) {
  5116. this._y = value;
  5117. this._onChangeCallback();
  5118. }
  5119. get z() {
  5120. return this._z;
  5121. }
  5122. set z( value ) {
  5123. this._z = value;
  5124. this._onChangeCallback();
  5125. }
  5126. get order() {
  5127. return this._order;
  5128. }
  5129. set order( value ) {
  5130. this._order = value;
  5131. this._onChangeCallback();
  5132. }
  5133. set( x, y, z, order = this._order ) {
  5134. this._x = x;
  5135. this._y = y;
  5136. this._z = z;
  5137. this._order = order;
  5138. this._onChangeCallback();
  5139. return this;
  5140. }
  5141. clone() {
  5142. return new this.constructor( this._x, this._y, this._z, this._order );
  5143. }
  5144. copy( euler ) {
  5145. this._x = euler._x;
  5146. this._y = euler._y;
  5147. this._z = euler._z;
  5148. this._order = euler._order;
  5149. this._onChangeCallback();
  5150. return this;
  5151. }
  5152. setFromRotationMatrix( m, order = this._order, update = true ) {
  5153. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5154. const te = m.elements;
  5155. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  5156. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  5157. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  5158. switch ( order ) {
  5159. case 'XYZ':
  5160. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  5161. if ( Math.abs( m13 ) < 0.9999999 ) {
  5162. this._x = Math.atan2( - m23, m33 );
  5163. this._z = Math.atan2( - m12, m11 );
  5164. } else {
  5165. this._x = Math.atan2( m32, m22 );
  5166. this._z = 0;
  5167. }
  5168. break;
  5169. case 'YXZ':
  5170. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  5171. if ( Math.abs( m23 ) < 0.9999999 ) {
  5172. this._y = Math.atan2( m13, m33 );
  5173. this._z = Math.atan2( m21, m22 );
  5174. } else {
  5175. this._y = Math.atan2( - m31, m11 );
  5176. this._z = 0;
  5177. }
  5178. break;
  5179. case 'ZXY':
  5180. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  5181. if ( Math.abs( m32 ) < 0.9999999 ) {
  5182. this._y = Math.atan2( - m31, m33 );
  5183. this._z = Math.atan2( - m12, m22 );
  5184. } else {
  5185. this._y = 0;
  5186. this._z = Math.atan2( m21, m11 );
  5187. }
  5188. break;
  5189. case 'ZYX':
  5190. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  5191. if ( Math.abs( m31 ) < 0.9999999 ) {
  5192. this._x = Math.atan2( m32, m33 );
  5193. this._z = Math.atan2( m21, m11 );
  5194. } else {
  5195. this._x = 0;
  5196. this._z = Math.atan2( - m12, m22 );
  5197. }
  5198. break;
  5199. case 'YZX':
  5200. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  5201. if ( Math.abs( m21 ) < 0.9999999 ) {
  5202. this._x = Math.atan2( - m23, m22 );
  5203. this._y = Math.atan2( - m31, m11 );
  5204. } else {
  5205. this._x = 0;
  5206. this._y = Math.atan2( m13, m33 );
  5207. }
  5208. break;
  5209. case 'XZY':
  5210. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  5211. if ( Math.abs( m12 ) < 0.9999999 ) {
  5212. this._x = Math.atan2( m32, m22 );
  5213. this._y = Math.atan2( m13, m11 );
  5214. } else {
  5215. this._x = Math.atan2( - m23, m33 );
  5216. this._y = 0;
  5217. }
  5218. break;
  5219. default:
  5220. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  5221. }
  5222. this._order = order;
  5223. if ( update === true ) this._onChangeCallback();
  5224. return this;
  5225. }
  5226. setFromQuaternion( q, order, update ) {
  5227. _matrix$1.makeRotationFromQuaternion( q );
  5228. return this.setFromRotationMatrix( _matrix$1, order, update );
  5229. }
  5230. setFromVector3( v, order = this._order ) {
  5231. return this.set( v.x, v.y, v.z, order );
  5232. }
  5233. reorder( newOrder ) {
  5234. // WARNING: this discards revolution information -bhouston
  5235. _quaternion$3.setFromEuler( this );
  5236. return this.setFromQuaternion( _quaternion$3, newOrder );
  5237. }
  5238. equals( euler ) {
  5239. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  5240. }
  5241. fromArray( array ) {
  5242. this._x = array[ 0 ];
  5243. this._y = array[ 1 ];
  5244. this._z = array[ 2 ];
  5245. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  5246. this._onChangeCallback();
  5247. return this;
  5248. }
  5249. toArray( array = [], offset = 0 ) {
  5250. array[ offset ] = this._x;
  5251. array[ offset + 1 ] = this._y;
  5252. array[ offset + 2 ] = this._z;
  5253. array[ offset + 3 ] = this._order;
  5254. return array;
  5255. }
  5256. toVector3( optionalResult ) {
  5257. if ( optionalResult ) {
  5258. return optionalResult.set( this._x, this._y, this._z );
  5259. } else {
  5260. return new Vector3( this._x, this._y, this._z );
  5261. }
  5262. }
  5263. _onChange( callback ) {
  5264. this._onChangeCallback = callback;
  5265. return this;
  5266. }
  5267. _onChangeCallback() {}
  5268. }
  5269. Euler.prototype.isEuler = true;
  5270. Euler.DefaultOrder = 'XYZ';
  5271. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  5272. class Layers {
  5273. constructor() {
  5274. this.mask = 1 | 0;
  5275. }
  5276. set( channel ) {
  5277. this.mask = 1 << channel | 0;
  5278. }
  5279. enable( channel ) {
  5280. this.mask |= 1 << channel | 0;
  5281. }
  5282. enableAll() {
  5283. this.mask = 0xffffffff | 0;
  5284. }
  5285. toggle( channel ) {
  5286. this.mask ^= 1 << channel | 0;
  5287. }
  5288. disable( channel ) {
  5289. this.mask &= ~ ( 1 << channel | 0 );
  5290. }
  5291. disableAll() {
  5292. this.mask = 0;
  5293. }
  5294. test( layers ) {
  5295. return ( this.mask & layers.mask ) !== 0;
  5296. }
  5297. }
  5298. let _object3DId = 0;
  5299. const _v1$4 = /*@__PURE__*/ new Vector3();
  5300. const _q1 = /*@__PURE__*/ new Quaternion();
  5301. const _m1$1 = /*@__PURE__*/ new Matrix4();
  5302. const _target = /*@__PURE__*/ new Vector3();
  5303. const _position$3 = /*@__PURE__*/ new Vector3();
  5304. const _scale$2 = /*@__PURE__*/ new Vector3();
  5305. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  5306. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  5307. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5308. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  5309. const _addedEvent = { type: 'added' };
  5310. const _removedEvent = { type: 'removed' };
  5311. class Object3D extends EventDispatcher {
  5312. constructor() {
  5313. super();
  5314. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  5315. this.uuid = generateUUID();
  5316. this.name = '';
  5317. this.type = 'Object3D';
  5318. this.parent = null;
  5319. this.children = [];
  5320. this.up = Object3D.DefaultUp.clone();
  5321. const position = new Vector3();
  5322. const rotation = new Euler();
  5323. const quaternion = new Quaternion();
  5324. const scale = new Vector3( 1, 1, 1 );
  5325. function onRotationChange() {
  5326. quaternion.setFromEuler( rotation, false );
  5327. }
  5328. function onQuaternionChange() {
  5329. rotation.setFromQuaternion( quaternion, undefined, false );
  5330. }
  5331. rotation._onChange( onRotationChange );
  5332. quaternion._onChange( onQuaternionChange );
  5333. Object.defineProperties( this, {
  5334. position: {
  5335. configurable: true,
  5336. enumerable: true,
  5337. value: position
  5338. },
  5339. rotation: {
  5340. configurable: true,
  5341. enumerable: true,
  5342. value: rotation
  5343. },
  5344. quaternion: {
  5345. configurable: true,
  5346. enumerable: true,
  5347. value: quaternion
  5348. },
  5349. scale: {
  5350. configurable: true,
  5351. enumerable: true,
  5352. value: scale
  5353. },
  5354. modelViewMatrix: {
  5355. value: new Matrix4()
  5356. },
  5357. normalMatrix: {
  5358. value: new Matrix3()
  5359. }
  5360. } );
  5361. this.matrix = new Matrix4();
  5362. this.matrixWorld = new Matrix4();
  5363. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5364. this.matrixWorldNeedsUpdate = false;
  5365. this.layers = new Layers();
  5366. this.visible = true;
  5367. this.castShadow = false;
  5368. this.receiveShadow = false;
  5369. this.frustumCulled = true;
  5370. this.renderOrder = 0;
  5371. this.animations = [];
  5372. this.userData = {};
  5373. }
  5374. onBeforeRender() {}
  5375. onAfterRender() {}
  5376. applyMatrix4( matrix ) {
  5377. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5378. this.matrix.premultiply( matrix );
  5379. this.matrix.decompose( this.position, this.quaternion, this.scale );
  5380. }
  5381. applyQuaternion( q ) {
  5382. this.quaternion.premultiply( q );
  5383. return this;
  5384. }
  5385. setRotationFromAxisAngle( axis, angle ) {
  5386. // assumes axis is normalized
  5387. this.quaternion.setFromAxisAngle( axis, angle );
  5388. }
  5389. setRotationFromEuler( euler ) {
  5390. this.quaternion.setFromEuler( euler, true );
  5391. }
  5392. setRotationFromMatrix( m ) {
  5393. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5394. this.quaternion.setFromRotationMatrix( m );
  5395. }
  5396. setRotationFromQuaternion( q ) {
  5397. // assumes q is normalized
  5398. this.quaternion.copy( q );
  5399. }
  5400. rotateOnAxis( axis, angle ) {
  5401. // rotate object on axis in object space
  5402. // axis is assumed to be normalized
  5403. _q1.setFromAxisAngle( axis, angle );
  5404. this.quaternion.multiply( _q1 );
  5405. return this;
  5406. }
  5407. rotateOnWorldAxis( axis, angle ) {
  5408. // rotate object on axis in world space
  5409. // axis is assumed to be normalized
  5410. // method assumes no rotated parent
  5411. _q1.setFromAxisAngle( axis, angle );
  5412. this.quaternion.premultiply( _q1 );
  5413. return this;
  5414. }
  5415. rotateX( angle ) {
  5416. return this.rotateOnAxis( _xAxis, angle );
  5417. }
  5418. rotateY( angle ) {
  5419. return this.rotateOnAxis( _yAxis, angle );
  5420. }
  5421. rotateZ( angle ) {
  5422. return this.rotateOnAxis( _zAxis, angle );
  5423. }
  5424. translateOnAxis( axis, distance ) {
  5425. // translate object by distance along axis in object space
  5426. // axis is assumed to be normalized
  5427. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  5428. this.position.add( _v1$4.multiplyScalar( distance ) );
  5429. return this;
  5430. }
  5431. translateX( distance ) {
  5432. return this.translateOnAxis( _xAxis, distance );
  5433. }
  5434. translateY( distance ) {
  5435. return this.translateOnAxis( _yAxis, distance );
  5436. }
  5437. translateZ( distance ) {
  5438. return this.translateOnAxis( _zAxis, distance );
  5439. }
  5440. localToWorld( vector ) {
  5441. return vector.applyMatrix4( this.matrixWorld );
  5442. }
  5443. worldToLocal( vector ) {
  5444. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  5445. }
  5446. lookAt( x, y, z ) {
  5447. // This method does not support objects having non-uniformly-scaled parent(s)
  5448. if ( x.isVector3 ) {
  5449. _target.copy( x );
  5450. } else {
  5451. _target.set( x, y, z );
  5452. }
  5453. const parent = this.parent;
  5454. this.updateWorldMatrix( true, false );
  5455. _position$3.setFromMatrixPosition( this.matrixWorld );
  5456. if ( this.isCamera || this.isLight ) {
  5457. _m1$1.lookAt( _position$3, _target, this.up );
  5458. } else {
  5459. _m1$1.lookAt( _target, _position$3, this.up );
  5460. }
  5461. this.quaternion.setFromRotationMatrix( _m1$1 );
  5462. if ( parent ) {
  5463. _m1$1.extractRotation( parent.matrixWorld );
  5464. _q1.setFromRotationMatrix( _m1$1 );
  5465. this.quaternion.premultiply( _q1.invert() );
  5466. }
  5467. }
  5468. add( object ) {
  5469. if ( arguments.length > 1 ) {
  5470. for ( let i = 0; i < arguments.length; i ++ ) {
  5471. this.add( arguments[ i ] );
  5472. }
  5473. return this;
  5474. }
  5475. if ( object === this ) {
  5476. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  5477. return this;
  5478. }
  5479. if ( object && object.isObject3D ) {
  5480. if ( object.parent !== null ) {
  5481. object.parent.remove( object );
  5482. }
  5483. object.parent = this;
  5484. this.children.push( object );
  5485. object.dispatchEvent( _addedEvent );
  5486. } else {
  5487. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  5488. }
  5489. return this;
  5490. }
  5491. remove( object ) {
  5492. if ( arguments.length > 1 ) {
  5493. for ( let i = 0; i < arguments.length; i ++ ) {
  5494. this.remove( arguments[ i ] );
  5495. }
  5496. return this;
  5497. }
  5498. const index = this.children.indexOf( object );
  5499. if ( index !== - 1 ) {
  5500. object.parent = null;
  5501. this.children.splice( index, 1 );
  5502. object.dispatchEvent( _removedEvent );
  5503. }
  5504. return this;
  5505. }
  5506. removeFromParent() {
  5507. const parent = this.parent;
  5508. if ( parent !== null ) {
  5509. parent.remove( this );
  5510. }
  5511. return this;
  5512. }
  5513. clear() {
  5514. for ( let i = 0; i < this.children.length; i ++ ) {
  5515. const object = this.children[ i ];
  5516. object.parent = null;
  5517. object.dispatchEvent( _removedEvent );
  5518. }
  5519. this.children.length = 0;
  5520. return this;
  5521. }
  5522. attach( object ) {
  5523. // adds object as a child of this, while maintaining the object's world transform
  5524. this.updateWorldMatrix( true, false );
  5525. _m1$1.copy( this.matrixWorld ).invert();
  5526. if ( object.parent !== null ) {
  5527. object.parent.updateWorldMatrix( true, false );
  5528. _m1$1.multiply( object.parent.matrixWorld );
  5529. }
  5530. object.applyMatrix4( _m1$1 );
  5531. this.add( object );
  5532. object.updateWorldMatrix( false, true );
  5533. return this;
  5534. }
  5535. getObjectById( id ) {
  5536. return this.getObjectByProperty( 'id', id );
  5537. }
  5538. getObjectByName( name ) {
  5539. return this.getObjectByProperty( 'name', name );
  5540. }
  5541. getObjectByProperty( name, value ) {
  5542. if ( this[ name ] === value ) return this;
  5543. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  5544. const child = this.children[ i ];
  5545. const object = child.getObjectByProperty( name, value );
  5546. if ( object !== undefined ) {
  5547. return object;
  5548. }
  5549. }
  5550. return undefined;
  5551. }
  5552. getWorldPosition( target ) {
  5553. this.updateWorldMatrix( true, false );
  5554. return target.setFromMatrixPosition( this.matrixWorld );
  5555. }
  5556. getWorldQuaternion( target ) {
  5557. this.updateWorldMatrix( true, false );
  5558. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  5559. return target;
  5560. }
  5561. getWorldScale( target ) {
  5562. this.updateWorldMatrix( true, false );
  5563. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  5564. return target;
  5565. }
  5566. getWorldDirection( target ) {
  5567. this.updateWorldMatrix( true, false );
  5568. const e = this.matrixWorld.elements;
  5569. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  5570. }
  5571. raycast() {}
  5572. traverse( callback ) {
  5573. callback( this );
  5574. const children = this.children;
  5575. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5576. children[ i ].traverse( callback );
  5577. }
  5578. }
  5579. traverseVisible( callback ) {
  5580. if ( this.visible === false ) return;
  5581. callback( this );
  5582. const children = this.children;
  5583. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5584. children[ i ].traverseVisible( callback );
  5585. }
  5586. }
  5587. traverseAncestors( callback ) {
  5588. const parent = this.parent;
  5589. if ( parent !== null ) {
  5590. callback( parent );
  5591. parent.traverseAncestors( callback );
  5592. }
  5593. }
  5594. updateMatrix() {
  5595. this.matrix.compose( this.position, this.quaternion, this.scale );
  5596. this.matrixWorldNeedsUpdate = true;
  5597. }
  5598. updateMatrixWorld( force ) {
  5599. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5600. if ( this.matrixWorldNeedsUpdate || force ) {
  5601. if ( this.parent === null ) {
  5602. this.matrixWorld.copy( this.matrix );
  5603. } else {
  5604. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5605. }
  5606. this.matrixWorldNeedsUpdate = false;
  5607. force = true;
  5608. }
  5609. // update children
  5610. const children = this.children;
  5611. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5612. children[ i ].updateMatrixWorld( force );
  5613. }
  5614. }
  5615. updateWorldMatrix( updateParents, updateChildren ) {
  5616. const parent = this.parent;
  5617. if ( updateParents === true && parent !== null ) {
  5618. parent.updateWorldMatrix( true, false );
  5619. }
  5620. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5621. if ( this.parent === null ) {
  5622. this.matrixWorld.copy( this.matrix );
  5623. } else {
  5624. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5625. }
  5626. // update children
  5627. if ( updateChildren === true ) {
  5628. const children = this.children;
  5629. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5630. children[ i ].updateWorldMatrix( false, true );
  5631. }
  5632. }
  5633. }
  5634. toJSON( meta ) {
  5635. // meta is a string when called from JSON.stringify
  5636. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5637. const output = {};
  5638. // meta is a hash used to collect geometries, materials.
  5639. // not providing it implies that this is the root object
  5640. // being serialized.
  5641. if ( isRootObject ) {
  5642. // initialize meta obj
  5643. meta = {
  5644. geometries: {},
  5645. materials: {},
  5646. textures: {},
  5647. images: {},
  5648. shapes: {},
  5649. skeletons: {},
  5650. animations: {}
  5651. };
  5652. output.metadata = {
  5653. version: 4.5,
  5654. type: 'Object',
  5655. generator: 'Object3D.toJSON'
  5656. };
  5657. }
  5658. // standard Object3D serialization
  5659. const object = {};
  5660. object.uuid = this.uuid;
  5661. object.type = this.type;
  5662. if ( this.name !== '' ) object.name = this.name;
  5663. if ( this.castShadow === true ) object.castShadow = true;
  5664. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5665. if ( this.visible === false ) object.visible = false;
  5666. if ( this.frustumCulled === false ) object.frustumCulled = false;
  5667. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  5668. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5669. object.layers = this.layers.mask;
  5670. object.matrix = this.matrix.toArray();
  5671. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  5672. // object specific properties
  5673. if ( this.isInstancedMesh ) {
  5674. object.type = 'InstancedMesh';
  5675. object.count = this.count;
  5676. object.instanceMatrix = this.instanceMatrix.toJSON();
  5677. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  5678. }
  5679. //
  5680. function serialize( library, element ) {
  5681. if ( library[ element.uuid ] === undefined ) {
  5682. library[ element.uuid ] = element.toJSON( meta );
  5683. }
  5684. return element.uuid;
  5685. }
  5686. if ( this.isScene ) {
  5687. if ( this.background ) {
  5688. if ( this.background.isColor ) {
  5689. object.background = this.background.toJSON();
  5690. } else if ( this.background.isTexture ) {
  5691. object.background = this.background.toJSON( meta ).uuid;
  5692. }
  5693. }
  5694. if ( this.environment && this.environment.isTexture ) {
  5695. object.environment = this.environment.toJSON( meta ).uuid;
  5696. }
  5697. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  5698. object.geometry = serialize( meta.geometries, this.geometry );
  5699. const parameters = this.geometry.parameters;
  5700. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  5701. const shapes = parameters.shapes;
  5702. if ( Array.isArray( shapes ) ) {
  5703. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  5704. const shape = shapes[ i ];
  5705. serialize( meta.shapes, shape );
  5706. }
  5707. } else {
  5708. serialize( meta.shapes, shapes );
  5709. }
  5710. }
  5711. }
  5712. if ( this.isSkinnedMesh ) {
  5713. object.bindMode = this.bindMode;
  5714. object.bindMatrix = this.bindMatrix.toArray();
  5715. if ( this.skeleton !== undefined ) {
  5716. serialize( meta.skeletons, this.skeleton );
  5717. object.skeleton = this.skeleton.uuid;
  5718. }
  5719. }
  5720. if ( this.material !== undefined ) {
  5721. if ( Array.isArray( this.material ) ) {
  5722. const uuids = [];
  5723. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  5724. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  5725. }
  5726. object.material = uuids;
  5727. } else {
  5728. object.material = serialize( meta.materials, this.material );
  5729. }
  5730. }
  5731. //
  5732. if ( this.children.length > 0 ) {
  5733. object.children = [];
  5734. for ( let i = 0; i < this.children.length; i ++ ) {
  5735. object.children.push( this.children[ i ].toJSON( meta ).object );
  5736. }
  5737. }
  5738. //
  5739. if ( this.animations.length > 0 ) {
  5740. object.animations = [];
  5741. for ( let i = 0; i < this.animations.length; i ++ ) {
  5742. const animation = this.animations[ i ];
  5743. object.animations.push( serialize( meta.animations, animation ) );
  5744. }
  5745. }
  5746. if ( isRootObject ) {
  5747. const geometries = extractFromCache( meta.geometries );
  5748. const materials = extractFromCache( meta.materials );
  5749. const textures = extractFromCache( meta.textures );
  5750. const images = extractFromCache( meta.images );
  5751. const shapes = extractFromCache( meta.shapes );
  5752. const skeletons = extractFromCache( meta.skeletons );
  5753. const animations = extractFromCache( meta.animations );
  5754. if ( geometries.length > 0 ) output.geometries = geometries;
  5755. if ( materials.length > 0 ) output.materials = materials;
  5756. if ( textures.length > 0 ) output.textures = textures;
  5757. if ( images.length > 0 ) output.images = images;
  5758. if ( shapes.length > 0 ) output.shapes = shapes;
  5759. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  5760. if ( animations.length > 0 ) output.animations = animations;
  5761. }
  5762. output.object = object;
  5763. return output;
  5764. // extract data from the cache hash
  5765. // remove metadata on each item
  5766. // and return as array
  5767. function extractFromCache( cache ) {
  5768. const values = [];
  5769. for ( const key in cache ) {
  5770. const data = cache[ key ];
  5771. delete data.metadata;
  5772. values.push( data );
  5773. }
  5774. return values;
  5775. }
  5776. }
  5777. clone( recursive ) {
  5778. return new this.constructor().copy( this, recursive );
  5779. }
  5780. copy( source, recursive = true ) {
  5781. this.name = source.name;
  5782. this.up.copy( source.up );
  5783. this.position.copy( source.position );
  5784. this.rotation.order = source.rotation.order;
  5785. this.quaternion.copy( source.quaternion );
  5786. this.scale.copy( source.scale );
  5787. this.matrix.copy( source.matrix );
  5788. this.matrixWorld.copy( source.matrixWorld );
  5789. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5790. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5791. this.layers.mask = source.layers.mask;
  5792. this.visible = source.visible;
  5793. this.castShadow = source.castShadow;
  5794. this.receiveShadow = source.receiveShadow;
  5795. this.frustumCulled = source.frustumCulled;
  5796. this.renderOrder = source.renderOrder;
  5797. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5798. if ( recursive === true ) {
  5799. for ( let i = 0; i < source.children.length; i ++ ) {
  5800. const child = source.children[ i ];
  5801. this.add( child.clone() );
  5802. }
  5803. }
  5804. return this;
  5805. }
  5806. }
  5807. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  5808. Object3D.DefaultMatrixAutoUpdate = true;
  5809. Object3D.prototype.isObject3D = true;
  5810. const _v0$1 = /*@__PURE__*/ new Vector3();
  5811. const _v1$3 = /*@__PURE__*/ new Vector3();
  5812. const _v2$2 = /*@__PURE__*/ new Vector3();
  5813. const _v3$1 = /*@__PURE__*/ new Vector3();
  5814. const _vab = /*@__PURE__*/ new Vector3();
  5815. const _vac = /*@__PURE__*/ new Vector3();
  5816. const _vbc = /*@__PURE__*/ new Vector3();
  5817. const _vap = /*@__PURE__*/ new Vector3();
  5818. const _vbp = /*@__PURE__*/ new Vector3();
  5819. const _vcp = /*@__PURE__*/ new Vector3();
  5820. class Triangle {
  5821. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5822. this.a = a;
  5823. this.b = b;
  5824. this.c = c;
  5825. }
  5826. static getNormal( a, b, c, target ) {
  5827. target.subVectors( c, b );
  5828. _v0$1.subVectors( a, b );
  5829. target.cross( _v0$1 );
  5830. const targetLengthSq = target.lengthSq();
  5831. if ( targetLengthSq > 0 ) {
  5832. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5833. }
  5834. return target.set( 0, 0, 0 );
  5835. }
  5836. // static/instance method to calculate barycentric coordinates
  5837. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5838. static getBarycoord( point, a, b, c, target ) {
  5839. _v0$1.subVectors( c, a );
  5840. _v1$3.subVectors( b, a );
  5841. _v2$2.subVectors( point, a );
  5842. const dot00 = _v0$1.dot( _v0$1 );
  5843. const dot01 = _v0$1.dot( _v1$3 );
  5844. const dot02 = _v0$1.dot( _v2$2 );
  5845. const dot11 = _v1$3.dot( _v1$3 );
  5846. const dot12 = _v1$3.dot( _v2$2 );
  5847. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5848. // collinear or singular triangle
  5849. if ( denom === 0 ) {
  5850. // arbitrary location outside of triangle?
  5851. // not sure if this is the best idea, maybe should be returning undefined
  5852. return target.set( - 2, - 1, - 1 );
  5853. }
  5854. const invDenom = 1 / denom;
  5855. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5856. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5857. // barycentric coordinates must always sum to 1
  5858. return target.set( 1 - u - v, v, u );
  5859. }
  5860. static containsPoint( point, a, b, c ) {
  5861. this.getBarycoord( point, a, b, c, _v3$1 );
  5862. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5863. }
  5864. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5865. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5866. target.set( 0, 0 );
  5867. target.addScaledVector( uv1, _v3$1.x );
  5868. target.addScaledVector( uv2, _v3$1.y );
  5869. target.addScaledVector( uv3, _v3$1.z );
  5870. return target;
  5871. }
  5872. static isFrontFacing( a, b, c, direction ) {
  5873. _v0$1.subVectors( c, b );
  5874. _v1$3.subVectors( a, b );
  5875. // strictly front facing
  5876. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5877. }
  5878. set( a, b, c ) {
  5879. this.a.copy( a );
  5880. this.b.copy( b );
  5881. this.c.copy( c );
  5882. return this;
  5883. }
  5884. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5885. this.a.copy( points[ i0 ] );
  5886. this.b.copy( points[ i1 ] );
  5887. this.c.copy( points[ i2 ] );
  5888. return this;
  5889. }
  5890. clone() {
  5891. return new this.constructor().copy( this );
  5892. }
  5893. copy( triangle ) {
  5894. this.a.copy( triangle.a );
  5895. this.b.copy( triangle.b );
  5896. this.c.copy( triangle.c );
  5897. return this;
  5898. }
  5899. getArea() {
  5900. _v0$1.subVectors( this.c, this.b );
  5901. _v1$3.subVectors( this.a, this.b );
  5902. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5903. }
  5904. getMidpoint( target ) {
  5905. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5906. }
  5907. getNormal( target ) {
  5908. return Triangle.getNormal( this.a, this.b, this.c, target );
  5909. }
  5910. getPlane( target ) {
  5911. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5912. }
  5913. getBarycoord( point, target ) {
  5914. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5915. }
  5916. getUV( point, uv1, uv2, uv3, target ) {
  5917. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5918. }
  5919. containsPoint( point ) {
  5920. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5921. }
  5922. isFrontFacing( direction ) {
  5923. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5924. }
  5925. intersectsBox( box ) {
  5926. return box.intersectsTriangle( this );
  5927. }
  5928. closestPointToPoint( p, target ) {
  5929. const a = this.a, b = this.b, c = this.c;
  5930. let v, w;
  5931. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5932. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5933. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5934. // basically, we're distinguishing which of the voronoi regions of the triangle
  5935. // the point lies in with the minimum amount of redundant computation.
  5936. _vab.subVectors( b, a );
  5937. _vac.subVectors( c, a );
  5938. _vap.subVectors( p, a );
  5939. const d1 = _vab.dot( _vap );
  5940. const d2 = _vac.dot( _vap );
  5941. if ( d1 <= 0 && d2 <= 0 ) {
  5942. // vertex region of A; barycentric coords (1, 0, 0)
  5943. return target.copy( a );
  5944. }
  5945. _vbp.subVectors( p, b );
  5946. const d3 = _vab.dot( _vbp );
  5947. const d4 = _vac.dot( _vbp );
  5948. if ( d3 >= 0 && d4 <= d3 ) {
  5949. // vertex region of B; barycentric coords (0, 1, 0)
  5950. return target.copy( b );
  5951. }
  5952. const vc = d1 * d4 - d3 * d2;
  5953. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5954. v = d1 / ( d1 - d3 );
  5955. // edge region of AB; barycentric coords (1-v, v, 0)
  5956. return target.copy( a ).addScaledVector( _vab, v );
  5957. }
  5958. _vcp.subVectors( p, c );
  5959. const d5 = _vab.dot( _vcp );
  5960. const d6 = _vac.dot( _vcp );
  5961. if ( d6 >= 0 && d5 <= d6 ) {
  5962. // vertex region of C; barycentric coords (0, 0, 1)
  5963. return target.copy( c );
  5964. }
  5965. const vb = d5 * d2 - d1 * d6;
  5966. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5967. w = d2 / ( d2 - d6 );
  5968. // edge region of AC; barycentric coords (1-w, 0, w)
  5969. return target.copy( a ).addScaledVector( _vac, w );
  5970. }
  5971. const va = d3 * d6 - d5 * d4;
  5972. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5973. _vbc.subVectors( c, b );
  5974. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5975. // edge region of BC; barycentric coords (0, 1-w, w)
  5976. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5977. }
  5978. // face region
  5979. const denom = 1 / ( va + vb + vc );
  5980. // u = va * denom
  5981. v = vb * denom;
  5982. w = vc * denom;
  5983. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5984. }
  5985. equals( triangle ) {
  5986. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5987. }
  5988. }
  5989. let materialId = 0;
  5990. class Material extends EventDispatcher {
  5991. constructor() {
  5992. super();
  5993. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5994. this.uuid = generateUUID();
  5995. this.name = '';
  5996. this.type = 'Material';
  5997. this.fog = true;
  5998. this.blending = NormalBlending;
  5999. this.side = FrontSide;
  6000. this.vertexColors = false;
  6001. this.opacity = 1;
  6002. this.format = RGBAFormat;
  6003. this.transparent = false;
  6004. this.blendSrc = SrcAlphaFactor;
  6005. this.blendDst = OneMinusSrcAlphaFactor;
  6006. this.blendEquation = AddEquation;
  6007. this.blendSrcAlpha = null;
  6008. this.blendDstAlpha = null;
  6009. this.blendEquationAlpha = null;
  6010. this.depthFunc = LessEqualDepth;
  6011. this.depthTest = true;
  6012. this.depthWrite = true;
  6013. this.stencilWriteMask = 0xff;
  6014. this.stencilFunc = AlwaysStencilFunc;
  6015. this.stencilRef = 0;
  6016. this.stencilFuncMask = 0xff;
  6017. this.stencilFail = KeepStencilOp;
  6018. this.stencilZFail = KeepStencilOp;
  6019. this.stencilZPass = KeepStencilOp;
  6020. this.stencilWrite = false;
  6021. this.clippingPlanes = null;
  6022. this.clipIntersection = false;
  6023. this.clipShadows = false;
  6024. this.shadowSide = null;
  6025. this.colorWrite = true;
  6026. this.precision = null; // override the renderer's default precision for this material
  6027. this.polygonOffset = false;
  6028. this.polygonOffsetFactor = 0;
  6029. this.polygonOffsetUnits = 0;
  6030. this.dithering = false;
  6031. this.alphaToCoverage = false;
  6032. this.premultipliedAlpha = false;
  6033. this.visible = true;
  6034. this.toneMapped = true;
  6035. this.userData = {};
  6036. this.version = 0;
  6037. this._alphaTest = 0;
  6038. }
  6039. get alphaTest() {
  6040. return this._alphaTest;
  6041. }
  6042. set alphaTest( value ) {
  6043. if ( this._alphaTest > 0 !== value > 0 ) {
  6044. this.version ++;
  6045. }
  6046. this._alphaTest = value;
  6047. }
  6048. onBuild( /* shaderobject, renderer */ ) {}
  6049. onBeforeCompile( /* shaderobject, renderer */ ) {}
  6050. customProgramCacheKey() {
  6051. return this.onBeforeCompile.toString();
  6052. }
  6053. setValues( values ) {
  6054. if ( values === undefined ) return;
  6055. for ( const key in values ) {
  6056. const newValue = values[ key ];
  6057. if ( newValue === undefined ) {
  6058. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6059. continue;
  6060. }
  6061. // for backward compatability if shading is set in the constructor
  6062. if ( key === 'shading' ) {
  6063. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  6064. this.flatShading = ( newValue === FlatShading ) ? true : false;
  6065. continue;
  6066. }
  6067. const currentValue = this[ key ];
  6068. if ( currentValue === undefined ) {
  6069. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  6070. continue;
  6071. }
  6072. if ( currentValue && currentValue.isColor ) {
  6073. currentValue.set( newValue );
  6074. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  6075. currentValue.copy( newValue );
  6076. } else {
  6077. this[ key ] = newValue;
  6078. }
  6079. }
  6080. }
  6081. toJSON( meta ) {
  6082. const isRoot = ( meta === undefined || typeof meta === 'string' );
  6083. if ( isRoot ) {
  6084. meta = {
  6085. textures: {},
  6086. images: {}
  6087. };
  6088. }
  6089. const data = {
  6090. metadata: {
  6091. version: 4.5,
  6092. type: 'Material',
  6093. generator: 'Material.toJSON'
  6094. }
  6095. };
  6096. // standard Material serialization
  6097. data.uuid = this.uuid;
  6098. data.type = this.type;
  6099. if ( this.name !== '' ) data.name = this.name;
  6100. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  6101. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  6102. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  6103. if ( this.sheenTint && this.sheenTint.isColor ) data.sheenTint = this.sheenTint.getHex();
  6104. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  6105. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  6106. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  6107. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  6108. if ( this.specularTint && this.specularTint.isColor ) data.specularTint = this.specularTint.getHex();
  6109. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  6110. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  6111. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  6112. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  6113. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  6114. }
  6115. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  6116. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  6117. }
  6118. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  6119. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  6120. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  6121. }
  6122. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  6123. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  6124. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  6125. if ( this.lightMap && this.lightMap.isTexture ) {
  6126. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  6127. data.lightMapIntensity = this.lightMapIntensity;
  6128. }
  6129. if ( this.aoMap && this.aoMap.isTexture ) {
  6130. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  6131. data.aoMapIntensity = this.aoMapIntensity;
  6132. }
  6133. if ( this.bumpMap && this.bumpMap.isTexture ) {
  6134. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  6135. data.bumpScale = this.bumpScale;
  6136. }
  6137. if ( this.normalMap && this.normalMap.isTexture ) {
  6138. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  6139. data.normalMapType = this.normalMapType;
  6140. data.normalScale = this.normalScale.toArray();
  6141. }
  6142. if ( this.displacementMap && this.displacementMap.isTexture ) {
  6143. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  6144. data.displacementScale = this.displacementScale;
  6145. data.displacementBias = this.displacementBias;
  6146. }
  6147. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  6148. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  6149. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  6150. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  6151. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  6152. if ( this.specularTintMap && this.specularTintMap.isTexture ) data.specularTintMap = this.specularTintMap.toJSON( meta ).uuid;
  6153. if ( this.envMap && this.envMap.isTexture ) {
  6154. data.envMap = this.envMap.toJSON( meta ).uuid;
  6155. if ( this.combine !== undefined ) data.combine = this.combine;
  6156. }
  6157. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  6158. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  6159. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  6160. if ( this.gradientMap && this.gradientMap.isTexture ) {
  6161. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  6162. }
  6163. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  6164. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  6165. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  6166. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  6167. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  6168. if ( this.attenuationTint !== undefined ) data.attenuationTint = this.attenuationTint.getHex();
  6169. if ( this.size !== undefined ) data.size = this.size;
  6170. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  6171. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  6172. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  6173. if ( this.side !== FrontSide ) data.side = this.side;
  6174. if ( this.vertexColors ) data.vertexColors = true;
  6175. if ( this.opacity < 1 ) data.opacity = this.opacity;
  6176. if ( this.format !== RGBAFormat ) data.format = this.format;
  6177. if ( this.transparent === true ) data.transparent = this.transparent;
  6178. data.depthFunc = this.depthFunc;
  6179. data.depthTest = this.depthTest;
  6180. data.depthWrite = this.depthWrite;
  6181. data.colorWrite = this.colorWrite;
  6182. data.stencilWrite = this.stencilWrite;
  6183. data.stencilWriteMask = this.stencilWriteMask;
  6184. data.stencilFunc = this.stencilFunc;
  6185. data.stencilRef = this.stencilRef;
  6186. data.stencilFuncMask = this.stencilFuncMask;
  6187. data.stencilFail = this.stencilFail;
  6188. data.stencilZFail = this.stencilZFail;
  6189. data.stencilZPass = this.stencilZPass;
  6190. // rotation (SpriteMaterial)
  6191. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  6192. if ( this.polygonOffset === true ) data.polygonOffset = true;
  6193. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  6194. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  6195. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  6196. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  6197. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  6198. if ( this.scale !== undefined ) data.scale = this.scale;
  6199. if ( this.dithering === true ) data.dithering = true;
  6200. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  6201. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  6202. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  6203. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  6204. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  6205. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  6206. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  6207. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  6208. if ( this.visible === false ) data.visible = false;
  6209. if ( this.toneMapped === false ) data.toneMapped = false;
  6210. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  6211. // TODO: Copied from Object3D.toJSON
  6212. function extractFromCache( cache ) {
  6213. const values = [];
  6214. for ( const key in cache ) {
  6215. const data = cache[ key ];
  6216. delete data.metadata;
  6217. values.push( data );
  6218. }
  6219. return values;
  6220. }
  6221. if ( isRoot ) {
  6222. const textures = extractFromCache( meta.textures );
  6223. const images = extractFromCache( meta.images );
  6224. if ( textures.length > 0 ) data.textures = textures;
  6225. if ( images.length > 0 ) data.images = images;
  6226. }
  6227. return data;
  6228. }
  6229. clone() {
  6230. return new this.constructor().copy( this );
  6231. }
  6232. copy( source ) {
  6233. this.name = source.name;
  6234. this.fog = source.fog;
  6235. this.blending = source.blending;
  6236. this.side = source.side;
  6237. this.vertexColors = source.vertexColors;
  6238. this.opacity = source.opacity;
  6239. this.format = source.format;
  6240. this.transparent = source.transparent;
  6241. this.blendSrc = source.blendSrc;
  6242. this.blendDst = source.blendDst;
  6243. this.blendEquation = source.blendEquation;
  6244. this.blendSrcAlpha = source.blendSrcAlpha;
  6245. this.blendDstAlpha = source.blendDstAlpha;
  6246. this.blendEquationAlpha = source.blendEquationAlpha;
  6247. this.depthFunc = source.depthFunc;
  6248. this.depthTest = source.depthTest;
  6249. this.depthWrite = source.depthWrite;
  6250. this.stencilWriteMask = source.stencilWriteMask;
  6251. this.stencilFunc = source.stencilFunc;
  6252. this.stencilRef = source.stencilRef;
  6253. this.stencilFuncMask = source.stencilFuncMask;
  6254. this.stencilFail = source.stencilFail;
  6255. this.stencilZFail = source.stencilZFail;
  6256. this.stencilZPass = source.stencilZPass;
  6257. this.stencilWrite = source.stencilWrite;
  6258. const srcPlanes = source.clippingPlanes;
  6259. let dstPlanes = null;
  6260. if ( srcPlanes !== null ) {
  6261. const n = srcPlanes.length;
  6262. dstPlanes = new Array( n );
  6263. for ( let i = 0; i !== n; ++ i ) {
  6264. dstPlanes[ i ] = srcPlanes[ i ].clone();
  6265. }
  6266. }
  6267. this.clippingPlanes = dstPlanes;
  6268. this.clipIntersection = source.clipIntersection;
  6269. this.clipShadows = source.clipShadows;
  6270. this.shadowSide = source.shadowSide;
  6271. this.colorWrite = source.colorWrite;
  6272. this.precision = source.precision;
  6273. this.polygonOffset = source.polygonOffset;
  6274. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6275. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6276. this.dithering = source.dithering;
  6277. this.alphaTest = source.alphaTest;
  6278. this.alphaToCoverage = source.alphaToCoverage;
  6279. this.premultipliedAlpha = source.premultipliedAlpha;
  6280. this.visible = source.visible;
  6281. this.toneMapped = source.toneMapped;
  6282. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6283. return this;
  6284. }
  6285. dispose() {
  6286. this.dispatchEvent( { type: 'dispose' } );
  6287. }
  6288. set needsUpdate( value ) {
  6289. if ( value === true ) this.version ++;
  6290. }
  6291. }
  6292. Material.prototype.isMaterial = true;
  6293. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  6294. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  6295. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  6296. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  6297. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  6298. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  6299. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  6300. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  6301. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  6302. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  6303. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  6304. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  6305. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  6306. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  6307. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  6308. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  6309. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  6310. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  6311. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  6312. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  6313. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  6314. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  6315. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  6316. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  6317. const _hslA = { h: 0, s: 0, l: 0 };
  6318. const _hslB = { h: 0, s: 0, l: 0 };
  6319. function hue2rgb( p, q, t ) {
  6320. if ( t < 0 ) t += 1;
  6321. if ( t > 1 ) t -= 1;
  6322. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  6323. if ( t < 1 / 2 ) return q;
  6324. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  6325. return p;
  6326. }
  6327. function SRGBToLinear( c ) {
  6328. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  6329. }
  6330. function LinearToSRGB( c ) {
  6331. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  6332. }
  6333. class Color {
  6334. constructor( r, g, b ) {
  6335. if ( g === undefined && b === undefined ) {
  6336. // r is THREE.Color, hex or string
  6337. return this.set( r );
  6338. }
  6339. return this.setRGB( r, g, b );
  6340. }
  6341. set( value ) {
  6342. if ( value && value.isColor ) {
  6343. this.copy( value );
  6344. } else if ( typeof value === 'number' ) {
  6345. this.setHex( value );
  6346. } else if ( typeof value === 'string' ) {
  6347. this.setStyle( value );
  6348. }
  6349. return this;
  6350. }
  6351. setScalar( scalar ) {
  6352. this.r = scalar;
  6353. this.g = scalar;
  6354. this.b = scalar;
  6355. return this;
  6356. }
  6357. setHex( hex ) {
  6358. hex = Math.floor( hex );
  6359. this.r = ( hex >> 16 & 255 ) / 255;
  6360. this.g = ( hex >> 8 & 255 ) / 255;
  6361. this.b = ( hex & 255 ) / 255;
  6362. return this;
  6363. }
  6364. setRGB( r, g, b ) {
  6365. this.r = r;
  6366. this.g = g;
  6367. this.b = b;
  6368. return this;
  6369. }
  6370. setHSL( h, s, l ) {
  6371. // h,s,l ranges are in 0.0 - 1.0
  6372. h = euclideanModulo( h, 1 );
  6373. s = clamp( s, 0, 1 );
  6374. l = clamp( l, 0, 1 );
  6375. if ( s === 0 ) {
  6376. this.r = this.g = this.b = l;
  6377. } else {
  6378. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  6379. const q = ( 2 * l ) - p;
  6380. this.r = hue2rgb( q, p, h + 1 / 3 );
  6381. this.g = hue2rgb( q, p, h );
  6382. this.b = hue2rgb( q, p, h - 1 / 3 );
  6383. }
  6384. return this;
  6385. }
  6386. setStyle( style ) {
  6387. function handleAlpha( string ) {
  6388. if ( string === undefined ) return;
  6389. if ( parseFloat( string ) < 1 ) {
  6390. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  6391. }
  6392. }
  6393. let m;
  6394. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  6395. // rgb / hsl
  6396. let color;
  6397. const name = m[ 1 ];
  6398. const components = m[ 2 ];
  6399. switch ( name ) {
  6400. case 'rgb':
  6401. case 'rgba':
  6402. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6403. // rgb(255,0,0) rgba(255,0,0,0.5)
  6404. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  6405. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  6406. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  6407. handleAlpha( color[ 4 ] );
  6408. return this;
  6409. }
  6410. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6411. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6412. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  6413. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  6414. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  6415. handleAlpha( color[ 4 ] );
  6416. return this;
  6417. }
  6418. break;
  6419. case 'hsl':
  6420. case 'hsla':
  6421. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6422. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6423. const h = parseFloat( color[ 1 ] ) / 360;
  6424. const s = parseInt( color[ 2 ], 10 ) / 100;
  6425. const l = parseInt( color[ 3 ], 10 ) / 100;
  6426. handleAlpha( color[ 4 ] );
  6427. return this.setHSL( h, s, l );
  6428. }
  6429. break;
  6430. }
  6431. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  6432. // hex color
  6433. const hex = m[ 1 ];
  6434. const size = hex.length;
  6435. if ( size === 3 ) {
  6436. // #ff0
  6437. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  6438. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  6439. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  6440. return this;
  6441. } else if ( size === 6 ) {
  6442. // #ff0000
  6443. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  6444. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  6445. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  6446. return this;
  6447. }
  6448. }
  6449. if ( style && style.length > 0 ) {
  6450. return this.setColorName( style );
  6451. }
  6452. return this;
  6453. }
  6454. setColorName( style ) {
  6455. // color keywords
  6456. const hex = _colorKeywords[ style.toLowerCase() ];
  6457. if ( hex !== undefined ) {
  6458. // red
  6459. this.setHex( hex );
  6460. } else {
  6461. // unknown color
  6462. console.warn( 'THREE.Color: Unknown color ' + style );
  6463. }
  6464. return this;
  6465. }
  6466. clone() {
  6467. return new this.constructor( this.r, this.g, this.b );
  6468. }
  6469. copy( color ) {
  6470. this.r = color.r;
  6471. this.g = color.g;
  6472. this.b = color.b;
  6473. return this;
  6474. }
  6475. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  6476. this.r = Math.pow( color.r, gammaFactor );
  6477. this.g = Math.pow( color.g, gammaFactor );
  6478. this.b = Math.pow( color.b, gammaFactor );
  6479. return this;
  6480. }
  6481. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  6482. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  6483. this.r = Math.pow( color.r, safeInverse );
  6484. this.g = Math.pow( color.g, safeInverse );
  6485. this.b = Math.pow( color.b, safeInverse );
  6486. return this;
  6487. }
  6488. convertGammaToLinear( gammaFactor ) {
  6489. this.copyGammaToLinear( this, gammaFactor );
  6490. return this;
  6491. }
  6492. convertLinearToGamma( gammaFactor ) {
  6493. this.copyLinearToGamma( this, gammaFactor );
  6494. return this;
  6495. }
  6496. copySRGBToLinear( color ) {
  6497. this.r = SRGBToLinear( color.r );
  6498. this.g = SRGBToLinear( color.g );
  6499. this.b = SRGBToLinear( color.b );
  6500. return this;
  6501. }
  6502. copyLinearToSRGB( color ) {
  6503. this.r = LinearToSRGB( color.r );
  6504. this.g = LinearToSRGB( color.g );
  6505. this.b = LinearToSRGB( color.b );
  6506. return this;
  6507. }
  6508. convertSRGBToLinear() {
  6509. this.copySRGBToLinear( this );
  6510. return this;
  6511. }
  6512. convertLinearToSRGB() {
  6513. this.copyLinearToSRGB( this );
  6514. return this;
  6515. }
  6516. getHex() {
  6517. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  6518. }
  6519. getHexString() {
  6520. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  6521. }
  6522. getHSL( target ) {
  6523. // h,s,l ranges are in 0.0 - 1.0
  6524. const r = this.r, g = this.g, b = this.b;
  6525. const max = Math.max( r, g, b );
  6526. const min = Math.min( r, g, b );
  6527. let hue, saturation;
  6528. const lightness = ( min + max ) / 2.0;
  6529. if ( min === max ) {
  6530. hue = 0;
  6531. saturation = 0;
  6532. } else {
  6533. const delta = max - min;
  6534. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  6535. switch ( max ) {
  6536. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  6537. case g: hue = ( b - r ) / delta + 2; break;
  6538. case b: hue = ( r - g ) / delta + 4; break;
  6539. }
  6540. hue /= 6;
  6541. }
  6542. target.h = hue;
  6543. target.s = saturation;
  6544. target.l = lightness;
  6545. return target;
  6546. }
  6547. getStyle() {
  6548. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  6549. }
  6550. offsetHSL( h, s, l ) {
  6551. this.getHSL( _hslA );
  6552. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  6553. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  6554. return this;
  6555. }
  6556. add( color ) {
  6557. this.r += color.r;
  6558. this.g += color.g;
  6559. this.b += color.b;
  6560. return this;
  6561. }
  6562. addColors( color1, color2 ) {
  6563. this.r = color1.r + color2.r;
  6564. this.g = color1.g + color2.g;
  6565. this.b = color1.b + color2.b;
  6566. return this;
  6567. }
  6568. addScalar( s ) {
  6569. this.r += s;
  6570. this.g += s;
  6571. this.b += s;
  6572. return this;
  6573. }
  6574. sub( color ) {
  6575. this.r = Math.max( 0, this.r - color.r );
  6576. this.g = Math.max( 0, this.g - color.g );
  6577. this.b = Math.max( 0, this.b - color.b );
  6578. return this;
  6579. }
  6580. multiply( color ) {
  6581. this.r *= color.r;
  6582. this.g *= color.g;
  6583. this.b *= color.b;
  6584. return this;
  6585. }
  6586. multiplyScalar( s ) {
  6587. this.r *= s;
  6588. this.g *= s;
  6589. this.b *= s;
  6590. return this;
  6591. }
  6592. lerp( color, alpha ) {
  6593. this.r += ( color.r - this.r ) * alpha;
  6594. this.g += ( color.g - this.g ) * alpha;
  6595. this.b += ( color.b - this.b ) * alpha;
  6596. return this;
  6597. }
  6598. lerpColors( color1, color2, alpha ) {
  6599. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  6600. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  6601. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  6602. return this;
  6603. }
  6604. lerpHSL( color, alpha ) {
  6605. this.getHSL( _hslA );
  6606. color.getHSL( _hslB );
  6607. const h = lerp( _hslA.h, _hslB.h, alpha );
  6608. const s = lerp( _hslA.s, _hslB.s, alpha );
  6609. const l = lerp( _hslA.l, _hslB.l, alpha );
  6610. this.setHSL( h, s, l );
  6611. return this;
  6612. }
  6613. equals( c ) {
  6614. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  6615. }
  6616. fromArray( array, offset = 0 ) {
  6617. this.r = array[ offset ];
  6618. this.g = array[ offset + 1 ];
  6619. this.b = array[ offset + 2 ];
  6620. return this;
  6621. }
  6622. toArray( array = [], offset = 0 ) {
  6623. array[ offset ] = this.r;
  6624. array[ offset + 1 ] = this.g;
  6625. array[ offset + 2 ] = this.b;
  6626. return array;
  6627. }
  6628. fromBufferAttribute( attribute, index ) {
  6629. this.r = attribute.getX( index );
  6630. this.g = attribute.getY( index );
  6631. this.b = attribute.getZ( index );
  6632. if ( attribute.normalized === true ) {
  6633. // assuming Uint8Array
  6634. this.r /= 255;
  6635. this.g /= 255;
  6636. this.b /= 255;
  6637. }
  6638. return this;
  6639. }
  6640. toJSON() {
  6641. return this.getHex();
  6642. }
  6643. }
  6644. Color.NAMES = _colorKeywords;
  6645. Color.prototype.isColor = true;
  6646. Color.prototype.r = 1;
  6647. Color.prototype.g = 1;
  6648. Color.prototype.b = 1;
  6649. /**
  6650. * parameters = {
  6651. * color: <hex>,
  6652. * opacity: <float>,
  6653. * map: new THREE.Texture( <Image> ),
  6654. *
  6655. * lightMap: new THREE.Texture( <Image> ),
  6656. * lightMapIntensity: <float>
  6657. *
  6658. * aoMap: new THREE.Texture( <Image> ),
  6659. * aoMapIntensity: <float>
  6660. *
  6661. * specularMap: new THREE.Texture( <Image> ),
  6662. *
  6663. * alphaMap: new THREE.Texture( <Image> ),
  6664. *
  6665. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6666. * combine: THREE.Multiply,
  6667. * reflectivity: <float>,
  6668. * refractionRatio: <float>,
  6669. *
  6670. * depthTest: <bool>,
  6671. * depthWrite: <bool>,
  6672. *
  6673. * wireframe: <boolean>,
  6674. * wireframeLinewidth: <float>,
  6675. * }
  6676. */
  6677. class MeshBasicMaterial extends Material {
  6678. constructor( parameters ) {
  6679. super();
  6680. this.type = 'MeshBasicMaterial';
  6681. this.color = new Color( 0xffffff ); // emissive
  6682. this.map = null;
  6683. this.lightMap = null;
  6684. this.lightMapIntensity = 1.0;
  6685. this.aoMap = null;
  6686. this.aoMapIntensity = 1.0;
  6687. this.specularMap = null;
  6688. this.alphaMap = null;
  6689. this.envMap = null;
  6690. this.combine = MultiplyOperation;
  6691. this.reflectivity = 1;
  6692. this.refractionRatio = 0.98;
  6693. this.wireframe = false;
  6694. this.wireframeLinewidth = 1;
  6695. this.wireframeLinecap = 'round';
  6696. this.wireframeLinejoin = 'round';
  6697. this.setValues( parameters );
  6698. }
  6699. copy( source ) {
  6700. super.copy( source );
  6701. this.color.copy( source.color );
  6702. this.map = source.map;
  6703. this.lightMap = source.lightMap;
  6704. this.lightMapIntensity = source.lightMapIntensity;
  6705. this.aoMap = source.aoMap;
  6706. this.aoMapIntensity = source.aoMapIntensity;
  6707. this.specularMap = source.specularMap;
  6708. this.alphaMap = source.alphaMap;
  6709. this.envMap = source.envMap;
  6710. this.combine = source.combine;
  6711. this.reflectivity = source.reflectivity;
  6712. this.refractionRatio = source.refractionRatio;
  6713. this.wireframe = source.wireframe;
  6714. this.wireframeLinewidth = source.wireframeLinewidth;
  6715. this.wireframeLinecap = source.wireframeLinecap;
  6716. this.wireframeLinejoin = source.wireframeLinejoin;
  6717. return this;
  6718. }
  6719. }
  6720. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6721. const _vector$9 = /*@__PURE__*/ new Vector3();
  6722. const _vector2$1 = /*@__PURE__*/ new Vector2();
  6723. class BufferAttribute {
  6724. constructor( array, itemSize, normalized ) {
  6725. if ( Array.isArray( array ) ) {
  6726. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  6727. }
  6728. this.name = '';
  6729. this.array = array;
  6730. this.itemSize = itemSize;
  6731. this.count = array !== undefined ? array.length / itemSize : 0;
  6732. this.normalized = normalized === true;
  6733. this.usage = StaticDrawUsage;
  6734. this.updateRange = { offset: 0, count: - 1 };
  6735. this.version = 0;
  6736. }
  6737. onUploadCallback() {}
  6738. set needsUpdate( value ) {
  6739. if ( value === true ) this.version ++;
  6740. }
  6741. setUsage( value ) {
  6742. this.usage = value;
  6743. return this;
  6744. }
  6745. copy( source ) {
  6746. this.name = source.name;
  6747. this.array = new source.array.constructor( source.array );
  6748. this.itemSize = source.itemSize;
  6749. this.count = source.count;
  6750. this.normalized = source.normalized;
  6751. this.usage = source.usage;
  6752. return this;
  6753. }
  6754. copyAt( index1, attribute, index2 ) {
  6755. index1 *= this.itemSize;
  6756. index2 *= attribute.itemSize;
  6757. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6758. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6759. }
  6760. return this;
  6761. }
  6762. copyArray( array ) {
  6763. this.array.set( array );
  6764. return this;
  6765. }
  6766. copyColorsArray( colors ) {
  6767. const array = this.array;
  6768. let offset = 0;
  6769. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  6770. let color = colors[ i ];
  6771. if ( color === undefined ) {
  6772. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  6773. color = new Color();
  6774. }
  6775. array[ offset ++ ] = color.r;
  6776. array[ offset ++ ] = color.g;
  6777. array[ offset ++ ] = color.b;
  6778. }
  6779. return this;
  6780. }
  6781. copyVector2sArray( vectors ) {
  6782. const array = this.array;
  6783. let offset = 0;
  6784. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6785. let vector = vectors[ i ];
  6786. if ( vector === undefined ) {
  6787. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  6788. vector = new Vector2();
  6789. }
  6790. array[ offset ++ ] = vector.x;
  6791. array[ offset ++ ] = vector.y;
  6792. }
  6793. return this;
  6794. }
  6795. copyVector3sArray( vectors ) {
  6796. const array = this.array;
  6797. let offset = 0;
  6798. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6799. let vector = vectors[ i ];
  6800. if ( vector === undefined ) {
  6801. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  6802. vector = new Vector3();
  6803. }
  6804. array[ offset ++ ] = vector.x;
  6805. array[ offset ++ ] = vector.y;
  6806. array[ offset ++ ] = vector.z;
  6807. }
  6808. return this;
  6809. }
  6810. copyVector4sArray( vectors ) {
  6811. const array = this.array;
  6812. let offset = 0;
  6813. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6814. let vector = vectors[ i ];
  6815. if ( vector === undefined ) {
  6816. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  6817. vector = new Vector4();
  6818. }
  6819. array[ offset ++ ] = vector.x;
  6820. array[ offset ++ ] = vector.y;
  6821. array[ offset ++ ] = vector.z;
  6822. array[ offset ++ ] = vector.w;
  6823. }
  6824. return this;
  6825. }
  6826. applyMatrix3( m ) {
  6827. if ( this.itemSize === 2 ) {
  6828. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6829. _vector2$1.fromBufferAttribute( this, i );
  6830. _vector2$1.applyMatrix3( m );
  6831. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6832. }
  6833. } else if ( this.itemSize === 3 ) {
  6834. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6835. _vector$9.fromBufferAttribute( this, i );
  6836. _vector$9.applyMatrix3( m );
  6837. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6838. }
  6839. }
  6840. return this;
  6841. }
  6842. applyMatrix4( m ) {
  6843. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6844. _vector$9.x = this.getX( i );
  6845. _vector$9.y = this.getY( i );
  6846. _vector$9.z = this.getZ( i );
  6847. _vector$9.applyMatrix4( m );
  6848. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6849. }
  6850. return this;
  6851. }
  6852. applyNormalMatrix( m ) {
  6853. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6854. _vector$9.x = this.getX( i );
  6855. _vector$9.y = this.getY( i );
  6856. _vector$9.z = this.getZ( i );
  6857. _vector$9.applyNormalMatrix( m );
  6858. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6859. }
  6860. return this;
  6861. }
  6862. transformDirection( m ) {
  6863. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6864. _vector$9.x = this.getX( i );
  6865. _vector$9.y = this.getY( i );
  6866. _vector$9.z = this.getZ( i );
  6867. _vector$9.transformDirection( m );
  6868. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6869. }
  6870. return this;
  6871. }
  6872. set( value, offset = 0 ) {
  6873. this.array.set( value, offset );
  6874. return this;
  6875. }
  6876. getX( index ) {
  6877. return this.array[ index * this.itemSize ];
  6878. }
  6879. setX( index, x ) {
  6880. this.array[ index * this.itemSize ] = x;
  6881. return this;
  6882. }
  6883. getY( index ) {
  6884. return this.array[ index * this.itemSize + 1 ];
  6885. }
  6886. setY( index, y ) {
  6887. this.array[ index * this.itemSize + 1 ] = y;
  6888. return this;
  6889. }
  6890. getZ( index ) {
  6891. return this.array[ index * this.itemSize + 2 ];
  6892. }
  6893. setZ( index, z ) {
  6894. this.array[ index * this.itemSize + 2 ] = z;
  6895. return this;
  6896. }
  6897. getW( index ) {
  6898. return this.array[ index * this.itemSize + 3 ];
  6899. }
  6900. setW( index, w ) {
  6901. this.array[ index * this.itemSize + 3 ] = w;
  6902. return this;
  6903. }
  6904. setXY( index, x, y ) {
  6905. index *= this.itemSize;
  6906. this.array[ index + 0 ] = x;
  6907. this.array[ index + 1 ] = y;
  6908. return this;
  6909. }
  6910. setXYZ( index, x, y, z ) {
  6911. index *= this.itemSize;
  6912. this.array[ index + 0 ] = x;
  6913. this.array[ index + 1 ] = y;
  6914. this.array[ index + 2 ] = z;
  6915. return this;
  6916. }
  6917. setXYZW( index, x, y, z, w ) {
  6918. index *= this.itemSize;
  6919. this.array[ index + 0 ] = x;
  6920. this.array[ index + 1 ] = y;
  6921. this.array[ index + 2 ] = z;
  6922. this.array[ index + 3 ] = w;
  6923. return this;
  6924. }
  6925. onUpload( callback ) {
  6926. this.onUploadCallback = callback;
  6927. return this;
  6928. }
  6929. clone() {
  6930. return new this.constructor( this.array, this.itemSize ).copy( this );
  6931. }
  6932. toJSON() {
  6933. const data = {
  6934. itemSize: this.itemSize,
  6935. type: this.array.constructor.name,
  6936. array: Array.prototype.slice.call( this.array ),
  6937. normalized: this.normalized
  6938. };
  6939. if ( this.name !== '' ) data.name = this.name;
  6940. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6941. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  6942. return data;
  6943. }
  6944. }
  6945. BufferAttribute.prototype.isBufferAttribute = true;
  6946. //
  6947. class Int8BufferAttribute extends BufferAttribute {
  6948. constructor( array, itemSize, normalized ) {
  6949. super( new Int8Array( array ), itemSize, normalized );
  6950. }
  6951. }
  6952. class Uint8BufferAttribute extends BufferAttribute {
  6953. constructor( array, itemSize, normalized ) {
  6954. super( new Uint8Array( array ), itemSize, normalized );
  6955. }
  6956. }
  6957. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6958. constructor( array, itemSize, normalized ) {
  6959. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6960. }
  6961. }
  6962. class Int16BufferAttribute extends BufferAttribute {
  6963. constructor( array, itemSize, normalized ) {
  6964. super( new Int16Array( array ), itemSize, normalized );
  6965. }
  6966. }
  6967. class Uint16BufferAttribute extends BufferAttribute {
  6968. constructor( array, itemSize, normalized ) {
  6969. super( new Uint16Array( array ), itemSize, normalized );
  6970. }
  6971. }
  6972. class Int32BufferAttribute extends BufferAttribute {
  6973. constructor( array, itemSize, normalized ) {
  6974. super( new Int32Array( array ), itemSize, normalized );
  6975. }
  6976. }
  6977. class Uint32BufferAttribute extends BufferAttribute {
  6978. constructor( array, itemSize, normalized ) {
  6979. super( new Uint32Array( array ), itemSize, normalized );
  6980. }
  6981. }
  6982. class Float16BufferAttribute extends BufferAttribute {
  6983. constructor( array, itemSize, normalized ) {
  6984. super( new Uint16Array( array ), itemSize, normalized );
  6985. }
  6986. }
  6987. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6988. class Float32BufferAttribute extends BufferAttribute {
  6989. constructor( array, itemSize, normalized ) {
  6990. super( new Float32Array( array ), itemSize, normalized );
  6991. }
  6992. }
  6993. class Float64BufferAttribute extends BufferAttribute {
  6994. constructor( array, itemSize, normalized ) {
  6995. super( new Float64Array( array ), itemSize, normalized );
  6996. }
  6997. }
  6998. function arrayMax( array ) {
  6999. if ( array.length === 0 ) return - Infinity;
  7000. let max = array[ 0 ];
  7001. for ( let i = 1, l = array.length; i < l; ++ i ) {
  7002. if ( array[ i ] > max ) max = array[ i ];
  7003. }
  7004. return max;
  7005. }
  7006. const TYPED_ARRAYS = {
  7007. Int8Array: Int8Array,
  7008. Uint8Array: Uint8Array,
  7009. Uint8ClampedArray: Uint8ClampedArray,
  7010. Int16Array: Int16Array,
  7011. Uint16Array: Uint16Array,
  7012. Int32Array: Int32Array,
  7013. Uint32Array: Uint32Array,
  7014. Float32Array: Float32Array,
  7015. Float64Array: Float64Array
  7016. };
  7017. function getTypedArray( type, buffer ) {
  7018. return new TYPED_ARRAYS[ type ]( buffer );
  7019. }
  7020. let _id = 0;
  7021. const _m1 = /*@__PURE__*/ new Matrix4();
  7022. const _obj = /*@__PURE__*/ new Object3D();
  7023. const _offset = /*@__PURE__*/ new Vector3();
  7024. const _box$1 = /*@__PURE__*/ new Box3();
  7025. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  7026. const _vector$8 = /*@__PURE__*/ new Vector3();
  7027. class BufferGeometry extends EventDispatcher {
  7028. constructor() {
  7029. super();
  7030. Object.defineProperty( this, 'id', { value: _id ++ } );
  7031. this.uuid = generateUUID();
  7032. this.name = '';
  7033. this.type = 'BufferGeometry';
  7034. this.index = null;
  7035. this.attributes = {};
  7036. this.morphAttributes = {};
  7037. this.morphTargetsRelative = false;
  7038. this.groups = [];
  7039. this.boundingBox = null;
  7040. this.boundingSphere = null;
  7041. this.drawRange = { start: 0, count: Infinity };
  7042. this.userData = {};
  7043. }
  7044. getIndex() {
  7045. return this.index;
  7046. }
  7047. setIndex( index ) {
  7048. if ( Array.isArray( index ) ) {
  7049. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  7050. } else {
  7051. this.index = index;
  7052. }
  7053. return this;
  7054. }
  7055. getAttribute( name ) {
  7056. return this.attributes[ name ];
  7057. }
  7058. setAttribute( name, attribute ) {
  7059. this.attributes[ name ] = attribute;
  7060. return this;
  7061. }
  7062. deleteAttribute( name ) {
  7063. delete this.attributes[ name ];
  7064. return this;
  7065. }
  7066. hasAttribute( name ) {
  7067. return this.attributes[ name ] !== undefined;
  7068. }
  7069. addGroup( start, count, materialIndex = 0 ) {
  7070. this.groups.push( {
  7071. start: start,
  7072. count: count,
  7073. materialIndex: materialIndex
  7074. } );
  7075. }
  7076. clearGroups() {
  7077. this.groups = [];
  7078. }
  7079. setDrawRange( start, count ) {
  7080. this.drawRange.start = start;
  7081. this.drawRange.count = count;
  7082. }
  7083. applyMatrix4( matrix ) {
  7084. const position = this.attributes.position;
  7085. if ( position !== undefined ) {
  7086. position.applyMatrix4( matrix );
  7087. position.needsUpdate = true;
  7088. }
  7089. const normal = this.attributes.normal;
  7090. if ( normal !== undefined ) {
  7091. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7092. normal.applyNormalMatrix( normalMatrix );
  7093. normal.needsUpdate = true;
  7094. }
  7095. const tangent = this.attributes.tangent;
  7096. if ( tangent !== undefined ) {
  7097. tangent.transformDirection( matrix );
  7098. tangent.needsUpdate = true;
  7099. }
  7100. if ( this.boundingBox !== null ) {
  7101. this.computeBoundingBox();
  7102. }
  7103. if ( this.boundingSphere !== null ) {
  7104. this.computeBoundingSphere();
  7105. }
  7106. return this;
  7107. }
  7108. applyQuaternion( q ) {
  7109. _m1.makeRotationFromQuaternion( q );
  7110. this.applyMatrix4( _m1 );
  7111. return this;
  7112. }
  7113. rotateX( angle ) {
  7114. // rotate geometry around world x-axis
  7115. _m1.makeRotationX( angle );
  7116. this.applyMatrix4( _m1 );
  7117. return this;
  7118. }
  7119. rotateY( angle ) {
  7120. // rotate geometry around world y-axis
  7121. _m1.makeRotationY( angle );
  7122. this.applyMatrix4( _m1 );
  7123. return this;
  7124. }
  7125. rotateZ( angle ) {
  7126. // rotate geometry around world z-axis
  7127. _m1.makeRotationZ( angle );
  7128. this.applyMatrix4( _m1 );
  7129. return this;
  7130. }
  7131. translate( x, y, z ) {
  7132. // translate geometry
  7133. _m1.makeTranslation( x, y, z );
  7134. this.applyMatrix4( _m1 );
  7135. return this;
  7136. }
  7137. scale( x, y, z ) {
  7138. // scale geometry
  7139. _m1.makeScale( x, y, z );
  7140. this.applyMatrix4( _m1 );
  7141. return this;
  7142. }
  7143. lookAt( vector ) {
  7144. _obj.lookAt( vector );
  7145. _obj.updateMatrix();
  7146. this.applyMatrix4( _obj.matrix );
  7147. return this;
  7148. }
  7149. center() {
  7150. this.computeBoundingBox();
  7151. this.boundingBox.getCenter( _offset ).negate();
  7152. this.translate( _offset.x, _offset.y, _offset.z );
  7153. return this;
  7154. }
  7155. setFromPoints( points ) {
  7156. const position = [];
  7157. for ( let i = 0, l = points.length; i < l; i ++ ) {
  7158. const point = points[ i ];
  7159. position.push( point.x, point.y, point.z || 0 );
  7160. }
  7161. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  7162. return this;
  7163. }
  7164. computeBoundingBox() {
  7165. if ( this.boundingBox === null ) {
  7166. this.boundingBox = new Box3();
  7167. }
  7168. const position = this.attributes.position;
  7169. const morphAttributesPosition = this.morphAttributes.position;
  7170. if ( position && position.isGLBufferAttribute ) {
  7171. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  7172. this.boundingBox.set(
  7173. new Vector3( - Infinity, - Infinity, - Infinity ),
  7174. new Vector3( + Infinity, + Infinity, + Infinity )
  7175. );
  7176. return;
  7177. }
  7178. if ( position !== undefined ) {
  7179. this.boundingBox.setFromBufferAttribute( position );
  7180. // process morph attributes if present
  7181. if ( morphAttributesPosition ) {
  7182. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  7183. const morphAttribute = morphAttributesPosition[ i ];
  7184. _box$1.setFromBufferAttribute( morphAttribute );
  7185. if ( this.morphTargetsRelative ) {
  7186. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  7187. this.boundingBox.expandByPoint( _vector$8 );
  7188. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  7189. this.boundingBox.expandByPoint( _vector$8 );
  7190. } else {
  7191. this.boundingBox.expandByPoint( _box$1.min );
  7192. this.boundingBox.expandByPoint( _box$1.max );
  7193. }
  7194. }
  7195. }
  7196. } else {
  7197. this.boundingBox.makeEmpty();
  7198. }
  7199. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  7200. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  7201. }
  7202. }
  7203. computeBoundingSphere() {
  7204. if ( this.boundingSphere === null ) {
  7205. this.boundingSphere = new Sphere();
  7206. }
  7207. const position = this.attributes.position;
  7208. const morphAttributesPosition = this.morphAttributes.position;
  7209. if ( position && position.isGLBufferAttribute ) {
  7210. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  7211. this.boundingSphere.set( new Vector3(), Infinity );
  7212. return;
  7213. }
  7214. if ( position ) {
  7215. // first, find the center of the bounding sphere
  7216. const center = this.boundingSphere.center;
  7217. _box$1.setFromBufferAttribute( position );
  7218. // process morph attributes if present
  7219. if ( morphAttributesPosition ) {
  7220. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  7221. const morphAttribute = morphAttributesPosition[ i ];
  7222. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  7223. if ( this.morphTargetsRelative ) {
  7224. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  7225. _box$1.expandByPoint( _vector$8 );
  7226. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  7227. _box$1.expandByPoint( _vector$8 );
  7228. } else {
  7229. _box$1.expandByPoint( _boxMorphTargets.min );
  7230. _box$1.expandByPoint( _boxMorphTargets.max );
  7231. }
  7232. }
  7233. }
  7234. _box$1.getCenter( center );
  7235. // second, try to find a boundingSphere with a radius smaller than the
  7236. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7237. let maxRadiusSq = 0;
  7238. for ( let i = 0, il = position.count; i < il; i ++ ) {
  7239. _vector$8.fromBufferAttribute( position, i );
  7240. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  7241. }
  7242. // process morph attributes if present
  7243. if ( morphAttributesPosition ) {
  7244. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  7245. const morphAttribute = morphAttributesPosition[ i ];
  7246. const morphTargetsRelative = this.morphTargetsRelative;
  7247. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  7248. _vector$8.fromBufferAttribute( morphAttribute, j );
  7249. if ( morphTargetsRelative ) {
  7250. _offset.fromBufferAttribute( position, j );
  7251. _vector$8.add( _offset );
  7252. }
  7253. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  7254. }
  7255. }
  7256. }
  7257. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  7258. if ( isNaN( this.boundingSphere.radius ) ) {
  7259. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  7260. }
  7261. }
  7262. }
  7263. computeTangents() {
  7264. const index = this.index;
  7265. const attributes = this.attributes;
  7266. // based on http://www.terathon.com/code/tangent.html
  7267. // (per vertex tangents)
  7268. if ( index === null ||
  7269. attributes.position === undefined ||
  7270. attributes.normal === undefined ||
  7271. attributes.uv === undefined ) {
  7272. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  7273. return;
  7274. }
  7275. const indices = index.array;
  7276. const positions = attributes.position.array;
  7277. const normals = attributes.normal.array;
  7278. const uvs = attributes.uv.array;
  7279. const nVertices = positions.length / 3;
  7280. if ( attributes.tangent === undefined ) {
  7281. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  7282. }
  7283. const tangents = attributes.tangent.array;
  7284. const tan1 = [], tan2 = [];
  7285. for ( let i = 0; i < nVertices; i ++ ) {
  7286. tan1[ i ] = new Vector3();
  7287. tan2[ i ] = new Vector3();
  7288. }
  7289. const vA = new Vector3(),
  7290. vB = new Vector3(),
  7291. vC = new Vector3(),
  7292. uvA = new Vector2(),
  7293. uvB = new Vector2(),
  7294. uvC = new Vector2(),
  7295. sdir = new Vector3(),
  7296. tdir = new Vector3();
  7297. function handleTriangle( a, b, c ) {
  7298. vA.fromArray( positions, a * 3 );
  7299. vB.fromArray( positions, b * 3 );
  7300. vC.fromArray( positions, c * 3 );
  7301. uvA.fromArray( uvs, a * 2 );
  7302. uvB.fromArray( uvs, b * 2 );
  7303. uvC.fromArray( uvs, c * 2 );
  7304. vB.sub( vA );
  7305. vC.sub( vA );
  7306. uvB.sub( uvA );
  7307. uvC.sub( uvA );
  7308. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  7309. // silently ignore degenerate uv triangles having coincident or colinear vertices
  7310. if ( ! isFinite( r ) ) return;
  7311. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  7312. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  7313. tan1[ a ].add( sdir );
  7314. tan1[ b ].add( sdir );
  7315. tan1[ c ].add( sdir );
  7316. tan2[ a ].add( tdir );
  7317. tan2[ b ].add( tdir );
  7318. tan2[ c ].add( tdir );
  7319. }
  7320. let groups = this.groups;
  7321. if ( groups.length === 0 ) {
  7322. groups = [ {
  7323. start: 0,
  7324. count: indices.length
  7325. } ];
  7326. }
  7327. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  7328. const group = groups[ i ];
  7329. const start = group.start;
  7330. const count = group.count;
  7331. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  7332. handleTriangle(
  7333. indices[ j + 0 ],
  7334. indices[ j + 1 ],
  7335. indices[ j + 2 ]
  7336. );
  7337. }
  7338. }
  7339. const tmp = new Vector3(), tmp2 = new Vector3();
  7340. const n = new Vector3(), n2 = new Vector3();
  7341. function handleVertex( v ) {
  7342. n.fromArray( normals, v * 3 );
  7343. n2.copy( n );
  7344. const t = tan1[ v ];
  7345. // Gram-Schmidt orthogonalize
  7346. tmp.copy( t );
  7347. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  7348. // Calculate handedness
  7349. tmp2.crossVectors( n2, t );
  7350. const test = tmp2.dot( tan2[ v ] );
  7351. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  7352. tangents[ v * 4 ] = tmp.x;
  7353. tangents[ v * 4 + 1 ] = tmp.y;
  7354. tangents[ v * 4 + 2 ] = tmp.z;
  7355. tangents[ v * 4 + 3 ] = w;
  7356. }
  7357. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  7358. const group = groups[ i ];
  7359. const start = group.start;
  7360. const count = group.count;
  7361. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  7362. handleVertex( indices[ j + 0 ] );
  7363. handleVertex( indices[ j + 1 ] );
  7364. handleVertex( indices[ j + 2 ] );
  7365. }
  7366. }
  7367. }
  7368. computeVertexNormals() {
  7369. const index = this.index;
  7370. const positionAttribute = this.getAttribute( 'position' );
  7371. if ( positionAttribute !== undefined ) {
  7372. let normalAttribute = this.getAttribute( 'normal' );
  7373. if ( normalAttribute === undefined ) {
  7374. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  7375. this.setAttribute( 'normal', normalAttribute );
  7376. } else {
  7377. // reset existing normals to zero
  7378. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  7379. normalAttribute.setXYZ( i, 0, 0, 0 );
  7380. }
  7381. }
  7382. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  7383. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  7384. const cb = new Vector3(), ab = new Vector3();
  7385. // indexed elements
  7386. if ( index ) {
  7387. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  7388. const vA = index.getX( i + 0 );
  7389. const vB = index.getX( i + 1 );
  7390. const vC = index.getX( i + 2 );
  7391. pA.fromBufferAttribute( positionAttribute, vA );
  7392. pB.fromBufferAttribute( positionAttribute, vB );
  7393. pC.fromBufferAttribute( positionAttribute, vC );
  7394. cb.subVectors( pC, pB );
  7395. ab.subVectors( pA, pB );
  7396. cb.cross( ab );
  7397. nA.fromBufferAttribute( normalAttribute, vA );
  7398. nB.fromBufferAttribute( normalAttribute, vB );
  7399. nC.fromBufferAttribute( normalAttribute, vC );
  7400. nA.add( cb );
  7401. nB.add( cb );
  7402. nC.add( cb );
  7403. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  7404. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  7405. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  7406. }
  7407. } else {
  7408. // non-indexed elements (unconnected triangle soup)
  7409. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  7410. pA.fromBufferAttribute( positionAttribute, i + 0 );
  7411. pB.fromBufferAttribute( positionAttribute, i + 1 );
  7412. pC.fromBufferAttribute( positionAttribute, i + 2 );
  7413. cb.subVectors( pC, pB );
  7414. ab.subVectors( pA, pB );
  7415. cb.cross( ab );
  7416. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  7417. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  7418. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  7419. }
  7420. }
  7421. this.normalizeNormals();
  7422. normalAttribute.needsUpdate = true;
  7423. }
  7424. }
  7425. merge( geometry, offset ) {
  7426. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  7427. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7428. return;
  7429. }
  7430. if ( offset === undefined ) {
  7431. offset = 0;
  7432. console.warn(
  7433. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  7434. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  7435. );
  7436. }
  7437. const attributes = this.attributes;
  7438. for ( const key in attributes ) {
  7439. if ( geometry.attributes[ key ] === undefined ) continue;
  7440. const attribute1 = attributes[ key ];
  7441. const attributeArray1 = attribute1.array;
  7442. const attribute2 = geometry.attributes[ key ];
  7443. const attributeArray2 = attribute2.array;
  7444. const attributeOffset = attribute2.itemSize * offset;
  7445. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  7446. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  7447. attributeArray1[ j ] = attributeArray2[ i ];
  7448. }
  7449. }
  7450. return this;
  7451. }
  7452. normalizeNormals() {
  7453. const normals = this.attributes.normal;
  7454. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  7455. _vector$8.fromBufferAttribute( normals, i );
  7456. _vector$8.normalize();
  7457. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  7458. }
  7459. }
  7460. toNonIndexed() {
  7461. function convertBufferAttribute( attribute, indices ) {
  7462. const array = attribute.array;
  7463. const itemSize = attribute.itemSize;
  7464. const normalized = attribute.normalized;
  7465. const array2 = new array.constructor( indices.length * itemSize );
  7466. let index = 0, index2 = 0;
  7467. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  7468. if ( attribute.isInterleavedBufferAttribute ) {
  7469. index = indices[ i ] * attribute.data.stride + attribute.offset;
  7470. } else {
  7471. index = indices[ i ] * itemSize;
  7472. }
  7473. for ( let j = 0; j < itemSize; j ++ ) {
  7474. array2[ index2 ++ ] = array[ index ++ ];
  7475. }
  7476. }
  7477. return new BufferAttribute( array2, itemSize, normalized );
  7478. }
  7479. //
  7480. if ( this.index === null ) {
  7481. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  7482. return this;
  7483. }
  7484. const geometry2 = new BufferGeometry();
  7485. const indices = this.index.array;
  7486. const attributes = this.attributes;
  7487. // attributes
  7488. for ( const name in attributes ) {
  7489. const attribute = attributes[ name ];
  7490. const newAttribute = convertBufferAttribute( attribute, indices );
  7491. geometry2.setAttribute( name, newAttribute );
  7492. }
  7493. // morph attributes
  7494. const morphAttributes = this.morphAttributes;
  7495. for ( const name in morphAttributes ) {
  7496. const morphArray = [];
  7497. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7498. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  7499. const attribute = morphAttribute[ i ];
  7500. const newAttribute = convertBufferAttribute( attribute, indices );
  7501. morphArray.push( newAttribute );
  7502. }
  7503. geometry2.morphAttributes[ name ] = morphArray;
  7504. }
  7505. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  7506. // groups
  7507. const groups = this.groups;
  7508. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7509. const group = groups[ i ];
  7510. geometry2.addGroup( group.start, group.count, group.materialIndex );
  7511. }
  7512. return geometry2;
  7513. }
  7514. toJSON() {
  7515. const data = {
  7516. metadata: {
  7517. version: 4.5,
  7518. type: 'BufferGeometry',
  7519. generator: 'BufferGeometry.toJSON'
  7520. }
  7521. };
  7522. // standard BufferGeometry serialization
  7523. data.uuid = this.uuid;
  7524. data.type = this.type;
  7525. if ( this.name !== '' ) data.name = this.name;
  7526. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  7527. if ( this.parameters !== undefined ) {
  7528. const parameters = this.parameters;
  7529. for ( const key in parameters ) {
  7530. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7531. }
  7532. return data;
  7533. }
  7534. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  7535. data.data = { attributes: {} };
  7536. const index = this.index;
  7537. if ( index !== null ) {
  7538. data.data.index = {
  7539. type: index.array.constructor.name,
  7540. array: Array.prototype.slice.call( index.array )
  7541. };
  7542. }
  7543. const attributes = this.attributes;
  7544. for ( const key in attributes ) {
  7545. const attribute = attributes[ key ];
  7546. data.data.attributes[ key ] = attribute.toJSON( data.data );
  7547. }
  7548. const morphAttributes = {};
  7549. let hasMorphAttributes = false;
  7550. for ( const key in this.morphAttributes ) {
  7551. const attributeArray = this.morphAttributes[ key ];
  7552. const array = [];
  7553. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  7554. const attribute = attributeArray[ i ];
  7555. array.push( attribute.toJSON( data.data ) );
  7556. }
  7557. if ( array.length > 0 ) {
  7558. morphAttributes[ key ] = array;
  7559. hasMorphAttributes = true;
  7560. }
  7561. }
  7562. if ( hasMorphAttributes ) {
  7563. data.data.morphAttributes = morphAttributes;
  7564. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7565. }
  7566. const groups = this.groups;
  7567. if ( groups.length > 0 ) {
  7568. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7569. }
  7570. const boundingSphere = this.boundingSphere;
  7571. if ( boundingSphere !== null ) {
  7572. data.data.boundingSphere = {
  7573. center: boundingSphere.center.toArray(),
  7574. radius: boundingSphere.radius
  7575. };
  7576. }
  7577. return data;
  7578. }
  7579. clone() {
  7580. /*
  7581. // Handle primitives
  7582. const parameters = this.parameters;
  7583. if ( parameters !== undefined ) {
  7584. const values = [];
  7585. for ( const key in parameters ) {
  7586. values.push( parameters[ key ] );
  7587. }
  7588. const geometry = Object.create( this.constructor.prototype );
  7589. this.constructor.apply( geometry, values );
  7590. return geometry;
  7591. }
  7592. return new this.constructor().copy( this );
  7593. */
  7594. return new BufferGeometry().copy( this );
  7595. }
  7596. copy( source ) {
  7597. // reset
  7598. this.index = null;
  7599. this.attributes = {};
  7600. this.morphAttributes = {};
  7601. this.groups = [];
  7602. this.boundingBox = null;
  7603. this.boundingSphere = null;
  7604. // used for storing cloned, shared data
  7605. const data = {};
  7606. // name
  7607. this.name = source.name;
  7608. // index
  7609. const index = source.index;
  7610. if ( index !== null ) {
  7611. this.setIndex( index.clone( data ) );
  7612. }
  7613. // attributes
  7614. const attributes = source.attributes;
  7615. for ( const name in attributes ) {
  7616. const attribute = attributes[ name ];
  7617. this.setAttribute( name, attribute.clone( data ) );
  7618. }
  7619. // morph attributes
  7620. const morphAttributes = source.morphAttributes;
  7621. for ( const name in morphAttributes ) {
  7622. const array = [];
  7623. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7624. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  7625. array.push( morphAttribute[ i ].clone( data ) );
  7626. }
  7627. this.morphAttributes[ name ] = array;
  7628. }
  7629. this.morphTargetsRelative = source.morphTargetsRelative;
  7630. // groups
  7631. const groups = source.groups;
  7632. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7633. const group = groups[ i ];
  7634. this.addGroup( group.start, group.count, group.materialIndex );
  7635. }
  7636. // bounding box
  7637. const boundingBox = source.boundingBox;
  7638. if ( boundingBox !== null ) {
  7639. this.boundingBox = boundingBox.clone();
  7640. }
  7641. // bounding sphere
  7642. const boundingSphere = source.boundingSphere;
  7643. if ( boundingSphere !== null ) {
  7644. this.boundingSphere = boundingSphere.clone();
  7645. }
  7646. // draw range
  7647. this.drawRange.start = source.drawRange.start;
  7648. this.drawRange.count = source.drawRange.count;
  7649. // user data
  7650. this.userData = source.userData;
  7651. return this;
  7652. }
  7653. dispose() {
  7654. this.dispatchEvent( { type: 'dispose' } );
  7655. }
  7656. }
  7657. BufferGeometry.prototype.isBufferGeometry = true;
  7658. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  7659. const _ray$2 = /*@__PURE__*/ new Ray();
  7660. const _sphere$3 = /*@__PURE__*/ new Sphere();
  7661. const _vA$1 = /*@__PURE__*/ new Vector3();
  7662. const _vB$1 = /*@__PURE__*/ new Vector3();
  7663. const _vC$1 = /*@__PURE__*/ new Vector3();
  7664. const _tempA = /*@__PURE__*/ new Vector3();
  7665. const _tempB = /*@__PURE__*/ new Vector3();
  7666. const _tempC = /*@__PURE__*/ new Vector3();
  7667. const _morphA = /*@__PURE__*/ new Vector3();
  7668. const _morphB = /*@__PURE__*/ new Vector3();
  7669. const _morphC = /*@__PURE__*/ new Vector3();
  7670. const _uvA$1 = /*@__PURE__*/ new Vector2();
  7671. const _uvB$1 = /*@__PURE__*/ new Vector2();
  7672. const _uvC$1 = /*@__PURE__*/ new Vector2();
  7673. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  7674. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  7675. class Mesh extends Object3D {
  7676. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  7677. super();
  7678. this.type = 'Mesh';
  7679. this.geometry = geometry;
  7680. this.material = material;
  7681. this.updateMorphTargets();
  7682. }
  7683. copy( source ) {
  7684. super.copy( source );
  7685. if ( source.morphTargetInfluences !== undefined ) {
  7686. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7687. }
  7688. if ( source.morphTargetDictionary !== undefined ) {
  7689. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  7690. }
  7691. this.material = source.material;
  7692. this.geometry = source.geometry;
  7693. return this;
  7694. }
  7695. updateMorphTargets() {
  7696. const geometry = this.geometry;
  7697. if ( geometry.isBufferGeometry ) {
  7698. const morphAttributes = geometry.morphAttributes;
  7699. const keys = Object.keys( morphAttributes );
  7700. if ( keys.length > 0 ) {
  7701. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  7702. if ( morphAttribute !== undefined ) {
  7703. this.morphTargetInfluences = [];
  7704. this.morphTargetDictionary = {};
  7705. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  7706. const name = morphAttribute[ m ].name || String( m );
  7707. this.morphTargetInfluences.push( 0 );
  7708. this.morphTargetDictionary[ name ] = m;
  7709. }
  7710. }
  7711. }
  7712. } else {
  7713. const morphTargets = geometry.morphTargets;
  7714. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  7715. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  7716. }
  7717. }
  7718. }
  7719. raycast( raycaster, intersects ) {
  7720. const geometry = this.geometry;
  7721. const material = this.material;
  7722. const matrixWorld = this.matrixWorld;
  7723. if ( material === undefined ) return;
  7724. // Checking boundingSphere distance to ray
  7725. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7726. _sphere$3.copy( geometry.boundingSphere );
  7727. _sphere$3.applyMatrix4( matrixWorld );
  7728. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  7729. //
  7730. _inverseMatrix$2.copy( matrixWorld ).invert();
  7731. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  7732. // Check boundingBox before continuing
  7733. if ( geometry.boundingBox !== null ) {
  7734. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  7735. }
  7736. let intersection;
  7737. if ( geometry.isBufferGeometry ) {
  7738. const index = geometry.index;
  7739. const position = geometry.attributes.position;
  7740. const morphPosition = geometry.morphAttributes.position;
  7741. const morphTargetsRelative = geometry.morphTargetsRelative;
  7742. const uv = geometry.attributes.uv;
  7743. const uv2 = geometry.attributes.uv2;
  7744. const groups = geometry.groups;
  7745. const drawRange = geometry.drawRange;
  7746. if ( index !== null ) {
  7747. // indexed buffer geometry
  7748. if ( Array.isArray( material ) ) {
  7749. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7750. const group = groups[ i ];
  7751. const groupMaterial = material[ group.materialIndex ];
  7752. const start = Math.max( group.start, drawRange.start );
  7753. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7754. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7755. const a = index.getX( j );
  7756. const b = index.getX( j + 1 );
  7757. const c = index.getX( j + 2 );
  7758. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7759. if ( intersection ) {
  7760. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7761. intersection.face.materialIndex = group.materialIndex;
  7762. intersects.push( intersection );
  7763. }
  7764. }
  7765. }
  7766. } else {
  7767. const start = Math.max( 0, drawRange.start );
  7768. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7769. for ( let i = start, il = end; i < il; i += 3 ) {
  7770. const a = index.getX( i );
  7771. const b = index.getX( i + 1 );
  7772. const c = index.getX( i + 2 );
  7773. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7774. if ( intersection ) {
  7775. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7776. intersects.push( intersection );
  7777. }
  7778. }
  7779. }
  7780. } else if ( position !== undefined ) {
  7781. // non-indexed buffer geometry
  7782. if ( Array.isArray( material ) ) {
  7783. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7784. const group = groups[ i ];
  7785. const groupMaterial = material[ group.materialIndex ];
  7786. const start = Math.max( group.start, drawRange.start );
  7787. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7788. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7789. const a = j;
  7790. const b = j + 1;
  7791. const c = j + 2;
  7792. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7793. if ( intersection ) {
  7794. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7795. intersection.face.materialIndex = group.materialIndex;
  7796. intersects.push( intersection );
  7797. }
  7798. }
  7799. }
  7800. } else {
  7801. const start = Math.max( 0, drawRange.start );
  7802. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7803. for ( let i = start, il = end; i < il; i += 3 ) {
  7804. const a = i;
  7805. const b = i + 1;
  7806. const c = i + 2;
  7807. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7808. if ( intersection ) {
  7809. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7810. intersects.push( intersection );
  7811. }
  7812. }
  7813. }
  7814. }
  7815. } else if ( geometry.isGeometry ) {
  7816. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  7817. }
  7818. }
  7819. }
  7820. Mesh.prototype.isMesh = true;
  7821. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7822. let intersect;
  7823. if ( material.side === BackSide ) {
  7824. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7825. } else {
  7826. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  7827. }
  7828. if ( intersect === null ) return null;
  7829. _intersectionPointWorld.copy( point );
  7830. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7831. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7832. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7833. return {
  7834. distance: distance,
  7835. point: _intersectionPointWorld.clone(),
  7836. object: object
  7837. };
  7838. }
  7839. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  7840. _vA$1.fromBufferAttribute( position, a );
  7841. _vB$1.fromBufferAttribute( position, b );
  7842. _vC$1.fromBufferAttribute( position, c );
  7843. const morphInfluences = object.morphTargetInfluences;
  7844. if ( morphPosition && morphInfluences ) {
  7845. _morphA.set( 0, 0, 0 );
  7846. _morphB.set( 0, 0, 0 );
  7847. _morphC.set( 0, 0, 0 );
  7848. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  7849. const influence = morphInfluences[ i ];
  7850. const morphAttribute = morphPosition[ i ];
  7851. if ( influence === 0 ) continue;
  7852. _tempA.fromBufferAttribute( morphAttribute, a );
  7853. _tempB.fromBufferAttribute( morphAttribute, b );
  7854. _tempC.fromBufferAttribute( morphAttribute, c );
  7855. if ( morphTargetsRelative ) {
  7856. _morphA.addScaledVector( _tempA, influence );
  7857. _morphB.addScaledVector( _tempB, influence );
  7858. _morphC.addScaledVector( _tempC, influence );
  7859. } else {
  7860. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  7861. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  7862. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  7863. }
  7864. }
  7865. _vA$1.add( _morphA );
  7866. _vB$1.add( _morphB );
  7867. _vC$1.add( _morphC );
  7868. }
  7869. if ( object.isSkinnedMesh ) {
  7870. object.boneTransform( a, _vA$1 );
  7871. object.boneTransform( b, _vB$1 );
  7872. object.boneTransform( c, _vC$1 );
  7873. }
  7874. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7875. if ( intersection ) {
  7876. if ( uv ) {
  7877. _uvA$1.fromBufferAttribute( uv, a );
  7878. _uvB$1.fromBufferAttribute( uv, b );
  7879. _uvC$1.fromBufferAttribute( uv, c );
  7880. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7881. }
  7882. if ( uv2 ) {
  7883. _uvA$1.fromBufferAttribute( uv2, a );
  7884. _uvB$1.fromBufferAttribute( uv2, b );
  7885. _uvC$1.fromBufferAttribute( uv2, c );
  7886. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7887. }
  7888. const face = {
  7889. a: a,
  7890. b: b,
  7891. c: c,
  7892. normal: new Vector3(),
  7893. materialIndex: 0
  7894. };
  7895. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7896. intersection.face = face;
  7897. }
  7898. return intersection;
  7899. }
  7900. class BoxGeometry extends BufferGeometry {
  7901. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7902. super();
  7903. this.type = 'BoxGeometry';
  7904. this.parameters = {
  7905. width: width,
  7906. height: height,
  7907. depth: depth,
  7908. widthSegments: widthSegments,
  7909. heightSegments: heightSegments,
  7910. depthSegments: depthSegments
  7911. };
  7912. const scope = this;
  7913. // segments
  7914. widthSegments = Math.floor( widthSegments );
  7915. heightSegments = Math.floor( heightSegments );
  7916. depthSegments = Math.floor( depthSegments );
  7917. // buffers
  7918. const indices = [];
  7919. const vertices = [];
  7920. const normals = [];
  7921. const uvs = [];
  7922. // helper variables
  7923. let numberOfVertices = 0;
  7924. let groupStart = 0;
  7925. // build each side of the box geometry
  7926. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7927. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7928. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7929. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7930. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7931. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7932. // build geometry
  7933. this.setIndex( indices );
  7934. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7935. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7936. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7937. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7938. const segmentWidth = width / gridX;
  7939. const segmentHeight = height / gridY;
  7940. const widthHalf = width / 2;
  7941. const heightHalf = height / 2;
  7942. const depthHalf = depth / 2;
  7943. const gridX1 = gridX + 1;
  7944. const gridY1 = gridY + 1;
  7945. let vertexCounter = 0;
  7946. let groupCount = 0;
  7947. const vector = new Vector3();
  7948. // generate vertices, normals and uvs
  7949. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7950. const y = iy * segmentHeight - heightHalf;
  7951. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7952. const x = ix * segmentWidth - widthHalf;
  7953. // set values to correct vector component
  7954. vector[ u ] = x * udir;
  7955. vector[ v ] = y * vdir;
  7956. vector[ w ] = depthHalf;
  7957. // now apply vector to vertex buffer
  7958. vertices.push( vector.x, vector.y, vector.z );
  7959. // set values to correct vector component
  7960. vector[ u ] = 0;
  7961. vector[ v ] = 0;
  7962. vector[ w ] = depth > 0 ? 1 : - 1;
  7963. // now apply vector to normal buffer
  7964. normals.push( vector.x, vector.y, vector.z );
  7965. // uvs
  7966. uvs.push( ix / gridX );
  7967. uvs.push( 1 - ( iy / gridY ) );
  7968. // counters
  7969. vertexCounter += 1;
  7970. }
  7971. }
  7972. // indices
  7973. // 1. you need three indices to draw a single face
  7974. // 2. a single segment consists of two faces
  7975. // 3. so we need to generate six (2*3) indices per segment
  7976. for ( let iy = 0; iy < gridY; iy ++ ) {
  7977. for ( let ix = 0; ix < gridX; ix ++ ) {
  7978. const a = numberOfVertices + ix + gridX1 * iy;
  7979. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7980. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7981. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7982. // faces
  7983. indices.push( a, b, d );
  7984. indices.push( b, c, d );
  7985. // increase counter
  7986. groupCount += 6;
  7987. }
  7988. }
  7989. // add a group to the geometry. this will ensure multi material support
  7990. scope.addGroup( groupStart, groupCount, materialIndex );
  7991. // calculate new start value for groups
  7992. groupStart += groupCount;
  7993. // update total number of vertices
  7994. numberOfVertices += vertexCounter;
  7995. }
  7996. }
  7997. static fromJSON( data ) {
  7998. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7999. }
  8000. }
  8001. /**
  8002. * Uniform Utilities
  8003. */
  8004. function cloneUniforms( src ) {
  8005. const dst = {};
  8006. for ( const u in src ) {
  8007. dst[ u ] = {};
  8008. for ( const p in src[ u ] ) {
  8009. const property = src[ u ][ p ];
  8010. if ( property && ( property.isColor ||
  8011. property.isMatrix3 || property.isMatrix4 ||
  8012. property.isVector2 || property.isVector3 || property.isVector4 ||
  8013. property.isTexture || property.isQuaternion ) ) {
  8014. dst[ u ][ p ] = property.clone();
  8015. } else if ( Array.isArray( property ) ) {
  8016. dst[ u ][ p ] = property.slice();
  8017. } else {
  8018. dst[ u ][ p ] = property;
  8019. }
  8020. }
  8021. }
  8022. return dst;
  8023. }
  8024. function mergeUniforms( uniforms ) {
  8025. const merged = {};
  8026. for ( let u = 0; u < uniforms.length; u ++ ) {
  8027. const tmp = cloneUniforms( uniforms[ u ] );
  8028. for ( const p in tmp ) {
  8029. merged[ p ] = tmp[ p ];
  8030. }
  8031. }
  8032. return merged;
  8033. }
  8034. // Legacy
  8035. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  8036. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8037. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8038. /**
  8039. * parameters = {
  8040. * defines: { "label" : "value" },
  8041. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8042. *
  8043. * fragmentShader: <string>,
  8044. * vertexShader: <string>,
  8045. *
  8046. * wireframe: <boolean>,
  8047. * wireframeLinewidth: <float>,
  8048. *
  8049. * lights: <bool>
  8050. * }
  8051. */
  8052. class ShaderMaterial extends Material {
  8053. constructor( parameters ) {
  8054. super();
  8055. this.type = 'ShaderMaterial';
  8056. this.defines = {};
  8057. this.uniforms = {};
  8058. this.vertexShader = default_vertex;
  8059. this.fragmentShader = default_fragment;
  8060. this.linewidth = 1;
  8061. this.wireframe = false;
  8062. this.wireframeLinewidth = 1;
  8063. this.fog = false; // set to use scene fog
  8064. this.lights = false; // set to use scene lights
  8065. this.clipping = false; // set to use user-defined clipping planes
  8066. this.extensions = {
  8067. derivatives: false, // set to use derivatives
  8068. fragDepth: false, // set to use fragment depth values
  8069. drawBuffers: false, // set to use draw buffers
  8070. shaderTextureLOD: false // set to use shader texture LOD
  8071. };
  8072. // When rendered geometry doesn't include these attributes but the material does,
  8073. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8074. this.defaultAttributeValues = {
  8075. 'color': [ 1, 1, 1 ],
  8076. 'uv': [ 0, 0 ],
  8077. 'uv2': [ 0, 0 ]
  8078. };
  8079. this.index0AttributeName = undefined;
  8080. this.uniformsNeedUpdate = false;
  8081. this.glslVersion = null;
  8082. if ( parameters !== undefined ) {
  8083. if ( parameters.attributes !== undefined ) {
  8084. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  8085. }
  8086. this.setValues( parameters );
  8087. }
  8088. }
  8089. copy( source ) {
  8090. super.copy( source );
  8091. this.fragmentShader = source.fragmentShader;
  8092. this.vertexShader = source.vertexShader;
  8093. this.uniforms = cloneUniforms( source.uniforms );
  8094. this.defines = Object.assign( {}, source.defines );
  8095. this.wireframe = source.wireframe;
  8096. this.wireframeLinewidth = source.wireframeLinewidth;
  8097. this.lights = source.lights;
  8098. this.clipping = source.clipping;
  8099. this.extensions = Object.assign( {}, source.extensions );
  8100. this.glslVersion = source.glslVersion;
  8101. return this;
  8102. }
  8103. toJSON( meta ) {
  8104. const data = super.toJSON( meta );
  8105. data.glslVersion = this.glslVersion;
  8106. data.uniforms = {};
  8107. for ( const name in this.uniforms ) {
  8108. const uniform = this.uniforms[ name ];
  8109. const value = uniform.value;
  8110. if ( value && value.isTexture ) {
  8111. data.uniforms[ name ] = {
  8112. type: 't',
  8113. value: value.toJSON( meta ).uuid
  8114. };
  8115. } else if ( value && value.isColor ) {
  8116. data.uniforms[ name ] = {
  8117. type: 'c',
  8118. value: value.getHex()
  8119. };
  8120. } else if ( value && value.isVector2 ) {
  8121. data.uniforms[ name ] = {
  8122. type: 'v2',
  8123. value: value.toArray()
  8124. };
  8125. } else if ( value && value.isVector3 ) {
  8126. data.uniforms[ name ] = {
  8127. type: 'v3',
  8128. value: value.toArray()
  8129. };
  8130. } else if ( value && value.isVector4 ) {
  8131. data.uniforms[ name ] = {
  8132. type: 'v4',
  8133. value: value.toArray()
  8134. };
  8135. } else if ( value && value.isMatrix3 ) {
  8136. data.uniforms[ name ] = {
  8137. type: 'm3',
  8138. value: value.toArray()
  8139. };
  8140. } else if ( value && value.isMatrix4 ) {
  8141. data.uniforms[ name ] = {
  8142. type: 'm4',
  8143. value: value.toArray()
  8144. };
  8145. } else {
  8146. data.uniforms[ name ] = {
  8147. value: value
  8148. };
  8149. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  8150. }
  8151. }
  8152. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  8153. data.vertexShader = this.vertexShader;
  8154. data.fragmentShader = this.fragmentShader;
  8155. const extensions = {};
  8156. for ( const key in this.extensions ) {
  8157. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  8158. }
  8159. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  8160. return data;
  8161. }
  8162. }
  8163. ShaderMaterial.prototype.isShaderMaterial = true;
  8164. class Camera extends Object3D {
  8165. constructor() {
  8166. super();
  8167. this.type = 'Camera';
  8168. this.matrixWorldInverse = new Matrix4();
  8169. this.projectionMatrix = new Matrix4();
  8170. this.projectionMatrixInverse = new Matrix4();
  8171. }
  8172. copy( source, recursive ) {
  8173. super.copy( source, recursive );
  8174. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  8175. this.projectionMatrix.copy( source.projectionMatrix );
  8176. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  8177. return this;
  8178. }
  8179. getWorldDirection( target ) {
  8180. this.updateWorldMatrix( true, false );
  8181. const e = this.matrixWorld.elements;
  8182. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  8183. }
  8184. updateMatrixWorld( force ) {
  8185. super.updateMatrixWorld( force );
  8186. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  8187. }
  8188. updateWorldMatrix( updateParents, updateChildren ) {
  8189. super.updateWorldMatrix( updateParents, updateChildren );
  8190. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  8191. }
  8192. clone() {
  8193. return new this.constructor().copy( this );
  8194. }
  8195. }
  8196. Camera.prototype.isCamera = true;
  8197. class PerspectiveCamera extends Camera {
  8198. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  8199. super();
  8200. this.type = 'PerspectiveCamera';
  8201. this.fov = fov;
  8202. this.zoom = 1;
  8203. this.near = near;
  8204. this.far = far;
  8205. this.focus = 10;
  8206. this.aspect = aspect;
  8207. this.view = null;
  8208. this.filmGauge = 35; // width of the film (default in millimeters)
  8209. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  8210. this.updateProjectionMatrix();
  8211. }
  8212. copy( source, recursive ) {
  8213. super.copy( source, recursive );
  8214. this.fov = source.fov;
  8215. this.zoom = source.zoom;
  8216. this.near = source.near;
  8217. this.far = source.far;
  8218. this.focus = source.focus;
  8219. this.aspect = source.aspect;
  8220. this.view = source.view === null ? null : Object.assign( {}, source.view );
  8221. this.filmGauge = source.filmGauge;
  8222. this.filmOffset = source.filmOffset;
  8223. return this;
  8224. }
  8225. /**
  8226. * Sets the FOV by focal length in respect to the current .filmGauge.
  8227. *
  8228. * The default film gauge is 35, so that the focal length can be specified for
  8229. * a 35mm (full frame) camera.
  8230. *
  8231. * Values for focal length and film gauge must have the same unit.
  8232. */
  8233. setFocalLength( focalLength ) {
  8234. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  8235. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  8236. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  8237. this.updateProjectionMatrix();
  8238. }
  8239. /**
  8240. * Calculates the focal length from the current .fov and .filmGauge.
  8241. */
  8242. getFocalLength() {
  8243. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  8244. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8245. }
  8246. getEffectiveFOV() {
  8247. return RAD2DEG * 2 * Math.atan(
  8248. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  8249. }
  8250. getFilmWidth() {
  8251. // film not completely covered in portrait format (aspect < 1)
  8252. return this.filmGauge * Math.min( this.aspect, 1 );
  8253. }
  8254. getFilmHeight() {
  8255. // film not completely covered in landscape format (aspect > 1)
  8256. return this.filmGauge / Math.max( this.aspect, 1 );
  8257. }
  8258. /**
  8259. * Sets an offset in a larger frustum. This is useful for multi-window or
  8260. * multi-monitor/multi-machine setups.
  8261. *
  8262. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8263. * the monitors are in grid like this
  8264. *
  8265. * +---+---+---+
  8266. * | A | B | C |
  8267. * +---+---+---+
  8268. * | D | E | F |
  8269. * +---+---+---+
  8270. *
  8271. * then for each monitor you would call it like this
  8272. *
  8273. * const w = 1920;
  8274. * const h = 1080;
  8275. * const fullWidth = w * 3;
  8276. * const fullHeight = h * 2;
  8277. *
  8278. * --A--
  8279. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8280. * --B--
  8281. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8282. * --C--
  8283. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8284. * --D--
  8285. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8286. * --E--
  8287. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8288. * --F--
  8289. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8290. *
  8291. * Note there is no reason monitors have to be the same size or in a grid.
  8292. */
  8293. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  8294. this.aspect = fullWidth / fullHeight;
  8295. if ( this.view === null ) {
  8296. this.view = {
  8297. enabled: true,
  8298. fullWidth: 1,
  8299. fullHeight: 1,
  8300. offsetX: 0,
  8301. offsetY: 0,
  8302. width: 1,
  8303. height: 1
  8304. };
  8305. }
  8306. this.view.enabled = true;
  8307. this.view.fullWidth = fullWidth;
  8308. this.view.fullHeight = fullHeight;
  8309. this.view.offsetX = x;
  8310. this.view.offsetY = y;
  8311. this.view.width = width;
  8312. this.view.height = height;
  8313. this.updateProjectionMatrix();
  8314. }
  8315. clearViewOffset() {
  8316. if ( this.view !== null ) {
  8317. this.view.enabled = false;
  8318. }
  8319. this.updateProjectionMatrix();
  8320. }
  8321. updateProjectionMatrix() {
  8322. const near = this.near;
  8323. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  8324. let height = 2 * top;
  8325. let width = this.aspect * height;
  8326. let left = - 0.5 * width;
  8327. const view = this.view;
  8328. if ( this.view !== null && this.view.enabled ) {
  8329. const fullWidth = view.fullWidth,
  8330. fullHeight = view.fullHeight;
  8331. left += view.offsetX * width / fullWidth;
  8332. top -= view.offsetY * height / fullHeight;
  8333. width *= view.width / fullWidth;
  8334. height *= view.height / fullHeight;
  8335. }
  8336. const skew = this.filmOffset;
  8337. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  8338. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  8339. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  8340. }
  8341. toJSON( meta ) {
  8342. const data = super.toJSON( meta );
  8343. data.object.fov = this.fov;
  8344. data.object.zoom = this.zoom;
  8345. data.object.near = this.near;
  8346. data.object.far = this.far;
  8347. data.object.focus = this.focus;
  8348. data.object.aspect = this.aspect;
  8349. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  8350. data.object.filmGauge = this.filmGauge;
  8351. data.object.filmOffset = this.filmOffset;
  8352. return data;
  8353. }
  8354. }
  8355. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  8356. const fov = 90, aspect = 1;
  8357. class CubeCamera extends Object3D {
  8358. constructor( near, far, renderTarget ) {
  8359. super();
  8360. this.type = 'CubeCamera';
  8361. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  8362. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  8363. return;
  8364. }
  8365. this.renderTarget = renderTarget;
  8366. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  8367. cameraPX.layers = this.layers;
  8368. cameraPX.up.set( 0, - 1, 0 );
  8369. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  8370. this.add( cameraPX );
  8371. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  8372. cameraNX.layers = this.layers;
  8373. cameraNX.up.set( 0, - 1, 0 );
  8374. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  8375. this.add( cameraNX );
  8376. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  8377. cameraPY.layers = this.layers;
  8378. cameraPY.up.set( 0, 0, 1 );
  8379. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  8380. this.add( cameraPY );
  8381. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  8382. cameraNY.layers = this.layers;
  8383. cameraNY.up.set( 0, 0, - 1 );
  8384. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  8385. this.add( cameraNY );
  8386. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  8387. cameraPZ.layers = this.layers;
  8388. cameraPZ.up.set( 0, - 1, 0 );
  8389. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  8390. this.add( cameraPZ );
  8391. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  8392. cameraNZ.layers = this.layers;
  8393. cameraNZ.up.set( 0, - 1, 0 );
  8394. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  8395. this.add( cameraNZ );
  8396. }
  8397. update( renderer, scene ) {
  8398. if ( this.parent === null ) this.updateMatrixWorld();
  8399. const renderTarget = this.renderTarget;
  8400. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  8401. const currentXrEnabled = renderer.xr.enabled;
  8402. const currentRenderTarget = renderer.getRenderTarget();
  8403. renderer.xr.enabled = false;
  8404. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8405. renderTarget.texture.generateMipmaps = false;
  8406. renderer.setRenderTarget( renderTarget, 0 );
  8407. renderer.render( scene, cameraPX );
  8408. renderer.setRenderTarget( renderTarget, 1 );
  8409. renderer.render( scene, cameraNX );
  8410. renderer.setRenderTarget( renderTarget, 2 );
  8411. renderer.render( scene, cameraPY );
  8412. renderer.setRenderTarget( renderTarget, 3 );
  8413. renderer.render( scene, cameraNY );
  8414. renderer.setRenderTarget( renderTarget, 4 );
  8415. renderer.render( scene, cameraPZ );
  8416. renderTarget.texture.generateMipmaps = generateMipmaps;
  8417. renderer.setRenderTarget( renderTarget, 5 );
  8418. renderer.render( scene, cameraNZ );
  8419. renderer.setRenderTarget( currentRenderTarget );
  8420. renderer.xr.enabled = currentXrEnabled;
  8421. }
  8422. }
  8423. class CubeTexture extends Texture {
  8424. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  8425. images = images !== undefined ? images : [];
  8426. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8427. format = format !== undefined ? format : RGBFormat;
  8428. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8429. this.flipY = false;
  8430. }
  8431. get images() {
  8432. return this.image;
  8433. }
  8434. set images( value ) {
  8435. this.image = value;
  8436. }
  8437. }
  8438. CubeTexture.prototype.isCubeTexture = true;
  8439. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  8440. constructor( size, options, dummy ) {
  8441. if ( Number.isInteger( options ) ) {
  8442. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  8443. options = dummy;
  8444. }
  8445. super( size, size, options );
  8446. options = options || {};
  8447. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8448. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8449. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8450. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8451. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  8452. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  8453. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  8454. this.texture.isRenderTargetTexture = true;
  8455. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  8456. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  8457. this.texture._needsFlipEnvMap = false;
  8458. }
  8459. fromEquirectangularTexture( renderer, texture ) {
  8460. this.texture.type = texture.type;
  8461. this.texture.format = RGBAFormat; // see #18859
  8462. this.texture.encoding = texture.encoding;
  8463. this.texture.generateMipmaps = texture.generateMipmaps;
  8464. this.texture.minFilter = texture.minFilter;
  8465. this.texture.magFilter = texture.magFilter;
  8466. const shader = {
  8467. uniforms: {
  8468. tEquirect: { value: null },
  8469. },
  8470. vertexShader: /* glsl */`
  8471. varying vec3 vWorldDirection;
  8472. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8473. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8474. }
  8475. void main() {
  8476. vWorldDirection = transformDirection( position, modelMatrix );
  8477. #include <begin_vertex>
  8478. #include <project_vertex>
  8479. }
  8480. `,
  8481. fragmentShader: /* glsl */`
  8482. uniform sampler2D tEquirect;
  8483. varying vec3 vWorldDirection;
  8484. #include <common>
  8485. void main() {
  8486. vec3 direction = normalize( vWorldDirection );
  8487. vec2 sampleUV = equirectUv( direction );
  8488. gl_FragColor = texture2D( tEquirect, sampleUV );
  8489. }
  8490. `
  8491. };
  8492. const geometry = new BoxGeometry( 5, 5, 5 );
  8493. const material = new ShaderMaterial( {
  8494. name: 'CubemapFromEquirect',
  8495. uniforms: cloneUniforms( shader.uniforms ),
  8496. vertexShader: shader.vertexShader,
  8497. fragmentShader: shader.fragmentShader,
  8498. side: BackSide,
  8499. blending: NoBlending
  8500. } );
  8501. material.uniforms.tEquirect.value = texture;
  8502. const mesh = new Mesh( geometry, material );
  8503. const currentMinFilter = texture.minFilter;
  8504. // Avoid blurred poles
  8505. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  8506. const camera = new CubeCamera( 1, 10, this );
  8507. camera.update( renderer, mesh );
  8508. texture.minFilter = currentMinFilter;
  8509. mesh.geometry.dispose();
  8510. mesh.material.dispose();
  8511. return this;
  8512. }
  8513. clear( renderer, color, depth, stencil ) {
  8514. const currentRenderTarget = renderer.getRenderTarget();
  8515. for ( let i = 0; i < 6; i ++ ) {
  8516. renderer.setRenderTarget( this, i );
  8517. renderer.clear( color, depth, stencil );
  8518. }
  8519. renderer.setRenderTarget( currentRenderTarget );
  8520. }
  8521. }
  8522. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8523. const _vector1 = /*@__PURE__*/ new Vector3();
  8524. const _vector2 = /*@__PURE__*/ new Vector3();
  8525. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8526. class Plane {
  8527. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8528. // normal is assumed to be normalized
  8529. this.normal = normal;
  8530. this.constant = constant;
  8531. }
  8532. set( normal, constant ) {
  8533. this.normal.copy( normal );
  8534. this.constant = constant;
  8535. return this;
  8536. }
  8537. setComponents( x, y, z, w ) {
  8538. this.normal.set( x, y, z );
  8539. this.constant = w;
  8540. return this;
  8541. }
  8542. setFromNormalAndCoplanarPoint( normal, point ) {
  8543. this.normal.copy( normal );
  8544. this.constant = - point.dot( this.normal );
  8545. return this;
  8546. }
  8547. setFromCoplanarPoints( a, b, c ) {
  8548. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8549. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8550. this.setFromNormalAndCoplanarPoint( normal, a );
  8551. return this;
  8552. }
  8553. copy( plane ) {
  8554. this.normal.copy( plane.normal );
  8555. this.constant = plane.constant;
  8556. return this;
  8557. }
  8558. normalize() {
  8559. // Note: will lead to a divide by zero if the plane is invalid.
  8560. const inverseNormalLength = 1.0 / this.normal.length();
  8561. this.normal.multiplyScalar( inverseNormalLength );
  8562. this.constant *= inverseNormalLength;
  8563. return this;
  8564. }
  8565. negate() {
  8566. this.constant *= - 1;
  8567. this.normal.negate();
  8568. return this;
  8569. }
  8570. distanceToPoint( point ) {
  8571. return this.normal.dot( point ) + this.constant;
  8572. }
  8573. distanceToSphere( sphere ) {
  8574. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8575. }
  8576. projectPoint( point, target ) {
  8577. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  8578. }
  8579. intersectLine( line, target ) {
  8580. const direction = line.delta( _vector1 );
  8581. const denominator = this.normal.dot( direction );
  8582. if ( denominator === 0 ) {
  8583. // line is coplanar, return origin
  8584. if ( this.distanceToPoint( line.start ) === 0 ) {
  8585. return target.copy( line.start );
  8586. }
  8587. // Unsure if this is the correct method to handle this case.
  8588. return null;
  8589. }
  8590. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8591. if ( t < 0 || t > 1 ) {
  8592. return null;
  8593. }
  8594. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  8595. }
  8596. intersectsLine( line ) {
  8597. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8598. const startSign = this.distanceToPoint( line.start );
  8599. const endSign = this.distanceToPoint( line.end );
  8600. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8601. }
  8602. intersectsBox( box ) {
  8603. return box.intersectsPlane( this );
  8604. }
  8605. intersectsSphere( sphere ) {
  8606. return sphere.intersectsPlane( this );
  8607. }
  8608. coplanarPoint( target ) {
  8609. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8610. }
  8611. applyMatrix4( matrix, optionalNormalMatrix ) {
  8612. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8613. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8614. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8615. this.constant = - referencePoint.dot( normal );
  8616. return this;
  8617. }
  8618. translate( offset ) {
  8619. this.constant -= offset.dot( this.normal );
  8620. return this;
  8621. }
  8622. equals( plane ) {
  8623. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8624. }
  8625. clone() {
  8626. return new this.constructor().copy( this );
  8627. }
  8628. }
  8629. Plane.prototype.isPlane = true;
  8630. const _sphere$2 = /*@__PURE__*/ new Sphere();
  8631. const _vector$7 = /*@__PURE__*/ new Vector3();
  8632. class Frustum {
  8633. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8634. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8635. }
  8636. set( p0, p1, p2, p3, p4, p5 ) {
  8637. const planes = this.planes;
  8638. planes[ 0 ].copy( p0 );
  8639. planes[ 1 ].copy( p1 );
  8640. planes[ 2 ].copy( p2 );
  8641. planes[ 3 ].copy( p3 );
  8642. planes[ 4 ].copy( p4 );
  8643. planes[ 5 ].copy( p5 );
  8644. return this;
  8645. }
  8646. copy( frustum ) {
  8647. const planes = this.planes;
  8648. for ( let i = 0; i < 6; i ++ ) {
  8649. planes[ i ].copy( frustum.planes[ i ] );
  8650. }
  8651. return this;
  8652. }
  8653. setFromProjectionMatrix( m ) {
  8654. const planes = this.planes;
  8655. const me = m.elements;
  8656. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8657. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8658. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8659. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8660. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8661. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8662. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8663. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8664. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8665. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8666. return this;
  8667. }
  8668. intersectsObject( object ) {
  8669. const geometry = object.geometry;
  8670. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8671. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8672. return this.intersectsSphere( _sphere$2 );
  8673. }
  8674. intersectsSprite( sprite ) {
  8675. _sphere$2.center.set( 0, 0, 0 );
  8676. _sphere$2.radius = 0.7071067811865476;
  8677. _sphere$2.applyMatrix4( sprite.matrixWorld );
  8678. return this.intersectsSphere( _sphere$2 );
  8679. }
  8680. intersectsSphere( sphere ) {
  8681. const planes = this.planes;
  8682. const center = sphere.center;
  8683. const negRadius = - sphere.radius;
  8684. for ( let i = 0; i < 6; i ++ ) {
  8685. const distance = planes[ i ].distanceToPoint( center );
  8686. if ( distance < negRadius ) {
  8687. return false;
  8688. }
  8689. }
  8690. return true;
  8691. }
  8692. intersectsBox( box ) {
  8693. const planes = this.planes;
  8694. for ( let i = 0; i < 6; i ++ ) {
  8695. const plane = planes[ i ];
  8696. // corner at max distance
  8697. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8698. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8699. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8700. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  8701. return false;
  8702. }
  8703. }
  8704. return true;
  8705. }
  8706. containsPoint( point ) {
  8707. const planes = this.planes;
  8708. for ( let i = 0; i < 6; i ++ ) {
  8709. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8710. return false;
  8711. }
  8712. }
  8713. return true;
  8714. }
  8715. clone() {
  8716. return new this.constructor().copy( this );
  8717. }
  8718. }
  8719. function WebGLAnimation() {
  8720. let context = null;
  8721. let isAnimating = false;
  8722. let animationLoop = null;
  8723. let requestId = null;
  8724. function onAnimationFrame( time, frame ) {
  8725. animationLoop( time, frame );
  8726. requestId = context.requestAnimationFrame( onAnimationFrame );
  8727. }
  8728. return {
  8729. start: function () {
  8730. if ( isAnimating === true ) return;
  8731. if ( animationLoop === null ) return;
  8732. requestId = context.requestAnimationFrame( onAnimationFrame );
  8733. isAnimating = true;
  8734. },
  8735. stop: function () {
  8736. context.cancelAnimationFrame( requestId );
  8737. isAnimating = false;
  8738. },
  8739. setAnimationLoop: function ( callback ) {
  8740. animationLoop = callback;
  8741. },
  8742. setContext: function ( value ) {
  8743. context = value;
  8744. }
  8745. };
  8746. }
  8747. function WebGLAttributes( gl, capabilities ) {
  8748. const isWebGL2 = capabilities.isWebGL2;
  8749. const buffers = new WeakMap();
  8750. function createBuffer( attribute, bufferType ) {
  8751. const array = attribute.array;
  8752. const usage = attribute.usage;
  8753. const buffer = gl.createBuffer();
  8754. gl.bindBuffer( bufferType, buffer );
  8755. gl.bufferData( bufferType, array, usage );
  8756. attribute.onUploadCallback();
  8757. let type = 5126;
  8758. if ( array instanceof Float32Array ) {
  8759. type = 5126;
  8760. } else if ( array instanceof Float64Array ) {
  8761. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8762. } else if ( array instanceof Uint16Array ) {
  8763. if ( attribute.isFloat16BufferAttribute ) {
  8764. if ( isWebGL2 ) {
  8765. type = 5131;
  8766. } else {
  8767. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  8768. }
  8769. } else {
  8770. type = 5123;
  8771. }
  8772. } else if ( array instanceof Int16Array ) {
  8773. type = 5122;
  8774. } else if ( array instanceof Uint32Array ) {
  8775. type = 5125;
  8776. } else if ( array instanceof Int32Array ) {
  8777. type = 5124;
  8778. } else if ( array instanceof Int8Array ) {
  8779. type = 5120;
  8780. } else if ( array instanceof Uint8Array ) {
  8781. type = 5121;
  8782. } else if ( array instanceof Uint8ClampedArray ) {
  8783. type = 5121;
  8784. }
  8785. return {
  8786. buffer: buffer,
  8787. type: type,
  8788. bytesPerElement: array.BYTES_PER_ELEMENT,
  8789. version: attribute.version
  8790. };
  8791. }
  8792. function updateBuffer( buffer, attribute, bufferType ) {
  8793. const array = attribute.array;
  8794. const updateRange = attribute.updateRange;
  8795. gl.bindBuffer( bufferType, buffer );
  8796. if ( updateRange.count === - 1 ) {
  8797. // Not using update ranges
  8798. gl.bufferSubData( bufferType, 0, array );
  8799. } else {
  8800. if ( isWebGL2 ) {
  8801. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8802. array, updateRange.offset, updateRange.count );
  8803. } else {
  8804. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8805. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8806. }
  8807. updateRange.count = - 1; // reset range
  8808. }
  8809. }
  8810. //
  8811. function get( attribute ) {
  8812. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8813. return buffers.get( attribute );
  8814. }
  8815. function remove( attribute ) {
  8816. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8817. const data = buffers.get( attribute );
  8818. if ( data ) {
  8819. gl.deleteBuffer( data.buffer );
  8820. buffers.delete( attribute );
  8821. }
  8822. }
  8823. function update( attribute, bufferType ) {
  8824. if ( attribute.isGLBufferAttribute ) {
  8825. const cached = buffers.get( attribute );
  8826. if ( ! cached || cached.version < attribute.version ) {
  8827. buffers.set( attribute, {
  8828. buffer: attribute.buffer,
  8829. type: attribute.type,
  8830. bytesPerElement: attribute.elementSize,
  8831. version: attribute.version
  8832. } );
  8833. }
  8834. return;
  8835. }
  8836. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8837. const data = buffers.get( attribute );
  8838. if ( data === undefined ) {
  8839. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8840. } else if ( data.version < attribute.version ) {
  8841. updateBuffer( data.buffer, attribute, bufferType );
  8842. data.version = attribute.version;
  8843. }
  8844. }
  8845. return {
  8846. get: get,
  8847. remove: remove,
  8848. update: update
  8849. };
  8850. }
  8851. class PlaneGeometry extends BufferGeometry {
  8852. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8853. super();
  8854. this.type = 'PlaneGeometry';
  8855. this.parameters = {
  8856. width: width,
  8857. height: height,
  8858. widthSegments: widthSegments,
  8859. heightSegments: heightSegments
  8860. };
  8861. const width_half = width / 2;
  8862. const height_half = height / 2;
  8863. const gridX = Math.floor( widthSegments );
  8864. const gridY = Math.floor( heightSegments );
  8865. const gridX1 = gridX + 1;
  8866. const gridY1 = gridY + 1;
  8867. const segment_width = width / gridX;
  8868. const segment_height = height / gridY;
  8869. //
  8870. const indices = [];
  8871. const vertices = [];
  8872. const normals = [];
  8873. const uvs = [];
  8874. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8875. const y = iy * segment_height - height_half;
  8876. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8877. const x = ix * segment_width - width_half;
  8878. vertices.push( x, - y, 0 );
  8879. normals.push( 0, 0, 1 );
  8880. uvs.push( ix / gridX );
  8881. uvs.push( 1 - ( iy / gridY ) );
  8882. }
  8883. }
  8884. for ( let iy = 0; iy < gridY; iy ++ ) {
  8885. for ( let ix = 0; ix < gridX; ix ++ ) {
  8886. const a = ix + gridX1 * iy;
  8887. const b = ix + gridX1 * ( iy + 1 );
  8888. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8889. const d = ( ix + 1 ) + gridX1 * iy;
  8890. indices.push( a, b, d );
  8891. indices.push( b, c, d );
  8892. }
  8893. }
  8894. this.setIndex( indices );
  8895. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8896. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8897. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8898. }
  8899. static fromJSON( data ) {
  8900. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8901. }
  8902. }
  8903. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8904. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8905. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8906. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8907. 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";
  8908. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8909. var begin_vertex = "vec3 transformed = vec3( position );";
  8910. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8911. 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\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotVH = saturate( dot( geometry.viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float NoH ) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float NoV, float NoL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( NoL + NoV - NoL * NoV ) ) );\n}\nvec3 BRDF_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  8912. 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";
  8913. 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";
  8914. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8915. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8916. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8917. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8918. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8919. 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";
  8920. 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";
  8921. 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}";
  8922. 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";
  8923. 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";
  8924. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8925. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8926. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8927. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8928. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8929. 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}";
  8930. 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";
  8931. 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";
  8932. 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";
  8933. 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";
  8934. 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";
  8935. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8936. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8937. 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";
  8938. 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";
  8939. 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}";
  8940. 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";
  8941. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8942. 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";
  8943. 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 = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  8944. 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";
  8945. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8946. 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)";
  8947. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8948. 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)";
  8949. 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";
  8950. 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\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  8951. 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";
  8952. 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";
  8953. 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";
  8954. 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";
  8955. 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";
  8956. 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";
  8957. 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";
  8958. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8959. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8960. 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";
  8961. 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";
  8962. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8963. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8964. 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";
  8965. 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";
  8966. 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";
  8967. 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;";
  8968. 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";
  8969. 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";
  8970. 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";
  8971. 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";
  8972. 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";
  8973. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8974. 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";
  8975. 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";
  8976. 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 );";
  8977. 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}";
  8978. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8979. 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;";
  8980. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8981. 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";
  8982. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8983. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8984. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8985. 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";
  8986. 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";
  8987. 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}";
  8988. 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";
  8989. 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";
  8990. 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";
  8991. 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";
  8992. 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";
  8993. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8994. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8995. 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; }";
  8996. 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";
  8997. 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";
  8998. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8999. 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";
  9000. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  9001. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  9002. 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";
  9003. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  9004. 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";
  9005. 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}";
  9006. 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}";
  9007. 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}";
  9008. 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}";
  9009. 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}";
  9010. 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}";
  9011. 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}";
  9012. 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}";
  9013. 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}";
  9014. 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}";
  9015. 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}";
  9016. 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}";
  9017. 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}";
  9018. 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}";
  9019. 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}";
  9020. 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}";
  9021. 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}";
  9022. 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}";
  9023. 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}";
  9024. 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}";
  9025. 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}";
  9026. 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}";
  9027. 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}";
  9028. 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}";
  9029. 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}";
  9030. 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}";
  9031. 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}";
  9032. 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}";
  9033. 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}";
  9034. 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}";
  9035. 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}";
  9036. 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}";
  9037. const ShaderChunk = {
  9038. alphamap_fragment: alphamap_fragment,
  9039. alphamap_pars_fragment: alphamap_pars_fragment,
  9040. alphatest_fragment: alphatest_fragment,
  9041. alphatest_pars_fragment: alphatest_pars_fragment,
  9042. aomap_fragment: aomap_fragment,
  9043. aomap_pars_fragment: aomap_pars_fragment,
  9044. begin_vertex: begin_vertex,
  9045. beginnormal_vertex: beginnormal_vertex,
  9046. bsdfs: bsdfs,
  9047. bumpmap_pars_fragment: bumpmap_pars_fragment,
  9048. clipping_planes_fragment: clipping_planes_fragment,
  9049. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  9050. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  9051. clipping_planes_vertex: clipping_planes_vertex,
  9052. color_fragment: color_fragment,
  9053. color_pars_fragment: color_pars_fragment,
  9054. color_pars_vertex: color_pars_vertex,
  9055. color_vertex: color_vertex,
  9056. common: common,
  9057. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  9058. defaultnormal_vertex: defaultnormal_vertex,
  9059. displacementmap_pars_vertex: displacementmap_pars_vertex,
  9060. displacementmap_vertex: displacementmap_vertex,
  9061. emissivemap_fragment: emissivemap_fragment,
  9062. emissivemap_pars_fragment: emissivemap_pars_fragment,
  9063. encodings_fragment: encodings_fragment,
  9064. encodings_pars_fragment: encodings_pars_fragment,
  9065. envmap_fragment: envmap_fragment,
  9066. envmap_common_pars_fragment: envmap_common_pars_fragment,
  9067. envmap_pars_fragment: envmap_pars_fragment,
  9068. envmap_pars_vertex: envmap_pars_vertex,
  9069. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  9070. envmap_vertex: envmap_vertex,
  9071. fog_vertex: fog_vertex,
  9072. fog_pars_vertex: fog_pars_vertex,
  9073. fog_fragment: fog_fragment,
  9074. fog_pars_fragment: fog_pars_fragment,
  9075. gradientmap_pars_fragment: gradientmap_pars_fragment,
  9076. lightmap_fragment: lightmap_fragment,
  9077. lightmap_pars_fragment: lightmap_pars_fragment,
  9078. lights_lambert_vertex: lights_lambert_vertex,
  9079. lights_pars_begin: lights_pars_begin,
  9080. lights_toon_fragment: lights_toon_fragment,
  9081. lights_toon_pars_fragment: lights_toon_pars_fragment,
  9082. lights_phong_fragment: lights_phong_fragment,
  9083. lights_phong_pars_fragment: lights_phong_pars_fragment,
  9084. lights_physical_fragment: lights_physical_fragment,
  9085. lights_physical_pars_fragment: lights_physical_pars_fragment,
  9086. lights_fragment_begin: lights_fragment_begin,
  9087. lights_fragment_maps: lights_fragment_maps,
  9088. lights_fragment_end: lights_fragment_end,
  9089. logdepthbuf_fragment: logdepthbuf_fragment,
  9090. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  9091. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  9092. logdepthbuf_vertex: logdepthbuf_vertex,
  9093. map_fragment: map_fragment,
  9094. map_pars_fragment: map_pars_fragment,
  9095. map_particle_fragment: map_particle_fragment,
  9096. map_particle_pars_fragment: map_particle_pars_fragment,
  9097. metalnessmap_fragment: metalnessmap_fragment,
  9098. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  9099. morphnormal_vertex: morphnormal_vertex,
  9100. morphtarget_pars_vertex: morphtarget_pars_vertex,
  9101. morphtarget_vertex: morphtarget_vertex,
  9102. normal_fragment_begin: normal_fragment_begin,
  9103. normal_fragment_maps: normal_fragment_maps,
  9104. normal_pars_fragment: normal_pars_fragment,
  9105. normal_pars_vertex: normal_pars_vertex,
  9106. normal_vertex: normal_vertex,
  9107. normalmap_pars_fragment: normalmap_pars_fragment,
  9108. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  9109. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  9110. clearcoat_pars_fragment: clearcoat_pars_fragment,
  9111. output_fragment: output_fragment,
  9112. packing: packing,
  9113. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  9114. project_vertex: project_vertex,
  9115. dithering_fragment: dithering_fragment,
  9116. dithering_pars_fragment: dithering_pars_fragment,
  9117. roughnessmap_fragment: roughnessmap_fragment,
  9118. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  9119. shadowmap_pars_fragment: shadowmap_pars_fragment,
  9120. shadowmap_pars_vertex: shadowmap_pars_vertex,
  9121. shadowmap_vertex: shadowmap_vertex,
  9122. shadowmask_pars_fragment: shadowmask_pars_fragment,
  9123. skinbase_vertex: skinbase_vertex,
  9124. skinning_pars_vertex: skinning_pars_vertex,
  9125. skinning_vertex: skinning_vertex,
  9126. skinnormal_vertex: skinnormal_vertex,
  9127. specularmap_fragment: specularmap_fragment,
  9128. specularmap_pars_fragment: specularmap_pars_fragment,
  9129. tonemapping_fragment: tonemapping_fragment,
  9130. tonemapping_pars_fragment: tonemapping_pars_fragment,
  9131. transmission_fragment: transmission_fragment,
  9132. transmission_pars_fragment: transmission_pars_fragment,
  9133. uv_pars_fragment: uv_pars_fragment,
  9134. uv_pars_vertex: uv_pars_vertex,
  9135. uv_vertex: uv_vertex,
  9136. uv2_pars_fragment: uv2_pars_fragment,
  9137. uv2_pars_vertex: uv2_pars_vertex,
  9138. uv2_vertex: uv2_vertex,
  9139. worldpos_vertex: worldpos_vertex,
  9140. background_frag: background_frag,
  9141. background_vert: background_vert,
  9142. cube_frag: cube_frag,
  9143. cube_vert: cube_vert,
  9144. depth_frag: depth_frag,
  9145. depth_vert: depth_vert,
  9146. distanceRGBA_frag: distanceRGBA_frag,
  9147. distanceRGBA_vert: distanceRGBA_vert,
  9148. equirect_frag: equirect_frag,
  9149. equirect_vert: equirect_vert,
  9150. linedashed_frag: linedashed_frag,
  9151. linedashed_vert: linedashed_vert,
  9152. meshbasic_frag: meshbasic_frag,
  9153. meshbasic_vert: meshbasic_vert,
  9154. meshlambert_frag: meshlambert_frag,
  9155. meshlambert_vert: meshlambert_vert,
  9156. meshmatcap_frag: meshmatcap_frag,
  9157. meshmatcap_vert: meshmatcap_vert,
  9158. meshnormal_frag: meshnormal_frag,
  9159. meshnormal_vert: meshnormal_vert,
  9160. meshphong_frag: meshphong_frag,
  9161. meshphong_vert: meshphong_vert,
  9162. meshphysical_frag: meshphysical_frag,
  9163. meshphysical_vert: meshphysical_vert,
  9164. meshtoon_frag: meshtoon_frag,
  9165. meshtoon_vert: meshtoon_vert,
  9166. points_frag: points_frag,
  9167. points_vert: points_vert,
  9168. shadow_frag: shadow_frag,
  9169. shadow_vert: shadow_vert,
  9170. sprite_frag: sprite_frag,
  9171. sprite_vert: sprite_vert
  9172. };
  9173. /**
  9174. * Uniforms library for shared webgl shaders
  9175. */
  9176. const UniformsLib = {
  9177. common: {
  9178. diffuse: { value: new Color( 0xffffff ) },
  9179. opacity: { value: 1.0 },
  9180. map: { value: null },
  9181. uvTransform: { value: new Matrix3() },
  9182. uv2Transform: { value: new Matrix3() },
  9183. alphaMap: { value: null },
  9184. alphaTest: { value: 0 }
  9185. },
  9186. specularmap: {
  9187. specularMap: { value: null },
  9188. },
  9189. envmap: {
  9190. envMap: { value: null },
  9191. flipEnvMap: { value: - 1 },
  9192. reflectivity: { value: 1.0 }, // basic, lambert, phong
  9193. ior: { value: 1.5 }, // standard, physical
  9194. refractionRatio: { value: 0.98 },
  9195. maxMipLevel: { value: 0 }
  9196. },
  9197. aomap: {
  9198. aoMap: { value: null },
  9199. aoMapIntensity: { value: 1 }
  9200. },
  9201. lightmap: {
  9202. lightMap: { value: null },
  9203. lightMapIntensity: { value: 1 }
  9204. },
  9205. emissivemap: {
  9206. emissiveMap: { value: null }
  9207. },
  9208. bumpmap: {
  9209. bumpMap: { value: null },
  9210. bumpScale: { value: 1 }
  9211. },
  9212. normalmap: {
  9213. normalMap: { value: null },
  9214. normalScale: { value: new Vector2( 1, 1 ) }
  9215. },
  9216. displacementmap: {
  9217. displacementMap: { value: null },
  9218. displacementScale: { value: 1 },
  9219. displacementBias: { value: 0 }
  9220. },
  9221. roughnessmap: {
  9222. roughnessMap: { value: null }
  9223. },
  9224. metalnessmap: {
  9225. metalnessMap: { value: null }
  9226. },
  9227. gradientmap: {
  9228. gradientMap: { value: null }
  9229. },
  9230. fog: {
  9231. fogDensity: { value: 0.00025 },
  9232. fogNear: { value: 1 },
  9233. fogFar: { value: 2000 },
  9234. fogColor: { value: new Color( 0xffffff ) }
  9235. },
  9236. lights: {
  9237. ambientLightColor: { value: [] },
  9238. lightProbe: { value: [] },
  9239. directionalLights: { value: [], properties: {
  9240. direction: {},
  9241. color: {}
  9242. } },
  9243. directionalLightShadows: { value: [], properties: {
  9244. shadowBias: {},
  9245. shadowNormalBias: {},
  9246. shadowRadius: {},
  9247. shadowMapSize: {}
  9248. } },
  9249. directionalShadowMap: { value: [] },
  9250. directionalShadowMatrix: { value: [] },
  9251. spotLights: { value: [], properties: {
  9252. color: {},
  9253. position: {},
  9254. direction: {},
  9255. distance: {},
  9256. coneCos: {},
  9257. penumbraCos: {},
  9258. decay: {}
  9259. } },
  9260. spotLightShadows: { value: [], properties: {
  9261. shadowBias: {},
  9262. shadowNormalBias: {},
  9263. shadowRadius: {},
  9264. shadowMapSize: {}
  9265. } },
  9266. spotShadowMap: { value: [] },
  9267. spotShadowMatrix: { value: [] },
  9268. pointLights: { value: [], properties: {
  9269. color: {},
  9270. position: {},
  9271. decay: {},
  9272. distance: {}
  9273. } },
  9274. pointLightShadows: { value: [], properties: {
  9275. shadowBias: {},
  9276. shadowNormalBias: {},
  9277. shadowRadius: {},
  9278. shadowMapSize: {},
  9279. shadowCameraNear: {},
  9280. shadowCameraFar: {}
  9281. } },
  9282. pointShadowMap: { value: [] },
  9283. pointShadowMatrix: { value: [] },
  9284. hemisphereLights: { value: [], properties: {
  9285. direction: {},
  9286. skyColor: {},
  9287. groundColor: {}
  9288. } },
  9289. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9290. rectAreaLights: { value: [], properties: {
  9291. color: {},
  9292. position: {},
  9293. width: {},
  9294. height: {}
  9295. } },
  9296. ltc_1: { value: null },
  9297. ltc_2: { value: null }
  9298. },
  9299. points: {
  9300. diffuse: { value: new Color( 0xffffff ) },
  9301. opacity: { value: 1.0 },
  9302. size: { value: 1.0 },
  9303. scale: { value: 1.0 },
  9304. map: { value: null },
  9305. alphaMap: { value: null },
  9306. alphaTest: { value: 0 },
  9307. uvTransform: { value: new Matrix3() }
  9308. },
  9309. sprite: {
  9310. diffuse: { value: new Color( 0xffffff ) },
  9311. opacity: { value: 1.0 },
  9312. center: { value: new Vector2( 0.5, 0.5 ) },
  9313. rotation: { value: 0.0 },
  9314. map: { value: null },
  9315. alphaMap: { value: null },
  9316. alphaTest: { value: 0 },
  9317. uvTransform: { value: new Matrix3() }
  9318. }
  9319. };
  9320. const ShaderLib = {
  9321. basic: {
  9322. uniforms: mergeUniforms( [
  9323. UniformsLib.common,
  9324. UniformsLib.specularmap,
  9325. UniformsLib.envmap,
  9326. UniformsLib.aomap,
  9327. UniformsLib.lightmap,
  9328. UniformsLib.fog
  9329. ] ),
  9330. vertexShader: ShaderChunk.meshbasic_vert,
  9331. fragmentShader: ShaderChunk.meshbasic_frag
  9332. },
  9333. lambert: {
  9334. uniforms: mergeUniforms( [
  9335. UniformsLib.common,
  9336. UniformsLib.specularmap,
  9337. UniformsLib.envmap,
  9338. UniformsLib.aomap,
  9339. UniformsLib.lightmap,
  9340. UniformsLib.emissivemap,
  9341. UniformsLib.fog,
  9342. UniformsLib.lights,
  9343. {
  9344. emissive: { value: new Color( 0x000000 ) }
  9345. }
  9346. ] ),
  9347. vertexShader: ShaderChunk.meshlambert_vert,
  9348. fragmentShader: ShaderChunk.meshlambert_frag
  9349. },
  9350. phong: {
  9351. uniforms: mergeUniforms( [
  9352. UniformsLib.common,
  9353. UniformsLib.specularmap,
  9354. UniformsLib.envmap,
  9355. UniformsLib.aomap,
  9356. UniformsLib.lightmap,
  9357. UniformsLib.emissivemap,
  9358. UniformsLib.bumpmap,
  9359. UniformsLib.normalmap,
  9360. UniformsLib.displacementmap,
  9361. UniformsLib.fog,
  9362. UniformsLib.lights,
  9363. {
  9364. emissive: { value: new Color( 0x000000 ) },
  9365. specular: { value: new Color( 0x111111 ) },
  9366. shininess: { value: 30 }
  9367. }
  9368. ] ),
  9369. vertexShader: ShaderChunk.meshphong_vert,
  9370. fragmentShader: ShaderChunk.meshphong_frag
  9371. },
  9372. standard: {
  9373. uniforms: mergeUniforms( [
  9374. UniformsLib.common,
  9375. UniformsLib.envmap,
  9376. UniformsLib.aomap,
  9377. UniformsLib.lightmap,
  9378. UniformsLib.emissivemap,
  9379. UniformsLib.bumpmap,
  9380. UniformsLib.normalmap,
  9381. UniformsLib.displacementmap,
  9382. UniformsLib.roughnessmap,
  9383. UniformsLib.metalnessmap,
  9384. UniformsLib.fog,
  9385. UniformsLib.lights,
  9386. {
  9387. emissive: { value: new Color( 0x000000 ) },
  9388. roughness: { value: 1.0 },
  9389. metalness: { value: 0.0 },
  9390. envMapIntensity: { value: 1 } // temporary
  9391. }
  9392. ] ),
  9393. vertexShader: ShaderChunk.meshphysical_vert,
  9394. fragmentShader: ShaderChunk.meshphysical_frag
  9395. },
  9396. toon: {
  9397. uniforms: mergeUniforms( [
  9398. UniformsLib.common,
  9399. UniformsLib.aomap,
  9400. UniformsLib.lightmap,
  9401. UniformsLib.emissivemap,
  9402. UniformsLib.bumpmap,
  9403. UniformsLib.normalmap,
  9404. UniformsLib.displacementmap,
  9405. UniformsLib.gradientmap,
  9406. UniformsLib.fog,
  9407. UniformsLib.lights,
  9408. {
  9409. emissive: { value: new Color( 0x000000 ) }
  9410. }
  9411. ] ),
  9412. vertexShader: ShaderChunk.meshtoon_vert,
  9413. fragmentShader: ShaderChunk.meshtoon_frag
  9414. },
  9415. matcap: {
  9416. uniforms: mergeUniforms( [
  9417. UniformsLib.common,
  9418. UniformsLib.bumpmap,
  9419. UniformsLib.normalmap,
  9420. UniformsLib.displacementmap,
  9421. UniformsLib.fog,
  9422. {
  9423. matcap: { value: null }
  9424. }
  9425. ] ),
  9426. vertexShader: ShaderChunk.meshmatcap_vert,
  9427. fragmentShader: ShaderChunk.meshmatcap_frag
  9428. },
  9429. points: {
  9430. uniforms: mergeUniforms( [
  9431. UniformsLib.points,
  9432. UniformsLib.fog
  9433. ] ),
  9434. vertexShader: ShaderChunk.points_vert,
  9435. fragmentShader: ShaderChunk.points_frag
  9436. },
  9437. dashed: {
  9438. uniforms: mergeUniforms( [
  9439. UniformsLib.common,
  9440. UniformsLib.fog,
  9441. {
  9442. scale: { value: 1 },
  9443. dashSize: { value: 1 },
  9444. totalSize: { value: 2 }
  9445. }
  9446. ] ),
  9447. vertexShader: ShaderChunk.linedashed_vert,
  9448. fragmentShader: ShaderChunk.linedashed_frag
  9449. },
  9450. depth: {
  9451. uniforms: mergeUniforms( [
  9452. UniformsLib.common,
  9453. UniformsLib.displacementmap
  9454. ] ),
  9455. vertexShader: ShaderChunk.depth_vert,
  9456. fragmentShader: ShaderChunk.depth_frag
  9457. },
  9458. normal: {
  9459. uniforms: mergeUniforms( [
  9460. UniformsLib.common,
  9461. UniformsLib.bumpmap,
  9462. UniformsLib.normalmap,
  9463. UniformsLib.displacementmap,
  9464. {
  9465. opacity: { value: 1.0 }
  9466. }
  9467. ] ),
  9468. vertexShader: ShaderChunk.meshnormal_vert,
  9469. fragmentShader: ShaderChunk.meshnormal_frag
  9470. },
  9471. sprite: {
  9472. uniforms: mergeUniforms( [
  9473. UniformsLib.sprite,
  9474. UniformsLib.fog
  9475. ] ),
  9476. vertexShader: ShaderChunk.sprite_vert,
  9477. fragmentShader: ShaderChunk.sprite_frag
  9478. },
  9479. background: {
  9480. uniforms: {
  9481. uvTransform: { value: new Matrix3() },
  9482. t2D: { value: null },
  9483. },
  9484. vertexShader: ShaderChunk.background_vert,
  9485. fragmentShader: ShaderChunk.background_frag
  9486. },
  9487. /* -------------------------------------------------------------------------
  9488. // Cube map shader
  9489. ------------------------------------------------------------------------- */
  9490. cube: {
  9491. uniforms: mergeUniforms( [
  9492. UniformsLib.envmap,
  9493. {
  9494. opacity: { value: 1.0 }
  9495. }
  9496. ] ),
  9497. vertexShader: ShaderChunk.cube_vert,
  9498. fragmentShader: ShaderChunk.cube_frag
  9499. },
  9500. equirect: {
  9501. uniforms: {
  9502. tEquirect: { value: null },
  9503. },
  9504. vertexShader: ShaderChunk.equirect_vert,
  9505. fragmentShader: ShaderChunk.equirect_frag
  9506. },
  9507. distanceRGBA: {
  9508. uniforms: mergeUniforms( [
  9509. UniformsLib.common,
  9510. UniformsLib.displacementmap,
  9511. {
  9512. referencePosition: { value: new Vector3() },
  9513. nearDistance: { value: 1 },
  9514. farDistance: { value: 1000 }
  9515. }
  9516. ] ),
  9517. vertexShader: ShaderChunk.distanceRGBA_vert,
  9518. fragmentShader: ShaderChunk.distanceRGBA_frag
  9519. },
  9520. shadow: {
  9521. uniforms: mergeUniforms( [
  9522. UniformsLib.lights,
  9523. UniformsLib.fog,
  9524. {
  9525. color: { value: new Color( 0x00000 ) },
  9526. opacity: { value: 1.0 }
  9527. },
  9528. ] ),
  9529. vertexShader: ShaderChunk.shadow_vert,
  9530. fragmentShader: ShaderChunk.shadow_frag
  9531. }
  9532. };
  9533. ShaderLib.physical = {
  9534. uniforms: mergeUniforms( [
  9535. ShaderLib.standard.uniforms,
  9536. {
  9537. clearcoat: { value: 0 },
  9538. clearcoatMap: { value: null },
  9539. clearcoatRoughness: { value: 0 },
  9540. clearcoatRoughnessMap: { value: null },
  9541. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  9542. clearcoatNormalMap: { value: null },
  9543. sheenTint: { value: new Color( 0x000000 ) },
  9544. transmission: { value: 0 },
  9545. transmissionMap: { value: null },
  9546. transmissionSamplerSize: { value: new Vector2() },
  9547. transmissionSamplerMap: { value: null },
  9548. thickness: { value: 0 },
  9549. thicknessMap: { value: null },
  9550. attenuationDistance: { value: 0 },
  9551. attenuationTint: { value: new Color( 0x000000 ) },
  9552. specularIntensity: { value: 0 },
  9553. specularIntensityMap: { value: null },
  9554. specularTint: { value: new Color( 1, 1, 1 ) },
  9555. specularTintMap: { value: null },
  9556. }
  9557. ] ),
  9558. vertexShader: ShaderChunk.meshphysical_vert,
  9559. fragmentShader: ShaderChunk.meshphysical_frag
  9560. };
  9561. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  9562. const clearColor = new Color( 0x000000 );
  9563. let clearAlpha = 0;
  9564. let planeMesh;
  9565. let boxMesh;
  9566. let currentBackground = null;
  9567. let currentBackgroundVersion = 0;
  9568. let currentTonemapping = null;
  9569. function render( renderList, scene ) {
  9570. let forceClear = false;
  9571. let background = scene.isScene === true ? scene.background : null;
  9572. if ( background && background.isTexture ) {
  9573. background = cubemaps.get( background );
  9574. }
  9575. // Ignore background in AR
  9576. // TODO: Reconsider this.
  9577. const xr = renderer.xr;
  9578. const session = xr.getSession && xr.getSession();
  9579. if ( session && session.environmentBlendMode === 'additive' ) {
  9580. background = null;
  9581. }
  9582. if ( background === null ) {
  9583. setClear( clearColor, clearAlpha );
  9584. } else if ( background && background.isColor ) {
  9585. setClear( background, 1 );
  9586. forceClear = true;
  9587. }
  9588. if ( renderer.autoClear || forceClear ) {
  9589. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9590. }
  9591. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  9592. if ( boxMesh === undefined ) {
  9593. boxMesh = new Mesh(
  9594. new BoxGeometry( 1, 1, 1 ),
  9595. new ShaderMaterial( {
  9596. name: 'BackgroundCubeMaterial',
  9597. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  9598. vertexShader: ShaderLib.cube.vertexShader,
  9599. fragmentShader: ShaderLib.cube.fragmentShader,
  9600. side: BackSide,
  9601. depthTest: false,
  9602. depthWrite: false,
  9603. fog: false
  9604. } )
  9605. );
  9606. boxMesh.geometry.deleteAttribute( 'normal' );
  9607. boxMesh.geometry.deleteAttribute( 'uv' );
  9608. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9609. this.matrixWorld.copyPosition( camera.matrixWorld );
  9610. };
  9611. // enable code injection for non-built-in material
  9612. Object.defineProperty( boxMesh.material, 'envMap', {
  9613. get: function () {
  9614. return this.uniforms.envMap.value;
  9615. }
  9616. } );
  9617. objects.update( boxMesh );
  9618. }
  9619. boxMesh.material.uniforms.envMap.value = background;
  9620. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  9621. if ( currentBackground !== background ||
  9622. currentBackgroundVersion !== background.version ||
  9623. currentTonemapping !== renderer.toneMapping ) {
  9624. boxMesh.material.needsUpdate = true;
  9625. currentBackground = background;
  9626. currentBackgroundVersion = background.version;
  9627. currentTonemapping = renderer.toneMapping;
  9628. }
  9629. // push to the pre-sorted opaque render list
  9630. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9631. } else if ( background && background.isTexture ) {
  9632. if ( planeMesh === undefined ) {
  9633. planeMesh = new Mesh(
  9634. new PlaneGeometry( 2, 2 ),
  9635. new ShaderMaterial( {
  9636. name: 'BackgroundMaterial',
  9637. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9638. vertexShader: ShaderLib.background.vertexShader,
  9639. fragmentShader: ShaderLib.background.fragmentShader,
  9640. side: FrontSide,
  9641. depthTest: false,
  9642. depthWrite: false,
  9643. fog: false
  9644. } )
  9645. );
  9646. planeMesh.geometry.deleteAttribute( 'normal' );
  9647. // enable code injection for non-built-in material
  9648. Object.defineProperty( planeMesh.material, 'map', {
  9649. get: function () {
  9650. return this.uniforms.t2D.value;
  9651. }
  9652. } );
  9653. objects.update( planeMesh );
  9654. }
  9655. planeMesh.material.uniforms.t2D.value = background;
  9656. if ( background.matrixAutoUpdate === true ) {
  9657. background.updateMatrix();
  9658. }
  9659. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9660. if ( currentBackground !== background ||
  9661. currentBackgroundVersion !== background.version ||
  9662. currentTonemapping !== renderer.toneMapping ) {
  9663. planeMesh.material.needsUpdate = true;
  9664. currentBackground = background;
  9665. currentBackgroundVersion = background.version;
  9666. currentTonemapping = renderer.toneMapping;
  9667. }
  9668. // push to the pre-sorted opaque render list
  9669. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9670. }
  9671. }
  9672. function setClear( color, alpha ) {
  9673. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9674. }
  9675. return {
  9676. getClearColor: function () {
  9677. return clearColor;
  9678. },
  9679. setClearColor: function ( color, alpha = 1 ) {
  9680. clearColor.set( color );
  9681. clearAlpha = alpha;
  9682. setClear( clearColor, clearAlpha );
  9683. },
  9684. getClearAlpha: function () {
  9685. return clearAlpha;
  9686. },
  9687. setClearAlpha: function ( alpha ) {
  9688. clearAlpha = alpha;
  9689. setClear( clearColor, clearAlpha );
  9690. },
  9691. render: render
  9692. };
  9693. }
  9694. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9695. const maxVertexAttributes = gl.getParameter( 34921 );
  9696. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9697. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9698. const bindingStates = {};
  9699. const defaultState = createBindingState( null );
  9700. let currentState = defaultState;
  9701. function setup( object, material, program, geometry, index ) {
  9702. let updateBuffers = false;
  9703. if ( vaoAvailable ) {
  9704. const state = getBindingState( geometry, program, material );
  9705. if ( currentState !== state ) {
  9706. currentState = state;
  9707. bindVertexArrayObject( currentState.object );
  9708. }
  9709. updateBuffers = needsUpdate( geometry, index );
  9710. if ( updateBuffers ) saveCache( geometry, index );
  9711. } else {
  9712. const wireframe = ( material.wireframe === true );
  9713. if ( currentState.geometry !== geometry.id ||
  9714. currentState.program !== program.id ||
  9715. currentState.wireframe !== wireframe ) {
  9716. currentState.geometry = geometry.id;
  9717. currentState.program = program.id;
  9718. currentState.wireframe = wireframe;
  9719. updateBuffers = true;
  9720. }
  9721. }
  9722. if ( object.isInstancedMesh === true ) {
  9723. updateBuffers = true;
  9724. }
  9725. if ( index !== null ) {
  9726. attributes.update( index, 34963 );
  9727. }
  9728. if ( updateBuffers ) {
  9729. setupVertexAttributes( object, material, program, geometry );
  9730. if ( index !== null ) {
  9731. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  9732. }
  9733. }
  9734. }
  9735. function createVertexArrayObject() {
  9736. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9737. return extension.createVertexArrayOES();
  9738. }
  9739. function bindVertexArrayObject( vao ) {
  9740. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9741. return extension.bindVertexArrayOES( vao );
  9742. }
  9743. function deleteVertexArrayObject( vao ) {
  9744. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9745. return extension.deleteVertexArrayOES( vao );
  9746. }
  9747. function getBindingState( geometry, program, material ) {
  9748. const wireframe = ( material.wireframe === true );
  9749. let programMap = bindingStates[ geometry.id ];
  9750. if ( programMap === undefined ) {
  9751. programMap = {};
  9752. bindingStates[ geometry.id ] = programMap;
  9753. }
  9754. let stateMap = programMap[ program.id ];
  9755. if ( stateMap === undefined ) {
  9756. stateMap = {};
  9757. programMap[ program.id ] = stateMap;
  9758. }
  9759. let state = stateMap[ wireframe ];
  9760. if ( state === undefined ) {
  9761. state = createBindingState( createVertexArrayObject() );
  9762. stateMap[ wireframe ] = state;
  9763. }
  9764. return state;
  9765. }
  9766. function createBindingState( vao ) {
  9767. const newAttributes = [];
  9768. const enabledAttributes = [];
  9769. const attributeDivisors = [];
  9770. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9771. newAttributes[ i ] = 0;
  9772. enabledAttributes[ i ] = 0;
  9773. attributeDivisors[ i ] = 0;
  9774. }
  9775. return {
  9776. // for backward compatibility on non-VAO support browser
  9777. geometry: null,
  9778. program: null,
  9779. wireframe: false,
  9780. newAttributes: newAttributes,
  9781. enabledAttributes: enabledAttributes,
  9782. attributeDivisors: attributeDivisors,
  9783. object: vao,
  9784. attributes: {},
  9785. index: null
  9786. };
  9787. }
  9788. function needsUpdate( geometry, index ) {
  9789. const cachedAttributes = currentState.attributes;
  9790. const geometryAttributes = geometry.attributes;
  9791. let attributesNum = 0;
  9792. for ( const key in geometryAttributes ) {
  9793. const cachedAttribute = cachedAttributes[ key ];
  9794. const geometryAttribute = geometryAttributes[ key ];
  9795. if ( cachedAttribute === undefined ) return true;
  9796. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9797. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  9798. attributesNum ++;
  9799. }
  9800. if ( currentState.attributesNum !== attributesNum ) return true;
  9801. if ( currentState.index !== index ) return true;
  9802. return false;
  9803. }
  9804. function saveCache( geometry, index ) {
  9805. const cache = {};
  9806. const attributes = geometry.attributes;
  9807. let attributesNum = 0;
  9808. for ( const key in attributes ) {
  9809. const attribute = attributes[ key ];
  9810. const data = {};
  9811. data.attribute = attribute;
  9812. if ( attribute.data ) {
  9813. data.data = attribute.data;
  9814. }
  9815. cache[ key ] = data;
  9816. attributesNum ++;
  9817. }
  9818. currentState.attributes = cache;
  9819. currentState.attributesNum = attributesNum;
  9820. currentState.index = index;
  9821. }
  9822. function initAttributes() {
  9823. const newAttributes = currentState.newAttributes;
  9824. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9825. newAttributes[ i ] = 0;
  9826. }
  9827. }
  9828. function enableAttribute( attribute ) {
  9829. enableAttributeAndDivisor( attribute, 0 );
  9830. }
  9831. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9832. const newAttributes = currentState.newAttributes;
  9833. const enabledAttributes = currentState.enabledAttributes;
  9834. const attributeDivisors = currentState.attributeDivisors;
  9835. newAttributes[ attribute ] = 1;
  9836. if ( enabledAttributes[ attribute ] === 0 ) {
  9837. gl.enableVertexAttribArray( attribute );
  9838. enabledAttributes[ attribute ] = 1;
  9839. }
  9840. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9841. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9842. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9843. attributeDivisors[ attribute ] = meshPerAttribute;
  9844. }
  9845. }
  9846. function disableUnusedAttributes() {
  9847. const newAttributes = currentState.newAttributes;
  9848. const enabledAttributes = currentState.enabledAttributes;
  9849. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9850. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9851. gl.disableVertexAttribArray( i );
  9852. enabledAttributes[ i ] = 0;
  9853. }
  9854. }
  9855. }
  9856. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  9857. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  9858. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9859. } else {
  9860. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9861. }
  9862. }
  9863. function setupVertexAttributes( object, material, program, geometry ) {
  9864. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9865. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9866. }
  9867. initAttributes();
  9868. const geometryAttributes = geometry.attributes;
  9869. const programAttributes = program.getAttributes();
  9870. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9871. for ( const name in programAttributes ) {
  9872. const programAttribute = programAttributes[ name ];
  9873. if ( programAttribute.location >= 0 ) {
  9874. let geometryAttribute = geometryAttributes[ name ];
  9875. if ( geometryAttribute === undefined ) {
  9876. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9877. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9878. }
  9879. if ( geometryAttribute !== undefined ) {
  9880. const normalized = geometryAttribute.normalized;
  9881. const size = geometryAttribute.itemSize;
  9882. const attribute = attributes.get( geometryAttribute );
  9883. // TODO Attribute may not be available on context restore
  9884. if ( attribute === undefined ) continue;
  9885. const buffer = attribute.buffer;
  9886. const type = attribute.type;
  9887. const bytesPerElement = attribute.bytesPerElement;
  9888. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9889. const data = geometryAttribute.data;
  9890. const stride = data.stride;
  9891. const offset = geometryAttribute.offset;
  9892. if ( data && data.isInstancedInterleavedBuffer ) {
  9893. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9894. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9895. }
  9896. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9897. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9898. }
  9899. } else {
  9900. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9901. enableAttribute( programAttribute.location + i );
  9902. }
  9903. }
  9904. gl.bindBuffer( 34962, buffer );
  9905. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9906. vertexAttribPointer(
  9907. programAttribute.location + i,
  9908. size / programAttribute.locationSize,
  9909. type,
  9910. normalized,
  9911. stride * bytesPerElement,
  9912. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  9913. );
  9914. }
  9915. } else {
  9916. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9917. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9918. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9919. }
  9920. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9921. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9922. }
  9923. } else {
  9924. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9925. enableAttribute( programAttribute.location + i );
  9926. }
  9927. }
  9928. gl.bindBuffer( 34962, buffer );
  9929. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9930. vertexAttribPointer(
  9931. programAttribute.location + i,
  9932. size / programAttribute.locationSize,
  9933. type,
  9934. normalized,
  9935. size * bytesPerElement,
  9936. ( size / programAttribute.locationSize ) * i * bytesPerElement
  9937. );
  9938. }
  9939. }
  9940. } else if ( materialDefaultAttributeValues !== undefined ) {
  9941. const value = materialDefaultAttributeValues[ name ];
  9942. if ( value !== undefined ) {
  9943. switch ( value.length ) {
  9944. case 2:
  9945. gl.vertexAttrib2fv( programAttribute.location, value );
  9946. break;
  9947. case 3:
  9948. gl.vertexAttrib3fv( programAttribute.location, value );
  9949. break;
  9950. case 4:
  9951. gl.vertexAttrib4fv( programAttribute.location, value );
  9952. break;
  9953. default:
  9954. gl.vertexAttrib1fv( programAttribute.location, value );
  9955. }
  9956. }
  9957. }
  9958. }
  9959. }
  9960. disableUnusedAttributes();
  9961. }
  9962. function dispose() {
  9963. reset();
  9964. for ( const geometryId in bindingStates ) {
  9965. const programMap = bindingStates[ geometryId ];
  9966. for ( const programId in programMap ) {
  9967. const stateMap = programMap[ programId ];
  9968. for ( const wireframe in stateMap ) {
  9969. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9970. delete stateMap[ wireframe ];
  9971. }
  9972. delete programMap[ programId ];
  9973. }
  9974. delete bindingStates[ geometryId ];
  9975. }
  9976. }
  9977. function releaseStatesOfGeometry( geometry ) {
  9978. if ( bindingStates[ geometry.id ] === undefined ) return;
  9979. const programMap = bindingStates[ geometry.id ];
  9980. for ( const programId in programMap ) {
  9981. const stateMap = programMap[ programId ];
  9982. for ( const wireframe in stateMap ) {
  9983. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9984. delete stateMap[ wireframe ];
  9985. }
  9986. delete programMap[ programId ];
  9987. }
  9988. delete bindingStates[ geometry.id ];
  9989. }
  9990. function releaseStatesOfProgram( program ) {
  9991. for ( const geometryId in bindingStates ) {
  9992. const programMap = bindingStates[ geometryId ];
  9993. if ( programMap[ program.id ] === undefined ) continue;
  9994. const stateMap = programMap[ program.id ];
  9995. for ( const wireframe in stateMap ) {
  9996. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9997. delete stateMap[ wireframe ];
  9998. }
  9999. delete programMap[ program.id ];
  10000. }
  10001. }
  10002. function reset() {
  10003. resetDefaultState();
  10004. if ( currentState === defaultState ) return;
  10005. currentState = defaultState;
  10006. bindVertexArrayObject( currentState.object );
  10007. }
  10008. // for backward-compatilibity
  10009. function resetDefaultState() {
  10010. defaultState.geometry = null;
  10011. defaultState.program = null;
  10012. defaultState.wireframe = false;
  10013. }
  10014. return {
  10015. setup: setup,
  10016. reset: reset,
  10017. resetDefaultState: resetDefaultState,
  10018. dispose: dispose,
  10019. releaseStatesOfGeometry: releaseStatesOfGeometry,
  10020. releaseStatesOfProgram: releaseStatesOfProgram,
  10021. initAttributes: initAttributes,
  10022. enableAttribute: enableAttribute,
  10023. disableUnusedAttributes: disableUnusedAttributes
  10024. };
  10025. }
  10026. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  10027. const isWebGL2 = capabilities.isWebGL2;
  10028. let mode;
  10029. function setMode( value ) {
  10030. mode = value;
  10031. }
  10032. function render( start, count ) {
  10033. gl.drawArrays( mode, start, count );
  10034. info.update( count, mode, 1 );
  10035. }
  10036. function renderInstances( start, count, primcount ) {
  10037. if ( primcount === 0 ) return;
  10038. let extension, methodName;
  10039. if ( isWebGL2 ) {
  10040. extension = gl;
  10041. methodName = 'drawArraysInstanced';
  10042. } else {
  10043. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10044. methodName = 'drawArraysInstancedANGLE';
  10045. if ( extension === null ) {
  10046. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10047. return;
  10048. }
  10049. }
  10050. extension[ methodName ]( mode, start, count, primcount );
  10051. info.update( count, mode, primcount );
  10052. }
  10053. //
  10054. this.setMode = setMode;
  10055. this.render = render;
  10056. this.renderInstances = renderInstances;
  10057. }
  10058. function WebGLCapabilities( gl, extensions, parameters ) {
  10059. let maxAnisotropy;
  10060. function getMaxAnisotropy() {
  10061. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  10062. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  10063. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10064. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  10065. } else {
  10066. maxAnisotropy = 0;
  10067. }
  10068. return maxAnisotropy;
  10069. }
  10070. function getMaxPrecision( precision ) {
  10071. if ( precision === 'highp' ) {
  10072. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  10073. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  10074. return 'highp';
  10075. }
  10076. precision = 'mediump';
  10077. }
  10078. if ( precision === 'mediump' ) {
  10079. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  10080. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  10081. return 'mediump';
  10082. }
  10083. }
  10084. return 'lowp';
  10085. }
  10086. /* eslint-disable no-undef */
  10087. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  10088. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  10089. /* eslint-enable no-undef */
  10090. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  10091. const maxPrecision = getMaxPrecision( precision );
  10092. if ( maxPrecision !== precision ) {
  10093. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  10094. precision = maxPrecision;
  10095. }
  10096. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  10097. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  10098. const maxTextures = gl.getParameter( 34930 );
  10099. const maxVertexTextures = gl.getParameter( 35660 );
  10100. const maxTextureSize = gl.getParameter( 3379 );
  10101. const maxCubemapSize = gl.getParameter( 34076 );
  10102. const maxAttributes = gl.getParameter( 34921 );
  10103. const maxVertexUniforms = gl.getParameter( 36347 );
  10104. const maxVaryings = gl.getParameter( 36348 );
  10105. const maxFragmentUniforms = gl.getParameter( 36349 );
  10106. const vertexTextures = maxVertexTextures > 0;
  10107. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  10108. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  10109. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  10110. return {
  10111. isWebGL2: isWebGL2,
  10112. drawBuffers: drawBuffers,
  10113. getMaxAnisotropy: getMaxAnisotropy,
  10114. getMaxPrecision: getMaxPrecision,
  10115. precision: precision,
  10116. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10117. maxTextures: maxTextures,
  10118. maxVertexTextures: maxVertexTextures,
  10119. maxTextureSize: maxTextureSize,
  10120. maxCubemapSize: maxCubemapSize,
  10121. maxAttributes: maxAttributes,
  10122. maxVertexUniforms: maxVertexUniforms,
  10123. maxVaryings: maxVaryings,
  10124. maxFragmentUniforms: maxFragmentUniforms,
  10125. vertexTextures: vertexTextures,
  10126. floatFragmentTextures: floatFragmentTextures,
  10127. floatVertexTextures: floatVertexTextures,
  10128. maxSamples: maxSamples
  10129. };
  10130. }
  10131. function WebGLClipping( properties ) {
  10132. const scope = this;
  10133. let globalState = null,
  10134. numGlobalPlanes = 0,
  10135. localClippingEnabled = false,
  10136. renderingShadows = false;
  10137. const plane = new Plane(),
  10138. viewNormalMatrix = new Matrix3(),
  10139. uniform = { value: null, needsUpdate: false };
  10140. this.uniform = uniform;
  10141. this.numPlanes = 0;
  10142. this.numIntersection = 0;
  10143. this.init = function ( planes, enableLocalClipping, camera ) {
  10144. const enabled =
  10145. planes.length !== 0 ||
  10146. enableLocalClipping ||
  10147. // enable state of previous frame - the clipping code has to
  10148. // run another frame in order to reset the state:
  10149. numGlobalPlanes !== 0 ||
  10150. localClippingEnabled;
  10151. localClippingEnabled = enableLocalClipping;
  10152. globalState = projectPlanes( planes, camera, 0 );
  10153. numGlobalPlanes = planes.length;
  10154. return enabled;
  10155. };
  10156. this.beginShadows = function () {
  10157. renderingShadows = true;
  10158. projectPlanes( null );
  10159. };
  10160. this.endShadows = function () {
  10161. renderingShadows = false;
  10162. resetGlobalState();
  10163. };
  10164. this.setState = function ( material, camera, useCache ) {
  10165. const planes = material.clippingPlanes,
  10166. clipIntersection = material.clipIntersection,
  10167. clipShadows = material.clipShadows;
  10168. const materialProperties = properties.get( material );
  10169. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  10170. // there's no local clipping
  10171. if ( renderingShadows ) {
  10172. // there's no global clipping
  10173. projectPlanes( null );
  10174. } else {
  10175. resetGlobalState();
  10176. }
  10177. } else {
  10178. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10179. lGlobal = nGlobal * 4;
  10180. let dstArray = materialProperties.clippingState || null;
  10181. uniform.value = dstArray; // ensure unique state
  10182. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  10183. for ( let i = 0; i !== lGlobal; ++ i ) {
  10184. dstArray[ i ] = globalState[ i ];
  10185. }
  10186. materialProperties.clippingState = dstArray;
  10187. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  10188. this.numPlanes += nGlobal;
  10189. }
  10190. };
  10191. function resetGlobalState() {
  10192. if ( uniform.value !== globalState ) {
  10193. uniform.value = globalState;
  10194. uniform.needsUpdate = numGlobalPlanes > 0;
  10195. }
  10196. scope.numPlanes = numGlobalPlanes;
  10197. scope.numIntersection = 0;
  10198. }
  10199. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  10200. const nPlanes = planes !== null ? planes.length : 0;
  10201. let dstArray = null;
  10202. if ( nPlanes !== 0 ) {
  10203. dstArray = uniform.value;
  10204. if ( skipTransform !== true || dstArray === null ) {
  10205. const flatSize = dstOffset + nPlanes * 4,
  10206. viewMatrix = camera.matrixWorldInverse;
  10207. viewNormalMatrix.getNormalMatrix( viewMatrix );
  10208. if ( dstArray === null || dstArray.length < flatSize ) {
  10209. dstArray = new Float32Array( flatSize );
  10210. }
  10211. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  10212. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  10213. plane.normal.toArray( dstArray, i4 );
  10214. dstArray[ i4 + 3 ] = plane.constant;
  10215. }
  10216. }
  10217. uniform.value = dstArray;
  10218. uniform.needsUpdate = true;
  10219. }
  10220. scope.numPlanes = nPlanes;
  10221. scope.numIntersection = 0;
  10222. return dstArray;
  10223. }
  10224. }
  10225. function WebGLCubeMaps( renderer ) {
  10226. let cubemaps = new WeakMap();
  10227. function mapTextureMapping( texture, mapping ) {
  10228. if ( mapping === EquirectangularReflectionMapping ) {
  10229. texture.mapping = CubeReflectionMapping;
  10230. } else if ( mapping === EquirectangularRefractionMapping ) {
  10231. texture.mapping = CubeRefractionMapping;
  10232. }
  10233. return texture;
  10234. }
  10235. function get( texture ) {
  10236. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  10237. const mapping = texture.mapping;
  10238. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  10239. if ( cubemaps.has( texture ) ) {
  10240. const cubemap = cubemaps.get( texture ).texture;
  10241. return mapTextureMapping( cubemap, texture.mapping );
  10242. } else {
  10243. const image = texture.image;
  10244. if ( image && image.height > 0 ) {
  10245. const currentRenderTarget = renderer.getRenderTarget();
  10246. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  10247. renderTarget.fromEquirectangularTexture( renderer, texture );
  10248. cubemaps.set( texture, renderTarget );
  10249. renderer.setRenderTarget( currentRenderTarget );
  10250. texture.addEventListener( 'dispose', onTextureDispose );
  10251. return mapTextureMapping( renderTarget.texture, texture.mapping );
  10252. } else {
  10253. // image not yet ready. try the conversion next frame
  10254. return null;
  10255. }
  10256. }
  10257. }
  10258. }
  10259. return texture;
  10260. }
  10261. function onTextureDispose( event ) {
  10262. const texture = event.target;
  10263. texture.removeEventListener( 'dispose', onTextureDispose );
  10264. const cubemap = cubemaps.get( texture );
  10265. if ( cubemap !== undefined ) {
  10266. cubemaps.delete( texture );
  10267. cubemap.dispose();
  10268. }
  10269. }
  10270. function dispose() {
  10271. cubemaps = new WeakMap();
  10272. }
  10273. return {
  10274. get: get,
  10275. dispose: dispose
  10276. };
  10277. }
  10278. class OrthographicCamera extends Camera {
  10279. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  10280. super();
  10281. this.type = 'OrthographicCamera';
  10282. this.zoom = 1;
  10283. this.view = null;
  10284. this.left = left;
  10285. this.right = right;
  10286. this.top = top;
  10287. this.bottom = bottom;
  10288. this.near = near;
  10289. this.far = far;
  10290. this.updateProjectionMatrix();
  10291. }
  10292. copy( source, recursive ) {
  10293. super.copy( source, recursive );
  10294. this.left = source.left;
  10295. this.right = source.right;
  10296. this.top = source.top;
  10297. this.bottom = source.bottom;
  10298. this.near = source.near;
  10299. this.far = source.far;
  10300. this.zoom = source.zoom;
  10301. this.view = source.view === null ? null : Object.assign( {}, source.view );
  10302. return this;
  10303. }
  10304. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  10305. if ( this.view === null ) {
  10306. this.view = {
  10307. enabled: true,
  10308. fullWidth: 1,
  10309. fullHeight: 1,
  10310. offsetX: 0,
  10311. offsetY: 0,
  10312. width: 1,
  10313. height: 1
  10314. };
  10315. }
  10316. this.view.enabled = true;
  10317. this.view.fullWidth = fullWidth;
  10318. this.view.fullHeight = fullHeight;
  10319. this.view.offsetX = x;
  10320. this.view.offsetY = y;
  10321. this.view.width = width;
  10322. this.view.height = height;
  10323. this.updateProjectionMatrix();
  10324. }
  10325. clearViewOffset() {
  10326. if ( this.view !== null ) {
  10327. this.view.enabled = false;
  10328. }
  10329. this.updateProjectionMatrix();
  10330. }
  10331. updateProjectionMatrix() {
  10332. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  10333. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  10334. const cx = ( this.right + this.left ) / 2;
  10335. const cy = ( this.top + this.bottom ) / 2;
  10336. let left = cx - dx;
  10337. let right = cx + dx;
  10338. let top = cy + dy;
  10339. let bottom = cy - dy;
  10340. if ( this.view !== null && this.view.enabled ) {
  10341. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  10342. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  10343. left += scaleW * this.view.offsetX;
  10344. right = left + scaleW * this.view.width;
  10345. top -= scaleH * this.view.offsetY;
  10346. bottom = top - scaleH * this.view.height;
  10347. }
  10348. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  10349. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  10350. }
  10351. toJSON( meta ) {
  10352. const data = super.toJSON( meta );
  10353. data.object.zoom = this.zoom;
  10354. data.object.left = this.left;
  10355. data.object.right = this.right;
  10356. data.object.top = this.top;
  10357. data.object.bottom = this.bottom;
  10358. data.object.near = this.near;
  10359. data.object.far = this.far;
  10360. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  10361. return data;
  10362. }
  10363. }
  10364. OrthographicCamera.prototype.isOrthographicCamera = true;
  10365. class RawShaderMaterial extends ShaderMaterial {
  10366. constructor( parameters ) {
  10367. super( parameters );
  10368. this.type = 'RawShaderMaterial';
  10369. }
  10370. }
  10371. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  10372. const LOD_MIN = 4;
  10373. const LOD_MAX = 8;
  10374. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  10375. // The standard deviations (radians) associated with the extra mips. These are
  10376. // chosen to approximate a Trowbridge-Reitz distribution function times the
  10377. // geometric shadowing function. These sigma values squared must match the
  10378. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  10379. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  10380. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10381. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  10382. // samples and exit early, but not recompile the shader.
  10383. const MAX_SAMPLES = 20;
  10384. const ENCODINGS = {
  10385. [ LinearEncoding ]: 0,
  10386. [ sRGBEncoding ]: 1,
  10387. [ RGBEEncoding ]: 2,
  10388. [ RGBM7Encoding ]: 3,
  10389. [ RGBM16Encoding ]: 4,
  10390. [ RGBDEncoding ]: 5,
  10391. [ GammaEncoding ]: 6
  10392. };
  10393. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  10394. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  10395. const _clearColor = /*@__PURE__*/ new Color();
  10396. let _oldTarget = null;
  10397. // Golden Ratio
  10398. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  10399. const INV_PHI = 1 / PHI;
  10400. // Vertices of a dodecahedron (except the opposites, which represent the
  10401. // same axis), used as axis directions evenly spread on a sphere.
  10402. const _axisDirections = [
  10403. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  10404. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  10405. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  10406. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  10407. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  10408. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  10409. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  10410. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  10411. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  10412. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  10413. /**
  10414. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  10415. * (PMREM) from a cubeMap environment texture. This allows different levels of
  10416. * blur to be quickly accessed based on material roughness. It is packed into a
  10417. * special CubeUV format that allows us to perform custom interpolation so that
  10418. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  10419. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  10420. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  10421. * higher roughness levels. In this way we maintain resolution to smoothly
  10422. * interpolate diffuse lighting while limiting sampling computation.
  10423. *
  10424. * Paper: Fast, Accurate Image-Based Lighting
  10425. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  10426. */
  10427. class PMREMGenerator {
  10428. constructor( renderer ) {
  10429. this._renderer = renderer;
  10430. this._pingPongRenderTarget = null;
  10431. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  10432. this._equirectShader = null;
  10433. this._cubemapShader = null;
  10434. this._compileMaterial( this._blurMaterial );
  10435. }
  10436. /**
  10437. * Generates a PMREM from a supplied Scene, which can be faster than using an
  10438. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  10439. * in radians to be applied to the scene before PMREM generation. Optional near
  10440. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  10441. * is placed at the origin).
  10442. */
  10443. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  10444. _oldTarget = this._renderer.getRenderTarget();
  10445. const cubeUVRenderTarget = this._allocateTargets();
  10446. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  10447. if ( sigma > 0 ) {
  10448. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  10449. }
  10450. this._applyPMREM( cubeUVRenderTarget );
  10451. this._cleanup( cubeUVRenderTarget );
  10452. return cubeUVRenderTarget;
  10453. }
  10454. /**
  10455. * Generates a PMREM from an equirectangular texture, which can be either LDR
  10456. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  10457. * as this matches best with the 256 x 256 cubemap output.
  10458. */
  10459. fromEquirectangular( equirectangular ) {
  10460. return this._fromTexture( equirectangular );
  10461. }
  10462. /**
  10463. * Generates a PMREM from an cubemap texture, which can be either LDR
  10464. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  10465. * as this matches best with the 256 x 256 cubemap output.
  10466. */
  10467. fromCubemap( cubemap ) {
  10468. return this._fromTexture( cubemap );
  10469. }
  10470. /**
  10471. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  10472. * your texture's network fetch for increased concurrency.
  10473. */
  10474. compileCubemapShader() {
  10475. if ( this._cubemapShader === null ) {
  10476. this._cubemapShader = _getCubemapShader();
  10477. this._compileMaterial( this._cubemapShader );
  10478. }
  10479. }
  10480. /**
  10481. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  10482. * your texture's network fetch for increased concurrency.
  10483. */
  10484. compileEquirectangularShader() {
  10485. if ( this._equirectShader === null ) {
  10486. this._equirectShader = _getEquirectShader();
  10487. this._compileMaterial( this._equirectShader );
  10488. }
  10489. }
  10490. /**
  10491. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  10492. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  10493. * one of them will cause any others to also become unusable.
  10494. */
  10495. dispose() {
  10496. this._blurMaterial.dispose();
  10497. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  10498. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  10499. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  10500. _lodPlanes[ i ].dispose();
  10501. }
  10502. }
  10503. // private interface
  10504. _cleanup( outputTarget ) {
  10505. this._pingPongRenderTarget.dispose();
  10506. this._renderer.setRenderTarget( _oldTarget );
  10507. outputTarget.scissorTest = false;
  10508. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  10509. }
  10510. _fromTexture( texture ) {
  10511. _oldTarget = this._renderer.getRenderTarget();
  10512. const cubeUVRenderTarget = this._allocateTargets( texture );
  10513. this._textureToCubeUV( texture, cubeUVRenderTarget );
  10514. this._applyPMREM( cubeUVRenderTarget );
  10515. this._cleanup( cubeUVRenderTarget );
  10516. return cubeUVRenderTarget;
  10517. }
  10518. _allocateTargets( texture ) { // warning: null texture is valid
  10519. const params = {
  10520. magFilter: NearestFilter,
  10521. minFilter: NearestFilter,
  10522. generateMipmaps: false,
  10523. type: UnsignedByteType,
  10524. format: RGBEFormat,
  10525. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  10526. depthBuffer: false
  10527. };
  10528. const cubeUVRenderTarget = _createRenderTarget( params );
  10529. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  10530. this._pingPongRenderTarget = _createRenderTarget( params );
  10531. return cubeUVRenderTarget;
  10532. }
  10533. _compileMaterial( material ) {
  10534. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  10535. this._renderer.compile( tmpMesh, _flatCamera );
  10536. }
  10537. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  10538. const fov = 90;
  10539. const aspect = 1;
  10540. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  10541. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  10542. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  10543. const renderer = this._renderer;
  10544. const originalAutoClear = renderer.autoClear;
  10545. const outputEncoding = renderer.outputEncoding;
  10546. const toneMapping = renderer.toneMapping;
  10547. renderer.getClearColor( _clearColor );
  10548. renderer.toneMapping = NoToneMapping;
  10549. renderer.outputEncoding = LinearEncoding;
  10550. renderer.autoClear = false;
  10551. const backgroundMaterial = new MeshBasicMaterial( {
  10552. name: 'PMREM.Background',
  10553. side: BackSide,
  10554. depthWrite: false,
  10555. depthTest: false,
  10556. } );
  10557. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  10558. let useSolidColor = false;
  10559. const background = scene.background;
  10560. if ( background ) {
  10561. if ( background.isColor ) {
  10562. backgroundMaterial.color.copy( background );
  10563. scene.background = null;
  10564. useSolidColor = true;
  10565. }
  10566. } else {
  10567. backgroundMaterial.color.copy( _clearColor );
  10568. useSolidColor = true;
  10569. }
  10570. for ( let i = 0; i < 6; i ++ ) {
  10571. const col = i % 3;
  10572. if ( col == 0 ) {
  10573. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10574. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  10575. } else if ( col == 1 ) {
  10576. cubeCamera.up.set( 0, 0, upSign[ i ] );
  10577. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  10578. } else {
  10579. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10580. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  10581. }
  10582. _setViewport( cubeUVRenderTarget,
  10583. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  10584. renderer.setRenderTarget( cubeUVRenderTarget );
  10585. if ( useSolidColor ) {
  10586. renderer.render( backgroundBox, cubeCamera );
  10587. }
  10588. renderer.render( scene, cubeCamera );
  10589. }
  10590. backgroundBox.geometry.dispose();
  10591. backgroundBox.material.dispose();
  10592. renderer.toneMapping = toneMapping;
  10593. renderer.outputEncoding = outputEncoding;
  10594. renderer.autoClear = originalAutoClear;
  10595. scene.background = background;
  10596. }
  10597. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  10598. const renderer = this._renderer;
  10599. if ( texture.isCubeTexture ) {
  10600. if ( this._cubemapShader == null ) {
  10601. this._cubemapShader = _getCubemapShader();
  10602. }
  10603. } else {
  10604. if ( this._equirectShader == null ) {
  10605. this._equirectShader = _getEquirectShader();
  10606. }
  10607. }
  10608. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  10609. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  10610. const uniforms = material.uniforms;
  10611. uniforms[ 'envMap' ].value = texture;
  10612. if ( ! texture.isCubeTexture ) {
  10613. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  10614. }
  10615. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  10616. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  10617. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  10618. renderer.setRenderTarget( cubeUVRenderTarget );
  10619. renderer.render( mesh, _flatCamera );
  10620. }
  10621. _applyPMREM( cubeUVRenderTarget ) {
  10622. const renderer = this._renderer;
  10623. const autoClear = renderer.autoClear;
  10624. renderer.autoClear = false;
  10625. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  10626. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  10627. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  10628. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  10629. }
  10630. renderer.autoClear = autoClear;
  10631. }
  10632. /**
  10633. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  10634. * vertically and horizontally, but this breaks down on a cube. Here we apply
  10635. * the blur latitudinally (around the poles), and then longitudinally (towards
  10636. * the poles) to approximate the orthogonally-separable blur. It is least
  10637. * accurate at the poles, but still does a decent job.
  10638. */
  10639. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  10640. const pingPongRenderTarget = this._pingPongRenderTarget;
  10641. this._halfBlur(
  10642. cubeUVRenderTarget,
  10643. pingPongRenderTarget,
  10644. lodIn,
  10645. lodOut,
  10646. sigma,
  10647. 'latitudinal',
  10648. poleAxis );
  10649. this._halfBlur(
  10650. pingPongRenderTarget,
  10651. cubeUVRenderTarget,
  10652. lodOut,
  10653. lodOut,
  10654. sigma,
  10655. 'longitudinal',
  10656. poleAxis );
  10657. }
  10658. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10659. const renderer = this._renderer;
  10660. const blurMaterial = this._blurMaterial;
  10661. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10662. console.error(
  10663. 'blur direction must be either latitudinal or longitudinal!' );
  10664. }
  10665. // Number of standard deviations at which to cut off the discrete approximation.
  10666. const STANDARD_DEVIATIONS = 3;
  10667. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  10668. const blurUniforms = blurMaterial.uniforms;
  10669. const pixels = _sizeLods[ lodIn ] - 1;
  10670. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10671. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10672. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10673. if ( samples > MAX_SAMPLES ) {
  10674. console.warn( `sigmaRadians, ${
  10675. sigmaRadians}, is too large and will clip, as it requested ${
  10676. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10677. }
  10678. const weights = [];
  10679. let sum = 0;
  10680. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10681. const x = i / sigmaPixels;
  10682. const weight = Math.exp( - x * x / 2 );
  10683. weights.push( weight );
  10684. if ( i == 0 ) {
  10685. sum += weight;
  10686. } else if ( i < samples ) {
  10687. sum += 2 * weight;
  10688. }
  10689. }
  10690. for ( let i = 0; i < weights.length; i ++ ) {
  10691. weights[ i ] = weights[ i ] / sum;
  10692. }
  10693. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10694. blurUniforms[ 'samples' ].value = samples;
  10695. blurUniforms[ 'weights' ].value = weights;
  10696. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10697. if ( poleAxis ) {
  10698. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10699. }
  10700. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10701. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  10702. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  10703. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  10704. const outputSize = _sizeLods[ lodOut ];
  10705. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  10706. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  10707. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10708. renderer.setRenderTarget( targetOut );
  10709. renderer.render( blurMesh, _flatCamera );
  10710. }
  10711. }
  10712. function _isLDR( texture ) {
  10713. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  10714. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  10715. }
  10716. function _createPlanes() {
  10717. const _lodPlanes = [];
  10718. const _sizeLods = [];
  10719. const _sigmas = [];
  10720. let lod = LOD_MAX;
  10721. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  10722. const sizeLod = Math.pow( 2, lod );
  10723. _sizeLods.push( sizeLod );
  10724. let sigma = 1.0 / sizeLod;
  10725. if ( i > LOD_MAX - LOD_MIN ) {
  10726. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  10727. } else if ( i == 0 ) {
  10728. sigma = 0;
  10729. }
  10730. _sigmas.push( sigma );
  10731. const texelSize = 1.0 / ( sizeLod - 1 );
  10732. const min = - texelSize / 2;
  10733. const max = 1 + texelSize / 2;
  10734. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10735. const cubeFaces = 6;
  10736. const vertices = 6;
  10737. const positionSize = 3;
  10738. const uvSize = 2;
  10739. const faceIndexSize = 1;
  10740. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10741. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10742. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10743. for ( let face = 0; face < cubeFaces; face ++ ) {
  10744. const x = ( face % 3 ) * 2 / 3 - 1;
  10745. const y = face > 2 ? 0 : - 1;
  10746. const coordinates = [
  10747. x, y, 0,
  10748. x + 2 / 3, y, 0,
  10749. x + 2 / 3, y + 1, 0,
  10750. x, y, 0,
  10751. x + 2 / 3, y + 1, 0,
  10752. x, y + 1, 0
  10753. ];
  10754. position.set( coordinates, positionSize * vertices * face );
  10755. uv.set( uv1, uvSize * vertices * face );
  10756. const fill = [ face, face, face, face, face, face ];
  10757. faceIndex.set( fill, faceIndexSize * vertices * face );
  10758. }
  10759. const planes = new BufferGeometry();
  10760. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10761. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10762. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10763. _lodPlanes.push( planes );
  10764. if ( lod > LOD_MIN ) {
  10765. lod --;
  10766. }
  10767. }
  10768. return { _lodPlanes, _sizeLods, _sigmas };
  10769. }
  10770. function _createRenderTarget( params ) {
  10771. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  10772. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10773. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10774. cubeUVRenderTarget.scissorTest = true;
  10775. return cubeUVRenderTarget;
  10776. }
  10777. function _setViewport( target, x, y, width, height ) {
  10778. target.viewport.set( x, y, width, height );
  10779. target.scissor.set( x, y, width, height );
  10780. }
  10781. function _getBlurShader( maxSamples ) {
  10782. const weights = new Float32Array( maxSamples );
  10783. const poleAxis = new Vector3( 0, 1, 0 );
  10784. const shaderMaterial = new RawShaderMaterial( {
  10785. name: 'SphericalGaussianBlur',
  10786. defines: { 'n': maxSamples },
  10787. uniforms: {
  10788. 'envMap': { value: null },
  10789. 'samples': { value: 1 },
  10790. 'weights': { value: weights },
  10791. 'latitudinal': { value: false },
  10792. 'dTheta': { value: 0 },
  10793. 'mipInt': { value: 0 },
  10794. 'poleAxis': { value: poleAxis },
  10795. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  10796. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  10797. },
  10798. vertexShader: _getCommonVertexShader(),
  10799. fragmentShader: /* glsl */`
  10800. precision mediump float;
  10801. precision mediump int;
  10802. varying vec3 vOutputDirection;
  10803. uniform sampler2D envMap;
  10804. uniform int samples;
  10805. uniform float weights[ n ];
  10806. uniform bool latitudinal;
  10807. uniform float dTheta;
  10808. uniform float mipInt;
  10809. uniform vec3 poleAxis;
  10810. ${ _getEncodings() }
  10811. #define ENVMAP_TYPE_CUBE_UV
  10812. #include <cube_uv_reflection_fragment>
  10813. vec3 getSample( float theta, vec3 axis ) {
  10814. float cosTheta = cos( theta );
  10815. // Rodrigues' axis-angle rotation
  10816. vec3 sampleDirection = vOutputDirection * cosTheta
  10817. + cross( axis, vOutputDirection ) * sin( theta )
  10818. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10819. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10820. }
  10821. void main() {
  10822. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10823. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10824. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10825. }
  10826. axis = normalize( axis );
  10827. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10828. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10829. for ( int i = 1; i < n; i++ ) {
  10830. if ( i >= samples ) {
  10831. break;
  10832. }
  10833. float theta = dTheta * float( i );
  10834. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10835. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10836. }
  10837. gl_FragColor = linearToOutputTexel( gl_FragColor );
  10838. }
  10839. `,
  10840. blending: NoBlending,
  10841. depthTest: false,
  10842. depthWrite: false
  10843. } );
  10844. return shaderMaterial;
  10845. }
  10846. function _getEquirectShader() {
  10847. const texelSize = new Vector2( 1, 1 );
  10848. const shaderMaterial = new RawShaderMaterial( {
  10849. name: 'EquirectangularToCubeUV',
  10850. uniforms: {
  10851. 'envMap': { value: null },
  10852. 'texelSize': { value: texelSize },
  10853. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  10854. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  10855. },
  10856. vertexShader: _getCommonVertexShader(),
  10857. fragmentShader: /* glsl */`
  10858. precision mediump float;
  10859. precision mediump int;
  10860. varying vec3 vOutputDirection;
  10861. uniform sampler2D envMap;
  10862. uniform vec2 texelSize;
  10863. ${ _getEncodings() }
  10864. #include <common>
  10865. void main() {
  10866. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10867. vec3 outputDirection = normalize( vOutputDirection );
  10868. vec2 uv = equirectUv( outputDirection );
  10869. vec2 f = fract( uv / texelSize - 0.5 );
  10870. uv -= f * texelSize;
  10871. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10872. uv.x += texelSize.x;
  10873. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10874. uv.y += texelSize.y;
  10875. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10876. uv.x -= texelSize.x;
  10877. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  10878. vec3 tm = mix( tl, tr, f.x );
  10879. vec3 bm = mix( bl, br, f.x );
  10880. gl_FragColor.rgb = mix( tm, bm, f.y );
  10881. gl_FragColor = linearToOutputTexel( gl_FragColor );
  10882. }
  10883. `,
  10884. blending: NoBlending,
  10885. depthTest: false,
  10886. depthWrite: false
  10887. } );
  10888. return shaderMaterial;
  10889. }
  10890. function _getCubemapShader() {
  10891. const shaderMaterial = new RawShaderMaterial( {
  10892. name: 'CubemapToCubeUV',
  10893. uniforms: {
  10894. 'envMap': { value: null },
  10895. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  10896. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  10897. },
  10898. vertexShader: _getCommonVertexShader(),
  10899. fragmentShader: /* glsl */`
  10900. precision mediump float;
  10901. precision mediump int;
  10902. varying vec3 vOutputDirection;
  10903. uniform samplerCube envMap;
  10904. ${ _getEncodings() }
  10905. void main() {
  10906. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10907. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  10908. gl_FragColor = linearToOutputTexel( gl_FragColor );
  10909. }
  10910. `,
  10911. blending: NoBlending,
  10912. depthTest: false,
  10913. depthWrite: false
  10914. } );
  10915. return shaderMaterial;
  10916. }
  10917. function _getCommonVertexShader() {
  10918. return /* glsl */`
  10919. precision mediump float;
  10920. precision mediump int;
  10921. attribute vec3 position;
  10922. attribute vec2 uv;
  10923. attribute float faceIndex;
  10924. varying vec3 vOutputDirection;
  10925. // RH coordinate system; PMREM face-indexing convention
  10926. vec3 getDirection( vec2 uv, float face ) {
  10927. uv = 2.0 * uv - 1.0;
  10928. vec3 direction = vec3( uv, 1.0 );
  10929. if ( face == 0.0 ) {
  10930. direction = direction.zyx; // ( 1, v, u ) pos x
  10931. } else if ( face == 1.0 ) {
  10932. direction = direction.xzy;
  10933. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10934. } else if ( face == 2.0 ) {
  10935. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10936. } else if ( face == 3.0 ) {
  10937. direction = direction.zyx;
  10938. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10939. } else if ( face == 4.0 ) {
  10940. direction = direction.xzy;
  10941. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10942. } else if ( face == 5.0 ) {
  10943. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10944. }
  10945. return direction;
  10946. }
  10947. void main() {
  10948. vOutputDirection = getDirection( uv, faceIndex );
  10949. gl_Position = vec4( position, 1.0 );
  10950. }
  10951. `;
  10952. }
  10953. function _getEncodings() {
  10954. return /* glsl */`
  10955. uniform int inputEncoding;
  10956. uniform int outputEncoding;
  10957. #include <encodings_pars_fragment>
  10958. vec4 inputTexelToLinear( vec4 value ) {
  10959. if ( inputEncoding == 0 ) {
  10960. return value;
  10961. } else if ( inputEncoding == 1 ) {
  10962. return sRGBToLinear( value );
  10963. } else if ( inputEncoding == 2 ) {
  10964. return RGBEToLinear( value );
  10965. } else if ( inputEncoding == 3 ) {
  10966. return RGBMToLinear( value, 7.0 );
  10967. } else if ( inputEncoding == 4 ) {
  10968. return RGBMToLinear( value, 16.0 );
  10969. } else if ( inputEncoding == 5 ) {
  10970. return RGBDToLinear( value, 256.0 );
  10971. } else {
  10972. return GammaToLinear( value, 2.2 );
  10973. }
  10974. }
  10975. vec4 linearToOutputTexel( vec4 value ) {
  10976. if ( outputEncoding == 0 ) {
  10977. return value;
  10978. } else if ( outputEncoding == 1 ) {
  10979. return LinearTosRGB( value );
  10980. } else if ( outputEncoding == 2 ) {
  10981. return LinearToRGBE( value );
  10982. } else if ( outputEncoding == 3 ) {
  10983. return LinearToRGBM( value, 7.0 );
  10984. } else if ( outputEncoding == 4 ) {
  10985. return LinearToRGBM( value, 16.0 );
  10986. } else if ( outputEncoding == 5 ) {
  10987. return LinearToRGBD( value, 256.0 );
  10988. } else {
  10989. return LinearToGamma( value, 2.2 );
  10990. }
  10991. }
  10992. vec4 envMapTexelToLinear( vec4 color ) {
  10993. return inputTexelToLinear( color );
  10994. }
  10995. `;
  10996. }
  10997. function WebGLCubeUVMaps( renderer ) {
  10998. let cubeUVmaps = new WeakMap();
  10999. let pmremGenerator = null;
  11000. function get( texture ) {
  11001. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  11002. const mapping = texture.mapping;
  11003. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  11004. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  11005. if ( isEquirectMap || isCubeMap ) {
  11006. // equirect/cube map to cubeUV conversion
  11007. if ( cubeUVmaps.has( texture ) ) {
  11008. return cubeUVmaps.get( texture ).texture;
  11009. } else {
  11010. const image = texture.image;
  11011. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  11012. const currentRenderTarget = renderer.getRenderTarget();
  11013. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  11014. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  11015. cubeUVmaps.set( texture, renderTarget );
  11016. renderer.setRenderTarget( currentRenderTarget );
  11017. texture.addEventListener( 'dispose', onTextureDispose );
  11018. return renderTarget.texture;
  11019. } else {
  11020. // image not yet ready. try the conversion next frame
  11021. return null;
  11022. }
  11023. }
  11024. }
  11025. }
  11026. return texture;
  11027. }
  11028. function isCubeTextureComplete( image ) {
  11029. let count = 0;
  11030. const length = 6;
  11031. for ( let i = 0; i < length; i ++ ) {
  11032. if ( image[ i ] !== undefined ) count ++;
  11033. }
  11034. return count === length;
  11035. }
  11036. function onTextureDispose( event ) {
  11037. const texture = event.target;
  11038. texture.removeEventListener( 'dispose', onTextureDispose );
  11039. const cubemapUV = cubeUVmaps.get( texture );
  11040. if ( cubemapUV !== undefined ) {
  11041. cubeUVmaps.delete( texture );
  11042. cubemapUV.dispose();
  11043. }
  11044. }
  11045. function dispose() {
  11046. cubeUVmaps = new WeakMap();
  11047. if ( pmremGenerator !== null ) {
  11048. pmremGenerator.dispose();
  11049. pmremGenerator = null;
  11050. }
  11051. }
  11052. return {
  11053. get: get,
  11054. dispose: dispose
  11055. };
  11056. }
  11057. function WebGLExtensions( gl ) {
  11058. const extensions = {};
  11059. function getExtension( name ) {
  11060. if ( extensions[ name ] !== undefined ) {
  11061. return extensions[ name ];
  11062. }
  11063. let extension;
  11064. switch ( name ) {
  11065. case 'WEBGL_depth_texture':
  11066. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11067. break;
  11068. case 'EXT_texture_filter_anisotropic':
  11069. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11070. break;
  11071. case 'WEBGL_compressed_texture_s3tc':
  11072. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11073. break;
  11074. case 'WEBGL_compressed_texture_pvrtc':
  11075. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11076. break;
  11077. default:
  11078. extension = gl.getExtension( name );
  11079. }
  11080. extensions[ name ] = extension;
  11081. return extension;
  11082. }
  11083. return {
  11084. has: function ( name ) {
  11085. return getExtension( name ) !== null;
  11086. },
  11087. init: function ( capabilities ) {
  11088. if ( capabilities.isWebGL2 ) {
  11089. getExtension( 'EXT_color_buffer_float' );
  11090. } else {
  11091. getExtension( 'WEBGL_depth_texture' );
  11092. getExtension( 'OES_texture_float' );
  11093. getExtension( 'OES_texture_half_float' );
  11094. getExtension( 'OES_texture_half_float_linear' );
  11095. getExtension( 'OES_standard_derivatives' );
  11096. getExtension( 'OES_element_index_uint' );
  11097. getExtension( 'OES_vertex_array_object' );
  11098. getExtension( 'ANGLE_instanced_arrays' );
  11099. }
  11100. getExtension( 'OES_texture_float_linear' );
  11101. getExtension( 'EXT_color_buffer_half_float' );
  11102. },
  11103. get: function ( name ) {
  11104. const extension = getExtension( name );
  11105. if ( extension === null ) {
  11106. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11107. }
  11108. return extension;
  11109. }
  11110. };
  11111. }
  11112. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  11113. const geometries = {};
  11114. const wireframeAttributes = new WeakMap();
  11115. function onGeometryDispose( event ) {
  11116. const geometry = event.target;
  11117. if ( geometry.index !== null ) {
  11118. attributes.remove( geometry.index );
  11119. }
  11120. for ( const name in geometry.attributes ) {
  11121. attributes.remove( geometry.attributes[ name ] );
  11122. }
  11123. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11124. delete geometries[ geometry.id ];
  11125. const attribute = wireframeAttributes.get( geometry );
  11126. if ( attribute ) {
  11127. attributes.remove( attribute );
  11128. wireframeAttributes.delete( geometry );
  11129. }
  11130. bindingStates.releaseStatesOfGeometry( geometry );
  11131. if ( geometry.isInstancedBufferGeometry === true ) {
  11132. delete geometry._maxInstanceCount;
  11133. }
  11134. //
  11135. info.memory.geometries --;
  11136. }
  11137. function get( object, geometry ) {
  11138. if ( geometries[ geometry.id ] === true ) return geometry;
  11139. geometry.addEventListener( 'dispose', onGeometryDispose );
  11140. geometries[ geometry.id ] = true;
  11141. info.memory.geometries ++;
  11142. return geometry;
  11143. }
  11144. function update( geometry ) {
  11145. const geometryAttributes = geometry.attributes;
  11146. // Updating index buffer in VAO now. See WebGLBindingStates.
  11147. for ( const name in geometryAttributes ) {
  11148. attributes.update( geometryAttributes[ name ], 34962 );
  11149. }
  11150. // morph targets
  11151. const morphAttributes = geometry.morphAttributes;
  11152. for ( const name in morphAttributes ) {
  11153. const array = morphAttributes[ name ];
  11154. for ( let i = 0, l = array.length; i < l; i ++ ) {
  11155. attributes.update( array[ i ], 34962 );
  11156. }
  11157. }
  11158. }
  11159. function updateWireframeAttribute( geometry ) {
  11160. const indices = [];
  11161. const geometryIndex = geometry.index;
  11162. const geometryPosition = geometry.attributes.position;
  11163. let version = 0;
  11164. if ( geometryIndex !== null ) {
  11165. const array = geometryIndex.array;
  11166. version = geometryIndex.version;
  11167. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  11168. const a = array[ i + 0 ];
  11169. const b = array[ i + 1 ];
  11170. const c = array[ i + 2 ];
  11171. indices.push( a, b, b, c, c, a );
  11172. }
  11173. } else {
  11174. const array = geometryPosition.array;
  11175. version = geometryPosition.version;
  11176. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  11177. const a = i + 0;
  11178. const b = i + 1;
  11179. const c = i + 2;
  11180. indices.push( a, b, b, c, c, a );
  11181. }
  11182. }
  11183. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  11184. attribute.version = version;
  11185. // Updating index buffer in VAO now. See WebGLBindingStates
  11186. //
  11187. const previousAttribute = wireframeAttributes.get( geometry );
  11188. if ( previousAttribute ) attributes.remove( previousAttribute );
  11189. //
  11190. wireframeAttributes.set( geometry, attribute );
  11191. }
  11192. function getWireframeAttribute( geometry ) {
  11193. const currentAttribute = wireframeAttributes.get( geometry );
  11194. if ( currentAttribute ) {
  11195. const geometryIndex = geometry.index;
  11196. if ( geometryIndex !== null ) {
  11197. // if the attribute is obsolete, create a new one
  11198. if ( currentAttribute.version < geometryIndex.version ) {
  11199. updateWireframeAttribute( geometry );
  11200. }
  11201. }
  11202. } else {
  11203. updateWireframeAttribute( geometry );
  11204. }
  11205. return wireframeAttributes.get( geometry );
  11206. }
  11207. return {
  11208. get: get,
  11209. update: update,
  11210. getWireframeAttribute: getWireframeAttribute
  11211. };
  11212. }
  11213. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  11214. const isWebGL2 = capabilities.isWebGL2;
  11215. let mode;
  11216. function setMode( value ) {
  11217. mode = value;
  11218. }
  11219. let type, bytesPerElement;
  11220. function setIndex( value ) {
  11221. type = value.type;
  11222. bytesPerElement = value.bytesPerElement;
  11223. }
  11224. function render( start, count ) {
  11225. gl.drawElements( mode, count, type, start * bytesPerElement );
  11226. info.update( count, mode, 1 );
  11227. }
  11228. function renderInstances( start, count, primcount ) {
  11229. if ( primcount === 0 ) return;
  11230. let extension, methodName;
  11231. if ( isWebGL2 ) {
  11232. extension = gl;
  11233. methodName = 'drawElementsInstanced';
  11234. } else {
  11235. extension = extensions.get( 'ANGLE_instanced_arrays' );
  11236. methodName = 'drawElementsInstancedANGLE';
  11237. if ( extension === null ) {
  11238. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11239. return;
  11240. }
  11241. }
  11242. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  11243. info.update( count, mode, primcount );
  11244. }
  11245. //
  11246. this.setMode = setMode;
  11247. this.setIndex = setIndex;
  11248. this.render = render;
  11249. this.renderInstances = renderInstances;
  11250. }
  11251. function WebGLInfo( gl ) {
  11252. const memory = {
  11253. geometries: 0,
  11254. textures: 0
  11255. };
  11256. const render = {
  11257. frame: 0,
  11258. calls: 0,
  11259. triangles: 0,
  11260. points: 0,
  11261. lines: 0
  11262. };
  11263. function update( count, mode, instanceCount ) {
  11264. render.calls ++;
  11265. switch ( mode ) {
  11266. case 4:
  11267. render.triangles += instanceCount * ( count / 3 );
  11268. break;
  11269. case 1:
  11270. render.lines += instanceCount * ( count / 2 );
  11271. break;
  11272. case 3:
  11273. render.lines += instanceCount * ( count - 1 );
  11274. break;
  11275. case 2:
  11276. render.lines += instanceCount * count;
  11277. break;
  11278. case 0:
  11279. render.points += instanceCount * count;
  11280. break;
  11281. default:
  11282. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  11283. break;
  11284. }
  11285. }
  11286. function reset() {
  11287. render.frame ++;
  11288. render.calls = 0;
  11289. render.triangles = 0;
  11290. render.points = 0;
  11291. render.lines = 0;
  11292. }
  11293. return {
  11294. memory: memory,
  11295. render: render,
  11296. programs: null,
  11297. autoReset: true,
  11298. reset: reset,
  11299. update: update
  11300. };
  11301. }
  11302. function numericalSort( a, b ) {
  11303. return a[ 0 ] - b[ 0 ];
  11304. }
  11305. function absNumericalSort( a, b ) {
  11306. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  11307. }
  11308. function WebGLMorphtargets( gl ) {
  11309. const influencesList = {};
  11310. const morphInfluences = new Float32Array( 8 );
  11311. const workInfluences = [];
  11312. for ( let i = 0; i < 8; i ++ ) {
  11313. workInfluences[ i ] = [ i, 0 ];
  11314. }
  11315. function update( object, geometry, material, program ) {
  11316. const objectInfluences = object.morphTargetInfluences;
  11317. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  11318. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  11319. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  11320. let influences = influencesList[ geometry.id ];
  11321. if ( influences === undefined || influences.length !== length ) {
  11322. // initialise list
  11323. influences = [];
  11324. for ( let i = 0; i < length; i ++ ) {
  11325. influences[ i ] = [ i, 0 ];
  11326. }
  11327. influencesList[ geometry.id ] = influences;
  11328. }
  11329. // Collect influences
  11330. for ( let i = 0; i < length; i ++ ) {
  11331. const influence = influences[ i ];
  11332. influence[ 0 ] = i;
  11333. influence[ 1 ] = objectInfluences[ i ];
  11334. }
  11335. influences.sort( absNumericalSort );
  11336. for ( let i = 0; i < 8; i ++ ) {
  11337. if ( i < length && influences[ i ][ 1 ] ) {
  11338. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  11339. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  11340. } else {
  11341. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  11342. workInfluences[ i ][ 1 ] = 0;
  11343. }
  11344. }
  11345. workInfluences.sort( numericalSort );
  11346. const morphTargets = geometry.morphAttributes.position;
  11347. const morphNormals = geometry.morphAttributes.normal;
  11348. let morphInfluencesSum = 0;
  11349. for ( let i = 0; i < 8; i ++ ) {
  11350. const influence = workInfluences[ i ];
  11351. const index = influence[ 0 ];
  11352. const value = influence[ 1 ];
  11353. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  11354. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  11355. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  11356. }
  11357. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  11358. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  11359. }
  11360. morphInfluences[ i ] = value;
  11361. morphInfluencesSum += value;
  11362. } else {
  11363. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  11364. geometry.deleteAttribute( 'morphTarget' + i );
  11365. }
  11366. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  11367. geometry.deleteAttribute( 'morphNormal' + i );
  11368. }
  11369. morphInfluences[ i ] = 0;
  11370. }
  11371. }
  11372. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  11373. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  11374. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  11375. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  11376. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  11377. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  11378. }
  11379. return {
  11380. update: update
  11381. };
  11382. }
  11383. function WebGLObjects( gl, geometries, attributes, info ) {
  11384. let updateMap = new WeakMap();
  11385. function update( object ) {
  11386. const frame = info.render.frame;
  11387. const geometry = object.geometry;
  11388. const buffergeometry = geometries.get( object, geometry );
  11389. // Update once per frame
  11390. if ( updateMap.get( buffergeometry ) !== frame ) {
  11391. geometries.update( buffergeometry );
  11392. updateMap.set( buffergeometry, frame );
  11393. }
  11394. if ( object.isInstancedMesh ) {
  11395. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  11396. object.addEventListener( 'dispose', onInstancedMeshDispose );
  11397. }
  11398. attributes.update( object.instanceMatrix, 34962 );
  11399. if ( object.instanceColor !== null ) {
  11400. attributes.update( object.instanceColor, 34962 );
  11401. }
  11402. }
  11403. return buffergeometry;
  11404. }
  11405. function dispose() {
  11406. updateMap = new WeakMap();
  11407. }
  11408. function onInstancedMeshDispose( event ) {
  11409. const instancedMesh = event.target;
  11410. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  11411. attributes.remove( instancedMesh.instanceMatrix );
  11412. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  11413. }
  11414. return {
  11415. update: update,
  11416. dispose: dispose
  11417. };
  11418. }
  11419. class DataTexture2DArray extends Texture {
  11420. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  11421. super( null );
  11422. this.image = { data, width, height, depth };
  11423. this.magFilter = NearestFilter;
  11424. this.minFilter = NearestFilter;
  11425. this.wrapR = ClampToEdgeWrapping;
  11426. this.generateMipmaps = false;
  11427. this.flipY = false;
  11428. this.unpackAlignment = 1;
  11429. this.needsUpdate = true;
  11430. }
  11431. }
  11432. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11433. class DataTexture3D extends Texture {
  11434. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  11435. // We're going to add .setXXX() methods for setting properties later.
  11436. // Users can still set in DataTexture3D directly.
  11437. //
  11438. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  11439. // texture.anisotropy = 16;
  11440. //
  11441. // See #14839
  11442. super( null );
  11443. this.image = { data, width, height, depth };
  11444. this.magFilter = NearestFilter;
  11445. this.minFilter = NearestFilter;
  11446. this.wrapR = ClampToEdgeWrapping;
  11447. this.generateMipmaps = false;
  11448. this.flipY = false;
  11449. this.unpackAlignment = 1;
  11450. this.needsUpdate = true;
  11451. }
  11452. }
  11453. DataTexture3D.prototype.isDataTexture3D = true;
  11454. /**
  11455. * Uniforms of a program.
  11456. * Those form a tree structure with a special top-level container for the root,
  11457. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11458. *
  11459. *
  11460. * Properties of inner nodes including the top-level container:
  11461. *
  11462. * .seq - array of nested uniforms
  11463. * .map - nested uniforms by name
  11464. *
  11465. *
  11466. * Methods of all nodes except the top-level container:
  11467. *
  11468. * .setValue( gl, value, [textures] )
  11469. *
  11470. * uploads a uniform value(s)
  11471. * the 'textures' parameter is needed for sampler uniforms
  11472. *
  11473. *
  11474. * Static methods of the top-level container (textures factorizations):
  11475. *
  11476. * .upload( gl, seq, values, textures )
  11477. *
  11478. * sets uniforms in 'seq' to 'values[id].value'
  11479. *
  11480. * .seqWithValue( seq, values ) : filteredSeq
  11481. *
  11482. * filters 'seq' entries with corresponding entry in values
  11483. *
  11484. *
  11485. * Methods of the top-level container (textures factorizations):
  11486. *
  11487. * .setValue( gl, name, value, textures )
  11488. *
  11489. * sets uniform with name 'name' to 'value'
  11490. *
  11491. * .setOptional( gl, obj, prop )
  11492. *
  11493. * like .set for an optional property of the object
  11494. *
  11495. */
  11496. const emptyTexture = new Texture();
  11497. const emptyTexture2dArray = new DataTexture2DArray();
  11498. const emptyTexture3d = new DataTexture3D();
  11499. const emptyCubeTexture = new CubeTexture();
  11500. // --- Utilities ---
  11501. // Array Caches (provide typed arrays for temporary by size)
  11502. const arrayCacheF32 = [];
  11503. const arrayCacheI32 = [];
  11504. // Float32Array caches used for uploading Matrix uniforms
  11505. const mat4array = new Float32Array( 16 );
  11506. const mat3array = new Float32Array( 9 );
  11507. const mat2array = new Float32Array( 4 );
  11508. // Flattening for arrays of vectors and matrices
  11509. function flatten( array, nBlocks, blockSize ) {
  11510. const firstElem = array[ 0 ];
  11511. if ( firstElem <= 0 || firstElem > 0 ) return array;
  11512. // unoptimized: ! isNaN( firstElem )
  11513. // see http://jacksondunstan.com/articles/983
  11514. const n = nBlocks * blockSize;
  11515. let r = arrayCacheF32[ n ];
  11516. if ( r === undefined ) {
  11517. r = new Float32Array( n );
  11518. arrayCacheF32[ n ] = r;
  11519. }
  11520. if ( nBlocks !== 0 ) {
  11521. firstElem.toArray( r, 0 );
  11522. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  11523. offset += blockSize;
  11524. array[ i ].toArray( r, offset );
  11525. }
  11526. }
  11527. return r;
  11528. }
  11529. function arraysEqual( a, b ) {
  11530. if ( a.length !== b.length ) return false;
  11531. for ( let i = 0, l = a.length; i < l; i ++ ) {
  11532. if ( a[ i ] !== b[ i ] ) return false;
  11533. }
  11534. return true;
  11535. }
  11536. function copyArray( a, b ) {
  11537. for ( let i = 0, l = b.length; i < l; i ++ ) {
  11538. a[ i ] = b[ i ];
  11539. }
  11540. }
  11541. // Texture unit allocation
  11542. function allocTexUnits( textures, n ) {
  11543. let r = arrayCacheI32[ n ];
  11544. if ( r === undefined ) {
  11545. r = new Int32Array( n );
  11546. arrayCacheI32[ n ] = r;
  11547. }
  11548. for ( let i = 0; i !== n; ++ i ) {
  11549. r[ i ] = textures.allocateTextureUnit();
  11550. }
  11551. return r;
  11552. }
  11553. // --- Setters ---
  11554. // Note: Defining these methods externally, because they come in a bunch
  11555. // and this way their names minify.
  11556. // Single scalar
  11557. function setValueV1f( gl, v ) {
  11558. const cache = this.cache;
  11559. if ( cache[ 0 ] === v ) return;
  11560. gl.uniform1f( this.addr, v );
  11561. cache[ 0 ] = v;
  11562. }
  11563. // Single float vector (from flat array or THREE.VectorN)
  11564. function setValueV2f( gl, v ) {
  11565. const cache = this.cache;
  11566. if ( v.x !== undefined ) {
  11567. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11568. gl.uniform2f( this.addr, v.x, v.y );
  11569. cache[ 0 ] = v.x;
  11570. cache[ 1 ] = v.y;
  11571. }
  11572. } else {
  11573. if ( arraysEqual( cache, v ) ) return;
  11574. gl.uniform2fv( this.addr, v );
  11575. copyArray( cache, v );
  11576. }
  11577. }
  11578. function setValueV3f( gl, v ) {
  11579. const cache = this.cache;
  11580. if ( v.x !== undefined ) {
  11581. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11582. gl.uniform3f( this.addr, v.x, v.y, v.z );
  11583. cache[ 0 ] = v.x;
  11584. cache[ 1 ] = v.y;
  11585. cache[ 2 ] = v.z;
  11586. }
  11587. } else if ( v.r !== undefined ) {
  11588. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  11589. gl.uniform3f( this.addr, v.r, v.g, v.b );
  11590. cache[ 0 ] = v.r;
  11591. cache[ 1 ] = v.g;
  11592. cache[ 2 ] = v.b;
  11593. }
  11594. } else {
  11595. if ( arraysEqual( cache, v ) ) return;
  11596. gl.uniform3fv( this.addr, v );
  11597. copyArray( cache, v );
  11598. }
  11599. }
  11600. function setValueV4f( gl, v ) {
  11601. const cache = this.cache;
  11602. if ( v.x !== undefined ) {
  11603. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11604. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  11605. cache[ 0 ] = v.x;
  11606. cache[ 1 ] = v.y;
  11607. cache[ 2 ] = v.z;
  11608. cache[ 3 ] = v.w;
  11609. }
  11610. } else {
  11611. if ( arraysEqual( cache, v ) ) return;
  11612. gl.uniform4fv( this.addr, v );
  11613. copyArray( cache, v );
  11614. }
  11615. }
  11616. // Single matrix (from flat array or THREE.MatrixN)
  11617. function setValueM2( gl, v ) {
  11618. const cache = this.cache;
  11619. const elements = v.elements;
  11620. if ( elements === undefined ) {
  11621. if ( arraysEqual( cache, v ) ) return;
  11622. gl.uniformMatrix2fv( this.addr, false, v );
  11623. copyArray( cache, v );
  11624. } else {
  11625. if ( arraysEqual( cache, elements ) ) return;
  11626. mat2array.set( elements );
  11627. gl.uniformMatrix2fv( this.addr, false, mat2array );
  11628. copyArray( cache, elements );
  11629. }
  11630. }
  11631. function setValueM3( gl, v ) {
  11632. const cache = this.cache;
  11633. const elements = v.elements;
  11634. if ( elements === undefined ) {
  11635. if ( arraysEqual( cache, v ) ) return;
  11636. gl.uniformMatrix3fv( this.addr, false, v );
  11637. copyArray( cache, v );
  11638. } else {
  11639. if ( arraysEqual( cache, elements ) ) return;
  11640. mat3array.set( elements );
  11641. gl.uniformMatrix3fv( this.addr, false, mat3array );
  11642. copyArray( cache, elements );
  11643. }
  11644. }
  11645. function setValueM4( gl, v ) {
  11646. const cache = this.cache;
  11647. const elements = v.elements;
  11648. if ( elements === undefined ) {
  11649. if ( arraysEqual( cache, v ) ) return;
  11650. gl.uniformMatrix4fv( this.addr, false, v );
  11651. copyArray( cache, v );
  11652. } else {
  11653. if ( arraysEqual( cache, elements ) ) return;
  11654. mat4array.set( elements );
  11655. gl.uniformMatrix4fv( this.addr, false, mat4array );
  11656. copyArray( cache, elements );
  11657. }
  11658. }
  11659. // Single integer / boolean
  11660. function setValueV1i( gl, v ) {
  11661. const cache = this.cache;
  11662. if ( cache[ 0 ] === v ) return;
  11663. gl.uniform1i( this.addr, v );
  11664. cache[ 0 ] = v;
  11665. }
  11666. // Single integer / boolean vector (from flat array)
  11667. function setValueV2i( gl, v ) {
  11668. const cache = this.cache;
  11669. if ( arraysEqual( cache, v ) ) return;
  11670. gl.uniform2iv( this.addr, v );
  11671. copyArray( cache, v );
  11672. }
  11673. function setValueV3i( gl, v ) {
  11674. const cache = this.cache;
  11675. if ( arraysEqual( cache, v ) ) return;
  11676. gl.uniform3iv( this.addr, v );
  11677. copyArray( cache, v );
  11678. }
  11679. function setValueV4i( gl, v ) {
  11680. const cache = this.cache;
  11681. if ( arraysEqual( cache, v ) ) return;
  11682. gl.uniform4iv( this.addr, v );
  11683. copyArray( cache, v );
  11684. }
  11685. // Single unsigned integer
  11686. function setValueV1ui( gl, v ) {
  11687. const cache = this.cache;
  11688. if ( cache[ 0 ] === v ) return;
  11689. gl.uniform1ui( this.addr, v );
  11690. cache[ 0 ] = v;
  11691. }
  11692. // Single unsigned integer vector (from flat array)
  11693. function setValueV2ui( gl, v ) {
  11694. const cache = this.cache;
  11695. if ( arraysEqual( cache, v ) ) return;
  11696. gl.uniform2uiv( this.addr, v );
  11697. copyArray( cache, v );
  11698. }
  11699. function setValueV3ui( gl, v ) {
  11700. const cache = this.cache;
  11701. if ( arraysEqual( cache, v ) ) return;
  11702. gl.uniform3uiv( this.addr, v );
  11703. copyArray( cache, v );
  11704. }
  11705. function setValueV4ui( gl, v ) {
  11706. const cache = this.cache;
  11707. if ( arraysEqual( cache, v ) ) return;
  11708. gl.uniform4uiv( this.addr, v );
  11709. copyArray( cache, v );
  11710. }
  11711. // Single texture (2D / Cube)
  11712. function setValueT1( gl, v, textures ) {
  11713. const cache = this.cache;
  11714. const unit = textures.allocateTextureUnit();
  11715. if ( cache[ 0 ] !== unit ) {
  11716. gl.uniform1i( this.addr, unit );
  11717. cache[ 0 ] = unit;
  11718. }
  11719. textures.safeSetTexture2D( v || emptyTexture, unit );
  11720. }
  11721. function setValueT3D1( gl, v, textures ) {
  11722. const cache = this.cache;
  11723. const unit = textures.allocateTextureUnit();
  11724. if ( cache[ 0 ] !== unit ) {
  11725. gl.uniform1i( this.addr, unit );
  11726. cache[ 0 ] = unit;
  11727. }
  11728. textures.setTexture3D( v || emptyTexture3d, unit );
  11729. }
  11730. function setValueT6( gl, v, textures ) {
  11731. const cache = this.cache;
  11732. const unit = textures.allocateTextureUnit();
  11733. if ( cache[ 0 ] !== unit ) {
  11734. gl.uniform1i( this.addr, unit );
  11735. cache[ 0 ] = unit;
  11736. }
  11737. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  11738. }
  11739. function setValueT2DArray1( gl, v, textures ) {
  11740. const cache = this.cache;
  11741. const unit = textures.allocateTextureUnit();
  11742. if ( cache[ 0 ] !== unit ) {
  11743. gl.uniform1i( this.addr, unit );
  11744. cache[ 0 ] = unit;
  11745. }
  11746. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  11747. }
  11748. // Helper to pick the right setter for the singular case
  11749. function getSingularSetter( type ) {
  11750. switch ( type ) {
  11751. case 0x1406: return setValueV1f; // FLOAT
  11752. case 0x8b50: return setValueV2f; // _VEC2
  11753. case 0x8b51: return setValueV3f; // _VEC3
  11754. case 0x8b52: return setValueV4f; // _VEC4
  11755. case 0x8b5a: return setValueM2; // _MAT2
  11756. case 0x8b5b: return setValueM3; // _MAT3
  11757. case 0x8b5c: return setValueM4; // _MAT4
  11758. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11759. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11760. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11761. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11762. case 0x1405: return setValueV1ui; // UINT
  11763. case 0x8dc6: return setValueV2ui; // _VEC2
  11764. case 0x8dc7: return setValueV3ui; // _VEC3
  11765. case 0x8dc8: return setValueV4ui; // _VEC4
  11766. case 0x8b5e: // SAMPLER_2D
  11767. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11768. case 0x8dca: // INT_SAMPLER_2D
  11769. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11770. case 0x8b62: // SAMPLER_2D_SHADOW
  11771. return setValueT1;
  11772. case 0x8b5f: // SAMPLER_3D
  11773. case 0x8dcb: // INT_SAMPLER_3D
  11774. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11775. return setValueT3D1;
  11776. case 0x8b60: // SAMPLER_CUBE
  11777. case 0x8dcc: // INT_SAMPLER_CUBE
  11778. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11779. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11780. return setValueT6;
  11781. case 0x8dc1: // SAMPLER_2D_ARRAY
  11782. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11783. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11784. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11785. return setValueT2DArray1;
  11786. }
  11787. }
  11788. // Array of scalars
  11789. function setValueV1fArray( gl, v ) {
  11790. gl.uniform1fv( this.addr, v );
  11791. }
  11792. // Array of vectors (from flat array or array of THREE.VectorN)
  11793. function setValueV2fArray( gl, v ) {
  11794. const data = flatten( v, this.size, 2 );
  11795. gl.uniform2fv( this.addr, data );
  11796. }
  11797. function setValueV3fArray( gl, v ) {
  11798. const data = flatten( v, this.size, 3 );
  11799. gl.uniform3fv( this.addr, data );
  11800. }
  11801. function setValueV4fArray( gl, v ) {
  11802. const data = flatten( v, this.size, 4 );
  11803. gl.uniform4fv( this.addr, data );
  11804. }
  11805. // Array of matrices (from flat array or array of THREE.MatrixN)
  11806. function setValueM2Array( gl, v ) {
  11807. const data = flatten( v, this.size, 4 );
  11808. gl.uniformMatrix2fv( this.addr, false, data );
  11809. }
  11810. function setValueM3Array( gl, v ) {
  11811. const data = flatten( v, this.size, 9 );
  11812. gl.uniformMatrix3fv( this.addr, false, data );
  11813. }
  11814. function setValueM4Array( gl, v ) {
  11815. const data = flatten( v, this.size, 16 );
  11816. gl.uniformMatrix4fv( this.addr, false, data );
  11817. }
  11818. // Array of integer / boolean
  11819. function setValueV1iArray( gl, v ) {
  11820. gl.uniform1iv( this.addr, v );
  11821. }
  11822. // Array of integer / boolean vectors (from flat array)
  11823. function setValueV2iArray( gl, v ) {
  11824. gl.uniform2iv( this.addr, v );
  11825. }
  11826. function setValueV3iArray( gl, v ) {
  11827. gl.uniform3iv( this.addr, v );
  11828. }
  11829. function setValueV4iArray( gl, v ) {
  11830. gl.uniform4iv( this.addr, v );
  11831. }
  11832. // Array of unsigned integer
  11833. function setValueV1uiArray( gl, v ) {
  11834. gl.uniform1uiv( this.addr, v );
  11835. }
  11836. // Array of unsigned integer vectors (from flat array)
  11837. function setValueV2uiArray( gl, v ) {
  11838. gl.uniform2uiv( this.addr, v );
  11839. }
  11840. function setValueV3uiArray( gl, v ) {
  11841. gl.uniform3uiv( this.addr, v );
  11842. }
  11843. function setValueV4uiArray( gl, v ) {
  11844. gl.uniform4uiv( this.addr, v );
  11845. }
  11846. // Array of textures (2D / Cube)
  11847. function setValueT1Array( gl, v, textures ) {
  11848. const n = v.length;
  11849. const units = allocTexUnits( textures, n );
  11850. gl.uniform1iv( this.addr, units );
  11851. for ( let i = 0; i !== n; ++ i ) {
  11852. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11853. }
  11854. }
  11855. function setValueT6Array( gl, v, textures ) {
  11856. const n = v.length;
  11857. const units = allocTexUnits( textures, n );
  11858. gl.uniform1iv( this.addr, units );
  11859. for ( let i = 0; i !== n; ++ i ) {
  11860. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11861. }
  11862. }
  11863. // Helper to pick the right setter for a pure (bottom-level) array
  11864. function getPureArraySetter( type ) {
  11865. switch ( type ) {
  11866. case 0x1406: return setValueV1fArray; // FLOAT
  11867. case 0x8b50: return setValueV2fArray; // _VEC2
  11868. case 0x8b51: return setValueV3fArray; // _VEC3
  11869. case 0x8b52: return setValueV4fArray; // _VEC4
  11870. case 0x8b5a: return setValueM2Array; // _MAT2
  11871. case 0x8b5b: return setValueM3Array; // _MAT3
  11872. case 0x8b5c: return setValueM4Array; // _MAT4
  11873. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11874. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11875. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11876. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11877. case 0x1405: return setValueV1uiArray; // UINT
  11878. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11879. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11880. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11881. case 0x8b5e: // SAMPLER_2D
  11882. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11883. case 0x8dca: // INT_SAMPLER_2D
  11884. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11885. case 0x8b62: // SAMPLER_2D_SHADOW
  11886. return setValueT1Array;
  11887. case 0x8b60: // SAMPLER_CUBE
  11888. case 0x8dcc: // INT_SAMPLER_CUBE
  11889. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11890. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11891. return setValueT6Array;
  11892. }
  11893. }
  11894. // --- Uniform Classes ---
  11895. function SingleUniform( id, activeInfo, addr ) {
  11896. this.id = id;
  11897. this.addr = addr;
  11898. this.cache = [];
  11899. this.setValue = getSingularSetter( activeInfo.type );
  11900. // this.path = activeInfo.name; // DEBUG
  11901. }
  11902. function PureArrayUniform( id, activeInfo, addr ) {
  11903. this.id = id;
  11904. this.addr = addr;
  11905. this.cache = [];
  11906. this.size = activeInfo.size;
  11907. this.setValue = getPureArraySetter( activeInfo.type );
  11908. // this.path = activeInfo.name; // DEBUG
  11909. }
  11910. PureArrayUniform.prototype.updateCache = function ( data ) {
  11911. const cache = this.cache;
  11912. if ( data instanceof Float32Array && cache.length !== data.length ) {
  11913. this.cache = new Float32Array( data.length );
  11914. }
  11915. copyArray( cache, data );
  11916. };
  11917. function StructuredUniform( id ) {
  11918. this.id = id;
  11919. this.seq = [];
  11920. this.map = {};
  11921. }
  11922. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  11923. const seq = this.seq;
  11924. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11925. const u = seq[ i ];
  11926. u.setValue( gl, value[ u.id ], textures );
  11927. }
  11928. };
  11929. // --- Top-level ---
  11930. // Parser - builds up the property tree from the path strings
  11931. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11932. // extracts
  11933. // - the identifier (member name or array index)
  11934. // - followed by an optional right bracket (found when array index)
  11935. // - followed by an optional left bracket or dot (type of subscript)
  11936. //
  11937. // Note: These portions can be read in a non-overlapping fashion and
  11938. // allow straightforward parsing of the hierarchy that WebGL encodes
  11939. // in the uniform names.
  11940. function addUniform( container, uniformObject ) {
  11941. container.seq.push( uniformObject );
  11942. container.map[ uniformObject.id ] = uniformObject;
  11943. }
  11944. function parseUniform( activeInfo, addr, container ) {
  11945. const path = activeInfo.name,
  11946. pathLength = path.length;
  11947. // reset RegExp object, because of the early exit of a previous run
  11948. RePathPart.lastIndex = 0;
  11949. while ( true ) {
  11950. const match = RePathPart.exec( path ),
  11951. matchEnd = RePathPart.lastIndex;
  11952. let id = match[ 1 ];
  11953. const idIsIndex = match[ 2 ] === ']',
  11954. subscript = match[ 3 ];
  11955. if ( idIsIndex ) id = id | 0; // convert to integer
  11956. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11957. // bare name or "pure" bottom-level array "[0]" suffix
  11958. addUniform( container, subscript === undefined ?
  11959. new SingleUniform( id, activeInfo, addr ) :
  11960. new PureArrayUniform( id, activeInfo, addr ) );
  11961. break;
  11962. } else {
  11963. // step into inner node / create it in case it doesn't exist
  11964. const map = container.map;
  11965. let next = map[ id ];
  11966. if ( next === undefined ) {
  11967. next = new StructuredUniform( id );
  11968. addUniform( container, next );
  11969. }
  11970. container = next;
  11971. }
  11972. }
  11973. }
  11974. // Root Container
  11975. function WebGLUniforms( gl, program ) {
  11976. this.seq = [];
  11977. this.map = {};
  11978. const n = gl.getProgramParameter( program, 35718 );
  11979. for ( let i = 0; i < n; ++ i ) {
  11980. const info = gl.getActiveUniform( program, i ),
  11981. addr = gl.getUniformLocation( program, info.name );
  11982. parseUniform( info, addr, this );
  11983. }
  11984. }
  11985. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  11986. const u = this.map[ name ];
  11987. if ( u !== undefined ) u.setValue( gl, value, textures );
  11988. };
  11989. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  11990. const v = object[ name ];
  11991. if ( v !== undefined ) this.setValue( gl, name, v );
  11992. };
  11993. // Static interface
  11994. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  11995. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11996. const u = seq[ i ],
  11997. v = values[ u.id ];
  11998. if ( v.needsUpdate !== false ) {
  11999. // note: always updating when .needsUpdate is undefined
  12000. u.setValue( gl, v.value, textures );
  12001. }
  12002. }
  12003. };
  12004. WebGLUniforms.seqWithValue = function ( seq, values ) {
  12005. const r = [];
  12006. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  12007. const u = seq[ i ];
  12008. if ( u.id in values ) r.push( u );
  12009. }
  12010. return r;
  12011. };
  12012. function WebGLShader( gl, type, string ) {
  12013. const shader = gl.createShader( type );
  12014. gl.shaderSource( shader, string );
  12015. gl.compileShader( shader );
  12016. return shader;
  12017. }
  12018. let programIdCount = 0;
  12019. function addLineNumbers( string ) {
  12020. const lines = string.split( '\n' );
  12021. for ( let i = 0; i < lines.length; i ++ ) {
  12022. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  12023. }
  12024. return lines.join( '\n' );
  12025. }
  12026. function getEncodingComponents( encoding ) {
  12027. switch ( encoding ) {
  12028. case LinearEncoding:
  12029. return [ 'Linear', '( value )' ];
  12030. case sRGBEncoding:
  12031. return [ 'sRGB', '( value )' ];
  12032. case RGBEEncoding:
  12033. return [ 'RGBE', '( value )' ];
  12034. case RGBM7Encoding:
  12035. return [ 'RGBM', '( value, 7.0 )' ];
  12036. case RGBM16Encoding:
  12037. return [ 'RGBM', '( value, 16.0 )' ];
  12038. case RGBDEncoding:
  12039. return [ 'RGBD', '( value, 256.0 )' ];
  12040. case GammaEncoding:
  12041. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  12042. case LogLuvEncoding:
  12043. return [ 'LogLuv', '( value )' ];
  12044. default:
  12045. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  12046. return [ 'Linear', '( value )' ];
  12047. }
  12048. }
  12049. function getShaderErrors( gl, shader, type ) {
  12050. const status = gl.getShaderParameter( shader, 35713 );
  12051. const errors = gl.getShaderInfoLog( shader ).trim();
  12052. if ( status && errors === '' ) return '';
  12053. // --enable-privileged-webgl-extension
  12054. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12055. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers( gl.getShaderSource( shader ) );
  12056. }
  12057. function getTexelDecodingFunction( functionName, encoding ) {
  12058. const components = getEncodingComponents( encoding );
  12059. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  12060. }
  12061. function getTexelEncodingFunction( functionName, encoding ) {
  12062. const components = getEncodingComponents( encoding );
  12063. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  12064. }
  12065. function getToneMappingFunction( functionName, toneMapping ) {
  12066. let toneMappingName;
  12067. switch ( toneMapping ) {
  12068. case LinearToneMapping:
  12069. toneMappingName = 'Linear';
  12070. break;
  12071. case ReinhardToneMapping:
  12072. toneMappingName = 'Reinhard';
  12073. break;
  12074. case CineonToneMapping:
  12075. toneMappingName = 'OptimizedCineon';
  12076. break;
  12077. case ACESFilmicToneMapping:
  12078. toneMappingName = 'ACESFilmic';
  12079. break;
  12080. case CustomToneMapping:
  12081. toneMappingName = 'Custom';
  12082. break;
  12083. default:
  12084. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  12085. toneMappingName = 'Linear';
  12086. }
  12087. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  12088. }
  12089. function generateExtensions( parameters ) {
  12090. const chunks = [
  12091. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  12092. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  12093. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  12094. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  12095. ];
  12096. return chunks.filter( filterEmptyLine ).join( '\n' );
  12097. }
  12098. function generateDefines( defines ) {
  12099. const chunks = [];
  12100. for ( const name in defines ) {
  12101. const value = defines[ name ];
  12102. if ( value === false ) continue;
  12103. chunks.push( '#define ' + name + ' ' + value );
  12104. }
  12105. return chunks.join( '\n' );
  12106. }
  12107. function fetchAttributeLocations( gl, program ) {
  12108. const attributes = {};
  12109. const n = gl.getProgramParameter( program, 35721 );
  12110. for ( let i = 0; i < n; i ++ ) {
  12111. const info = gl.getActiveAttrib( program, i );
  12112. const name = info.name;
  12113. let locationSize = 1;
  12114. if ( info.type === 35674 ) locationSize = 2;
  12115. if ( info.type === 35675 ) locationSize = 3;
  12116. if ( info.type === 35676 ) locationSize = 4;
  12117. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  12118. attributes[ name ] = {
  12119. type: info.type,
  12120. location: gl.getAttribLocation( program, name ),
  12121. locationSize: locationSize
  12122. };
  12123. }
  12124. return attributes;
  12125. }
  12126. function filterEmptyLine( string ) {
  12127. return string !== '';
  12128. }
  12129. function replaceLightNums( string, parameters ) {
  12130. return string
  12131. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  12132. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  12133. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  12134. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  12135. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  12136. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  12137. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  12138. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  12139. }
  12140. function replaceClippingPlaneNums( string, parameters ) {
  12141. return string
  12142. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  12143. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  12144. }
  12145. // Resolve Includes
  12146. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  12147. function resolveIncludes( string ) {
  12148. return string.replace( includePattern, includeReplacer );
  12149. }
  12150. function includeReplacer( match, include ) {
  12151. const string = ShaderChunk[ include ];
  12152. if ( string === undefined ) {
  12153. throw new Error( 'Can not resolve #include <' + include + '>' );
  12154. }
  12155. return resolveIncludes( string );
  12156. }
  12157. // Unroll Loops
  12158. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12159. 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;
  12160. function unrollLoops( string ) {
  12161. return string
  12162. .replace( unrollLoopPattern, loopReplacer )
  12163. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  12164. }
  12165. function deprecatedLoopReplacer( match, start, end, snippet ) {
  12166. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  12167. return loopReplacer( match, start, end, snippet );
  12168. }
  12169. function loopReplacer( match, start, end, snippet ) {
  12170. let string = '';
  12171. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  12172. string += snippet
  12173. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  12174. .replace( /UNROLLED_LOOP_INDEX/g, i );
  12175. }
  12176. return string;
  12177. }
  12178. //
  12179. function generatePrecision( parameters ) {
  12180. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  12181. if ( parameters.precision === 'highp' ) {
  12182. precisionstring += '\n#define HIGH_PRECISION';
  12183. } else if ( parameters.precision === 'mediump' ) {
  12184. precisionstring += '\n#define MEDIUM_PRECISION';
  12185. } else if ( parameters.precision === 'lowp' ) {
  12186. precisionstring += '\n#define LOW_PRECISION';
  12187. }
  12188. return precisionstring;
  12189. }
  12190. function generateShadowMapTypeDefine( parameters ) {
  12191. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12192. if ( parameters.shadowMapType === PCFShadowMap ) {
  12193. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12194. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  12195. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12196. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  12197. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  12198. }
  12199. return shadowMapTypeDefine;
  12200. }
  12201. function generateEnvMapTypeDefine( parameters ) {
  12202. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12203. if ( parameters.envMap ) {
  12204. switch ( parameters.envMapMode ) {
  12205. case CubeReflectionMapping:
  12206. case CubeRefractionMapping:
  12207. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12208. break;
  12209. case CubeUVReflectionMapping:
  12210. case CubeUVRefractionMapping:
  12211. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12212. break;
  12213. }
  12214. }
  12215. return envMapTypeDefine;
  12216. }
  12217. function generateEnvMapModeDefine( parameters ) {
  12218. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12219. if ( parameters.envMap ) {
  12220. switch ( parameters.envMapMode ) {
  12221. case CubeRefractionMapping:
  12222. case CubeUVRefractionMapping:
  12223. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12224. break;
  12225. }
  12226. }
  12227. return envMapModeDefine;
  12228. }
  12229. function generateEnvMapBlendingDefine( parameters ) {
  12230. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  12231. if ( parameters.envMap ) {
  12232. switch ( parameters.combine ) {
  12233. case MultiplyOperation:
  12234. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12235. break;
  12236. case MixOperation:
  12237. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12238. break;
  12239. case AddOperation:
  12240. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12241. break;
  12242. }
  12243. }
  12244. return envMapBlendingDefine;
  12245. }
  12246. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  12247. // TODO Send this event to Three.js DevTools
  12248. // console.log( 'WebGLProgram', cacheKey );
  12249. const gl = renderer.getContext();
  12250. const defines = parameters.defines;
  12251. let vertexShader = parameters.vertexShader;
  12252. let fragmentShader = parameters.fragmentShader;
  12253. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  12254. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  12255. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  12256. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  12257. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  12258. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  12259. const customDefines = generateDefines( defines );
  12260. const program = gl.createProgram();
  12261. let prefixVertex, prefixFragment;
  12262. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  12263. if ( parameters.isRawShaderMaterial ) {
  12264. prefixVertex = [
  12265. customDefines
  12266. ].filter( filterEmptyLine ).join( '\n' );
  12267. if ( prefixVertex.length > 0 ) {
  12268. prefixVertex += '\n';
  12269. }
  12270. prefixFragment = [
  12271. customExtensions,
  12272. customDefines
  12273. ].filter( filterEmptyLine ).join( '\n' );
  12274. if ( prefixFragment.length > 0 ) {
  12275. prefixFragment += '\n';
  12276. }
  12277. } else {
  12278. prefixVertex = [
  12279. generatePrecision( parameters ),
  12280. '#define SHADER_NAME ' + parameters.shaderName,
  12281. customDefines,
  12282. parameters.instancing ? '#define USE_INSTANCING' : '',
  12283. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  12284. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  12285. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  12286. '#define MAX_BONES ' + parameters.maxBones,
  12287. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  12288. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  12289. parameters.map ? '#define USE_MAP' : '',
  12290. parameters.envMap ? '#define USE_ENVMAP' : '',
  12291. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12292. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12293. parameters.aoMap ? '#define USE_AOMAP' : '',
  12294. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12295. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12296. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12297. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  12298. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  12299. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12300. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12301. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12302. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  12303. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12304. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  12305. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  12306. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12307. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12308. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12309. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12310. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12311. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12312. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  12313. parameters.vertexColors ? '#define USE_COLOR' : '',
  12314. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12315. parameters.vertexUvs ? '#define USE_UV' : '',
  12316. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  12317. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12318. parameters.skinning ? '#define USE_SKINNING' : '',
  12319. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  12320. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  12321. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  12322. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12323. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12324. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12325. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12326. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  12327. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12328. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12329. 'uniform mat4 modelMatrix;',
  12330. 'uniform mat4 modelViewMatrix;',
  12331. 'uniform mat4 projectionMatrix;',
  12332. 'uniform mat4 viewMatrix;',
  12333. 'uniform mat3 normalMatrix;',
  12334. 'uniform vec3 cameraPosition;',
  12335. 'uniform bool isOrthographic;',
  12336. '#ifdef USE_INSTANCING',
  12337. ' attribute mat4 instanceMatrix;',
  12338. '#endif',
  12339. '#ifdef USE_INSTANCING_COLOR',
  12340. ' attribute vec3 instanceColor;',
  12341. '#endif',
  12342. 'attribute vec3 position;',
  12343. 'attribute vec3 normal;',
  12344. 'attribute vec2 uv;',
  12345. '#ifdef USE_TANGENT',
  12346. ' attribute vec4 tangent;',
  12347. '#endif',
  12348. '#if defined( USE_COLOR_ALPHA )',
  12349. ' attribute vec4 color;',
  12350. '#elif defined( USE_COLOR )',
  12351. ' attribute vec3 color;',
  12352. '#endif',
  12353. '#ifdef USE_MORPHTARGETS',
  12354. ' attribute vec3 morphTarget0;',
  12355. ' attribute vec3 morphTarget1;',
  12356. ' attribute vec3 morphTarget2;',
  12357. ' attribute vec3 morphTarget3;',
  12358. ' #ifdef USE_MORPHNORMALS',
  12359. ' attribute vec3 morphNormal0;',
  12360. ' attribute vec3 morphNormal1;',
  12361. ' attribute vec3 morphNormal2;',
  12362. ' attribute vec3 morphNormal3;',
  12363. ' #else',
  12364. ' attribute vec3 morphTarget4;',
  12365. ' attribute vec3 morphTarget5;',
  12366. ' attribute vec3 morphTarget6;',
  12367. ' attribute vec3 morphTarget7;',
  12368. ' #endif',
  12369. '#endif',
  12370. '#ifdef USE_SKINNING',
  12371. ' attribute vec4 skinIndex;',
  12372. ' attribute vec4 skinWeight;',
  12373. '#endif',
  12374. '\n'
  12375. ].filter( filterEmptyLine ).join( '\n' );
  12376. prefixFragment = [
  12377. customExtensions,
  12378. generatePrecision( parameters ),
  12379. '#define SHADER_NAME ' + parameters.shaderName,
  12380. customDefines,
  12381. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  12382. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  12383. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  12384. parameters.map ? '#define USE_MAP' : '',
  12385. parameters.matcap ? '#define USE_MATCAP' : '',
  12386. parameters.envMap ? '#define USE_ENVMAP' : '',
  12387. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  12388. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12389. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  12390. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12391. parameters.aoMap ? '#define USE_AOMAP' : '',
  12392. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12393. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12394. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12395. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  12396. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  12397. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  12398. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12399. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12400. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12401. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12402. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  12403. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  12404. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12405. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12406. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12407. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  12408. parameters.sheenTint ? '#define USE_SHEEN' : '',
  12409. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12410. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12411. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12412. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  12413. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  12414. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12415. parameters.vertexUvs ? '#define USE_UV' : '',
  12416. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  12417. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12418. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12419. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12420. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12421. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12422. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12423. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  12424. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  12425. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12426. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12427. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  12428. 'uniform mat4 viewMatrix;',
  12429. 'uniform vec3 cameraPosition;',
  12430. 'uniform bool isOrthographic;',
  12431. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  12432. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12433. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  12434. parameters.dithering ? '#define DITHERING' : '',
  12435. parameters.format === RGBFormat ? '#define OPAQUE' : '',
  12436. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  12437. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  12438. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  12439. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  12440. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  12441. parameters.specularTintMap ? getTexelDecodingFunction( 'specularTintMapTexelToLinear', parameters.specularTintMapEncoding ) : '',
  12442. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  12443. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  12444. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  12445. '\n'
  12446. ].filter( filterEmptyLine ).join( '\n' );
  12447. }
  12448. vertexShader = resolveIncludes( vertexShader );
  12449. vertexShader = replaceLightNums( vertexShader, parameters );
  12450. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  12451. fragmentShader = resolveIncludes( fragmentShader );
  12452. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12453. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  12454. vertexShader = unrollLoops( vertexShader );
  12455. fragmentShader = unrollLoops( fragmentShader );
  12456. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  12457. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  12458. versionString = '#version 300 es\n';
  12459. prefixVertex = [
  12460. '#define attribute in',
  12461. '#define varying out',
  12462. '#define texture2D texture'
  12463. ].join( '\n' ) + '\n' + prefixVertex;
  12464. prefixFragment = [
  12465. '#define varying in',
  12466. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  12467. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  12468. '#define gl_FragDepthEXT gl_FragDepth',
  12469. '#define texture2D texture',
  12470. '#define textureCube texture',
  12471. '#define texture2DProj textureProj',
  12472. '#define texture2DLodEXT textureLod',
  12473. '#define texture2DProjLodEXT textureProjLod',
  12474. '#define textureCubeLodEXT textureLod',
  12475. '#define texture2DGradEXT textureGrad',
  12476. '#define texture2DProjGradEXT textureProjGrad',
  12477. '#define textureCubeGradEXT textureGrad'
  12478. ].join( '\n' ) + '\n' + prefixFragment;
  12479. }
  12480. const vertexGlsl = versionString + prefixVertex + vertexShader;
  12481. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  12482. // console.log( '*VERTEX*', vertexGlsl );
  12483. // console.log( '*FRAGMENT*', fragmentGlsl );
  12484. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  12485. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  12486. gl.attachShader( program, glVertexShader );
  12487. gl.attachShader( program, glFragmentShader );
  12488. // Force a particular attribute to index 0.
  12489. if ( parameters.index0AttributeName !== undefined ) {
  12490. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12491. } else if ( parameters.morphTargets === true ) {
  12492. // programs with morphTargets displace position out of attribute 0
  12493. gl.bindAttribLocation( program, 0, 'position' );
  12494. }
  12495. gl.linkProgram( program );
  12496. // check for link errors
  12497. if ( renderer.debug.checkShaderErrors ) {
  12498. const programLog = gl.getProgramInfoLog( program ).trim();
  12499. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12500. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12501. let runnable = true;
  12502. let haveDiagnostics = true;
  12503. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  12504. runnable = false;
  12505. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12506. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12507. console.error(
  12508. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12509. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  12510. 'Program Info Log: ' + programLog + '\n' +
  12511. vertexErrors + '\n' +
  12512. fragmentErrors
  12513. );
  12514. } else if ( programLog !== '' ) {
  12515. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12516. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12517. haveDiagnostics = false;
  12518. }
  12519. if ( haveDiagnostics ) {
  12520. this.diagnostics = {
  12521. runnable: runnable,
  12522. programLog: programLog,
  12523. vertexShader: {
  12524. log: vertexLog,
  12525. prefix: prefixVertex
  12526. },
  12527. fragmentShader: {
  12528. log: fragmentLog,
  12529. prefix: prefixFragment
  12530. }
  12531. };
  12532. }
  12533. }
  12534. // Clean up
  12535. // Crashes in iOS9 and iOS10. #18402
  12536. // gl.detachShader( program, glVertexShader );
  12537. // gl.detachShader( program, glFragmentShader );
  12538. gl.deleteShader( glVertexShader );
  12539. gl.deleteShader( glFragmentShader );
  12540. // set up caching for uniform locations
  12541. let cachedUniforms;
  12542. this.getUniforms = function () {
  12543. if ( cachedUniforms === undefined ) {
  12544. cachedUniforms = new WebGLUniforms( gl, program );
  12545. }
  12546. return cachedUniforms;
  12547. };
  12548. // set up caching for attribute locations
  12549. let cachedAttributes;
  12550. this.getAttributes = function () {
  12551. if ( cachedAttributes === undefined ) {
  12552. cachedAttributes = fetchAttributeLocations( gl, program );
  12553. }
  12554. return cachedAttributes;
  12555. };
  12556. // free resource
  12557. this.destroy = function () {
  12558. bindingStates.releaseStatesOfProgram( this );
  12559. gl.deleteProgram( program );
  12560. this.program = undefined;
  12561. };
  12562. //
  12563. this.name = parameters.shaderName;
  12564. this.id = programIdCount ++;
  12565. this.cacheKey = cacheKey;
  12566. this.usedTimes = 1;
  12567. this.program = program;
  12568. this.vertexShader = glVertexShader;
  12569. this.fragmentShader = glFragmentShader;
  12570. return this;
  12571. }
  12572. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12573. const programs = [];
  12574. const isWebGL2 = capabilities.isWebGL2;
  12575. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12576. const floatVertexTextures = capabilities.floatVertexTextures;
  12577. const maxVertexUniforms = capabilities.maxVertexUniforms;
  12578. const vertexTextures = capabilities.vertexTextures;
  12579. let precision = capabilities.precision;
  12580. const shaderIDs = {
  12581. MeshDepthMaterial: 'depth',
  12582. MeshDistanceMaterial: 'distanceRGBA',
  12583. MeshNormalMaterial: 'normal',
  12584. MeshBasicMaterial: 'basic',
  12585. MeshLambertMaterial: 'lambert',
  12586. MeshPhongMaterial: 'phong',
  12587. MeshToonMaterial: 'toon',
  12588. MeshStandardMaterial: 'physical',
  12589. MeshPhysicalMaterial: 'physical',
  12590. MeshMatcapMaterial: 'matcap',
  12591. LineBasicMaterial: 'basic',
  12592. LineDashedMaterial: 'dashed',
  12593. PointsMaterial: 'points',
  12594. ShadowMaterial: 'shadow',
  12595. SpriteMaterial: 'sprite'
  12596. };
  12597. const parameterNames = [
  12598. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  12599. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  12600. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap',
  12601. 'objectSpaceNormalMap', 'tangentSpaceNormalMap',
  12602. 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap',
  12603. 'displacementMap',
  12604. 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap',
  12605. 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  12606. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  12607. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha',
  12608. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  12609. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  12610. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  12611. 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format',
  12612. 'sheenTint', 'transmission', 'transmissionMap', 'thicknessMap'
  12613. ];
  12614. function getMaxBones( object ) {
  12615. const skeleton = object.skeleton;
  12616. const bones = skeleton.bones;
  12617. if ( floatVertexTextures ) {
  12618. return 1024;
  12619. } else {
  12620. // default for when object is not specified
  12621. // ( for example when prebuilding shader to be used with multiple objects )
  12622. //
  12623. // - leave some extra space for other uniforms
  12624. // - limit here is ANGLE's 254 max uniform vectors
  12625. // (up to 54 should be safe)
  12626. const nVertexUniforms = maxVertexUniforms;
  12627. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12628. const maxBones = Math.min( nVertexMatrices, bones.length );
  12629. if ( maxBones < bones.length ) {
  12630. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  12631. return 0;
  12632. }
  12633. return maxBones;
  12634. }
  12635. }
  12636. function getTextureEncodingFromMap( map ) {
  12637. let encoding;
  12638. if ( map && map.isTexture ) {
  12639. encoding = map.encoding;
  12640. } else if ( map && map.isWebGLRenderTarget ) {
  12641. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  12642. encoding = map.texture.encoding;
  12643. } else {
  12644. encoding = LinearEncoding;
  12645. }
  12646. return encoding;
  12647. }
  12648. function getParameters( material, lights, shadows, scene, object ) {
  12649. const fog = scene.fog;
  12650. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12651. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12652. const shaderID = shaderIDs[ material.type ];
  12653. // heuristics to create shader parameters according to lights in the scene
  12654. // (not to blow over maxLights budget)
  12655. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  12656. if ( material.precision !== null ) {
  12657. precision = capabilities.getMaxPrecision( material.precision );
  12658. if ( precision !== material.precision ) {
  12659. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12660. }
  12661. }
  12662. let vertexShader, fragmentShader;
  12663. if ( shaderID ) {
  12664. const shader = ShaderLib[ shaderID ];
  12665. vertexShader = shader.vertexShader;
  12666. fragmentShader = shader.fragmentShader;
  12667. } else {
  12668. vertexShader = material.vertexShader;
  12669. fragmentShader = material.fragmentShader;
  12670. }
  12671. const currentRenderTarget = renderer.getRenderTarget();
  12672. const useAlphaTest = material.alphaTest > 0;
  12673. const useClearcoat = material.clearcoat > 0;
  12674. const parameters = {
  12675. isWebGL2: isWebGL2,
  12676. shaderID: shaderID,
  12677. shaderName: material.type,
  12678. vertexShader: vertexShader,
  12679. fragmentShader: fragmentShader,
  12680. defines: material.defines,
  12681. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12682. glslVersion: material.glslVersion,
  12683. precision: precision,
  12684. instancing: object.isInstancedMesh === true,
  12685. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  12686. supportsVertexTextures: vertexTextures,
  12687. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  12688. map: !! material.map,
  12689. mapEncoding: getTextureEncodingFromMap( material.map ),
  12690. matcap: !! material.matcap,
  12691. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  12692. envMap: !! envMap,
  12693. envMapMode: envMap && envMap.mapping,
  12694. envMapEncoding: getTextureEncodingFromMap( envMap ),
  12695. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  12696. lightMap: !! material.lightMap,
  12697. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  12698. aoMap: !! material.aoMap,
  12699. emissiveMap: !! material.emissiveMap,
  12700. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  12701. bumpMap: !! material.bumpMap,
  12702. normalMap: !! material.normalMap,
  12703. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12704. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12705. clearcoat: useClearcoat,
  12706. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  12707. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  12708. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  12709. displacementMap: !! material.displacementMap,
  12710. roughnessMap: !! material.roughnessMap,
  12711. metalnessMap: !! material.metalnessMap,
  12712. specularMap: !! material.specularMap,
  12713. specularIntensityMap: !! material.specularIntensityMap,
  12714. specularTintMap: !! material.specularTintMap,
  12715. specularTintMapEncoding: getTextureEncodingFromMap( material.specularTintMap ),
  12716. alphaMap: !! material.alphaMap,
  12717. alphaTest: useAlphaTest,
  12718. gradientMap: !! material.gradientMap,
  12719. sheenTint: ( !! material.sheenTint && ( material.sheenTint.r > 0 || material.sheenTint.g > 0 || material.sheenTint.b > 0 ) ),
  12720. transmission: material.transmission > 0,
  12721. transmissionMap: !! material.transmissionMap,
  12722. thicknessMap: !! material.thicknessMap,
  12723. combine: material.combine,
  12724. vertexTangents: ( !! material.normalMap && !! object.geometry && !! object.geometry.attributes.tangent ),
  12725. vertexColors: material.vertexColors,
  12726. vertexAlphas: material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  12727. 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,
  12728. 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,
  12729. fog: !! fog,
  12730. useFog: material.fog,
  12731. fogExp2: ( fog && fog.isFogExp2 ),
  12732. flatShading: !! material.flatShading,
  12733. sizeAttenuation: material.sizeAttenuation,
  12734. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12735. skinning: object.isSkinnedMesh === true && maxBones > 0,
  12736. maxBones: maxBones,
  12737. useVertexTexture: floatVertexTextures,
  12738. morphTargets: !! object.geometry && !! object.geometry.morphAttributes.position,
  12739. morphNormals: !! object.geometry && !! object.geometry.morphAttributes.normal,
  12740. numDirLights: lights.directional.length,
  12741. numPointLights: lights.point.length,
  12742. numSpotLights: lights.spot.length,
  12743. numRectAreaLights: lights.rectArea.length,
  12744. numHemiLights: lights.hemi.length,
  12745. numDirLightShadows: lights.directionalShadowMap.length,
  12746. numPointLightShadows: lights.pointShadowMap.length,
  12747. numSpotLightShadows: lights.spotShadowMap.length,
  12748. numClippingPlanes: clipping.numPlanes,
  12749. numClipIntersection: clipping.numIntersection,
  12750. format: material.format,
  12751. dithering: material.dithering,
  12752. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12753. shadowMapType: renderer.shadowMap.type,
  12754. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12755. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12756. premultipliedAlpha: material.premultipliedAlpha,
  12757. doubleSided: material.side === DoubleSide,
  12758. flipSided: material.side === BackSide,
  12759. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  12760. index0AttributeName: material.index0AttributeName,
  12761. extensionDerivatives: material.extensions && material.extensions.derivatives,
  12762. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  12763. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  12764. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  12765. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  12766. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12767. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12768. customProgramCacheKey: material.customProgramCacheKey()
  12769. };
  12770. return parameters;
  12771. }
  12772. function getProgramCacheKey( parameters ) {
  12773. const array = [];
  12774. if ( parameters.shaderID ) {
  12775. array.push( parameters.shaderID );
  12776. } else {
  12777. array.push( parameters.fragmentShader );
  12778. array.push( parameters.vertexShader );
  12779. }
  12780. if ( parameters.defines !== undefined ) {
  12781. for ( const name in parameters.defines ) {
  12782. array.push( name );
  12783. array.push( parameters.defines[ name ] );
  12784. }
  12785. }
  12786. if ( parameters.isRawShaderMaterial === false ) {
  12787. for ( let i = 0; i < parameterNames.length; i ++ ) {
  12788. array.push( parameters[ parameterNames[ i ] ] );
  12789. }
  12790. array.push( renderer.outputEncoding );
  12791. array.push( renderer.gammaFactor );
  12792. }
  12793. array.push( parameters.customProgramCacheKey );
  12794. return array.join();
  12795. }
  12796. function getUniforms( material ) {
  12797. const shaderID = shaderIDs[ material.type ];
  12798. let uniforms;
  12799. if ( shaderID ) {
  12800. const shader = ShaderLib[ shaderID ];
  12801. uniforms = UniformsUtils.clone( shader.uniforms );
  12802. } else {
  12803. uniforms = material.uniforms;
  12804. }
  12805. return uniforms;
  12806. }
  12807. function acquireProgram( parameters, cacheKey ) {
  12808. let program;
  12809. // Check if code has been already compiled
  12810. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12811. const preexistingProgram = programs[ p ];
  12812. if ( preexistingProgram.cacheKey === cacheKey ) {
  12813. program = preexistingProgram;
  12814. ++ program.usedTimes;
  12815. break;
  12816. }
  12817. }
  12818. if ( program === undefined ) {
  12819. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12820. programs.push( program );
  12821. }
  12822. return program;
  12823. }
  12824. function releaseProgram( program ) {
  12825. if ( -- program.usedTimes === 0 ) {
  12826. // Remove from unordered set
  12827. const i = programs.indexOf( program );
  12828. programs[ i ] = programs[ programs.length - 1 ];
  12829. programs.pop();
  12830. // Free WebGL resources
  12831. program.destroy();
  12832. }
  12833. }
  12834. return {
  12835. getParameters: getParameters,
  12836. getProgramCacheKey: getProgramCacheKey,
  12837. getUniforms: getUniforms,
  12838. acquireProgram: acquireProgram,
  12839. releaseProgram: releaseProgram,
  12840. // Exposed for resource monitoring & error feedback via renderer.info:
  12841. programs: programs
  12842. };
  12843. }
  12844. function WebGLProperties() {
  12845. let properties = new WeakMap();
  12846. function get( object ) {
  12847. let map = properties.get( object );
  12848. if ( map === undefined ) {
  12849. map = {};
  12850. properties.set( object, map );
  12851. }
  12852. return map;
  12853. }
  12854. function remove( object ) {
  12855. properties.delete( object );
  12856. }
  12857. function update( object, key, value ) {
  12858. properties.get( object )[ key ] = value;
  12859. }
  12860. function dispose() {
  12861. properties = new WeakMap();
  12862. }
  12863. return {
  12864. get: get,
  12865. remove: remove,
  12866. update: update,
  12867. dispose: dispose
  12868. };
  12869. }
  12870. function painterSortStable( a, b ) {
  12871. if ( a.groupOrder !== b.groupOrder ) {
  12872. return a.groupOrder - b.groupOrder;
  12873. } else if ( a.renderOrder !== b.renderOrder ) {
  12874. return a.renderOrder - b.renderOrder;
  12875. } else if ( a.program !== b.program ) {
  12876. return a.program.id - b.program.id;
  12877. } else if ( a.material.id !== b.material.id ) {
  12878. return a.material.id - b.material.id;
  12879. } else if ( a.z !== b.z ) {
  12880. return a.z - b.z;
  12881. } else {
  12882. return a.id - b.id;
  12883. }
  12884. }
  12885. function reversePainterSortStable( a, b ) {
  12886. if ( a.groupOrder !== b.groupOrder ) {
  12887. return a.groupOrder - b.groupOrder;
  12888. } else if ( a.renderOrder !== b.renderOrder ) {
  12889. return a.renderOrder - b.renderOrder;
  12890. } else if ( a.z !== b.z ) {
  12891. return b.z - a.z;
  12892. } else {
  12893. return a.id - b.id;
  12894. }
  12895. }
  12896. function WebGLRenderList( properties ) {
  12897. const renderItems = [];
  12898. let renderItemsIndex = 0;
  12899. const opaque = [];
  12900. const transmissive = [];
  12901. const transparent = [];
  12902. const defaultProgram = { id: - 1 };
  12903. function init() {
  12904. renderItemsIndex = 0;
  12905. opaque.length = 0;
  12906. transmissive.length = 0;
  12907. transparent.length = 0;
  12908. }
  12909. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12910. let renderItem = renderItems[ renderItemsIndex ];
  12911. const materialProperties = properties.get( material );
  12912. if ( renderItem === undefined ) {
  12913. renderItem = {
  12914. id: object.id,
  12915. object: object,
  12916. geometry: geometry,
  12917. material: material,
  12918. program: materialProperties.program || defaultProgram,
  12919. groupOrder: groupOrder,
  12920. renderOrder: object.renderOrder,
  12921. z: z,
  12922. group: group
  12923. };
  12924. renderItems[ renderItemsIndex ] = renderItem;
  12925. } else {
  12926. renderItem.id = object.id;
  12927. renderItem.object = object;
  12928. renderItem.geometry = geometry;
  12929. renderItem.material = material;
  12930. renderItem.program = materialProperties.program || defaultProgram;
  12931. renderItem.groupOrder = groupOrder;
  12932. renderItem.renderOrder = object.renderOrder;
  12933. renderItem.z = z;
  12934. renderItem.group = group;
  12935. }
  12936. renderItemsIndex ++;
  12937. return renderItem;
  12938. }
  12939. function push( object, geometry, material, groupOrder, z, group ) {
  12940. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12941. if ( material.transmission > 0.0 ) {
  12942. transmissive.push( renderItem );
  12943. } else if ( material.transparent === true ) {
  12944. transparent.push( renderItem );
  12945. } else {
  12946. opaque.push( renderItem );
  12947. }
  12948. }
  12949. function unshift( object, geometry, material, groupOrder, z, group ) {
  12950. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12951. if ( material.transmission > 0.0 ) {
  12952. transmissive.unshift( renderItem );
  12953. } else if ( material.transparent === true ) {
  12954. transparent.unshift( renderItem );
  12955. } else {
  12956. opaque.unshift( renderItem );
  12957. }
  12958. }
  12959. function sort( customOpaqueSort, customTransparentSort ) {
  12960. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12961. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12962. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12963. }
  12964. function finish() {
  12965. // Clear references from inactive renderItems in the list
  12966. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12967. const renderItem = renderItems[ i ];
  12968. if ( renderItem.id === null ) break;
  12969. renderItem.id = null;
  12970. renderItem.object = null;
  12971. renderItem.geometry = null;
  12972. renderItem.material = null;
  12973. renderItem.program = null;
  12974. renderItem.group = null;
  12975. }
  12976. }
  12977. return {
  12978. opaque: opaque,
  12979. transmissive: transmissive,
  12980. transparent: transparent,
  12981. init: init,
  12982. push: push,
  12983. unshift: unshift,
  12984. finish: finish,
  12985. sort: sort
  12986. };
  12987. }
  12988. function WebGLRenderLists( properties ) {
  12989. let lists = new WeakMap();
  12990. function get( scene, renderCallDepth ) {
  12991. let list;
  12992. if ( lists.has( scene ) === false ) {
  12993. list = new WebGLRenderList( properties );
  12994. lists.set( scene, [ list ] );
  12995. } else {
  12996. if ( renderCallDepth >= lists.get( scene ).length ) {
  12997. list = new WebGLRenderList( properties );
  12998. lists.get( scene ).push( list );
  12999. } else {
  13000. list = lists.get( scene )[ renderCallDepth ];
  13001. }
  13002. }
  13003. return list;
  13004. }
  13005. function dispose() {
  13006. lists = new WeakMap();
  13007. }
  13008. return {
  13009. get: get,
  13010. dispose: dispose
  13011. };
  13012. }
  13013. function UniformsCache() {
  13014. const lights = {};
  13015. return {
  13016. get: function ( light ) {
  13017. if ( lights[ light.id ] !== undefined ) {
  13018. return lights[ light.id ];
  13019. }
  13020. let uniforms;
  13021. switch ( light.type ) {
  13022. case 'DirectionalLight':
  13023. uniforms = {
  13024. direction: new Vector3(),
  13025. color: new Color()
  13026. };
  13027. break;
  13028. case 'SpotLight':
  13029. uniforms = {
  13030. position: new Vector3(),
  13031. direction: new Vector3(),
  13032. color: new Color(),
  13033. distance: 0,
  13034. coneCos: 0,
  13035. penumbraCos: 0,
  13036. decay: 0
  13037. };
  13038. break;
  13039. case 'PointLight':
  13040. uniforms = {
  13041. position: new Vector3(),
  13042. color: new Color(),
  13043. distance: 0,
  13044. decay: 0
  13045. };
  13046. break;
  13047. case 'HemisphereLight':
  13048. uniforms = {
  13049. direction: new Vector3(),
  13050. skyColor: new Color(),
  13051. groundColor: new Color()
  13052. };
  13053. break;
  13054. case 'RectAreaLight':
  13055. uniforms = {
  13056. color: new Color(),
  13057. position: new Vector3(),
  13058. halfWidth: new Vector3(),
  13059. halfHeight: new Vector3()
  13060. };
  13061. break;
  13062. }
  13063. lights[ light.id ] = uniforms;
  13064. return uniforms;
  13065. }
  13066. };
  13067. }
  13068. function ShadowUniformsCache() {
  13069. const lights = {};
  13070. return {
  13071. get: function ( light ) {
  13072. if ( lights[ light.id ] !== undefined ) {
  13073. return lights[ light.id ];
  13074. }
  13075. let uniforms;
  13076. switch ( light.type ) {
  13077. case 'DirectionalLight':
  13078. uniforms = {
  13079. shadowBias: 0,
  13080. shadowNormalBias: 0,
  13081. shadowRadius: 1,
  13082. shadowMapSize: new Vector2()
  13083. };
  13084. break;
  13085. case 'SpotLight':
  13086. uniforms = {
  13087. shadowBias: 0,
  13088. shadowNormalBias: 0,
  13089. shadowRadius: 1,
  13090. shadowMapSize: new Vector2()
  13091. };
  13092. break;
  13093. case 'PointLight':
  13094. uniforms = {
  13095. shadowBias: 0,
  13096. shadowNormalBias: 0,
  13097. shadowRadius: 1,
  13098. shadowMapSize: new Vector2(),
  13099. shadowCameraNear: 1,
  13100. shadowCameraFar: 1000
  13101. };
  13102. break;
  13103. // TODO (abelnation): set RectAreaLight shadow uniforms
  13104. }
  13105. lights[ light.id ] = uniforms;
  13106. return uniforms;
  13107. }
  13108. };
  13109. }
  13110. let nextVersion = 0;
  13111. function shadowCastingLightsFirst( lightA, lightB ) {
  13112. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  13113. }
  13114. function WebGLLights( extensions, capabilities ) {
  13115. const cache = new UniformsCache();
  13116. const shadowCache = ShadowUniformsCache();
  13117. const state = {
  13118. version: 0,
  13119. hash: {
  13120. directionalLength: - 1,
  13121. pointLength: - 1,
  13122. spotLength: - 1,
  13123. rectAreaLength: - 1,
  13124. hemiLength: - 1,
  13125. numDirectionalShadows: - 1,
  13126. numPointShadows: - 1,
  13127. numSpotShadows: - 1
  13128. },
  13129. ambient: [ 0, 0, 0 ],
  13130. probe: [],
  13131. directional: [],
  13132. directionalShadow: [],
  13133. directionalShadowMap: [],
  13134. directionalShadowMatrix: [],
  13135. spot: [],
  13136. spotShadow: [],
  13137. spotShadowMap: [],
  13138. spotShadowMatrix: [],
  13139. rectArea: [],
  13140. rectAreaLTC1: null,
  13141. rectAreaLTC2: null,
  13142. point: [],
  13143. pointShadow: [],
  13144. pointShadowMap: [],
  13145. pointShadowMatrix: [],
  13146. hemi: []
  13147. };
  13148. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  13149. const vector3 = new Vector3();
  13150. const matrix4 = new Matrix4();
  13151. const matrix42 = new Matrix4();
  13152. function setup( lights, physicallyCorrectLights ) {
  13153. let r = 0, g = 0, b = 0;
  13154. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  13155. let directionalLength = 0;
  13156. let pointLength = 0;
  13157. let spotLength = 0;
  13158. let rectAreaLength = 0;
  13159. let hemiLength = 0;
  13160. let numDirectionalShadows = 0;
  13161. let numPointShadows = 0;
  13162. let numSpotShadows = 0;
  13163. lights.sort( shadowCastingLightsFirst );
  13164. // artist-friendly light intensity scaling factor
  13165. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  13166. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13167. const light = lights[ i ];
  13168. const color = light.color;
  13169. const intensity = light.intensity;
  13170. const distance = light.distance;
  13171. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13172. if ( light.isAmbientLight ) {
  13173. r += color.r * intensity * scaleFactor;
  13174. g += color.g * intensity * scaleFactor;
  13175. b += color.b * intensity * scaleFactor;
  13176. } else if ( light.isLightProbe ) {
  13177. for ( let j = 0; j < 9; j ++ ) {
  13178. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  13179. }
  13180. } else if ( light.isDirectionalLight ) {
  13181. const uniforms = cache.get( light );
  13182. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13183. if ( light.castShadow ) {
  13184. const shadow = light.shadow;
  13185. const shadowUniforms = shadowCache.get( light );
  13186. shadowUniforms.shadowBias = shadow.bias;
  13187. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13188. shadowUniforms.shadowRadius = shadow.radius;
  13189. shadowUniforms.shadowMapSize = shadow.mapSize;
  13190. state.directionalShadow[ directionalLength ] = shadowUniforms;
  13191. state.directionalShadowMap[ directionalLength ] = shadowMap;
  13192. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13193. numDirectionalShadows ++;
  13194. }
  13195. state.directional[ directionalLength ] = uniforms;
  13196. directionalLength ++;
  13197. } else if ( light.isSpotLight ) {
  13198. const uniforms = cache.get( light );
  13199. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13200. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  13201. uniforms.distance = distance;
  13202. uniforms.coneCos = Math.cos( light.angle );
  13203. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13204. uniforms.decay = light.decay;
  13205. if ( light.castShadow ) {
  13206. const shadow = light.shadow;
  13207. const shadowUniforms = shadowCache.get( light );
  13208. shadowUniforms.shadowBias = shadow.bias;
  13209. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13210. shadowUniforms.shadowRadius = shadow.radius;
  13211. shadowUniforms.shadowMapSize = shadow.mapSize;
  13212. state.spotShadow[ spotLength ] = shadowUniforms;
  13213. state.spotShadowMap[ spotLength ] = shadowMap;
  13214. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13215. numSpotShadows ++;
  13216. }
  13217. state.spot[ spotLength ] = uniforms;
  13218. spotLength ++;
  13219. } else if ( light.isRectAreaLight ) {
  13220. const uniforms = cache.get( light );
  13221. // (a) intensity is the total visible light emitted
  13222. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13223. // (b) intensity is the brightness of the light
  13224. uniforms.color.copy( color ).multiplyScalar( intensity );
  13225. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13226. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13227. state.rectArea[ rectAreaLength ] = uniforms;
  13228. rectAreaLength ++;
  13229. } else if ( light.isPointLight ) {
  13230. const uniforms = cache.get( light );
  13231. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13232. uniforms.distance = light.distance;
  13233. uniforms.decay = light.decay;
  13234. if ( light.castShadow ) {
  13235. const shadow = light.shadow;
  13236. const shadowUniforms = shadowCache.get( light );
  13237. shadowUniforms.shadowBias = shadow.bias;
  13238. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13239. shadowUniforms.shadowRadius = shadow.radius;
  13240. shadowUniforms.shadowMapSize = shadow.mapSize;
  13241. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13242. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13243. state.pointShadow[ pointLength ] = shadowUniforms;
  13244. state.pointShadowMap[ pointLength ] = shadowMap;
  13245. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13246. numPointShadows ++;
  13247. }
  13248. state.point[ pointLength ] = uniforms;
  13249. pointLength ++;
  13250. } else if ( light.isHemisphereLight ) {
  13251. const uniforms = cache.get( light );
  13252. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  13253. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  13254. state.hemi[ hemiLength ] = uniforms;
  13255. hemiLength ++;
  13256. }
  13257. }
  13258. if ( rectAreaLength > 0 ) {
  13259. if ( capabilities.isWebGL2 ) {
  13260. // WebGL 2
  13261. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13262. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13263. } else {
  13264. // WebGL 1
  13265. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13266. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13267. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13268. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  13269. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13270. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13271. } else {
  13272. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  13273. }
  13274. }
  13275. }
  13276. state.ambient[ 0 ] = r;
  13277. state.ambient[ 1 ] = g;
  13278. state.ambient[ 2 ] = b;
  13279. const hash = state.hash;
  13280. if ( hash.directionalLength !== directionalLength ||
  13281. hash.pointLength !== pointLength ||
  13282. hash.spotLength !== spotLength ||
  13283. hash.rectAreaLength !== rectAreaLength ||
  13284. hash.hemiLength !== hemiLength ||
  13285. hash.numDirectionalShadows !== numDirectionalShadows ||
  13286. hash.numPointShadows !== numPointShadows ||
  13287. hash.numSpotShadows !== numSpotShadows ) {
  13288. state.directional.length = directionalLength;
  13289. state.spot.length = spotLength;
  13290. state.rectArea.length = rectAreaLength;
  13291. state.point.length = pointLength;
  13292. state.hemi.length = hemiLength;
  13293. state.directionalShadow.length = numDirectionalShadows;
  13294. state.directionalShadowMap.length = numDirectionalShadows;
  13295. state.pointShadow.length = numPointShadows;
  13296. state.pointShadowMap.length = numPointShadows;
  13297. state.spotShadow.length = numSpotShadows;
  13298. state.spotShadowMap.length = numSpotShadows;
  13299. state.directionalShadowMatrix.length = numDirectionalShadows;
  13300. state.pointShadowMatrix.length = numPointShadows;
  13301. state.spotShadowMatrix.length = numSpotShadows;
  13302. hash.directionalLength = directionalLength;
  13303. hash.pointLength = pointLength;
  13304. hash.spotLength = spotLength;
  13305. hash.rectAreaLength = rectAreaLength;
  13306. hash.hemiLength = hemiLength;
  13307. hash.numDirectionalShadows = numDirectionalShadows;
  13308. hash.numPointShadows = numPointShadows;
  13309. hash.numSpotShadows = numSpotShadows;
  13310. state.version = nextVersion ++;
  13311. }
  13312. }
  13313. function setupView( lights, camera ) {
  13314. let directionalLength = 0;
  13315. let pointLength = 0;
  13316. let spotLength = 0;
  13317. let rectAreaLength = 0;
  13318. let hemiLength = 0;
  13319. const viewMatrix = camera.matrixWorldInverse;
  13320. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13321. const light = lights[ i ];
  13322. if ( light.isDirectionalLight ) {
  13323. const uniforms = state.directional[ directionalLength ];
  13324. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13325. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13326. uniforms.direction.sub( vector3 );
  13327. uniforms.direction.transformDirection( viewMatrix );
  13328. directionalLength ++;
  13329. } else if ( light.isSpotLight ) {
  13330. const uniforms = state.spot[ spotLength ];
  13331. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13332. uniforms.position.applyMatrix4( viewMatrix );
  13333. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13334. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13335. uniforms.direction.sub( vector3 );
  13336. uniforms.direction.transformDirection( viewMatrix );
  13337. spotLength ++;
  13338. } else if ( light.isRectAreaLight ) {
  13339. const uniforms = state.rectArea[ rectAreaLength ];
  13340. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13341. uniforms.position.applyMatrix4( viewMatrix );
  13342. // extract local rotation of light to derive width/height half vectors
  13343. matrix42.identity();
  13344. matrix4.copy( light.matrixWorld );
  13345. matrix4.premultiply( viewMatrix );
  13346. matrix42.extractRotation( matrix4 );
  13347. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13348. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13349. uniforms.halfWidth.applyMatrix4( matrix42 );
  13350. uniforms.halfHeight.applyMatrix4( matrix42 );
  13351. rectAreaLength ++;
  13352. } else if ( light.isPointLight ) {
  13353. const uniforms = state.point[ pointLength ];
  13354. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13355. uniforms.position.applyMatrix4( viewMatrix );
  13356. pointLength ++;
  13357. } else if ( light.isHemisphereLight ) {
  13358. const uniforms = state.hemi[ hemiLength ];
  13359. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13360. uniforms.direction.transformDirection( viewMatrix );
  13361. uniforms.direction.normalize();
  13362. hemiLength ++;
  13363. }
  13364. }
  13365. }
  13366. return {
  13367. setup: setup,
  13368. setupView: setupView,
  13369. state: state
  13370. };
  13371. }
  13372. function WebGLRenderState( extensions, capabilities ) {
  13373. const lights = new WebGLLights( extensions, capabilities );
  13374. const lightsArray = [];
  13375. const shadowsArray = [];
  13376. function init() {
  13377. lightsArray.length = 0;
  13378. shadowsArray.length = 0;
  13379. }
  13380. function pushLight( light ) {
  13381. lightsArray.push( light );
  13382. }
  13383. function pushShadow( shadowLight ) {
  13384. shadowsArray.push( shadowLight );
  13385. }
  13386. function setupLights( physicallyCorrectLights ) {
  13387. lights.setup( lightsArray, physicallyCorrectLights );
  13388. }
  13389. function setupLightsView( camera ) {
  13390. lights.setupView( lightsArray, camera );
  13391. }
  13392. const state = {
  13393. lightsArray: lightsArray,
  13394. shadowsArray: shadowsArray,
  13395. lights: lights
  13396. };
  13397. return {
  13398. init: init,
  13399. state: state,
  13400. setupLights: setupLights,
  13401. setupLightsView: setupLightsView,
  13402. pushLight: pushLight,
  13403. pushShadow: pushShadow
  13404. };
  13405. }
  13406. function WebGLRenderStates( extensions, capabilities ) {
  13407. let renderStates = new WeakMap();
  13408. function get( scene, renderCallDepth = 0 ) {
  13409. let renderState;
  13410. if ( renderStates.has( scene ) === false ) {
  13411. renderState = new WebGLRenderState( extensions, capabilities );
  13412. renderStates.set( scene, [ renderState ] );
  13413. } else {
  13414. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  13415. renderState = new WebGLRenderState( extensions, capabilities );
  13416. renderStates.get( scene ).push( renderState );
  13417. } else {
  13418. renderState = renderStates.get( scene )[ renderCallDepth ];
  13419. }
  13420. }
  13421. return renderState;
  13422. }
  13423. function dispose() {
  13424. renderStates = new WeakMap();
  13425. }
  13426. return {
  13427. get: get,
  13428. dispose: dispose
  13429. };
  13430. }
  13431. /**
  13432. * parameters = {
  13433. *
  13434. * opacity: <float>,
  13435. *
  13436. * map: new THREE.Texture( <Image> ),
  13437. *
  13438. * alphaMap: new THREE.Texture( <Image> ),
  13439. *
  13440. * displacementMap: new THREE.Texture( <Image> ),
  13441. * displacementScale: <float>,
  13442. * displacementBias: <float>,
  13443. *
  13444. * wireframe: <boolean>,
  13445. * wireframeLinewidth: <float>
  13446. * }
  13447. */
  13448. class MeshDepthMaterial extends Material {
  13449. constructor( parameters ) {
  13450. super();
  13451. this.type = 'MeshDepthMaterial';
  13452. this.depthPacking = BasicDepthPacking;
  13453. this.map = null;
  13454. this.alphaMap = null;
  13455. this.displacementMap = null;
  13456. this.displacementScale = 1;
  13457. this.displacementBias = 0;
  13458. this.wireframe = false;
  13459. this.wireframeLinewidth = 1;
  13460. this.fog = false;
  13461. this.setValues( parameters );
  13462. }
  13463. copy( source ) {
  13464. super.copy( source );
  13465. this.depthPacking = source.depthPacking;
  13466. this.map = source.map;
  13467. this.alphaMap = source.alphaMap;
  13468. this.displacementMap = source.displacementMap;
  13469. this.displacementScale = source.displacementScale;
  13470. this.displacementBias = source.displacementBias;
  13471. this.wireframe = source.wireframe;
  13472. this.wireframeLinewidth = source.wireframeLinewidth;
  13473. return this;
  13474. }
  13475. }
  13476. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13477. /**
  13478. * parameters = {
  13479. *
  13480. * referencePosition: <float>,
  13481. * nearDistance: <float>,
  13482. * farDistance: <float>,
  13483. *
  13484. * map: new THREE.Texture( <Image> ),
  13485. *
  13486. * alphaMap: new THREE.Texture( <Image> ),
  13487. *
  13488. * displacementMap: new THREE.Texture( <Image> ),
  13489. * displacementScale: <float>,
  13490. * displacementBias: <float>
  13491. *
  13492. * }
  13493. */
  13494. class MeshDistanceMaterial extends Material {
  13495. constructor( parameters ) {
  13496. super();
  13497. this.type = 'MeshDistanceMaterial';
  13498. this.referencePosition = new Vector3();
  13499. this.nearDistance = 1;
  13500. this.farDistance = 1000;
  13501. this.map = null;
  13502. this.alphaMap = null;
  13503. this.displacementMap = null;
  13504. this.displacementScale = 1;
  13505. this.displacementBias = 0;
  13506. this.fog = false;
  13507. this.setValues( parameters );
  13508. }
  13509. copy( source ) {
  13510. super.copy( source );
  13511. this.referencePosition.copy( source.referencePosition );
  13512. this.nearDistance = source.nearDistance;
  13513. this.farDistance = source.farDistance;
  13514. this.map = source.map;
  13515. this.alphaMap = source.alphaMap;
  13516. this.displacementMap = source.displacementMap;
  13517. this.displacementScale = source.displacementScale;
  13518. this.displacementBias = source.displacementBias;
  13519. return this;
  13520. }
  13521. }
  13522. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13523. 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}";
  13524. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13525. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13526. let _frustum = new Frustum();
  13527. const _shadowMapSize = new Vector2(),
  13528. _viewportSize = new Vector2(),
  13529. _viewport = new Vector4(),
  13530. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13531. _distanceMaterial = new MeshDistanceMaterial(),
  13532. _materialCache = {},
  13533. _maxTextureSize = _capabilities.maxTextureSize;
  13534. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  13535. const shadowMaterialVertical = new ShaderMaterial( {
  13536. uniforms: {
  13537. shadow_pass: { value: null },
  13538. resolution: { value: new Vector2() },
  13539. radius: { value: 4.0 },
  13540. samples: { value: 8.0 }
  13541. },
  13542. vertexShader: vsm_vert,
  13543. fragmentShader: vsm_frag
  13544. } );
  13545. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13546. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13547. const fullScreenTri = new BufferGeometry();
  13548. fullScreenTri.setAttribute(
  13549. 'position',
  13550. new BufferAttribute(
  13551. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13552. 3
  13553. )
  13554. );
  13555. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13556. const scope = this;
  13557. this.enabled = false;
  13558. this.autoUpdate = true;
  13559. this.needsUpdate = false;
  13560. this.type = PCFShadowMap;
  13561. this.render = function ( lights, scene, camera ) {
  13562. if ( scope.enabled === false ) return;
  13563. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13564. if ( lights.length === 0 ) return;
  13565. const currentRenderTarget = _renderer.getRenderTarget();
  13566. const activeCubeFace = _renderer.getActiveCubeFace();
  13567. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13568. const _state = _renderer.state;
  13569. // Set GL state for depth map.
  13570. _state.setBlending( NoBlending );
  13571. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13572. _state.buffers.depth.setTest( true );
  13573. _state.setScissorTest( false );
  13574. // render depth map
  13575. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13576. const light = lights[ i ];
  13577. const shadow = light.shadow;
  13578. if ( shadow === undefined ) {
  13579. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13580. continue;
  13581. }
  13582. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13583. _shadowMapSize.copy( shadow.mapSize );
  13584. const shadowFrameExtents = shadow.getFrameExtents();
  13585. _shadowMapSize.multiply( shadowFrameExtents );
  13586. _viewportSize.copy( shadow.mapSize );
  13587. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13588. if ( _shadowMapSize.x > _maxTextureSize ) {
  13589. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13590. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13591. shadow.mapSize.x = _viewportSize.x;
  13592. }
  13593. if ( _shadowMapSize.y > _maxTextureSize ) {
  13594. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13595. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13596. shadow.mapSize.y = _viewportSize.y;
  13597. }
  13598. }
  13599. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  13600. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  13601. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13602. shadow.map.texture.name = light.name + '.shadowMap';
  13603. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13604. shadow.camera.updateProjectionMatrix();
  13605. }
  13606. if ( shadow.map === null ) {
  13607. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  13608. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13609. shadow.map.texture.name = light.name + '.shadowMap';
  13610. shadow.camera.updateProjectionMatrix();
  13611. }
  13612. _renderer.setRenderTarget( shadow.map );
  13613. _renderer.clear();
  13614. const viewportCount = shadow.getViewportCount();
  13615. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13616. const viewport = shadow.getViewport( vp );
  13617. _viewport.set(
  13618. _viewportSize.x * viewport.x,
  13619. _viewportSize.y * viewport.y,
  13620. _viewportSize.x * viewport.z,
  13621. _viewportSize.y * viewport.w
  13622. );
  13623. _state.viewport( _viewport );
  13624. shadow.updateMatrices( light, vp );
  13625. _frustum = shadow.getFrustum();
  13626. renderObject( scene, camera, shadow.camera, light, this.type );
  13627. }
  13628. // do blur pass for VSM
  13629. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  13630. VSMPass( shadow, camera );
  13631. }
  13632. shadow.needsUpdate = false;
  13633. }
  13634. scope.needsUpdate = false;
  13635. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13636. };
  13637. function VSMPass( shadow, camera ) {
  13638. const geometry = _objects.update( fullScreenMesh );
  13639. // vertical pass
  13640. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13641. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13642. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13643. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  13644. _renderer.setRenderTarget( shadow.mapPass );
  13645. _renderer.clear();
  13646. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13647. // horizontal pass
  13648. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13649. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13650. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13651. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  13652. _renderer.setRenderTarget( shadow.map );
  13653. _renderer.clear();
  13654. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13655. }
  13656. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  13657. let result = null;
  13658. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13659. if ( customMaterial !== undefined ) {
  13660. result = customMaterial;
  13661. } else {
  13662. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13663. }
  13664. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) ||
  13665. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13666. ( material.alphaMap && material.alphaTest > 0 ) ) {
  13667. // in this case we need a unique material instance reflecting the
  13668. // appropriate state
  13669. const keyA = result.uuid, keyB = material.uuid;
  13670. let materialsForVariant = _materialCache[ keyA ];
  13671. if ( materialsForVariant === undefined ) {
  13672. materialsForVariant = {};
  13673. _materialCache[ keyA ] = materialsForVariant;
  13674. }
  13675. let cachedMaterial = materialsForVariant[ keyB ];
  13676. if ( cachedMaterial === undefined ) {
  13677. cachedMaterial = result.clone();
  13678. materialsForVariant[ keyB ] = cachedMaterial;
  13679. }
  13680. result = cachedMaterial;
  13681. }
  13682. result.visible = material.visible;
  13683. result.wireframe = material.wireframe;
  13684. if ( type === VSMShadowMap ) {
  13685. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13686. } else {
  13687. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13688. }
  13689. result.alphaMap = material.alphaMap;
  13690. result.alphaTest = material.alphaTest;
  13691. result.clipShadows = material.clipShadows;
  13692. result.clippingPlanes = material.clippingPlanes;
  13693. result.clipIntersection = material.clipIntersection;
  13694. result.displacementMap = material.displacementMap;
  13695. result.displacementScale = material.displacementScale;
  13696. result.displacementBias = material.displacementBias;
  13697. result.wireframeLinewidth = material.wireframeLinewidth;
  13698. result.linewidth = material.linewidth;
  13699. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13700. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  13701. result.nearDistance = shadowCameraNear;
  13702. result.farDistance = shadowCameraFar;
  13703. }
  13704. return result;
  13705. }
  13706. function renderObject( object, camera, shadowCamera, light, type ) {
  13707. if ( object.visible === false ) return;
  13708. const visible = object.layers.test( camera.layers );
  13709. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13710. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13711. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13712. const geometry = _objects.update( object );
  13713. const material = object.material;
  13714. if ( Array.isArray( material ) ) {
  13715. const groups = geometry.groups;
  13716. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13717. const group = groups[ k ];
  13718. const groupMaterial = material[ group.materialIndex ];
  13719. if ( groupMaterial && groupMaterial.visible ) {
  13720. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  13721. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13722. }
  13723. }
  13724. } else if ( material.visible ) {
  13725. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  13726. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13727. }
  13728. }
  13729. }
  13730. const children = object.children;
  13731. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13732. renderObject( children[ i ], camera, shadowCamera, light, type );
  13733. }
  13734. }
  13735. }
  13736. function WebGLState( gl, extensions, capabilities ) {
  13737. const isWebGL2 = capabilities.isWebGL2;
  13738. function ColorBuffer() {
  13739. let locked = false;
  13740. const color = new Vector4();
  13741. let currentColorMask = null;
  13742. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13743. return {
  13744. setMask: function ( colorMask ) {
  13745. if ( currentColorMask !== colorMask && ! locked ) {
  13746. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13747. currentColorMask = colorMask;
  13748. }
  13749. },
  13750. setLocked: function ( lock ) {
  13751. locked = lock;
  13752. },
  13753. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13754. if ( premultipliedAlpha === true ) {
  13755. r *= a; g *= a; b *= a;
  13756. }
  13757. color.set( r, g, b, a );
  13758. if ( currentColorClear.equals( color ) === false ) {
  13759. gl.clearColor( r, g, b, a );
  13760. currentColorClear.copy( color );
  13761. }
  13762. },
  13763. reset: function () {
  13764. locked = false;
  13765. currentColorMask = null;
  13766. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13767. }
  13768. };
  13769. }
  13770. function DepthBuffer() {
  13771. let locked = false;
  13772. let currentDepthMask = null;
  13773. let currentDepthFunc = null;
  13774. let currentDepthClear = null;
  13775. return {
  13776. setTest: function ( depthTest ) {
  13777. if ( depthTest ) {
  13778. enable( 2929 );
  13779. } else {
  13780. disable( 2929 );
  13781. }
  13782. },
  13783. setMask: function ( depthMask ) {
  13784. if ( currentDepthMask !== depthMask && ! locked ) {
  13785. gl.depthMask( depthMask );
  13786. currentDepthMask = depthMask;
  13787. }
  13788. },
  13789. setFunc: function ( depthFunc ) {
  13790. if ( currentDepthFunc !== depthFunc ) {
  13791. if ( depthFunc ) {
  13792. switch ( depthFunc ) {
  13793. case NeverDepth:
  13794. gl.depthFunc( 512 );
  13795. break;
  13796. case AlwaysDepth:
  13797. gl.depthFunc( 519 );
  13798. break;
  13799. case LessDepth:
  13800. gl.depthFunc( 513 );
  13801. break;
  13802. case LessEqualDepth:
  13803. gl.depthFunc( 515 );
  13804. break;
  13805. case EqualDepth:
  13806. gl.depthFunc( 514 );
  13807. break;
  13808. case GreaterEqualDepth:
  13809. gl.depthFunc( 518 );
  13810. break;
  13811. case GreaterDepth:
  13812. gl.depthFunc( 516 );
  13813. break;
  13814. case NotEqualDepth:
  13815. gl.depthFunc( 517 );
  13816. break;
  13817. default:
  13818. gl.depthFunc( 515 );
  13819. }
  13820. } else {
  13821. gl.depthFunc( 515 );
  13822. }
  13823. currentDepthFunc = depthFunc;
  13824. }
  13825. },
  13826. setLocked: function ( lock ) {
  13827. locked = lock;
  13828. },
  13829. setClear: function ( depth ) {
  13830. if ( currentDepthClear !== depth ) {
  13831. gl.clearDepth( depth );
  13832. currentDepthClear = depth;
  13833. }
  13834. },
  13835. reset: function () {
  13836. locked = false;
  13837. currentDepthMask = null;
  13838. currentDepthFunc = null;
  13839. currentDepthClear = null;
  13840. }
  13841. };
  13842. }
  13843. function StencilBuffer() {
  13844. let locked = false;
  13845. let currentStencilMask = null;
  13846. let currentStencilFunc = null;
  13847. let currentStencilRef = null;
  13848. let currentStencilFuncMask = null;
  13849. let currentStencilFail = null;
  13850. let currentStencilZFail = null;
  13851. let currentStencilZPass = null;
  13852. let currentStencilClear = null;
  13853. return {
  13854. setTest: function ( stencilTest ) {
  13855. if ( ! locked ) {
  13856. if ( stencilTest ) {
  13857. enable( 2960 );
  13858. } else {
  13859. disable( 2960 );
  13860. }
  13861. }
  13862. },
  13863. setMask: function ( stencilMask ) {
  13864. if ( currentStencilMask !== stencilMask && ! locked ) {
  13865. gl.stencilMask( stencilMask );
  13866. currentStencilMask = stencilMask;
  13867. }
  13868. },
  13869. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13870. if ( currentStencilFunc !== stencilFunc ||
  13871. currentStencilRef !== stencilRef ||
  13872. currentStencilFuncMask !== stencilMask ) {
  13873. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13874. currentStencilFunc = stencilFunc;
  13875. currentStencilRef = stencilRef;
  13876. currentStencilFuncMask = stencilMask;
  13877. }
  13878. },
  13879. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13880. if ( currentStencilFail !== stencilFail ||
  13881. currentStencilZFail !== stencilZFail ||
  13882. currentStencilZPass !== stencilZPass ) {
  13883. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13884. currentStencilFail = stencilFail;
  13885. currentStencilZFail = stencilZFail;
  13886. currentStencilZPass = stencilZPass;
  13887. }
  13888. },
  13889. setLocked: function ( lock ) {
  13890. locked = lock;
  13891. },
  13892. setClear: function ( stencil ) {
  13893. if ( currentStencilClear !== stencil ) {
  13894. gl.clearStencil( stencil );
  13895. currentStencilClear = stencil;
  13896. }
  13897. },
  13898. reset: function () {
  13899. locked = false;
  13900. currentStencilMask = null;
  13901. currentStencilFunc = null;
  13902. currentStencilRef = null;
  13903. currentStencilFuncMask = null;
  13904. currentStencilFail = null;
  13905. currentStencilZFail = null;
  13906. currentStencilZPass = null;
  13907. currentStencilClear = null;
  13908. }
  13909. };
  13910. }
  13911. //
  13912. const colorBuffer = new ColorBuffer();
  13913. const depthBuffer = new DepthBuffer();
  13914. const stencilBuffer = new StencilBuffer();
  13915. let enabledCapabilities = {};
  13916. let xrFramebuffer = null;
  13917. let currentBoundFramebuffers = {};
  13918. let currentProgram = null;
  13919. let currentBlendingEnabled = false;
  13920. let currentBlending = null;
  13921. let currentBlendEquation = null;
  13922. let currentBlendSrc = null;
  13923. let currentBlendDst = null;
  13924. let currentBlendEquationAlpha = null;
  13925. let currentBlendSrcAlpha = null;
  13926. let currentBlendDstAlpha = null;
  13927. let currentPremultipledAlpha = false;
  13928. let currentFlipSided = null;
  13929. let currentCullFace = null;
  13930. let currentLineWidth = null;
  13931. let currentPolygonOffsetFactor = null;
  13932. let currentPolygonOffsetUnits = null;
  13933. const maxTextures = gl.getParameter( 35661 );
  13934. let lineWidthAvailable = false;
  13935. let version = 0;
  13936. const glVersion = gl.getParameter( 7938 );
  13937. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13938. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13939. lineWidthAvailable = ( version >= 1.0 );
  13940. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13941. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13942. lineWidthAvailable = ( version >= 2.0 );
  13943. }
  13944. let currentTextureSlot = null;
  13945. let currentBoundTextures = {};
  13946. const scissorParam = gl.getParameter( 3088 );
  13947. const viewportParam = gl.getParameter( 2978 );
  13948. const currentScissor = new Vector4().fromArray( scissorParam );
  13949. const currentViewport = new Vector4().fromArray( viewportParam );
  13950. function createTexture( type, target, count ) {
  13951. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13952. const texture = gl.createTexture();
  13953. gl.bindTexture( type, texture );
  13954. gl.texParameteri( type, 10241, 9728 );
  13955. gl.texParameteri( type, 10240, 9728 );
  13956. for ( let i = 0; i < count; i ++ ) {
  13957. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13958. }
  13959. return texture;
  13960. }
  13961. const emptyTextures = {};
  13962. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13963. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13964. // init
  13965. colorBuffer.setClear( 0, 0, 0, 1 );
  13966. depthBuffer.setClear( 1 );
  13967. stencilBuffer.setClear( 0 );
  13968. enable( 2929 );
  13969. depthBuffer.setFunc( LessEqualDepth );
  13970. setFlipSided( false );
  13971. setCullFace( CullFaceBack );
  13972. enable( 2884 );
  13973. setBlending( NoBlending );
  13974. //
  13975. function enable( id ) {
  13976. if ( enabledCapabilities[ id ] !== true ) {
  13977. gl.enable( id );
  13978. enabledCapabilities[ id ] = true;
  13979. }
  13980. }
  13981. function disable( id ) {
  13982. if ( enabledCapabilities[ id ] !== false ) {
  13983. gl.disable( id );
  13984. enabledCapabilities[ id ] = false;
  13985. }
  13986. }
  13987. function bindXRFramebuffer( framebuffer ) {
  13988. if ( framebuffer !== xrFramebuffer ) {
  13989. gl.bindFramebuffer( 36160, framebuffer );
  13990. xrFramebuffer = framebuffer;
  13991. }
  13992. }
  13993. function bindFramebuffer( target, framebuffer ) {
  13994. if ( framebuffer === null && xrFramebuffer !== null ) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  13995. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13996. gl.bindFramebuffer( target, framebuffer );
  13997. currentBoundFramebuffers[ target ] = framebuffer;
  13998. if ( isWebGL2 ) {
  13999. // 36009 is equivalent to 36160
  14000. if ( target === 36009 ) {
  14001. currentBoundFramebuffers[ 36160 ] = framebuffer;
  14002. }
  14003. if ( target === 36160 ) {
  14004. currentBoundFramebuffers[ 36009 ] = framebuffer;
  14005. }
  14006. }
  14007. return true;
  14008. }
  14009. return false;
  14010. }
  14011. function useProgram( program ) {
  14012. if ( currentProgram !== program ) {
  14013. gl.useProgram( program );
  14014. currentProgram = program;
  14015. return true;
  14016. }
  14017. return false;
  14018. }
  14019. const equationToGL = {
  14020. [ AddEquation ]: 32774,
  14021. [ SubtractEquation ]: 32778,
  14022. [ ReverseSubtractEquation ]: 32779
  14023. };
  14024. if ( isWebGL2 ) {
  14025. equationToGL[ MinEquation ] = 32775;
  14026. equationToGL[ MaxEquation ] = 32776;
  14027. } else {
  14028. const extension = extensions.get( 'EXT_blend_minmax' );
  14029. if ( extension !== null ) {
  14030. equationToGL[ MinEquation ] = extension.MIN_EXT;
  14031. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  14032. }
  14033. }
  14034. const factorToGL = {
  14035. [ ZeroFactor ]: 0,
  14036. [ OneFactor ]: 1,
  14037. [ SrcColorFactor ]: 768,
  14038. [ SrcAlphaFactor ]: 770,
  14039. [ SrcAlphaSaturateFactor ]: 776,
  14040. [ DstColorFactor ]: 774,
  14041. [ DstAlphaFactor ]: 772,
  14042. [ OneMinusSrcColorFactor ]: 769,
  14043. [ OneMinusSrcAlphaFactor ]: 771,
  14044. [ OneMinusDstColorFactor ]: 775,
  14045. [ OneMinusDstAlphaFactor ]: 773
  14046. };
  14047. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  14048. if ( blending === NoBlending ) {
  14049. if ( currentBlendingEnabled === true ) {
  14050. disable( 3042 );
  14051. currentBlendingEnabled = false;
  14052. }
  14053. return;
  14054. }
  14055. if ( currentBlendingEnabled === false ) {
  14056. enable( 3042 );
  14057. currentBlendingEnabled = true;
  14058. }
  14059. if ( blending !== CustomBlending ) {
  14060. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  14061. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  14062. gl.blendEquation( 32774 );
  14063. currentBlendEquation = AddEquation;
  14064. currentBlendEquationAlpha = AddEquation;
  14065. }
  14066. if ( premultipliedAlpha ) {
  14067. switch ( blending ) {
  14068. case NormalBlending:
  14069. gl.blendFuncSeparate( 1, 771, 1, 771 );
  14070. break;
  14071. case AdditiveBlending:
  14072. gl.blendFunc( 1, 1 );
  14073. break;
  14074. case SubtractiveBlending:
  14075. gl.blendFuncSeparate( 0, 0, 769, 771 );
  14076. break;
  14077. case MultiplyBlending:
  14078. gl.blendFuncSeparate( 0, 768, 0, 770 );
  14079. break;
  14080. default:
  14081. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14082. break;
  14083. }
  14084. } else {
  14085. switch ( blending ) {
  14086. case NormalBlending:
  14087. gl.blendFuncSeparate( 770, 771, 1, 771 );
  14088. break;
  14089. case AdditiveBlending:
  14090. gl.blendFunc( 770, 1 );
  14091. break;
  14092. case SubtractiveBlending:
  14093. gl.blendFunc( 0, 769 );
  14094. break;
  14095. case MultiplyBlending:
  14096. gl.blendFunc( 0, 768 );
  14097. break;
  14098. default:
  14099. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14100. break;
  14101. }
  14102. }
  14103. currentBlendSrc = null;
  14104. currentBlendDst = null;
  14105. currentBlendSrcAlpha = null;
  14106. currentBlendDstAlpha = null;
  14107. currentBlending = blending;
  14108. currentPremultipledAlpha = premultipliedAlpha;
  14109. }
  14110. return;
  14111. }
  14112. // custom blending
  14113. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14114. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14115. blendDstAlpha = blendDstAlpha || blendDst;
  14116. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14117. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  14118. currentBlendEquation = blendEquation;
  14119. currentBlendEquationAlpha = blendEquationAlpha;
  14120. }
  14121. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14122. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  14123. currentBlendSrc = blendSrc;
  14124. currentBlendDst = blendDst;
  14125. currentBlendSrcAlpha = blendSrcAlpha;
  14126. currentBlendDstAlpha = blendDstAlpha;
  14127. }
  14128. currentBlending = blending;
  14129. currentPremultipledAlpha = null;
  14130. }
  14131. function setMaterial( material, frontFaceCW ) {
  14132. material.side === DoubleSide
  14133. ? disable( 2884 )
  14134. : enable( 2884 );
  14135. let flipSided = ( material.side === BackSide );
  14136. if ( frontFaceCW ) flipSided = ! flipSided;
  14137. setFlipSided( flipSided );
  14138. ( material.blending === NormalBlending && material.transparent === false )
  14139. ? setBlending( NoBlending )
  14140. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  14141. depthBuffer.setFunc( material.depthFunc );
  14142. depthBuffer.setTest( material.depthTest );
  14143. depthBuffer.setMask( material.depthWrite );
  14144. colorBuffer.setMask( material.colorWrite );
  14145. const stencilWrite = material.stencilWrite;
  14146. stencilBuffer.setTest( stencilWrite );
  14147. if ( stencilWrite ) {
  14148. stencilBuffer.setMask( material.stencilWriteMask );
  14149. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  14150. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  14151. }
  14152. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14153. material.alphaToCoverage === true
  14154. ? enable( 32926 )
  14155. : disable( 32926 );
  14156. }
  14157. //
  14158. function setFlipSided( flipSided ) {
  14159. if ( currentFlipSided !== flipSided ) {
  14160. if ( flipSided ) {
  14161. gl.frontFace( 2304 );
  14162. } else {
  14163. gl.frontFace( 2305 );
  14164. }
  14165. currentFlipSided = flipSided;
  14166. }
  14167. }
  14168. function setCullFace( cullFace ) {
  14169. if ( cullFace !== CullFaceNone ) {
  14170. enable( 2884 );
  14171. if ( cullFace !== currentCullFace ) {
  14172. if ( cullFace === CullFaceBack ) {
  14173. gl.cullFace( 1029 );
  14174. } else if ( cullFace === CullFaceFront ) {
  14175. gl.cullFace( 1028 );
  14176. } else {
  14177. gl.cullFace( 1032 );
  14178. }
  14179. }
  14180. } else {
  14181. disable( 2884 );
  14182. }
  14183. currentCullFace = cullFace;
  14184. }
  14185. function setLineWidth( width ) {
  14186. if ( width !== currentLineWidth ) {
  14187. if ( lineWidthAvailable ) gl.lineWidth( width );
  14188. currentLineWidth = width;
  14189. }
  14190. }
  14191. function setPolygonOffset( polygonOffset, factor, units ) {
  14192. if ( polygonOffset ) {
  14193. enable( 32823 );
  14194. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14195. gl.polygonOffset( factor, units );
  14196. currentPolygonOffsetFactor = factor;
  14197. currentPolygonOffsetUnits = units;
  14198. }
  14199. } else {
  14200. disable( 32823 );
  14201. }
  14202. }
  14203. function setScissorTest( scissorTest ) {
  14204. if ( scissorTest ) {
  14205. enable( 3089 );
  14206. } else {
  14207. disable( 3089 );
  14208. }
  14209. }
  14210. // texture
  14211. function activeTexture( webglSlot ) {
  14212. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  14213. if ( currentTextureSlot !== webglSlot ) {
  14214. gl.activeTexture( webglSlot );
  14215. currentTextureSlot = webglSlot;
  14216. }
  14217. }
  14218. function bindTexture( webglType, webglTexture ) {
  14219. if ( currentTextureSlot === null ) {
  14220. activeTexture();
  14221. }
  14222. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  14223. if ( boundTexture === undefined ) {
  14224. boundTexture = { type: undefined, texture: undefined };
  14225. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  14226. }
  14227. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14228. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14229. boundTexture.type = webglType;
  14230. boundTexture.texture = webglTexture;
  14231. }
  14232. }
  14233. function unbindTexture() {
  14234. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14235. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14236. gl.bindTexture( boundTexture.type, null );
  14237. boundTexture.type = undefined;
  14238. boundTexture.texture = undefined;
  14239. }
  14240. }
  14241. function compressedTexImage2D() {
  14242. try {
  14243. gl.compressedTexImage2D.apply( gl, arguments );
  14244. } catch ( error ) {
  14245. console.error( 'THREE.WebGLState:', error );
  14246. }
  14247. }
  14248. function texImage2D() {
  14249. try {
  14250. gl.texImage2D.apply( gl, arguments );
  14251. } catch ( error ) {
  14252. console.error( 'THREE.WebGLState:', error );
  14253. }
  14254. }
  14255. function texImage3D() {
  14256. try {
  14257. gl.texImage3D.apply( gl, arguments );
  14258. } catch ( error ) {
  14259. console.error( 'THREE.WebGLState:', error );
  14260. }
  14261. }
  14262. //
  14263. function scissor( scissor ) {
  14264. if ( currentScissor.equals( scissor ) === false ) {
  14265. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14266. currentScissor.copy( scissor );
  14267. }
  14268. }
  14269. function viewport( viewport ) {
  14270. if ( currentViewport.equals( viewport ) === false ) {
  14271. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14272. currentViewport.copy( viewport );
  14273. }
  14274. }
  14275. //
  14276. function reset() {
  14277. // reset state
  14278. gl.disable( 3042 );
  14279. gl.disable( 2884 );
  14280. gl.disable( 2929 );
  14281. gl.disable( 32823 );
  14282. gl.disable( 3089 );
  14283. gl.disable( 2960 );
  14284. gl.disable( 32926 );
  14285. gl.blendEquation( 32774 );
  14286. gl.blendFunc( 1, 0 );
  14287. gl.blendFuncSeparate( 1, 0, 1, 0 );
  14288. gl.colorMask( true, true, true, true );
  14289. gl.clearColor( 0, 0, 0, 0 );
  14290. gl.depthMask( true );
  14291. gl.depthFunc( 513 );
  14292. gl.clearDepth( 1 );
  14293. gl.stencilMask( 0xffffffff );
  14294. gl.stencilFunc( 519, 0, 0xffffffff );
  14295. gl.stencilOp( 7680, 7680, 7680 );
  14296. gl.clearStencil( 0 );
  14297. gl.cullFace( 1029 );
  14298. gl.frontFace( 2305 );
  14299. gl.polygonOffset( 0, 0 );
  14300. gl.activeTexture( 33984 );
  14301. gl.bindFramebuffer( 36160, null );
  14302. if ( isWebGL2 === true ) {
  14303. gl.bindFramebuffer( 36009, null );
  14304. gl.bindFramebuffer( 36008, null );
  14305. }
  14306. gl.useProgram( null );
  14307. gl.lineWidth( 1 );
  14308. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14309. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14310. // reset internals
  14311. enabledCapabilities = {};
  14312. currentTextureSlot = null;
  14313. currentBoundTextures = {};
  14314. xrFramebuffer = null;
  14315. currentBoundFramebuffers = {};
  14316. currentProgram = null;
  14317. currentBlendingEnabled = false;
  14318. currentBlending = null;
  14319. currentBlendEquation = null;
  14320. currentBlendSrc = null;
  14321. currentBlendDst = null;
  14322. currentBlendEquationAlpha = null;
  14323. currentBlendSrcAlpha = null;
  14324. currentBlendDstAlpha = null;
  14325. currentPremultipledAlpha = false;
  14326. currentFlipSided = null;
  14327. currentCullFace = null;
  14328. currentLineWidth = null;
  14329. currentPolygonOffsetFactor = null;
  14330. currentPolygonOffsetUnits = null;
  14331. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14332. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14333. colorBuffer.reset();
  14334. depthBuffer.reset();
  14335. stencilBuffer.reset();
  14336. }
  14337. return {
  14338. buffers: {
  14339. color: colorBuffer,
  14340. depth: depthBuffer,
  14341. stencil: stencilBuffer
  14342. },
  14343. enable: enable,
  14344. disable: disable,
  14345. bindFramebuffer: bindFramebuffer,
  14346. bindXRFramebuffer: bindXRFramebuffer,
  14347. useProgram: useProgram,
  14348. setBlending: setBlending,
  14349. setMaterial: setMaterial,
  14350. setFlipSided: setFlipSided,
  14351. setCullFace: setCullFace,
  14352. setLineWidth: setLineWidth,
  14353. setPolygonOffset: setPolygonOffset,
  14354. setScissorTest: setScissorTest,
  14355. activeTexture: activeTexture,
  14356. bindTexture: bindTexture,
  14357. unbindTexture: unbindTexture,
  14358. compressedTexImage2D: compressedTexImage2D,
  14359. texImage2D: texImage2D,
  14360. texImage3D: texImage3D,
  14361. scissor: scissor,
  14362. viewport: viewport,
  14363. reset: reset
  14364. };
  14365. }
  14366. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14367. const isWebGL2 = capabilities.isWebGL2;
  14368. const maxTextures = capabilities.maxTextures;
  14369. const maxCubemapSize = capabilities.maxCubemapSize;
  14370. const maxTextureSize = capabilities.maxTextureSize;
  14371. const maxSamples = capabilities.maxSamples;
  14372. const _videoTextures = new WeakMap();
  14373. let _canvas;
  14374. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14375. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14376. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14377. let useOffscreenCanvas = false;
  14378. try {
  14379. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14380. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14381. } catch ( err ) {
  14382. // Ignore any errors
  14383. }
  14384. function createCanvas( width, height ) {
  14385. // Use OffscreenCanvas when available. Specially needed in web workers
  14386. return useOffscreenCanvas ?
  14387. new OffscreenCanvas( width, height ) :
  14388. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14389. }
  14390. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14391. let scale = 1;
  14392. // handle case if texture exceeds max size
  14393. if ( image.width > maxSize || image.height > maxSize ) {
  14394. scale = maxSize / Math.max( image.width, image.height );
  14395. }
  14396. // only perform resize if necessary
  14397. if ( scale < 1 || needsPowerOfTwo === true ) {
  14398. // only perform resize for certain image types
  14399. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14400. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14401. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14402. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14403. const width = floor( scale * image.width );
  14404. const height = floor( scale * image.height );
  14405. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14406. // cube textures can't reuse the same canvas
  14407. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14408. canvas.width = width;
  14409. canvas.height = height;
  14410. const context = canvas.getContext( '2d' );
  14411. context.drawImage( image, 0, 0, width, height );
  14412. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14413. return canvas;
  14414. } else {
  14415. if ( 'data' in image ) {
  14416. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14417. }
  14418. return image;
  14419. }
  14420. }
  14421. return image;
  14422. }
  14423. function isPowerOfTwo$1( image ) {
  14424. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14425. }
  14426. function textureNeedsPowerOfTwo( texture ) {
  14427. if ( isWebGL2 ) return false;
  14428. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14429. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14430. }
  14431. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14432. return texture.generateMipmaps && supportsMips &&
  14433. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14434. }
  14435. function generateMipmap( target, texture, width, height, depth = 1 ) {
  14436. _gl.generateMipmap( target );
  14437. const textureProperties = properties.get( texture );
  14438. textureProperties.__maxMipLevel = Math.log2( Math.max( width, height, depth ) );
  14439. }
  14440. function getInternalFormat( internalFormatName, glFormat, glType ) {
  14441. if ( isWebGL2 === false ) return glFormat;
  14442. if ( internalFormatName !== null ) {
  14443. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14444. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14445. }
  14446. let internalFormat = glFormat;
  14447. if ( glFormat === 6403 ) {
  14448. if ( glType === 5126 ) internalFormat = 33326;
  14449. if ( glType === 5131 ) internalFormat = 33325;
  14450. if ( glType === 5121 ) internalFormat = 33321;
  14451. }
  14452. if ( glFormat === 6407 ) {
  14453. if ( glType === 5126 ) internalFormat = 34837;
  14454. if ( glType === 5131 ) internalFormat = 34843;
  14455. if ( glType === 5121 ) internalFormat = 32849;
  14456. }
  14457. if ( glFormat === 6408 ) {
  14458. if ( glType === 5126 ) internalFormat = 34836;
  14459. if ( glType === 5131 ) internalFormat = 34842;
  14460. if ( glType === 5121 ) internalFormat = 32856;
  14461. }
  14462. if ( internalFormat === 33325 || internalFormat === 33326 ||
  14463. internalFormat === 34842 || internalFormat === 34836 ) {
  14464. extensions.get( 'EXT_color_buffer_float' );
  14465. }
  14466. return internalFormat;
  14467. }
  14468. // Fallback filters for non-power-of-2 textures
  14469. function filterFallback( f ) {
  14470. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14471. return 9728;
  14472. }
  14473. return 9729;
  14474. }
  14475. //
  14476. function onTextureDispose( event ) {
  14477. const texture = event.target;
  14478. texture.removeEventListener( 'dispose', onTextureDispose );
  14479. deallocateTexture( texture );
  14480. if ( texture.isVideoTexture ) {
  14481. _videoTextures.delete( texture );
  14482. }
  14483. info.memory.textures --;
  14484. }
  14485. function onRenderTargetDispose( event ) {
  14486. const renderTarget = event.target;
  14487. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14488. deallocateRenderTarget( renderTarget );
  14489. }
  14490. //
  14491. function deallocateTexture( texture ) {
  14492. const textureProperties = properties.get( texture );
  14493. if ( textureProperties.__webglInit === undefined ) return;
  14494. _gl.deleteTexture( textureProperties.__webglTexture );
  14495. properties.remove( texture );
  14496. }
  14497. function deallocateRenderTarget( renderTarget ) {
  14498. const texture = renderTarget.texture;
  14499. const renderTargetProperties = properties.get( renderTarget );
  14500. const textureProperties = properties.get( texture );
  14501. if ( ! renderTarget ) return;
  14502. if ( textureProperties.__webglTexture !== undefined ) {
  14503. _gl.deleteTexture( textureProperties.__webglTexture );
  14504. info.memory.textures --;
  14505. }
  14506. if ( renderTarget.depthTexture ) {
  14507. renderTarget.depthTexture.dispose();
  14508. }
  14509. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14510. for ( let i = 0; i < 6; i ++ ) {
  14511. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14512. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14513. }
  14514. } else {
  14515. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14516. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14517. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14518. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  14519. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14520. }
  14521. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14522. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14523. const attachmentProperties = properties.get( texture[ i ] );
  14524. if ( attachmentProperties.__webglTexture ) {
  14525. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14526. info.memory.textures --;
  14527. }
  14528. properties.remove( texture[ i ] );
  14529. }
  14530. }
  14531. properties.remove( texture );
  14532. properties.remove( renderTarget );
  14533. }
  14534. //
  14535. let textureUnits = 0;
  14536. function resetTextureUnits() {
  14537. textureUnits = 0;
  14538. }
  14539. function allocateTextureUnit() {
  14540. const textureUnit = textureUnits;
  14541. if ( textureUnit >= maxTextures ) {
  14542. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14543. }
  14544. textureUnits += 1;
  14545. return textureUnit;
  14546. }
  14547. //
  14548. function setTexture2D( texture, slot ) {
  14549. const textureProperties = properties.get( texture );
  14550. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14551. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14552. const image = texture.image;
  14553. if ( image === undefined ) {
  14554. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  14555. } else if ( image.complete === false ) {
  14556. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14557. } else {
  14558. uploadTexture( textureProperties, texture, slot );
  14559. return;
  14560. }
  14561. }
  14562. state.activeTexture( 33984 + slot );
  14563. state.bindTexture( 3553, textureProperties.__webglTexture );
  14564. }
  14565. function setTexture2DArray( texture, slot ) {
  14566. const textureProperties = properties.get( texture );
  14567. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14568. uploadTexture( textureProperties, texture, slot );
  14569. return;
  14570. }
  14571. state.activeTexture( 33984 + slot );
  14572. state.bindTexture( 35866, textureProperties.__webglTexture );
  14573. }
  14574. function setTexture3D( texture, slot ) {
  14575. const textureProperties = properties.get( texture );
  14576. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14577. uploadTexture( textureProperties, texture, slot );
  14578. return;
  14579. }
  14580. state.activeTexture( 33984 + slot );
  14581. state.bindTexture( 32879, textureProperties.__webglTexture );
  14582. }
  14583. function setTextureCube( texture, slot ) {
  14584. const textureProperties = properties.get( texture );
  14585. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14586. uploadCubeTexture( textureProperties, texture, slot );
  14587. return;
  14588. }
  14589. state.activeTexture( 33984 + slot );
  14590. state.bindTexture( 34067, textureProperties.__webglTexture );
  14591. }
  14592. const wrappingToGL = {
  14593. [ RepeatWrapping ]: 10497,
  14594. [ ClampToEdgeWrapping ]: 33071,
  14595. [ MirroredRepeatWrapping ]: 33648
  14596. };
  14597. const filterToGL = {
  14598. [ NearestFilter ]: 9728,
  14599. [ NearestMipmapNearestFilter ]: 9984,
  14600. [ NearestMipmapLinearFilter ]: 9986,
  14601. [ LinearFilter ]: 9729,
  14602. [ LinearMipmapNearestFilter ]: 9985,
  14603. [ LinearMipmapLinearFilter ]: 9987
  14604. };
  14605. function setTextureParameters( textureType, texture, supportsMips ) {
  14606. if ( supportsMips ) {
  14607. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  14608. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  14609. if ( textureType === 32879 || textureType === 35866 ) {
  14610. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  14611. }
  14612. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  14613. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  14614. } else {
  14615. _gl.texParameteri( textureType, 10242, 33071 );
  14616. _gl.texParameteri( textureType, 10243, 33071 );
  14617. if ( textureType === 32879 || textureType === 35866 ) {
  14618. _gl.texParameteri( textureType, 32882, 33071 );
  14619. }
  14620. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14621. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14622. }
  14623. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  14624. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  14625. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14626. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14627. }
  14628. }
  14629. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14630. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14631. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14632. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14633. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14634. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14635. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14636. }
  14637. }
  14638. }
  14639. function initTexture( textureProperties, texture ) {
  14640. if ( textureProperties.__webglInit === undefined ) {
  14641. textureProperties.__webglInit = true;
  14642. texture.addEventListener( 'dispose', onTextureDispose );
  14643. textureProperties.__webglTexture = _gl.createTexture();
  14644. info.memory.textures ++;
  14645. }
  14646. }
  14647. function uploadTexture( textureProperties, texture, slot ) {
  14648. let textureType = 3553;
  14649. if ( texture.isDataTexture2DArray ) textureType = 35866;
  14650. if ( texture.isDataTexture3D ) textureType = 32879;
  14651. initTexture( textureProperties, texture );
  14652. state.activeTexture( 33984 + slot );
  14653. state.bindTexture( textureType, textureProperties.__webglTexture );
  14654. _gl.pixelStorei( 37440, texture.flipY );
  14655. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14656. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14657. _gl.pixelStorei( 37443, 0 );
  14658. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14659. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14660. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14661. glFormat = utils.convert( texture.format );
  14662. let glType = utils.convert( texture.type ),
  14663. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14664. setTextureParameters( textureType, texture, supportsMips );
  14665. let mipmap;
  14666. const mipmaps = texture.mipmaps;
  14667. if ( texture.isDepthTexture ) {
  14668. // populate depth texture with dummy data
  14669. glInternalFormat = 6402;
  14670. if ( isWebGL2 ) {
  14671. if ( texture.type === FloatType ) {
  14672. glInternalFormat = 36012;
  14673. } else if ( texture.type === UnsignedIntType ) {
  14674. glInternalFormat = 33190;
  14675. } else if ( texture.type === UnsignedInt248Type ) {
  14676. glInternalFormat = 35056;
  14677. } else {
  14678. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  14679. }
  14680. } else {
  14681. if ( texture.type === FloatType ) {
  14682. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14683. }
  14684. }
  14685. // validation checks for WebGL 1
  14686. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  14687. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14688. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14689. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14690. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14691. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14692. texture.type = UnsignedShortType;
  14693. glType = utils.convert( texture.type );
  14694. }
  14695. }
  14696. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  14697. // Depth stencil textures need the DEPTH_STENCIL internal format
  14698. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14699. glInternalFormat = 34041;
  14700. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14701. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14702. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14703. if ( texture.type !== UnsignedInt248Type ) {
  14704. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14705. texture.type = UnsignedInt248Type;
  14706. glType = utils.convert( texture.type );
  14707. }
  14708. }
  14709. //
  14710. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14711. } else if ( texture.isDataTexture ) {
  14712. // use manually created mipmaps if available
  14713. // if there are no manual mipmaps
  14714. // set 0 level mipmap and then use GL to generate other mipmap levels
  14715. if ( mipmaps.length > 0 && supportsMips ) {
  14716. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14717. mipmap = mipmaps[ i ];
  14718. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14719. }
  14720. texture.generateMipmaps = false;
  14721. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14722. } else {
  14723. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14724. textureProperties.__maxMipLevel = 0;
  14725. }
  14726. } else if ( texture.isCompressedTexture ) {
  14727. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14728. mipmap = mipmaps[ i ];
  14729. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14730. if ( glFormat !== null ) {
  14731. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14732. } else {
  14733. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14734. }
  14735. } else {
  14736. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14737. }
  14738. }
  14739. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14740. } else if ( texture.isDataTexture2DArray ) {
  14741. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14742. textureProperties.__maxMipLevel = 0;
  14743. } else if ( texture.isDataTexture3D ) {
  14744. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14745. textureProperties.__maxMipLevel = 0;
  14746. } else {
  14747. // regular Texture (image, video, canvas)
  14748. // use manually created mipmaps if available
  14749. // if there are no manual mipmaps
  14750. // set 0 level mipmap and then use GL to generate other mipmap levels
  14751. if ( mipmaps.length > 0 && supportsMips ) {
  14752. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14753. mipmap = mipmaps[ i ];
  14754. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14755. }
  14756. texture.generateMipmaps = false;
  14757. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14758. } else {
  14759. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14760. textureProperties.__maxMipLevel = 0;
  14761. }
  14762. }
  14763. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14764. generateMipmap( textureType, texture, image.width, image.height );
  14765. }
  14766. textureProperties.__version = texture.version;
  14767. if ( texture.onUpdate ) texture.onUpdate( texture );
  14768. }
  14769. function uploadCubeTexture( textureProperties, texture, slot ) {
  14770. if ( texture.image.length !== 6 ) return;
  14771. initTexture( textureProperties, texture );
  14772. state.activeTexture( 33984 + slot );
  14773. state.bindTexture( 34067, textureProperties.__webglTexture );
  14774. _gl.pixelStorei( 37440, texture.flipY );
  14775. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14776. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14777. _gl.pixelStorei( 37443, 0 );
  14778. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  14779. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14780. const cubeImage = [];
  14781. for ( let i = 0; i < 6; i ++ ) {
  14782. if ( ! isCompressed && ! isDataTexture ) {
  14783. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14784. } else {
  14785. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14786. }
  14787. }
  14788. const image = cubeImage[ 0 ],
  14789. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14790. glFormat = utils.convert( texture.format ),
  14791. glType = utils.convert( texture.type ),
  14792. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14793. setTextureParameters( 34067, texture, supportsMips );
  14794. let mipmaps;
  14795. if ( isCompressed ) {
  14796. for ( let i = 0; i < 6; i ++ ) {
  14797. mipmaps = cubeImage[ i ].mipmaps;
  14798. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14799. const mipmap = mipmaps[ j ];
  14800. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14801. if ( glFormat !== null ) {
  14802. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14803. } else {
  14804. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14805. }
  14806. } else {
  14807. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14808. }
  14809. }
  14810. }
  14811. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14812. } else {
  14813. mipmaps = texture.mipmaps;
  14814. for ( let i = 0; i < 6; i ++ ) {
  14815. if ( isDataTexture ) {
  14816. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14817. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14818. const mipmap = mipmaps[ j ];
  14819. const mipmapImage = mipmap.image[ i ].image;
  14820. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14821. }
  14822. } else {
  14823. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14824. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14825. const mipmap = mipmaps[ j ];
  14826. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14827. }
  14828. }
  14829. }
  14830. textureProperties.__maxMipLevel = mipmaps.length;
  14831. }
  14832. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14833. // We assume images for cube map have the same size.
  14834. generateMipmap( 34067, texture, image.width, image.height );
  14835. }
  14836. textureProperties.__version = texture.version;
  14837. if ( texture.onUpdate ) texture.onUpdate( texture );
  14838. }
  14839. // Render targets
  14840. // Setup storage for target texture and bind it to correct framebuffer
  14841. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14842. const glFormat = utils.convert( texture.format );
  14843. const glType = utils.convert( texture.type );
  14844. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14845. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14846. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14847. } else {
  14848. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14849. }
  14850. state.bindFramebuffer( 36160, framebuffer );
  14851. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14852. state.bindFramebuffer( 36160, null );
  14853. }
  14854. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14855. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14856. _gl.bindRenderbuffer( 36161, renderbuffer );
  14857. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14858. let glInternalFormat = 33189;
  14859. if ( isMultisample ) {
  14860. const depthTexture = renderTarget.depthTexture;
  14861. if ( depthTexture && depthTexture.isDepthTexture ) {
  14862. if ( depthTexture.type === FloatType ) {
  14863. glInternalFormat = 36012;
  14864. } else if ( depthTexture.type === UnsignedIntType ) {
  14865. glInternalFormat = 33190;
  14866. }
  14867. }
  14868. const samples = getRenderTargetSamples( renderTarget );
  14869. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14870. } else {
  14871. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14872. }
  14873. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14874. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14875. if ( isMultisample ) {
  14876. const samples = getRenderTargetSamples( renderTarget );
  14877. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14878. } else {
  14879. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14880. }
  14881. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14882. } else {
  14883. // Use the first texture for MRT so far
  14884. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  14885. const glFormat = utils.convert( texture.format );
  14886. const glType = utils.convert( texture.type );
  14887. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14888. if ( isMultisample ) {
  14889. const samples = getRenderTargetSamples( renderTarget );
  14890. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14891. } else {
  14892. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14893. }
  14894. }
  14895. _gl.bindRenderbuffer( 36161, null );
  14896. }
  14897. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14898. function setupDepthTexture( framebuffer, renderTarget ) {
  14899. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14900. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14901. state.bindFramebuffer( 36160, framebuffer );
  14902. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14903. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14904. }
  14905. // upload an empty depth texture with framebuffer size
  14906. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14907. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14908. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14909. renderTarget.depthTexture.image.width = renderTarget.width;
  14910. renderTarget.depthTexture.image.height = renderTarget.height;
  14911. renderTarget.depthTexture.needsUpdate = true;
  14912. }
  14913. setTexture2D( renderTarget.depthTexture, 0 );
  14914. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14915. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14916. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14917. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14918. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14919. } else {
  14920. throw new Error( 'Unknown depthTexture format' );
  14921. }
  14922. }
  14923. // Setup GL resources for a non-texture depth buffer
  14924. function setupDepthRenderbuffer( renderTarget ) {
  14925. const renderTargetProperties = properties.get( renderTarget );
  14926. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14927. if ( renderTarget.depthTexture ) {
  14928. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14929. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14930. } else {
  14931. if ( isCube ) {
  14932. renderTargetProperties.__webglDepthbuffer = [];
  14933. for ( let i = 0; i < 6; i ++ ) {
  14934. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14935. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14936. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14937. }
  14938. } else {
  14939. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14940. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14941. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14942. }
  14943. }
  14944. state.bindFramebuffer( 36160, null );
  14945. }
  14946. // Set up GL resources for the render target
  14947. function setupRenderTarget( renderTarget ) {
  14948. const texture = renderTarget.texture;
  14949. const renderTargetProperties = properties.get( renderTarget );
  14950. const textureProperties = properties.get( texture );
  14951. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14952. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14953. textureProperties.__webglTexture = _gl.createTexture();
  14954. textureProperties.__version = texture.version;
  14955. info.memory.textures ++;
  14956. }
  14957. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14958. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14959. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  14960. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  14961. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14962. // Handles WebGL2 RGBFormat fallback - #18858
  14963. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  14964. texture.format = RGBAFormat;
  14965. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  14966. }
  14967. // Setup framebuffer
  14968. if ( isCube ) {
  14969. renderTargetProperties.__webglFramebuffer = [];
  14970. for ( let i = 0; i < 6; i ++ ) {
  14971. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14972. }
  14973. } else {
  14974. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14975. if ( isMultipleRenderTargets ) {
  14976. if ( capabilities.drawBuffers ) {
  14977. const textures = renderTarget.texture;
  14978. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14979. const attachmentProperties = properties.get( textures[ i ] );
  14980. if ( attachmentProperties.__webglTexture === undefined ) {
  14981. attachmentProperties.__webglTexture = _gl.createTexture();
  14982. info.memory.textures ++;
  14983. }
  14984. }
  14985. } else {
  14986. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14987. }
  14988. } else if ( isMultisample ) {
  14989. if ( isWebGL2 ) {
  14990. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14991. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14992. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  14993. const glFormat = utils.convert( texture.format );
  14994. const glType = utils.convert( texture.type );
  14995. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  14996. const samples = getRenderTargetSamples( renderTarget );
  14997. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14998. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14999. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  15000. _gl.bindRenderbuffer( 36161, null );
  15001. if ( renderTarget.depthBuffer ) {
  15002. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15003. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15004. }
  15005. state.bindFramebuffer( 36160, null );
  15006. } else {
  15007. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  15008. }
  15009. }
  15010. }
  15011. // Setup color buffer
  15012. if ( isCube ) {
  15013. state.bindTexture( 34067, textureProperties.__webglTexture );
  15014. setTextureParameters( 34067, texture, supportsMips );
  15015. for ( let i = 0; i < 6; i ++ ) {
  15016. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  15017. }
  15018. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15019. generateMipmap( 34067, texture, renderTarget.width, renderTarget.height );
  15020. }
  15021. state.unbindTexture();
  15022. } else if ( isMultipleRenderTargets ) {
  15023. const textures = renderTarget.texture;
  15024. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15025. const attachment = textures[ i ];
  15026. const attachmentProperties = properties.get( attachment );
  15027. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  15028. setTextureParameters( 3553, attachment, supportsMips );
  15029. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  15030. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  15031. generateMipmap( 3553, attachment, renderTarget.width, renderTarget.height );
  15032. }
  15033. }
  15034. state.unbindTexture();
  15035. } else {
  15036. let glTextureType = 3553;
  15037. if ( isRenderTarget3D ) {
  15038. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  15039. if ( isWebGL2 ) {
  15040. const isTexture3D = texture.isDataTexture3D;
  15041. glTextureType = isTexture3D ? 32879 : 35866;
  15042. } else {
  15043. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  15044. }
  15045. }
  15046. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15047. setTextureParameters( glTextureType, texture, supportsMips );
  15048. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  15049. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15050. generateMipmap( glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth );
  15051. }
  15052. state.unbindTexture();
  15053. }
  15054. // Setup depth and stencil buffers
  15055. if ( renderTarget.depthBuffer ) {
  15056. setupDepthRenderbuffer( renderTarget );
  15057. }
  15058. }
  15059. function updateRenderTargetMipmap( renderTarget ) {
  15060. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15061. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  15062. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15063. const texture = textures[ i ];
  15064. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15065. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  15066. const webglTexture = properties.get( texture ).__webglTexture;
  15067. state.bindTexture( target, webglTexture );
  15068. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  15069. state.unbindTexture();
  15070. }
  15071. }
  15072. }
  15073. function updateMultisampleRenderTarget( renderTarget ) {
  15074. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  15075. if ( isWebGL2 ) {
  15076. const width = renderTarget.width;
  15077. const height = renderTarget.height;
  15078. let mask = 16384;
  15079. if ( renderTarget.depthBuffer ) mask |= 256;
  15080. if ( renderTarget.stencilBuffer ) mask |= 1024;
  15081. const renderTargetProperties = properties.get( renderTarget );
  15082. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  15083. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  15084. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  15085. state.bindFramebuffer( 36008, null );
  15086. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  15087. } else {
  15088. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  15089. }
  15090. }
  15091. }
  15092. function getRenderTargetSamples( renderTarget ) {
  15093. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  15094. Math.min( maxSamples, renderTarget.samples ) : 0;
  15095. }
  15096. function updateVideoTexture( texture ) {
  15097. const frame = info.render.frame;
  15098. // Check the last frame we updated the VideoTexture
  15099. if ( _videoTextures.get( texture ) !== frame ) {
  15100. _videoTextures.set( texture, frame );
  15101. texture.update();
  15102. }
  15103. }
  15104. // backwards compatibility
  15105. let warnedTexture2D = false;
  15106. let warnedTextureCube = false;
  15107. function safeSetTexture2D( texture, slot ) {
  15108. if ( texture && texture.isWebGLRenderTarget ) {
  15109. if ( warnedTexture2D === false ) {
  15110. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  15111. warnedTexture2D = true;
  15112. }
  15113. texture = texture.texture;
  15114. }
  15115. setTexture2D( texture, slot );
  15116. }
  15117. function safeSetTextureCube( texture, slot ) {
  15118. if ( texture && texture.isWebGLCubeRenderTarget ) {
  15119. if ( warnedTextureCube === false ) {
  15120. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  15121. warnedTextureCube = true;
  15122. }
  15123. texture = texture.texture;
  15124. }
  15125. setTextureCube( texture, slot );
  15126. }
  15127. //
  15128. this.allocateTextureUnit = allocateTextureUnit;
  15129. this.resetTextureUnits = resetTextureUnits;
  15130. this.setTexture2D = setTexture2D;
  15131. this.setTexture2DArray = setTexture2DArray;
  15132. this.setTexture3D = setTexture3D;
  15133. this.setTextureCube = setTextureCube;
  15134. this.setupRenderTarget = setupRenderTarget;
  15135. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15136. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15137. this.safeSetTexture2D = safeSetTexture2D;
  15138. this.safeSetTextureCube = safeSetTextureCube;
  15139. }
  15140. function WebGLUtils( gl, extensions, capabilities ) {
  15141. const isWebGL2 = capabilities.isWebGL2;
  15142. function convert( p ) {
  15143. let extension;
  15144. if ( p === UnsignedByteType ) return 5121;
  15145. if ( p === UnsignedShort4444Type ) return 32819;
  15146. if ( p === UnsignedShort5551Type ) return 32820;
  15147. if ( p === UnsignedShort565Type ) return 33635;
  15148. if ( p === ByteType ) return 5120;
  15149. if ( p === ShortType ) return 5122;
  15150. if ( p === UnsignedShortType ) return 5123;
  15151. if ( p === IntType ) return 5124;
  15152. if ( p === UnsignedIntType ) return 5125;
  15153. if ( p === FloatType ) return 5126;
  15154. if ( p === HalfFloatType ) {
  15155. if ( isWebGL2 ) return 5131;
  15156. extension = extensions.get( 'OES_texture_half_float' );
  15157. if ( extension !== null ) {
  15158. return extension.HALF_FLOAT_OES;
  15159. } else {
  15160. return null;
  15161. }
  15162. }
  15163. if ( p === AlphaFormat ) return 6406;
  15164. if ( p === RGBFormat ) return 6407;
  15165. if ( p === RGBAFormat ) return 6408;
  15166. if ( p === LuminanceFormat ) return 6409;
  15167. if ( p === LuminanceAlphaFormat ) return 6410;
  15168. if ( p === DepthFormat ) return 6402;
  15169. if ( p === DepthStencilFormat ) return 34041;
  15170. if ( p === RedFormat ) return 6403;
  15171. // WebGL2 formats.
  15172. if ( p === RedIntegerFormat ) return 36244;
  15173. if ( p === RGFormat ) return 33319;
  15174. if ( p === RGIntegerFormat ) return 33320;
  15175. if ( p === RGBIntegerFormat ) return 36248;
  15176. if ( p === RGBAIntegerFormat ) return 36249;
  15177. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  15178. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15179. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15180. if ( extension !== null ) {
  15181. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15182. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15183. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15184. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15185. } else {
  15186. return null;
  15187. }
  15188. }
  15189. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  15190. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15191. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15192. if ( extension !== null ) {
  15193. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15194. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15195. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15196. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15197. } else {
  15198. return null;
  15199. }
  15200. }
  15201. if ( p === RGB_ETC1_Format ) {
  15202. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15203. if ( extension !== null ) {
  15204. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15205. } else {
  15206. return null;
  15207. }
  15208. }
  15209. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15210. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15211. if ( extension !== null ) {
  15212. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  15213. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  15214. }
  15215. }
  15216. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15217. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15218. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15219. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15220. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  15221. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  15222. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  15223. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  15224. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  15225. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  15226. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15227. if ( extension !== null ) {
  15228. // TODO Complete?
  15229. return p;
  15230. } else {
  15231. return null;
  15232. }
  15233. }
  15234. if ( p === RGBA_BPTC_Format ) {
  15235. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15236. if ( extension !== null ) {
  15237. // TODO Complete?
  15238. return p;
  15239. } else {
  15240. return null;
  15241. }
  15242. }
  15243. if ( p === UnsignedInt248Type ) {
  15244. if ( isWebGL2 ) return 34042;
  15245. extension = extensions.get( 'WEBGL_depth_texture' );
  15246. if ( extension !== null ) {
  15247. return extension.UNSIGNED_INT_24_8_WEBGL;
  15248. } else {
  15249. return null;
  15250. }
  15251. }
  15252. }
  15253. return { convert: convert };
  15254. }
  15255. class ArrayCamera extends PerspectiveCamera {
  15256. constructor( array = [] ) {
  15257. super();
  15258. this.cameras = array;
  15259. }
  15260. }
  15261. ArrayCamera.prototype.isArrayCamera = true;
  15262. class Group extends Object3D {
  15263. constructor() {
  15264. super();
  15265. this.type = 'Group';
  15266. }
  15267. }
  15268. Group.prototype.isGroup = true;
  15269. const _moveEvent = { type: 'move' };
  15270. class WebXRController {
  15271. constructor() {
  15272. this._targetRay = null;
  15273. this._grip = null;
  15274. this._hand = null;
  15275. }
  15276. getHandSpace() {
  15277. if ( this._hand === null ) {
  15278. this._hand = new Group();
  15279. this._hand.matrixAutoUpdate = false;
  15280. this._hand.visible = false;
  15281. this._hand.joints = {};
  15282. this._hand.inputState = { pinching: false };
  15283. }
  15284. return this._hand;
  15285. }
  15286. getTargetRaySpace() {
  15287. if ( this._targetRay === null ) {
  15288. this._targetRay = new Group();
  15289. this._targetRay.matrixAutoUpdate = false;
  15290. this._targetRay.visible = false;
  15291. this._targetRay.hasLinearVelocity = false;
  15292. this._targetRay.linearVelocity = new Vector3();
  15293. this._targetRay.hasAngularVelocity = false;
  15294. this._targetRay.angularVelocity = new Vector3();
  15295. }
  15296. return this._targetRay;
  15297. }
  15298. getGripSpace() {
  15299. if ( this._grip === null ) {
  15300. this._grip = new Group();
  15301. this._grip.matrixAutoUpdate = false;
  15302. this._grip.visible = false;
  15303. this._grip.hasLinearVelocity = false;
  15304. this._grip.linearVelocity = new Vector3();
  15305. this._grip.hasAngularVelocity = false;
  15306. this._grip.angularVelocity = new Vector3();
  15307. }
  15308. return this._grip;
  15309. }
  15310. dispatchEvent( event ) {
  15311. if ( this._targetRay !== null ) {
  15312. this._targetRay.dispatchEvent( event );
  15313. }
  15314. if ( this._grip !== null ) {
  15315. this._grip.dispatchEvent( event );
  15316. }
  15317. if ( this._hand !== null ) {
  15318. this._hand.dispatchEvent( event );
  15319. }
  15320. return this;
  15321. }
  15322. disconnect( inputSource ) {
  15323. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15324. if ( this._targetRay !== null ) {
  15325. this._targetRay.visible = false;
  15326. }
  15327. if ( this._grip !== null ) {
  15328. this._grip.visible = false;
  15329. }
  15330. if ( this._hand !== null ) {
  15331. this._hand.visible = false;
  15332. }
  15333. return this;
  15334. }
  15335. update( inputSource, frame, referenceSpace ) {
  15336. let inputPose = null;
  15337. let gripPose = null;
  15338. let handPose = null;
  15339. const targetRay = this._targetRay;
  15340. const grip = this._grip;
  15341. const hand = this._hand;
  15342. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15343. if ( targetRay !== null ) {
  15344. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15345. if ( inputPose !== null ) {
  15346. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15347. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15348. if ( inputPose.linearVelocity ) {
  15349. targetRay.hasLinearVelocity = true;
  15350. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15351. } else {
  15352. targetRay.hasLinearVelocity = false;
  15353. }
  15354. if ( inputPose.angularVelocity ) {
  15355. targetRay.hasAngularVelocity = true;
  15356. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15357. } else {
  15358. targetRay.hasAngularVelocity = false;
  15359. }
  15360. this.dispatchEvent( _moveEvent );
  15361. }
  15362. }
  15363. if ( hand && inputSource.hand ) {
  15364. handPose = true;
  15365. for ( const inputjoint of inputSource.hand.values() ) {
  15366. // Update the joints groups with the XRJoint poses
  15367. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15368. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15369. // The transform of this joint will be updated with the joint pose on each frame
  15370. const joint = new Group();
  15371. joint.matrixAutoUpdate = false;
  15372. joint.visible = false;
  15373. hand.joints[ inputjoint.jointName ] = joint;
  15374. // ??
  15375. hand.add( joint );
  15376. }
  15377. const joint = hand.joints[ inputjoint.jointName ];
  15378. if ( jointPose !== null ) {
  15379. joint.matrix.fromArray( jointPose.transform.matrix );
  15380. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15381. joint.jointRadius = jointPose.radius;
  15382. }
  15383. joint.visible = jointPose !== null;
  15384. }
  15385. // Custom events
  15386. // Check pinchz
  15387. const indexTip = hand.joints[ 'index-finger-tip' ];
  15388. const thumbTip = hand.joints[ 'thumb-tip' ];
  15389. const distance = indexTip.position.distanceTo( thumbTip.position );
  15390. const distanceToPinch = 0.02;
  15391. const threshold = 0.005;
  15392. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15393. hand.inputState.pinching = false;
  15394. this.dispatchEvent( {
  15395. type: 'pinchend',
  15396. handedness: inputSource.handedness,
  15397. target: this
  15398. } );
  15399. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15400. hand.inputState.pinching = true;
  15401. this.dispatchEvent( {
  15402. type: 'pinchstart',
  15403. handedness: inputSource.handedness,
  15404. target: this
  15405. } );
  15406. }
  15407. } else {
  15408. if ( grip !== null && inputSource.gripSpace ) {
  15409. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15410. if ( gripPose !== null ) {
  15411. grip.matrix.fromArray( gripPose.transform.matrix );
  15412. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15413. if ( gripPose.linearVelocity ) {
  15414. grip.hasLinearVelocity = true;
  15415. grip.linearVelocity.copy( gripPose.linearVelocity );
  15416. } else {
  15417. grip.hasLinearVelocity = false;
  15418. }
  15419. if ( gripPose.angularVelocity ) {
  15420. grip.hasAngularVelocity = true;
  15421. grip.angularVelocity.copy( gripPose.angularVelocity );
  15422. } else {
  15423. grip.hasAngularVelocity = false;
  15424. }
  15425. }
  15426. }
  15427. }
  15428. }
  15429. if ( targetRay !== null ) {
  15430. targetRay.visible = ( inputPose !== null );
  15431. }
  15432. if ( grip !== null ) {
  15433. grip.visible = ( gripPose !== null );
  15434. }
  15435. if ( hand !== null ) {
  15436. hand.visible = ( handPose !== null );
  15437. }
  15438. return this;
  15439. }
  15440. }
  15441. class WebXRManager extends EventDispatcher {
  15442. constructor( renderer, gl ) {
  15443. super();
  15444. const scope = this;
  15445. const state = renderer.state;
  15446. let session = null;
  15447. let framebufferScaleFactor = 1.0;
  15448. let referenceSpace = null;
  15449. let referenceSpaceType = 'local-floor';
  15450. let pose = null;
  15451. let glBinding = null;
  15452. let glFramebuffer = null;
  15453. let glProjLayer = null;
  15454. let glBaseLayer = null;
  15455. let isMultisample = false;
  15456. let glMultisampledFramebuffer = null;
  15457. let glColorRenderbuffer = null;
  15458. let glDepthRenderbuffer = null;
  15459. let xrFrame = null;
  15460. let depthStyle = null;
  15461. let clearStyle = null;
  15462. const controllers = [];
  15463. const inputSourcesMap = new Map();
  15464. //
  15465. const cameraL = new PerspectiveCamera();
  15466. cameraL.layers.enable( 1 );
  15467. cameraL.viewport = new Vector4();
  15468. const cameraR = new PerspectiveCamera();
  15469. cameraR.layers.enable( 2 );
  15470. cameraR.viewport = new Vector4();
  15471. const cameras = [ cameraL, cameraR ];
  15472. const cameraVR = new ArrayCamera();
  15473. cameraVR.layers.enable( 1 );
  15474. cameraVR.layers.enable( 2 );
  15475. let _currentDepthNear = null;
  15476. let _currentDepthFar = null;
  15477. //
  15478. this.cameraAutoUpdate = true;
  15479. this.enabled = false;
  15480. this.isPresenting = false;
  15481. this.getController = function ( index ) {
  15482. let controller = controllers[ index ];
  15483. if ( controller === undefined ) {
  15484. controller = new WebXRController();
  15485. controllers[ index ] = controller;
  15486. }
  15487. return controller.getTargetRaySpace();
  15488. };
  15489. this.getControllerGrip = function ( index ) {
  15490. let controller = controllers[ index ];
  15491. if ( controller === undefined ) {
  15492. controller = new WebXRController();
  15493. controllers[ index ] = controller;
  15494. }
  15495. return controller.getGripSpace();
  15496. };
  15497. this.getHand = function ( index ) {
  15498. let controller = controllers[ index ];
  15499. if ( controller === undefined ) {
  15500. controller = new WebXRController();
  15501. controllers[ index ] = controller;
  15502. }
  15503. return controller.getHandSpace();
  15504. };
  15505. //
  15506. function onSessionEvent( event ) {
  15507. const controller = inputSourcesMap.get( event.inputSource );
  15508. if ( controller ) {
  15509. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15510. }
  15511. }
  15512. function onSessionEnd() {
  15513. inputSourcesMap.forEach( function ( controller, inputSource ) {
  15514. controller.disconnect( inputSource );
  15515. } );
  15516. inputSourcesMap.clear();
  15517. _currentDepthNear = null;
  15518. _currentDepthFar = null;
  15519. // restore framebuffer/rendering state
  15520. state.bindXRFramebuffer( null );
  15521. renderer.setRenderTarget( renderer.getRenderTarget() );
  15522. if ( glFramebuffer ) gl.deleteFramebuffer( glFramebuffer );
  15523. if ( glMultisampledFramebuffer ) gl.deleteFramebuffer( glMultisampledFramebuffer );
  15524. if ( glColorRenderbuffer ) gl.deleteRenderbuffer( glColorRenderbuffer );
  15525. if ( glDepthRenderbuffer ) gl.deleteRenderbuffer( glDepthRenderbuffer );
  15526. glFramebuffer = null;
  15527. glMultisampledFramebuffer = null;
  15528. glColorRenderbuffer = null;
  15529. glDepthRenderbuffer = null;
  15530. glBaseLayer = null;
  15531. glProjLayer = null;
  15532. glBinding = null;
  15533. session = null;
  15534. //
  15535. animation.stop();
  15536. scope.isPresenting = false;
  15537. scope.dispatchEvent( { type: 'sessionend' } );
  15538. }
  15539. this.setFramebufferScaleFactor = function ( value ) {
  15540. framebufferScaleFactor = value;
  15541. if ( scope.isPresenting === true ) {
  15542. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15543. }
  15544. };
  15545. this.setReferenceSpaceType = function ( value ) {
  15546. referenceSpaceType = value;
  15547. if ( scope.isPresenting === true ) {
  15548. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15549. }
  15550. };
  15551. this.getReferenceSpace = function () {
  15552. return referenceSpace;
  15553. };
  15554. this.getBaseLayer = function () {
  15555. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15556. };
  15557. this.getBinding = function () {
  15558. return glBinding;
  15559. };
  15560. this.getFrame = function () {
  15561. return xrFrame;
  15562. };
  15563. this.getSession = function () {
  15564. return session;
  15565. };
  15566. this.setSession = async function ( value ) {
  15567. session = value;
  15568. if ( session !== null ) {
  15569. session.addEventListener( 'select', onSessionEvent );
  15570. session.addEventListener( 'selectstart', onSessionEvent );
  15571. session.addEventListener( 'selectend', onSessionEvent );
  15572. session.addEventListener( 'squeeze', onSessionEvent );
  15573. session.addEventListener( 'squeezestart', onSessionEvent );
  15574. session.addEventListener( 'squeezeend', onSessionEvent );
  15575. session.addEventListener( 'end', onSessionEnd );
  15576. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15577. const attributes = gl.getContextAttributes();
  15578. if ( attributes.xrCompatible !== true ) {
  15579. await gl.makeXRCompatible();
  15580. }
  15581. if ( session.renderState.layers === undefined ) {
  15582. const layerInit = {
  15583. antialias: attributes.antialias,
  15584. alpha: attributes.alpha,
  15585. depth: attributes.depth,
  15586. stencil: attributes.stencil,
  15587. framebufferScaleFactor: framebufferScaleFactor
  15588. };
  15589. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15590. session.updateRenderState( { baseLayer: glBaseLayer } );
  15591. } else if ( gl instanceof WebGLRenderingContext ) {
  15592. // Use old style webgl layer because we can't use MSAA
  15593. // WebGL2 support.
  15594. const layerInit = {
  15595. antialias: true,
  15596. alpha: attributes.alpha,
  15597. depth: attributes.depth,
  15598. stencil: attributes.stencil,
  15599. framebufferScaleFactor: framebufferScaleFactor
  15600. };
  15601. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15602. session.updateRenderState( { layers: [ glBaseLayer ] } );
  15603. } else {
  15604. isMultisample = attributes.antialias;
  15605. let depthFormat = null;
  15606. if ( attributes.depth ) {
  15607. clearStyle = 256;
  15608. if ( attributes.stencil ) clearStyle |= 1024;
  15609. depthStyle = attributes.stencil ? 33306 : 36096;
  15610. depthFormat = attributes.stencil ? 35056 : 33190;
  15611. }
  15612. const projectionlayerInit = {
  15613. colorFormat: attributes.alpha ? 32856 : 32849,
  15614. depthFormat: depthFormat,
  15615. scaleFactor: framebufferScaleFactor
  15616. };
  15617. glBinding = new XRWebGLBinding( session, gl );
  15618. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15619. glFramebuffer = gl.createFramebuffer();
  15620. session.updateRenderState( { layers: [ glProjLayer ] } );
  15621. if ( isMultisample ) {
  15622. glMultisampledFramebuffer = gl.createFramebuffer();
  15623. glColorRenderbuffer = gl.createRenderbuffer();
  15624. gl.bindRenderbuffer( 36161, glColorRenderbuffer );
  15625. gl.renderbufferStorageMultisample(
  15626. 36161,
  15627. 4,
  15628. 32856,
  15629. glProjLayer.textureWidth,
  15630. glProjLayer.textureHeight );
  15631. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  15632. gl.framebufferRenderbuffer( 36160, 36064, 36161, glColorRenderbuffer );
  15633. gl.bindRenderbuffer( 36161, null );
  15634. if ( depthFormat !== null ) {
  15635. glDepthRenderbuffer = gl.createRenderbuffer();
  15636. gl.bindRenderbuffer( 36161, glDepthRenderbuffer );
  15637. gl.renderbufferStorageMultisample( 36161, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight );
  15638. gl.framebufferRenderbuffer( 36160, depthStyle, 36161, glDepthRenderbuffer );
  15639. gl.bindRenderbuffer( 36161, null );
  15640. }
  15641. state.bindFramebuffer( 36160, null );
  15642. }
  15643. }
  15644. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15645. animation.setContext( session );
  15646. animation.start();
  15647. scope.isPresenting = true;
  15648. scope.dispatchEvent( { type: 'sessionstart' } );
  15649. }
  15650. };
  15651. function onInputSourcesChange( event ) {
  15652. const inputSources = session.inputSources;
  15653. // Assign inputSources to available controllers
  15654. for ( let i = 0; i < controllers.length; i ++ ) {
  15655. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  15656. }
  15657. // Notify disconnected
  15658. for ( let i = 0; i < event.removed.length; i ++ ) {
  15659. const inputSource = event.removed[ i ];
  15660. const controller = inputSourcesMap.get( inputSource );
  15661. if ( controller ) {
  15662. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15663. inputSourcesMap.delete( inputSource );
  15664. }
  15665. }
  15666. // Notify connected
  15667. for ( let i = 0; i < event.added.length; i ++ ) {
  15668. const inputSource = event.added[ i ];
  15669. const controller = inputSourcesMap.get( inputSource );
  15670. if ( controller ) {
  15671. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  15672. }
  15673. }
  15674. }
  15675. //
  15676. const cameraLPos = new Vector3();
  15677. const cameraRPos = new Vector3();
  15678. /**
  15679. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15680. * the cameras' projection and world matrices have already been set.
  15681. * And that near and far planes are identical for both cameras.
  15682. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15683. */
  15684. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15685. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15686. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15687. const ipd = cameraLPos.distanceTo( cameraRPos );
  15688. const projL = cameraL.projectionMatrix.elements;
  15689. const projR = cameraR.projectionMatrix.elements;
  15690. // VR systems will have identical far and near planes, and
  15691. // most likely identical top and bottom frustum extents.
  15692. // Use the left camera for these values.
  15693. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15694. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15695. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15696. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15697. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15698. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15699. const left = near * leftFov;
  15700. const right = near * rightFov;
  15701. // Calculate the new camera's position offset from the
  15702. // left camera. xOffset should be roughly half `ipd`.
  15703. const zOffset = ipd / ( - leftFov + rightFov );
  15704. const xOffset = zOffset * - leftFov;
  15705. // TODO: Better way to apply this offset?
  15706. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15707. camera.translateX( xOffset );
  15708. camera.translateZ( zOffset );
  15709. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15710. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15711. // Find the union of the frustum values of the cameras and scale
  15712. // the values so that the near plane's position does not change in world space,
  15713. // although must now be relative to the new union camera.
  15714. const near2 = near + zOffset;
  15715. const far2 = far + zOffset;
  15716. const left2 = left - xOffset;
  15717. const right2 = right + ( ipd - xOffset );
  15718. const top2 = topFov * far / far2 * near2;
  15719. const bottom2 = bottomFov * far / far2 * near2;
  15720. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15721. }
  15722. function updateCamera( camera, parent ) {
  15723. if ( parent === null ) {
  15724. camera.matrixWorld.copy( camera.matrix );
  15725. } else {
  15726. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15727. }
  15728. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15729. }
  15730. this.updateCamera = function ( camera ) {
  15731. if ( session === null ) return;
  15732. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15733. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15734. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15735. // Note that the new renderState won't apply until the next frame. See #18320
  15736. session.updateRenderState( {
  15737. depthNear: cameraVR.near,
  15738. depthFar: cameraVR.far
  15739. } );
  15740. _currentDepthNear = cameraVR.near;
  15741. _currentDepthFar = cameraVR.far;
  15742. }
  15743. const parent = camera.parent;
  15744. const cameras = cameraVR.cameras;
  15745. updateCamera( cameraVR, parent );
  15746. for ( let i = 0; i < cameras.length; i ++ ) {
  15747. updateCamera( cameras[ i ], parent );
  15748. }
  15749. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15750. // update user camera and its children
  15751. camera.position.copy( cameraVR.position );
  15752. camera.quaternion.copy( cameraVR.quaternion );
  15753. camera.scale.copy( cameraVR.scale );
  15754. camera.matrix.copy( cameraVR.matrix );
  15755. camera.matrixWorld.copy( cameraVR.matrixWorld );
  15756. const children = camera.children;
  15757. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15758. children[ i ].updateMatrixWorld( true );
  15759. }
  15760. // update projection matrix for proper view frustum culling
  15761. if ( cameras.length === 2 ) {
  15762. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15763. } else {
  15764. // assume single camera setup (AR)
  15765. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15766. }
  15767. };
  15768. this.getCamera = function () {
  15769. return cameraVR;
  15770. };
  15771. this.getFoveation = function () {
  15772. if ( glProjLayer !== null ) {
  15773. return glProjLayer.fixedFoveation;
  15774. }
  15775. if ( glBaseLayer !== null ) {
  15776. return glBaseLayer.fixedFoveation;
  15777. }
  15778. return undefined;
  15779. };
  15780. this.setFoveation = function ( foveation ) {
  15781. // 0 = no foveation = full resolution
  15782. // 1 = maximum foveation = the edges render at lower resolution
  15783. if ( glProjLayer !== null ) {
  15784. glProjLayer.fixedFoveation = foveation;
  15785. }
  15786. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15787. glBaseLayer.fixedFoveation = foveation;
  15788. }
  15789. };
  15790. // Animation Loop
  15791. let onAnimationFrameCallback = null;
  15792. function onAnimationFrame( time, frame ) {
  15793. pose = frame.getViewerPose( referenceSpace );
  15794. xrFrame = frame;
  15795. if ( pose !== null ) {
  15796. const views = pose.views;
  15797. if ( glBaseLayer !== null ) {
  15798. state.bindXRFramebuffer( glBaseLayer.framebuffer );
  15799. }
  15800. let cameraVRNeedsUpdate = false;
  15801. // check if it's necessary to rebuild cameraVR's camera list
  15802. if ( views.length !== cameraVR.cameras.length ) {
  15803. cameraVR.cameras.length = 0;
  15804. cameraVRNeedsUpdate = true;
  15805. }
  15806. for ( let i = 0; i < views.length; i ++ ) {
  15807. const view = views[ i ];
  15808. let viewport = null;
  15809. if ( glBaseLayer !== null ) {
  15810. viewport = glBaseLayer.getViewport( view );
  15811. } else {
  15812. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15813. state.bindXRFramebuffer( glFramebuffer );
  15814. if ( glSubImage.depthStencilTexture !== undefined ) {
  15815. gl.framebufferTexture2D( 36160, depthStyle, 3553, glSubImage.depthStencilTexture, 0 );
  15816. }
  15817. gl.framebufferTexture2D( 36160, 36064, 3553, glSubImage.colorTexture, 0 );
  15818. viewport = glSubImage.viewport;
  15819. }
  15820. const camera = cameras[ i ];
  15821. camera.matrix.fromArray( view.transform.matrix );
  15822. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15823. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15824. if ( i === 0 ) {
  15825. cameraVR.matrix.copy( camera.matrix );
  15826. }
  15827. if ( cameraVRNeedsUpdate === true ) {
  15828. cameraVR.cameras.push( camera );
  15829. }
  15830. }
  15831. if ( isMultisample ) {
  15832. state.bindXRFramebuffer( glMultisampledFramebuffer );
  15833. if ( clearStyle !== null ) gl.clear( clearStyle );
  15834. }
  15835. }
  15836. //
  15837. const inputSources = session.inputSources;
  15838. for ( let i = 0; i < controllers.length; i ++ ) {
  15839. const controller = controllers[ i ];
  15840. const inputSource = inputSources[ i ];
  15841. controller.update( inputSource, frame, referenceSpace );
  15842. }
  15843. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15844. if ( isMultisample ) {
  15845. const width = glProjLayer.textureWidth;
  15846. const height = glProjLayer.textureHeight;
  15847. state.bindFramebuffer( 36008, glMultisampledFramebuffer );
  15848. state.bindFramebuffer( 36009, glFramebuffer );
  15849. // Invalidate the depth here to avoid flush of the depth data to main memory.
  15850. gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  15851. gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  15852. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, 16384, 9728 );
  15853. // Invalidate the MSAA buffer because it's not needed anymore.
  15854. gl.invalidateFramebuffer( 36008, [ 36064 ] );
  15855. state.bindFramebuffer( 36008, null );
  15856. state.bindFramebuffer( 36009, null );
  15857. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  15858. }
  15859. xrFrame = null;
  15860. }
  15861. const animation = new WebGLAnimation();
  15862. animation.setAnimationLoop( onAnimationFrame );
  15863. this.setAnimationLoop = function ( callback ) {
  15864. onAnimationFrameCallback = callback;
  15865. };
  15866. this.dispose = function () {};
  15867. }
  15868. }
  15869. function WebGLMaterials( properties ) {
  15870. function refreshFogUniforms( uniforms, fog ) {
  15871. uniforms.fogColor.value.copy( fog.color );
  15872. if ( fog.isFog ) {
  15873. uniforms.fogNear.value = fog.near;
  15874. uniforms.fogFar.value = fog.far;
  15875. } else if ( fog.isFogExp2 ) {
  15876. uniforms.fogDensity.value = fog.density;
  15877. }
  15878. }
  15879. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15880. if ( material.isMeshBasicMaterial ) {
  15881. refreshUniformsCommon( uniforms, material );
  15882. } else if ( material.isMeshLambertMaterial ) {
  15883. refreshUniformsCommon( uniforms, material );
  15884. refreshUniformsLambert( uniforms, material );
  15885. } else if ( material.isMeshToonMaterial ) {
  15886. refreshUniformsCommon( uniforms, material );
  15887. refreshUniformsToon( uniforms, material );
  15888. } else if ( material.isMeshPhongMaterial ) {
  15889. refreshUniformsCommon( uniforms, material );
  15890. refreshUniformsPhong( uniforms, material );
  15891. } else if ( material.isMeshStandardMaterial ) {
  15892. refreshUniformsCommon( uniforms, material );
  15893. if ( material.isMeshPhysicalMaterial ) {
  15894. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15895. } else {
  15896. refreshUniformsStandard( uniforms, material );
  15897. }
  15898. } else if ( material.isMeshMatcapMaterial ) {
  15899. refreshUniformsCommon( uniforms, material );
  15900. refreshUniformsMatcap( uniforms, material );
  15901. } else if ( material.isMeshDepthMaterial ) {
  15902. refreshUniformsCommon( uniforms, material );
  15903. refreshUniformsDepth( uniforms, material );
  15904. } else if ( material.isMeshDistanceMaterial ) {
  15905. refreshUniformsCommon( uniforms, material );
  15906. refreshUniformsDistance( uniforms, material );
  15907. } else if ( material.isMeshNormalMaterial ) {
  15908. refreshUniformsCommon( uniforms, material );
  15909. refreshUniformsNormal( uniforms, material );
  15910. } else if ( material.isLineBasicMaterial ) {
  15911. refreshUniformsLine( uniforms, material );
  15912. if ( material.isLineDashedMaterial ) {
  15913. refreshUniformsDash( uniforms, material );
  15914. }
  15915. } else if ( material.isPointsMaterial ) {
  15916. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15917. } else if ( material.isSpriteMaterial ) {
  15918. refreshUniformsSprites( uniforms, material );
  15919. } else if ( material.isShadowMaterial ) {
  15920. uniforms.color.value.copy( material.color );
  15921. uniforms.opacity.value = material.opacity;
  15922. } else if ( material.isShaderMaterial ) {
  15923. material.uniformsNeedUpdate = false; // #15581
  15924. }
  15925. }
  15926. function refreshUniformsCommon( uniforms, material ) {
  15927. uniforms.opacity.value = material.opacity;
  15928. if ( material.color ) {
  15929. uniforms.diffuse.value.copy( material.color );
  15930. }
  15931. if ( material.emissive ) {
  15932. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15933. }
  15934. if ( material.map ) {
  15935. uniforms.map.value = material.map;
  15936. }
  15937. if ( material.alphaMap ) {
  15938. uniforms.alphaMap.value = material.alphaMap;
  15939. }
  15940. if ( material.specularMap ) {
  15941. uniforms.specularMap.value = material.specularMap;
  15942. }
  15943. if ( material.alphaTest > 0 ) {
  15944. uniforms.alphaTest.value = material.alphaTest;
  15945. }
  15946. const envMap = properties.get( material ).envMap;
  15947. if ( envMap ) {
  15948. uniforms.envMap.value = envMap;
  15949. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15950. uniforms.reflectivity.value = material.reflectivity;
  15951. uniforms.ior.value = material.ior;
  15952. uniforms.refractionRatio.value = material.refractionRatio;
  15953. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  15954. if ( maxMipLevel !== undefined ) {
  15955. uniforms.maxMipLevel.value = maxMipLevel;
  15956. }
  15957. }
  15958. if ( material.lightMap ) {
  15959. uniforms.lightMap.value = material.lightMap;
  15960. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15961. }
  15962. if ( material.aoMap ) {
  15963. uniforms.aoMap.value = material.aoMap;
  15964. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15965. }
  15966. // uv repeat and offset setting priorities
  15967. // 1. color map
  15968. // 2. specular map
  15969. // 3. displacementMap map
  15970. // 4. normal map
  15971. // 5. bump map
  15972. // 6. roughnessMap map
  15973. // 7. metalnessMap map
  15974. // 8. alphaMap map
  15975. // 9. emissiveMap map
  15976. // 10. clearcoat map
  15977. // 11. clearcoat normal map
  15978. // 12. clearcoat roughnessMap map
  15979. // 13. specular intensity map
  15980. // 14. specular tint map
  15981. // 15. transmission map
  15982. // 16. thickness map
  15983. let uvScaleMap;
  15984. if ( material.map ) {
  15985. uvScaleMap = material.map;
  15986. } else if ( material.specularMap ) {
  15987. uvScaleMap = material.specularMap;
  15988. } else if ( material.displacementMap ) {
  15989. uvScaleMap = material.displacementMap;
  15990. } else if ( material.normalMap ) {
  15991. uvScaleMap = material.normalMap;
  15992. } else if ( material.bumpMap ) {
  15993. uvScaleMap = material.bumpMap;
  15994. } else if ( material.roughnessMap ) {
  15995. uvScaleMap = material.roughnessMap;
  15996. } else if ( material.metalnessMap ) {
  15997. uvScaleMap = material.metalnessMap;
  15998. } else if ( material.alphaMap ) {
  15999. uvScaleMap = material.alphaMap;
  16000. } else if ( material.emissiveMap ) {
  16001. uvScaleMap = material.emissiveMap;
  16002. } else if ( material.clearcoatMap ) {
  16003. uvScaleMap = material.clearcoatMap;
  16004. } else if ( material.clearcoatNormalMap ) {
  16005. uvScaleMap = material.clearcoatNormalMap;
  16006. } else if ( material.clearcoatRoughnessMap ) {
  16007. uvScaleMap = material.clearcoatRoughnessMap;
  16008. } else if ( material.specularIntensityMap ) {
  16009. uvScaleMap = material.specularIntensityMap;
  16010. } else if ( material.specularTintMap ) {
  16011. uvScaleMap = material.specularTintMap;
  16012. } else if ( material.transmissionMap ) {
  16013. uvScaleMap = material.transmissionMap;
  16014. } else if ( material.thicknessMap ) {
  16015. uvScaleMap = material.thicknessMap;
  16016. }
  16017. if ( uvScaleMap !== undefined ) {
  16018. // backwards compatibility
  16019. if ( uvScaleMap.isWebGLRenderTarget ) {
  16020. uvScaleMap = uvScaleMap.texture;
  16021. }
  16022. if ( uvScaleMap.matrixAutoUpdate === true ) {
  16023. uvScaleMap.updateMatrix();
  16024. }
  16025. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  16026. }
  16027. // uv repeat and offset setting priorities for uv2
  16028. // 1. ao map
  16029. // 2. light map
  16030. let uv2ScaleMap;
  16031. if ( material.aoMap ) {
  16032. uv2ScaleMap = material.aoMap;
  16033. } else if ( material.lightMap ) {
  16034. uv2ScaleMap = material.lightMap;
  16035. }
  16036. if ( uv2ScaleMap !== undefined ) {
  16037. // backwards compatibility
  16038. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  16039. uv2ScaleMap = uv2ScaleMap.texture;
  16040. }
  16041. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  16042. uv2ScaleMap.updateMatrix();
  16043. }
  16044. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  16045. }
  16046. }
  16047. function refreshUniformsLine( uniforms, material ) {
  16048. uniforms.diffuse.value.copy( material.color );
  16049. uniforms.opacity.value = material.opacity;
  16050. }
  16051. function refreshUniformsDash( uniforms, material ) {
  16052. uniforms.dashSize.value = material.dashSize;
  16053. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16054. uniforms.scale.value = material.scale;
  16055. }
  16056. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16057. uniforms.diffuse.value.copy( material.color );
  16058. uniforms.opacity.value = material.opacity;
  16059. uniforms.size.value = material.size * pixelRatio;
  16060. uniforms.scale.value = height * 0.5;
  16061. if ( material.map ) {
  16062. uniforms.map.value = material.map;
  16063. }
  16064. if ( material.alphaMap ) {
  16065. uniforms.alphaMap.value = material.alphaMap;
  16066. }
  16067. if ( material.alphaTest > 0 ) {
  16068. uniforms.alphaTest.value = material.alphaTest;
  16069. }
  16070. // uv repeat and offset setting priorities
  16071. // 1. color map
  16072. // 2. alpha map
  16073. let uvScaleMap;
  16074. if ( material.map ) {
  16075. uvScaleMap = material.map;
  16076. } else if ( material.alphaMap ) {
  16077. uvScaleMap = material.alphaMap;
  16078. }
  16079. if ( uvScaleMap !== undefined ) {
  16080. if ( uvScaleMap.matrixAutoUpdate === true ) {
  16081. uvScaleMap.updateMatrix();
  16082. }
  16083. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  16084. }
  16085. }
  16086. function refreshUniformsSprites( uniforms, material ) {
  16087. uniforms.diffuse.value.copy( material.color );
  16088. uniforms.opacity.value = material.opacity;
  16089. uniforms.rotation.value = material.rotation;
  16090. if ( material.map ) {
  16091. uniforms.map.value = material.map;
  16092. }
  16093. if ( material.alphaMap ) {
  16094. uniforms.alphaMap.value = material.alphaMap;
  16095. }
  16096. if ( material.alphaTest > 0 ) {
  16097. uniforms.alphaTest.value = material.alphaTest;
  16098. }
  16099. // uv repeat and offset setting priorities
  16100. // 1. color map
  16101. // 2. alpha map
  16102. let uvScaleMap;
  16103. if ( material.map ) {
  16104. uvScaleMap = material.map;
  16105. } else if ( material.alphaMap ) {
  16106. uvScaleMap = material.alphaMap;
  16107. }
  16108. if ( uvScaleMap !== undefined ) {
  16109. if ( uvScaleMap.matrixAutoUpdate === true ) {
  16110. uvScaleMap.updateMatrix();
  16111. }
  16112. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  16113. }
  16114. }
  16115. function refreshUniformsLambert( uniforms, material ) {
  16116. if ( material.emissiveMap ) {
  16117. uniforms.emissiveMap.value = material.emissiveMap;
  16118. }
  16119. }
  16120. function refreshUniformsPhong( uniforms, material ) {
  16121. uniforms.specular.value.copy( material.specular );
  16122. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16123. if ( material.emissiveMap ) {
  16124. uniforms.emissiveMap.value = material.emissiveMap;
  16125. }
  16126. if ( material.bumpMap ) {
  16127. uniforms.bumpMap.value = material.bumpMap;
  16128. uniforms.bumpScale.value = material.bumpScale;
  16129. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  16130. }
  16131. if ( material.normalMap ) {
  16132. uniforms.normalMap.value = material.normalMap;
  16133. uniforms.normalScale.value.copy( material.normalScale );
  16134. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  16135. }
  16136. if ( material.displacementMap ) {
  16137. uniforms.displacementMap.value = material.displacementMap;
  16138. uniforms.displacementScale.value = material.displacementScale;
  16139. uniforms.displacementBias.value = material.displacementBias;
  16140. }
  16141. }
  16142. function refreshUniformsToon( uniforms, material ) {
  16143. if ( material.gradientMap ) {
  16144. uniforms.gradientMap.value = material.gradientMap;
  16145. }
  16146. if ( material.emissiveMap ) {
  16147. uniforms.emissiveMap.value = material.emissiveMap;
  16148. }
  16149. if ( material.bumpMap ) {
  16150. uniforms.bumpMap.value = material.bumpMap;
  16151. uniforms.bumpScale.value = material.bumpScale;
  16152. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  16153. }
  16154. if ( material.normalMap ) {
  16155. uniforms.normalMap.value = material.normalMap;
  16156. uniforms.normalScale.value.copy( material.normalScale );
  16157. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  16158. }
  16159. if ( material.displacementMap ) {
  16160. uniforms.displacementMap.value = material.displacementMap;
  16161. uniforms.displacementScale.value = material.displacementScale;
  16162. uniforms.displacementBias.value = material.displacementBias;
  16163. }
  16164. }
  16165. function refreshUniformsStandard( uniforms, material ) {
  16166. uniforms.roughness.value = material.roughness;
  16167. uniforms.metalness.value = material.metalness;
  16168. if ( material.roughnessMap ) {
  16169. uniforms.roughnessMap.value = material.roughnessMap;
  16170. }
  16171. if ( material.metalnessMap ) {
  16172. uniforms.metalnessMap.value = material.metalnessMap;
  16173. }
  16174. if ( material.emissiveMap ) {
  16175. uniforms.emissiveMap.value = material.emissiveMap;
  16176. }
  16177. if ( material.bumpMap ) {
  16178. uniforms.bumpMap.value = material.bumpMap;
  16179. uniforms.bumpScale.value = material.bumpScale;
  16180. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  16181. }
  16182. if ( material.normalMap ) {
  16183. uniforms.normalMap.value = material.normalMap;
  16184. uniforms.normalScale.value.copy( material.normalScale );
  16185. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  16186. }
  16187. if ( material.displacementMap ) {
  16188. uniforms.displacementMap.value = material.displacementMap;
  16189. uniforms.displacementScale.value = material.displacementScale;
  16190. uniforms.displacementBias.value = material.displacementBias;
  16191. }
  16192. const envMap = properties.get( material ).envMap;
  16193. if ( envMap ) {
  16194. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16195. uniforms.envMapIntensity.value = material.envMapIntensity;
  16196. }
  16197. }
  16198. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16199. refreshUniformsStandard( uniforms, material );
  16200. uniforms.ior.value = material.ior; // also part of uniforms common
  16201. if ( material.sheenTint ) uniforms.sheenTint.value.copy( material.sheenTint );
  16202. if ( material.clearcoat > 0 ) {
  16203. uniforms.clearcoat.value = material.clearcoat;
  16204. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16205. if ( material.clearcoatMap ) {
  16206. uniforms.clearcoatMap.value = material.clearcoatMap;
  16207. }
  16208. if ( material.clearcoatRoughnessMap ) {
  16209. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16210. }
  16211. if ( material.clearcoatNormalMap ) {
  16212. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16213. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16214. if ( material.side === BackSide ) {
  16215. uniforms.clearcoatNormalScale.value.negate();
  16216. }
  16217. }
  16218. }
  16219. if ( material.transmission > 0 ) {
  16220. uniforms.transmission.value = material.transmission;
  16221. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16222. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16223. if ( material.transmissionMap ) {
  16224. uniforms.transmissionMap.value = material.transmissionMap;
  16225. }
  16226. uniforms.thickness.value = material.thickness;
  16227. if ( material.thicknessMap ) {
  16228. uniforms.thicknessMap.value = material.thicknessMap;
  16229. }
  16230. uniforms.attenuationDistance.value = material.attenuationDistance;
  16231. uniforms.attenuationTint.value.copy( material.attenuationTint );
  16232. }
  16233. uniforms.specularIntensity.value = material.specularIntensity;
  16234. uniforms.specularTint.value.copy( material.specularTint );
  16235. if ( material.specularIntensityMap ) {
  16236. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16237. }
  16238. if ( material.specularTintMap ) {
  16239. uniforms.specularTintMap.value = material.specularTintMap;
  16240. }
  16241. }
  16242. function refreshUniformsMatcap( uniforms, material ) {
  16243. if ( material.matcap ) {
  16244. uniforms.matcap.value = material.matcap;
  16245. }
  16246. if ( material.bumpMap ) {
  16247. uniforms.bumpMap.value = material.bumpMap;
  16248. uniforms.bumpScale.value = material.bumpScale;
  16249. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  16250. }
  16251. if ( material.normalMap ) {
  16252. uniforms.normalMap.value = material.normalMap;
  16253. uniforms.normalScale.value.copy( material.normalScale );
  16254. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  16255. }
  16256. if ( material.displacementMap ) {
  16257. uniforms.displacementMap.value = material.displacementMap;
  16258. uniforms.displacementScale.value = material.displacementScale;
  16259. uniforms.displacementBias.value = material.displacementBias;
  16260. }
  16261. }
  16262. function refreshUniformsDepth( uniforms, material ) {
  16263. if ( material.displacementMap ) {
  16264. uniforms.displacementMap.value = material.displacementMap;
  16265. uniforms.displacementScale.value = material.displacementScale;
  16266. uniforms.displacementBias.value = material.displacementBias;
  16267. }
  16268. }
  16269. function refreshUniformsDistance( uniforms, material ) {
  16270. if ( material.displacementMap ) {
  16271. uniforms.displacementMap.value = material.displacementMap;
  16272. uniforms.displacementScale.value = material.displacementScale;
  16273. uniforms.displacementBias.value = material.displacementBias;
  16274. }
  16275. uniforms.referencePosition.value.copy( material.referencePosition );
  16276. uniforms.nearDistance.value = material.nearDistance;
  16277. uniforms.farDistance.value = material.farDistance;
  16278. }
  16279. function refreshUniformsNormal( uniforms, material ) {
  16280. if ( material.bumpMap ) {
  16281. uniforms.bumpMap.value = material.bumpMap;
  16282. uniforms.bumpScale.value = material.bumpScale;
  16283. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  16284. }
  16285. if ( material.normalMap ) {
  16286. uniforms.normalMap.value = material.normalMap;
  16287. uniforms.normalScale.value.copy( material.normalScale );
  16288. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  16289. }
  16290. if ( material.displacementMap ) {
  16291. uniforms.displacementMap.value = material.displacementMap;
  16292. uniforms.displacementScale.value = material.displacementScale;
  16293. uniforms.displacementBias.value = material.displacementBias;
  16294. }
  16295. }
  16296. return {
  16297. refreshFogUniforms: refreshFogUniforms,
  16298. refreshMaterialUniforms: refreshMaterialUniforms
  16299. };
  16300. }
  16301. function createCanvasElement() {
  16302. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  16303. canvas.style.display = 'block';
  16304. return canvas;
  16305. }
  16306. function WebGLRenderer( parameters = {} ) {
  16307. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16308. _context = parameters.context !== undefined ? parameters.context : null,
  16309. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  16310. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16311. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16312. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16313. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16314. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16315. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16316. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16317. let currentRenderList = null;
  16318. let currentRenderState = null;
  16319. // render() can be called from within a callback triggered by another render.
  16320. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16321. const renderListStack = [];
  16322. const renderStateStack = [];
  16323. // public properties
  16324. this.domElement = _canvas;
  16325. // Debug configuration container
  16326. this.debug = {
  16327. /**
  16328. * Enables error checking and reporting when shader programs are being compiled
  16329. * @type {boolean}
  16330. */
  16331. checkShaderErrors: true
  16332. };
  16333. // clearing
  16334. this.autoClear = true;
  16335. this.autoClearColor = true;
  16336. this.autoClearDepth = true;
  16337. this.autoClearStencil = true;
  16338. // scene graph
  16339. this.sortObjects = true;
  16340. // user-defined clipping
  16341. this.clippingPlanes = [];
  16342. this.localClippingEnabled = false;
  16343. // physically based shading
  16344. this.gammaFactor = 2.0; // for backwards compatibility
  16345. this.outputEncoding = LinearEncoding;
  16346. // physical lights
  16347. this.physicallyCorrectLights = false;
  16348. // tone mapping
  16349. this.toneMapping = NoToneMapping;
  16350. this.toneMappingExposure = 1.0;
  16351. // internal properties
  16352. const _this = this;
  16353. let _isContextLost = false;
  16354. // internal state cache
  16355. let _currentActiveCubeFace = 0;
  16356. let _currentActiveMipmapLevel = 0;
  16357. let _currentRenderTarget = null;
  16358. let _currentMaterialId = - 1;
  16359. let _currentCamera = null;
  16360. const _currentViewport = new Vector4();
  16361. const _currentScissor = new Vector4();
  16362. let _currentScissorTest = null;
  16363. //
  16364. let _width = _canvas.width;
  16365. let _height = _canvas.height;
  16366. let _pixelRatio = 1;
  16367. let _opaqueSort = null;
  16368. let _transparentSort = null;
  16369. const _viewport = new Vector4( 0, 0, _width, _height );
  16370. const _scissor = new Vector4( 0, 0, _width, _height );
  16371. let _scissorTest = false;
  16372. //
  16373. const _currentDrawBuffers = [];
  16374. // frustum
  16375. const _frustum = new Frustum();
  16376. // clipping
  16377. let _clippingEnabled = false;
  16378. let _localClippingEnabled = false;
  16379. // transmission
  16380. let _transmissionRenderTarget = null;
  16381. // camera matrices cache
  16382. const _projScreenMatrix = new Matrix4();
  16383. const _vector3 = new Vector3();
  16384. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16385. function getTargetPixelRatio() {
  16386. return _currentRenderTarget === null ? _pixelRatio : 1;
  16387. }
  16388. // initialize
  16389. let _gl = _context;
  16390. function getContext( contextNames, contextAttributes ) {
  16391. for ( let i = 0; i < contextNames.length; i ++ ) {
  16392. const contextName = contextNames[ i ];
  16393. const context = _canvas.getContext( contextName, contextAttributes );
  16394. if ( context !== null ) return context;
  16395. }
  16396. return null;
  16397. }
  16398. try {
  16399. const contextAttributes = {
  16400. alpha: _alpha,
  16401. depth: _depth,
  16402. stencil: _stencil,
  16403. antialias: _antialias,
  16404. premultipliedAlpha: _premultipliedAlpha,
  16405. preserveDrawingBuffer: _preserveDrawingBuffer,
  16406. powerPreference: _powerPreference,
  16407. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16408. };
  16409. // event listeners must be registered before WebGL context is created, see #12753
  16410. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16411. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16412. if ( _gl === null ) {
  16413. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16414. if ( _this.isWebGL1Renderer === true ) {
  16415. contextNames.shift();
  16416. }
  16417. _gl = getContext( contextNames, contextAttributes );
  16418. if ( _gl === null ) {
  16419. if ( getContext( contextNames ) ) {
  16420. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16421. } else {
  16422. throw new Error( 'Error creating WebGL context.' );
  16423. }
  16424. }
  16425. }
  16426. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16427. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16428. _gl.getShaderPrecisionFormat = function () {
  16429. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16430. };
  16431. }
  16432. } catch ( error ) {
  16433. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16434. throw error;
  16435. }
  16436. let extensions, capabilities, state, info;
  16437. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16438. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16439. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16440. let utils, bindingStates;
  16441. function initGLContext() {
  16442. extensions = new WebGLExtensions( _gl );
  16443. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16444. extensions.init( capabilities );
  16445. utils = new WebGLUtils( _gl, extensions, capabilities );
  16446. state = new WebGLState( _gl, extensions, capabilities );
  16447. _currentDrawBuffers[ 0 ] = 1029;
  16448. info = new WebGLInfo( _gl );
  16449. properties = new WebGLProperties();
  16450. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16451. cubemaps = new WebGLCubeMaps( _this );
  16452. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16453. attributes = new WebGLAttributes( _gl, capabilities );
  16454. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16455. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16456. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16457. morphtargets = new WebGLMorphtargets( _gl );
  16458. clipping = new WebGLClipping( properties );
  16459. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16460. materials = new WebGLMaterials( properties );
  16461. renderLists = new WebGLRenderLists( properties );
  16462. renderStates = new WebGLRenderStates( extensions, capabilities );
  16463. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  16464. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16465. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16466. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16467. info.programs = programCache.programs;
  16468. _this.capabilities = capabilities;
  16469. _this.extensions = extensions;
  16470. _this.properties = properties;
  16471. _this.renderLists = renderLists;
  16472. _this.shadowMap = shadowMap;
  16473. _this.state = state;
  16474. _this.info = info;
  16475. }
  16476. initGLContext();
  16477. // xr
  16478. const xr = new WebXRManager( _this, _gl );
  16479. this.xr = xr;
  16480. // API
  16481. this.getContext = function () {
  16482. return _gl;
  16483. };
  16484. this.getContextAttributes = function () {
  16485. return _gl.getContextAttributes();
  16486. };
  16487. this.forceContextLoss = function () {
  16488. const extension = extensions.get( 'WEBGL_lose_context' );
  16489. if ( extension ) extension.loseContext();
  16490. };
  16491. this.forceContextRestore = function () {
  16492. const extension = extensions.get( 'WEBGL_lose_context' );
  16493. if ( extension ) extension.restoreContext();
  16494. };
  16495. this.getPixelRatio = function () {
  16496. return _pixelRatio;
  16497. };
  16498. this.setPixelRatio = function ( value ) {
  16499. if ( value === undefined ) return;
  16500. _pixelRatio = value;
  16501. this.setSize( _width, _height, false );
  16502. };
  16503. this.getSize = function ( target ) {
  16504. return target.set( _width, _height );
  16505. };
  16506. this.setSize = function ( width, height, updateStyle ) {
  16507. if ( xr.isPresenting ) {
  16508. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16509. return;
  16510. }
  16511. _width = width;
  16512. _height = height;
  16513. _canvas.width = Math.floor( width * _pixelRatio );
  16514. _canvas.height = Math.floor( height * _pixelRatio );
  16515. if ( updateStyle !== false ) {
  16516. _canvas.style.width = width + 'px';
  16517. _canvas.style.height = height + 'px';
  16518. }
  16519. this.setViewport( 0, 0, width, height );
  16520. };
  16521. this.getDrawingBufferSize = function ( target ) {
  16522. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16523. };
  16524. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16525. _width = width;
  16526. _height = height;
  16527. _pixelRatio = pixelRatio;
  16528. _canvas.width = Math.floor( width * pixelRatio );
  16529. _canvas.height = Math.floor( height * pixelRatio );
  16530. this.setViewport( 0, 0, width, height );
  16531. };
  16532. this.getCurrentViewport = function ( target ) {
  16533. return target.copy( _currentViewport );
  16534. };
  16535. this.getViewport = function ( target ) {
  16536. return target.copy( _viewport );
  16537. };
  16538. this.setViewport = function ( x, y, width, height ) {
  16539. if ( x.isVector4 ) {
  16540. _viewport.set( x.x, x.y, x.z, x.w );
  16541. } else {
  16542. _viewport.set( x, y, width, height );
  16543. }
  16544. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16545. };
  16546. this.getScissor = function ( target ) {
  16547. return target.copy( _scissor );
  16548. };
  16549. this.setScissor = function ( x, y, width, height ) {
  16550. if ( x.isVector4 ) {
  16551. _scissor.set( x.x, x.y, x.z, x.w );
  16552. } else {
  16553. _scissor.set( x, y, width, height );
  16554. }
  16555. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16556. };
  16557. this.getScissorTest = function () {
  16558. return _scissorTest;
  16559. };
  16560. this.setScissorTest = function ( boolean ) {
  16561. state.setScissorTest( _scissorTest = boolean );
  16562. };
  16563. this.setOpaqueSort = function ( method ) {
  16564. _opaqueSort = method;
  16565. };
  16566. this.setTransparentSort = function ( method ) {
  16567. _transparentSort = method;
  16568. };
  16569. // Clearing
  16570. this.getClearColor = function ( target ) {
  16571. return target.copy( background.getClearColor() );
  16572. };
  16573. this.setClearColor = function () {
  16574. background.setClearColor.apply( background, arguments );
  16575. };
  16576. this.getClearAlpha = function () {
  16577. return background.getClearAlpha();
  16578. };
  16579. this.setClearAlpha = function () {
  16580. background.setClearAlpha.apply( background, arguments );
  16581. };
  16582. this.clear = function ( color, depth, stencil ) {
  16583. let bits = 0;
  16584. if ( color === undefined || color ) bits |= 16384;
  16585. if ( depth === undefined || depth ) bits |= 256;
  16586. if ( stencil === undefined || stencil ) bits |= 1024;
  16587. _gl.clear( bits );
  16588. };
  16589. this.clearColor = function () {
  16590. this.clear( true, false, false );
  16591. };
  16592. this.clearDepth = function () {
  16593. this.clear( false, true, false );
  16594. };
  16595. this.clearStencil = function () {
  16596. this.clear( false, false, true );
  16597. };
  16598. //
  16599. this.dispose = function () {
  16600. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16601. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16602. renderLists.dispose();
  16603. renderStates.dispose();
  16604. properties.dispose();
  16605. cubemaps.dispose();
  16606. cubeuvmaps.dispose();
  16607. objects.dispose();
  16608. bindingStates.dispose();
  16609. xr.dispose();
  16610. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16611. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16612. if ( _transmissionRenderTarget ) {
  16613. _transmissionRenderTarget.dispose();
  16614. _transmissionRenderTarget = null;
  16615. }
  16616. animation.stop();
  16617. };
  16618. // Events
  16619. function onContextLost( event ) {
  16620. event.preventDefault();
  16621. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16622. _isContextLost = true;
  16623. }
  16624. function onContextRestore( /* event */ ) {
  16625. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16626. _isContextLost = false;
  16627. const infoAutoReset = info.autoReset;
  16628. const shadowMapEnabled = shadowMap.enabled;
  16629. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16630. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16631. const shadowMapType = shadowMap.type;
  16632. initGLContext();
  16633. info.autoReset = infoAutoReset;
  16634. shadowMap.enabled = shadowMapEnabled;
  16635. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16636. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16637. shadowMap.type = shadowMapType;
  16638. }
  16639. function onMaterialDispose( event ) {
  16640. const material = event.target;
  16641. material.removeEventListener( 'dispose', onMaterialDispose );
  16642. deallocateMaterial( material );
  16643. }
  16644. // Buffer deallocation
  16645. function deallocateMaterial( material ) {
  16646. releaseMaterialProgramReferences( material );
  16647. properties.remove( material );
  16648. }
  16649. function releaseMaterialProgramReferences( material ) {
  16650. const programs = properties.get( material ).programs;
  16651. if ( programs !== undefined ) {
  16652. programs.forEach( function ( program ) {
  16653. programCache.releaseProgram( program );
  16654. } );
  16655. }
  16656. }
  16657. // Buffer rendering
  16658. function renderObjectImmediate( object, program ) {
  16659. object.render( function ( object ) {
  16660. _this.renderBufferImmediate( object, program );
  16661. } );
  16662. }
  16663. this.renderBufferImmediate = function ( object, program ) {
  16664. bindingStates.initAttributes();
  16665. const buffers = properties.get( object );
  16666. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  16667. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  16668. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  16669. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  16670. const programAttributes = program.getAttributes();
  16671. if ( object.hasPositions ) {
  16672. _gl.bindBuffer( 34962, buffers.position );
  16673. _gl.bufferData( 34962, object.positionArray, 35048 );
  16674. bindingStates.enableAttribute( programAttributes.position.location );
  16675. _gl.vertexAttribPointer( programAttributes.position.location, 3, 5126, false, 0, 0 );
  16676. }
  16677. if ( object.hasNormals ) {
  16678. _gl.bindBuffer( 34962, buffers.normal );
  16679. _gl.bufferData( 34962, object.normalArray, 35048 );
  16680. bindingStates.enableAttribute( programAttributes.normal.location );
  16681. _gl.vertexAttribPointer( programAttributes.normal.location, 3, 5126, false, 0, 0 );
  16682. }
  16683. if ( object.hasUvs ) {
  16684. _gl.bindBuffer( 34962, buffers.uv );
  16685. _gl.bufferData( 34962, object.uvArray, 35048 );
  16686. bindingStates.enableAttribute( programAttributes.uv.location );
  16687. _gl.vertexAttribPointer( programAttributes.uv.location, 2, 5126, false, 0, 0 );
  16688. }
  16689. if ( object.hasColors ) {
  16690. _gl.bindBuffer( 34962, buffers.color );
  16691. _gl.bufferData( 34962, object.colorArray, 35048 );
  16692. bindingStates.enableAttribute( programAttributes.color.location );
  16693. _gl.vertexAttribPointer( programAttributes.color.location, 3, 5126, false, 0, 0 );
  16694. }
  16695. bindingStates.disableUnusedAttributes();
  16696. _gl.drawArrays( 4, 0, object.count );
  16697. object.count = 0;
  16698. };
  16699. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16700. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16701. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16702. const program = setProgram( camera, scene, material, object );
  16703. state.setMaterial( material, frontFaceCW );
  16704. //
  16705. let index = geometry.index;
  16706. const position = geometry.attributes.position;
  16707. //
  16708. if ( index === null ) {
  16709. if ( position === undefined || position.count === 0 ) return;
  16710. } else if ( index.count === 0 ) {
  16711. return;
  16712. }
  16713. //
  16714. let rangeFactor = 1;
  16715. if ( material.wireframe === true ) {
  16716. index = geometries.getWireframeAttribute( geometry );
  16717. rangeFactor = 2;
  16718. }
  16719. if ( geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined ) {
  16720. morphtargets.update( object, geometry, material, program );
  16721. }
  16722. bindingStates.setup( object, material, program, geometry, index );
  16723. let attribute;
  16724. let renderer = bufferRenderer;
  16725. if ( index !== null ) {
  16726. attribute = attributes.get( index );
  16727. renderer = indexedBufferRenderer;
  16728. renderer.setIndex( attribute );
  16729. }
  16730. //
  16731. const dataCount = ( index !== null ) ? index.count : position.count;
  16732. const rangeStart = geometry.drawRange.start * rangeFactor;
  16733. const rangeCount = geometry.drawRange.count * rangeFactor;
  16734. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16735. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16736. const drawStart = Math.max( rangeStart, groupStart );
  16737. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16738. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16739. if ( drawCount === 0 ) return;
  16740. //
  16741. if ( object.isMesh ) {
  16742. if ( material.wireframe === true ) {
  16743. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16744. renderer.setMode( 1 );
  16745. } else {
  16746. renderer.setMode( 4 );
  16747. }
  16748. } else if ( object.isLine ) {
  16749. let lineWidth = material.linewidth;
  16750. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16751. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16752. if ( object.isLineSegments ) {
  16753. renderer.setMode( 1 );
  16754. } else if ( object.isLineLoop ) {
  16755. renderer.setMode( 2 );
  16756. } else {
  16757. renderer.setMode( 3 );
  16758. }
  16759. } else if ( object.isPoints ) {
  16760. renderer.setMode( 0 );
  16761. } else if ( object.isSprite ) {
  16762. renderer.setMode( 4 );
  16763. }
  16764. if ( object.isInstancedMesh ) {
  16765. renderer.renderInstances( drawStart, drawCount, object.count );
  16766. } else if ( geometry.isInstancedBufferGeometry ) {
  16767. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  16768. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16769. } else {
  16770. renderer.render( drawStart, drawCount );
  16771. }
  16772. };
  16773. // Compile
  16774. this.compile = function ( scene, camera ) {
  16775. currentRenderState = renderStates.get( scene );
  16776. currentRenderState.init();
  16777. renderStateStack.push( currentRenderState );
  16778. scene.traverseVisible( function ( object ) {
  16779. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16780. currentRenderState.pushLight( object );
  16781. if ( object.castShadow ) {
  16782. currentRenderState.pushShadow( object );
  16783. }
  16784. }
  16785. } );
  16786. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16787. scene.traverse( function ( object ) {
  16788. const material = object.material;
  16789. if ( material ) {
  16790. if ( Array.isArray( material ) ) {
  16791. for ( let i = 0; i < material.length; i ++ ) {
  16792. const material2 = material[ i ];
  16793. getProgram( material2, scene, object );
  16794. }
  16795. } else {
  16796. getProgram( material, scene, object );
  16797. }
  16798. }
  16799. } );
  16800. renderStateStack.pop();
  16801. currentRenderState = null;
  16802. };
  16803. // Animation Loop
  16804. let onAnimationFrameCallback = null;
  16805. function onAnimationFrame( time ) {
  16806. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16807. }
  16808. function onXRSessionStart() {
  16809. animation.stop();
  16810. }
  16811. function onXRSessionEnd() {
  16812. animation.start();
  16813. }
  16814. const animation = new WebGLAnimation();
  16815. animation.setAnimationLoop( onAnimationFrame );
  16816. if ( typeof window !== 'undefined' ) animation.setContext( window );
  16817. this.setAnimationLoop = function ( callback ) {
  16818. onAnimationFrameCallback = callback;
  16819. xr.setAnimationLoop( callback );
  16820. ( callback === null ) ? animation.stop() : animation.start();
  16821. };
  16822. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16823. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16824. // Rendering
  16825. this.render = function ( scene, camera ) {
  16826. if ( camera !== undefined && camera.isCamera !== true ) {
  16827. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16828. return;
  16829. }
  16830. if ( _isContextLost === true ) return;
  16831. // update scene graph
  16832. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  16833. // update camera matrices and frustum
  16834. if ( camera.parent === null ) camera.updateMatrixWorld();
  16835. if ( xr.enabled === true && xr.isPresenting === true ) {
  16836. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16837. camera = xr.getCamera(); // use XR camera for rendering
  16838. }
  16839. //
  16840. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16841. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16842. currentRenderState.init();
  16843. renderStateStack.push( currentRenderState );
  16844. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16845. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16846. _localClippingEnabled = this.localClippingEnabled;
  16847. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16848. currentRenderList = renderLists.get( scene, renderListStack.length );
  16849. currentRenderList.init();
  16850. renderListStack.push( currentRenderList );
  16851. projectObject( scene, camera, 0, _this.sortObjects );
  16852. currentRenderList.finish();
  16853. if ( _this.sortObjects === true ) {
  16854. currentRenderList.sort( _opaqueSort, _transparentSort );
  16855. }
  16856. //
  16857. if ( _clippingEnabled === true ) clipping.beginShadows();
  16858. const shadowsArray = currentRenderState.state.shadowsArray;
  16859. shadowMap.render( shadowsArray, scene, camera );
  16860. if ( _clippingEnabled === true ) clipping.endShadows();
  16861. //
  16862. if ( this.info.autoReset === true ) this.info.reset();
  16863. //
  16864. background.render( currentRenderList, scene );
  16865. // render scene
  16866. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16867. if ( camera.isArrayCamera ) {
  16868. const cameras = camera.cameras;
  16869. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16870. const camera2 = cameras[ i ];
  16871. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16872. }
  16873. } else {
  16874. renderScene( currentRenderList, scene, camera );
  16875. }
  16876. //
  16877. if ( _currentRenderTarget !== null ) {
  16878. // resolve multisample renderbuffers to a single-sample texture if necessary
  16879. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16880. // Generate mipmap if we're using any kind of mipmap filtering
  16881. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16882. }
  16883. //
  16884. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16885. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16886. state.buffers.depth.setTest( true );
  16887. state.buffers.depth.setMask( true );
  16888. state.buffers.color.setMask( true );
  16889. state.setPolygonOffset( false );
  16890. // _gl.finish();
  16891. bindingStates.resetDefaultState();
  16892. _currentMaterialId = - 1;
  16893. _currentCamera = null;
  16894. renderStateStack.pop();
  16895. if ( renderStateStack.length > 0 ) {
  16896. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16897. } else {
  16898. currentRenderState = null;
  16899. }
  16900. renderListStack.pop();
  16901. if ( renderListStack.length > 0 ) {
  16902. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16903. } else {
  16904. currentRenderList = null;
  16905. }
  16906. };
  16907. function projectObject( object, camera, groupOrder, sortObjects ) {
  16908. if ( object.visible === false ) return;
  16909. const visible = object.layers.test( camera.layers );
  16910. if ( visible ) {
  16911. if ( object.isGroup ) {
  16912. groupOrder = object.renderOrder;
  16913. } else if ( object.isLOD ) {
  16914. if ( object.autoUpdate === true ) object.update( camera );
  16915. } else if ( object.isLight ) {
  16916. currentRenderState.pushLight( object );
  16917. if ( object.castShadow ) {
  16918. currentRenderState.pushShadow( object );
  16919. }
  16920. } else if ( object.isSprite ) {
  16921. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16922. if ( sortObjects ) {
  16923. _vector3.setFromMatrixPosition( object.matrixWorld )
  16924. .applyMatrix4( _projScreenMatrix );
  16925. }
  16926. const geometry = objects.update( object );
  16927. const material = object.material;
  16928. if ( material.visible ) {
  16929. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16930. }
  16931. }
  16932. } else if ( object.isImmediateRenderObject ) {
  16933. if ( sortObjects ) {
  16934. _vector3.setFromMatrixPosition( object.matrixWorld )
  16935. .applyMatrix4( _projScreenMatrix );
  16936. }
  16937. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  16938. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16939. if ( object.isSkinnedMesh ) {
  16940. // update skeleton only once in a frame
  16941. if ( object.skeleton.frame !== info.render.frame ) {
  16942. object.skeleton.update();
  16943. object.skeleton.frame = info.render.frame;
  16944. }
  16945. }
  16946. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16947. if ( sortObjects ) {
  16948. _vector3.setFromMatrixPosition( object.matrixWorld )
  16949. .applyMatrix4( _projScreenMatrix );
  16950. }
  16951. const geometry = objects.update( object );
  16952. const material = object.material;
  16953. if ( Array.isArray( material ) ) {
  16954. const groups = geometry.groups;
  16955. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16956. const group = groups[ i ];
  16957. const groupMaterial = material[ group.materialIndex ];
  16958. if ( groupMaterial && groupMaterial.visible ) {
  16959. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16960. }
  16961. }
  16962. } else if ( material.visible ) {
  16963. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16964. }
  16965. }
  16966. }
  16967. }
  16968. const children = object.children;
  16969. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16970. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16971. }
  16972. }
  16973. function renderScene( currentRenderList, scene, camera, viewport ) {
  16974. const opaqueObjects = currentRenderList.opaque;
  16975. const transmissiveObjects = currentRenderList.transmissive;
  16976. const transparentObjects = currentRenderList.transparent;
  16977. currentRenderState.setupLightsView( camera );
  16978. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16979. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16980. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16981. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16982. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16983. }
  16984. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16985. if ( _transmissionRenderTarget === null ) {
  16986. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  16987. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  16988. _transmissionRenderTarget = new renderTargetType( 1024, 1024, {
  16989. generateMipmaps: true,
  16990. type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType,
  16991. minFilter: LinearMipmapLinearFilter,
  16992. magFilter: NearestFilter,
  16993. wrapS: ClampToEdgeWrapping,
  16994. wrapT: ClampToEdgeWrapping
  16995. } );
  16996. }
  16997. const currentRenderTarget = _this.getRenderTarget();
  16998. _this.setRenderTarget( _transmissionRenderTarget );
  16999. _this.clear();
  17000. // Turn off the features which can affect the frag color for opaque objects pass.
  17001. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17002. const currentToneMapping = _this.toneMapping;
  17003. _this.toneMapping = NoToneMapping;
  17004. renderObjects( opaqueObjects, scene, camera );
  17005. _this.toneMapping = currentToneMapping;
  17006. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17007. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17008. _this.setRenderTarget( currentRenderTarget );
  17009. }
  17010. function renderObjects( renderList, scene, camera ) {
  17011. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17012. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17013. const renderItem = renderList[ i ];
  17014. const object = renderItem.object;
  17015. const geometry = renderItem.geometry;
  17016. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17017. const group = renderItem.group;
  17018. if ( object.layers.test( camera.layers ) ) {
  17019. renderObject( object, scene, camera, geometry, material, group );
  17020. }
  17021. }
  17022. }
  17023. function renderObject( object, scene, camera, geometry, material, group ) {
  17024. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17025. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17026. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17027. if ( object.isImmediateRenderObject ) {
  17028. const program = setProgram( camera, scene, material, object );
  17029. state.setMaterial( material );
  17030. bindingStates.reset();
  17031. renderObjectImmediate( object, program );
  17032. } else {
  17033. if ( material.transparent === true && material.side === DoubleSide ) {
  17034. material.side = BackSide;
  17035. material.needsUpdate = true;
  17036. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17037. material.side = FrontSide;
  17038. material.needsUpdate = true;
  17039. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17040. material.side = DoubleSide;
  17041. } else {
  17042. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17043. }
  17044. }
  17045. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17046. }
  17047. function getProgram( material, scene, object ) {
  17048. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17049. const materialProperties = properties.get( material );
  17050. const lights = currentRenderState.state.lights;
  17051. const shadowsArray = currentRenderState.state.shadowsArray;
  17052. const lightsStateVersion = lights.state.version;
  17053. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17054. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17055. let programs = materialProperties.programs;
  17056. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17057. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17058. materialProperties.fog = scene.fog;
  17059. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17060. if ( programs === undefined ) {
  17061. // new material
  17062. material.addEventListener( 'dispose', onMaterialDispose );
  17063. programs = new Map();
  17064. materialProperties.programs = programs;
  17065. }
  17066. let program = programs.get( programCacheKey );
  17067. if ( program !== undefined ) {
  17068. // early out if program and light state is identical
  17069. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17070. updateCommonMaterialProperties( material, parameters );
  17071. return program;
  17072. }
  17073. } else {
  17074. parameters.uniforms = programCache.getUniforms( material );
  17075. material.onBuild( parameters, _this );
  17076. material.onBeforeCompile( parameters, _this );
  17077. program = programCache.acquireProgram( parameters, programCacheKey );
  17078. programs.set( programCacheKey, program );
  17079. materialProperties.uniforms = parameters.uniforms;
  17080. }
  17081. const uniforms = materialProperties.uniforms;
  17082. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17083. uniforms.clippingPlanes = clipping.uniform;
  17084. }
  17085. updateCommonMaterialProperties( material, parameters );
  17086. // store the light setup it was created for
  17087. materialProperties.needsLights = materialNeedsLights( material );
  17088. materialProperties.lightsStateVersion = lightsStateVersion;
  17089. if ( materialProperties.needsLights ) {
  17090. // wire up the material to this renderer's lighting state
  17091. uniforms.ambientLightColor.value = lights.state.ambient;
  17092. uniforms.lightProbe.value = lights.state.probe;
  17093. uniforms.directionalLights.value = lights.state.directional;
  17094. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17095. uniforms.spotLights.value = lights.state.spot;
  17096. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17097. uniforms.rectAreaLights.value = lights.state.rectArea;
  17098. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17099. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17100. uniforms.pointLights.value = lights.state.point;
  17101. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17102. uniforms.hemisphereLights.value = lights.state.hemi;
  17103. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17104. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17105. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17106. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  17107. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17108. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17109. // TODO (abelnation): add area lights shadow info to uniforms
  17110. }
  17111. const progUniforms = program.getUniforms();
  17112. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17113. materialProperties.currentProgram = program;
  17114. materialProperties.uniformsList = uniformsList;
  17115. return program;
  17116. }
  17117. function updateCommonMaterialProperties( material, parameters ) {
  17118. const materialProperties = properties.get( material );
  17119. materialProperties.outputEncoding = parameters.outputEncoding;
  17120. materialProperties.instancing = parameters.instancing;
  17121. materialProperties.skinning = parameters.skinning;
  17122. materialProperties.morphTargets = parameters.morphTargets;
  17123. materialProperties.morphNormals = parameters.morphNormals;
  17124. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17125. materialProperties.numIntersection = parameters.numClipIntersection;
  17126. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17127. materialProperties.vertexTangents = parameters.vertexTangents;
  17128. }
  17129. function setProgram( camera, scene, material, object ) {
  17130. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17131. textures.resetTextureUnits();
  17132. const fog = scene.fog;
  17133. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17134. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  17135. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17136. const vertexAlphas = material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  17137. const vertexTangents = !! object.geometry && !! object.geometry.attributes.tangent;
  17138. const morphTargets = !! object.geometry && !! object.geometry.morphAttributes.position;
  17139. const morphNormals = !! object.geometry && !! object.geometry.morphAttributes.normal;
  17140. const materialProperties = properties.get( material );
  17141. const lights = currentRenderState.state.lights;
  17142. if ( _clippingEnabled === true ) {
  17143. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17144. const useCache =
  17145. camera === _currentCamera &&
  17146. material.id === _currentMaterialId;
  17147. // we might want to call this function with some ClippingGroup
  17148. // object instead of the material, once it becomes feasible
  17149. // (#8465, #8379)
  17150. clipping.setState( material, camera, useCache );
  17151. }
  17152. }
  17153. //
  17154. let needsProgramChange = false;
  17155. if ( material.version === materialProperties.__version ) {
  17156. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17157. needsProgramChange = true;
  17158. } else if ( materialProperties.outputEncoding !== encoding ) {
  17159. needsProgramChange = true;
  17160. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17161. needsProgramChange = true;
  17162. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17163. needsProgramChange = true;
  17164. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17165. needsProgramChange = true;
  17166. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17167. needsProgramChange = true;
  17168. } else if ( materialProperties.envMap !== envMap ) {
  17169. needsProgramChange = true;
  17170. } else if ( material.fog && materialProperties.fog !== fog ) {
  17171. needsProgramChange = true;
  17172. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17173. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17174. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17175. needsProgramChange = true;
  17176. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17177. needsProgramChange = true;
  17178. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17179. needsProgramChange = true;
  17180. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17181. needsProgramChange = true;
  17182. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17183. needsProgramChange = true;
  17184. }
  17185. } else {
  17186. needsProgramChange = true;
  17187. materialProperties.__version = material.version;
  17188. }
  17189. //
  17190. let program = materialProperties.currentProgram;
  17191. if ( needsProgramChange === true ) {
  17192. program = getProgram( material, scene, object );
  17193. }
  17194. let refreshProgram = false;
  17195. let refreshMaterial = false;
  17196. let refreshLights = false;
  17197. const p_uniforms = program.getUniforms(),
  17198. m_uniforms = materialProperties.uniforms;
  17199. if ( state.useProgram( program.program ) ) {
  17200. refreshProgram = true;
  17201. refreshMaterial = true;
  17202. refreshLights = true;
  17203. }
  17204. if ( material.id !== _currentMaterialId ) {
  17205. _currentMaterialId = material.id;
  17206. refreshMaterial = true;
  17207. }
  17208. if ( refreshProgram || _currentCamera !== camera ) {
  17209. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17210. if ( capabilities.logarithmicDepthBuffer ) {
  17211. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17212. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17213. }
  17214. if ( _currentCamera !== camera ) {
  17215. _currentCamera = camera;
  17216. // lighting uniforms depend on the camera so enforce an update
  17217. // now, in case this material supports lights - or later, when
  17218. // the next material that does gets activated:
  17219. refreshMaterial = true; // set to true on material change
  17220. refreshLights = true; // remains set until update done
  17221. }
  17222. // load material specific uniforms
  17223. // (shader material also gets them for the sake of genericity)
  17224. if ( material.isShaderMaterial ||
  17225. material.isMeshPhongMaterial ||
  17226. material.isMeshToonMaterial ||
  17227. material.isMeshStandardMaterial ||
  17228. material.envMap ) {
  17229. const uCamPos = p_uniforms.map.cameraPosition;
  17230. if ( uCamPos !== undefined ) {
  17231. uCamPos.setValue( _gl,
  17232. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17233. }
  17234. }
  17235. if ( material.isMeshPhongMaterial ||
  17236. material.isMeshToonMaterial ||
  17237. material.isMeshLambertMaterial ||
  17238. material.isMeshBasicMaterial ||
  17239. material.isMeshStandardMaterial ||
  17240. material.isShaderMaterial ) {
  17241. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17242. }
  17243. if ( material.isMeshPhongMaterial ||
  17244. material.isMeshToonMaterial ||
  17245. material.isMeshLambertMaterial ||
  17246. material.isMeshBasicMaterial ||
  17247. material.isMeshStandardMaterial ||
  17248. material.isShaderMaterial ||
  17249. material.isShadowMaterial ||
  17250. object.isSkinnedMesh ) {
  17251. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17252. }
  17253. }
  17254. // skinning uniforms must be set even if material didn't change
  17255. // auto-setting of texture unit for bone texture must go before other textures
  17256. // otherwise textures used for skinning can take over texture units reserved for other material textures
  17257. if ( object.isSkinnedMesh ) {
  17258. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17259. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17260. const skeleton = object.skeleton;
  17261. if ( skeleton ) {
  17262. if ( capabilities.floatVertexTextures ) {
  17263. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17264. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17265. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17266. } else {
  17267. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  17268. }
  17269. }
  17270. }
  17271. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17272. materialProperties.receiveShadow = object.receiveShadow;
  17273. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17274. }
  17275. if ( refreshMaterial ) {
  17276. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17277. if ( materialProperties.needsLights ) {
  17278. // the current material requires lighting info
  17279. // note: all lighting uniforms are always set correctly
  17280. // they simply reference the renderer's state for their
  17281. // values
  17282. //
  17283. // use the current material's .needsUpdate flags to set
  17284. // the GL state when required
  17285. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17286. }
  17287. // refresh uniforms common to several materials
  17288. if ( fog && material.fog ) {
  17289. materials.refreshFogUniforms( m_uniforms, fog );
  17290. }
  17291. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17292. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17293. }
  17294. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17295. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17296. material.uniformsNeedUpdate = false;
  17297. }
  17298. if ( material.isSpriteMaterial ) {
  17299. p_uniforms.setValue( _gl, 'center', object.center );
  17300. }
  17301. // common matrices
  17302. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17303. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17304. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17305. return program;
  17306. }
  17307. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17308. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17309. uniforms.ambientLightColor.needsUpdate = value;
  17310. uniforms.lightProbe.needsUpdate = value;
  17311. uniforms.directionalLights.needsUpdate = value;
  17312. uniforms.directionalLightShadows.needsUpdate = value;
  17313. uniforms.pointLights.needsUpdate = value;
  17314. uniforms.pointLightShadows.needsUpdate = value;
  17315. uniforms.spotLights.needsUpdate = value;
  17316. uniforms.spotLightShadows.needsUpdate = value;
  17317. uniforms.rectAreaLights.needsUpdate = value;
  17318. uniforms.hemisphereLights.needsUpdate = value;
  17319. }
  17320. function materialNeedsLights( material ) {
  17321. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17322. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17323. ( material.isShaderMaterial && material.lights === true );
  17324. }
  17325. this.getActiveCubeFace = function () {
  17326. return _currentActiveCubeFace;
  17327. };
  17328. this.getActiveMipmapLevel = function () {
  17329. return _currentActiveMipmapLevel;
  17330. };
  17331. this.getRenderTarget = function () {
  17332. return _currentRenderTarget;
  17333. };
  17334. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17335. _currentRenderTarget = renderTarget;
  17336. _currentActiveCubeFace = activeCubeFace;
  17337. _currentActiveMipmapLevel = activeMipmapLevel;
  17338. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  17339. textures.setupRenderTarget( renderTarget );
  17340. }
  17341. let framebuffer = null;
  17342. let isCube = false;
  17343. let isRenderTarget3D = false;
  17344. if ( renderTarget ) {
  17345. const texture = renderTarget.texture;
  17346. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  17347. isRenderTarget3D = true;
  17348. }
  17349. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17350. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17351. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17352. isCube = true;
  17353. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  17354. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17355. } else {
  17356. framebuffer = __webglFramebuffer;
  17357. }
  17358. _currentViewport.copy( renderTarget.viewport );
  17359. _currentScissor.copy( renderTarget.scissor );
  17360. _currentScissorTest = renderTarget.scissorTest;
  17361. } else {
  17362. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17363. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17364. _currentScissorTest = _scissorTest;
  17365. }
  17366. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17367. if ( framebufferBound && capabilities.drawBuffers ) {
  17368. let needsUpdate = false;
  17369. if ( renderTarget ) {
  17370. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  17371. const textures = renderTarget.texture;
  17372. if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
  17373. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  17374. _currentDrawBuffers[ i ] = 36064 + i;
  17375. }
  17376. _currentDrawBuffers.length = textures.length;
  17377. needsUpdate = true;
  17378. }
  17379. } else {
  17380. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
  17381. _currentDrawBuffers[ 0 ] = 36064;
  17382. _currentDrawBuffers.length = 1;
  17383. needsUpdate = true;
  17384. }
  17385. }
  17386. } else {
  17387. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
  17388. _currentDrawBuffers[ 0 ] = 1029;
  17389. _currentDrawBuffers.length = 1;
  17390. needsUpdate = true;
  17391. }
  17392. }
  17393. if ( needsUpdate ) {
  17394. if ( capabilities.isWebGL2 ) {
  17395. _gl.drawBuffers( _currentDrawBuffers );
  17396. } else {
  17397. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
  17398. }
  17399. }
  17400. }
  17401. state.viewport( _currentViewport );
  17402. state.scissor( _currentScissor );
  17403. state.setScissorTest( _currentScissorTest );
  17404. if ( isCube ) {
  17405. const textureProperties = properties.get( renderTarget.texture );
  17406. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17407. } else if ( isRenderTarget3D ) {
  17408. const textureProperties = properties.get( renderTarget.texture );
  17409. const layer = activeCubeFace || 0;
  17410. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17411. }
  17412. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17413. };
  17414. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17415. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17416. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17417. return;
  17418. }
  17419. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17420. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17421. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17422. }
  17423. if ( framebuffer ) {
  17424. state.bindFramebuffer( 36160, framebuffer );
  17425. try {
  17426. const texture = renderTarget.texture;
  17427. const textureFormat = texture.format;
  17428. const textureType = texture.type;
  17429. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17430. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17431. return;
  17432. }
  17433. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17434. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17435. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17436. ! halfFloatSupportedByExt ) {
  17437. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17438. return;
  17439. }
  17440. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  17441. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17442. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17443. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17444. }
  17445. } else {
  17446. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  17447. }
  17448. } finally {
  17449. // restore framebuffer of current render target if necessary
  17450. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17451. state.bindFramebuffer( 36160, framebuffer );
  17452. }
  17453. }
  17454. };
  17455. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17456. const levelScale = Math.pow( 2, - level );
  17457. const width = Math.floor( texture.image.width * levelScale );
  17458. const height = Math.floor( texture.image.height * levelScale );
  17459. let glFormat = utils.convert( texture.format );
  17460. if ( capabilities.isWebGL2 ) {
  17461. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  17462. // Not needed in Chrome 93+
  17463. if ( glFormat === 6407 ) glFormat = 32849;
  17464. if ( glFormat === 6408 ) glFormat = 32856;
  17465. }
  17466. textures.setTexture2D( texture, 0 );
  17467. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  17468. state.unbindTexture();
  17469. };
  17470. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17471. const width = srcTexture.image.width;
  17472. const height = srcTexture.image.height;
  17473. const glFormat = utils.convert( dstTexture.format );
  17474. const glType = utils.convert( dstTexture.type );
  17475. textures.setTexture2D( dstTexture, 0 );
  17476. // As another texture upload may have changed pixelStorei
  17477. // parameters, make sure they are correct for the dstTexture
  17478. _gl.pixelStorei( 37440, dstTexture.flipY );
  17479. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17480. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17481. if ( srcTexture.isDataTexture ) {
  17482. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17483. } else {
  17484. if ( srcTexture.isCompressedTexture ) {
  17485. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17486. } else {
  17487. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17488. }
  17489. }
  17490. // Generate mipmaps only when copying level 0
  17491. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17492. state.unbindTexture();
  17493. };
  17494. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17495. if ( _this.isWebGL1Renderer ) {
  17496. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17497. return;
  17498. }
  17499. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17500. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17501. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17502. const glFormat = utils.convert( dstTexture.format );
  17503. const glType = utils.convert( dstTexture.type );
  17504. let glTarget;
  17505. if ( dstTexture.isDataTexture3D ) {
  17506. textures.setTexture3D( dstTexture, 0 );
  17507. glTarget = 32879;
  17508. } else if ( dstTexture.isDataTexture2DArray ) {
  17509. textures.setTexture2DArray( dstTexture, 0 );
  17510. glTarget = 35866;
  17511. } else {
  17512. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17513. return;
  17514. }
  17515. _gl.pixelStorei( 37440, dstTexture.flipY );
  17516. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17517. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17518. const unpackRowLen = _gl.getParameter( 3314 );
  17519. const unpackImageHeight = _gl.getParameter( 32878 );
  17520. const unpackSkipPixels = _gl.getParameter( 3316 );
  17521. const unpackSkipRows = _gl.getParameter( 3315 );
  17522. const unpackSkipImages = _gl.getParameter( 32877 );
  17523. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17524. _gl.pixelStorei( 3314, image.width );
  17525. _gl.pixelStorei( 32878, image.height );
  17526. _gl.pixelStorei( 3316, sourceBox.min.x );
  17527. _gl.pixelStorei( 3315, sourceBox.min.y );
  17528. _gl.pixelStorei( 32877, sourceBox.min.z );
  17529. if ( srcTexture.isDataTexture || srcTexture.isDataTexture3D ) {
  17530. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17531. } else {
  17532. if ( srcTexture.isCompressedTexture ) {
  17533. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17534. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17535. } else {
  17536. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17537. }
  17538. }
  17539. _gl.pixelStorei( 3314, unpackRowLen );
  17540. _gl.pixelStorei( 32878, unpackImageHeight );
  17541. _gl.pixelStorei( 3316, unpackSkipPixels );
  17542. _gl.pixelStorei( 3315, unpackSkipRows );
  17543. _gl.pixelStorei( 32877, unpackSkipImages );
  17544. // Generate mipmaps only when copying level 0
  17545. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17546. state.unbindTexture();
  17547. };
  17548. this.initTexture = function ( texture ) {
  17549. textures.setTexture2D( texture, 0 );
  17550. state.unbindTexture();
  17551. };
  17552. this.resetState = function () {
  17553. _currentActiveCubeFace = 0;
  17554. _currentActiveMipmapLevel = 0;
  17555. _currentRenderTarget = null;
  17556. state.reset();
  17557. bindingStates.reset();
  17558. };
  17559. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17560. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  17561. }
  17562. }
  17563. class WebGL1Renderer extends WebGLRenderer {}
  17564. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17565. class FogExp2 {
  17566. constructor( color, density = 0.00025 ) {
  17567. this.name = '';
  17568. this.color = new Color( color );
  17569. this.density = density;
  17570. }
  17571. clone() {
  17572. return new FogExp2( this.color, this.density );
  17573. }
  17574. toJSON( /* meta */ ) {
  17575. return {
  17576. type: 'FogExp2',
  17577. color: this.color.getHex(),
  17578. density: this.density
  17579. };
  17580. }
  17581. }
  17582. FogExp2.prototype.isFogExp2 = true;
  17583. class Fog {
  17584. constructor( color, near = 1, far = 1000 ) {
  17585. this.name = '';
  17586. this.color = new Color( color );
  17587. this.near = near;
  17588. this.far = far;
  17589. }
  17590. clone() {
  17591. return new Fog( this.color, this.near, this.far );
  17592. }
  17593. toJSON( /* meta */ ) {
  17594. return {
  17595. type: 'Fog',
  17596. color: this.color.getHex(),
  17597. near: this.near,
  17598. far: this.far
  17599. };
  17600. }
  17601. }
  17602. Fog.prototype.isFog = true;
  17603. class Scene extends Object3D {
  17604. constructor() {
  17605. super();
  17606. this.type = 'Scene';
  17607. this.background = null;
  17608. this.environment = null;
  17609. this.fog = null;
  17610. this.overrideMaterial = null;
  17611. this.autoUpdate = true; // checked by the renderer
  17612. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17613. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  17614. }
  17615. }
  17616. copy( source, recursive ) {
  17617. super.copy( source, recursive );
  17618. if ( source.background !== null ) this.background = source.background.clone();
  17619. if ( source.environment !== null ) this.environment = source.environment.clone();
  17620. if ( source.fog !== null ) this.fog = source.fog.clone();
  17621. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17622. this.autoUpdate = source.autoUpdate;
  17623. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17624. return this;
  17625. }
  17626. toJSON( meta ) {
  17627. const data = super.toJSON( meta );
  17628. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17629. return data;
  17630. }
  17631. }
  17632. Scene.prototype.isScene = true;
  17633. class InterleavedBuffer {
  17634. constructor( array, stride ) {
  17635. this.array = array;
  17636. this.stride = stride;
  17637. this.count = array !== undefined ? array.length / stride : 0;
  17638. this.usage = StaticDrawUsage;
  17639. this.updateRange = { offset: 0, count: - 1 };
  17640. this.version = 0;
  17641. this.uuid = generateUUID();
  17642. }
  17643. onUploadCallback() {}
  17644. set needsUpdate( value ) {
  17645. if ( value === true ) this.version ++;
  17646. }
  17647. setUsage( value ) {
  17648. this.usage = value;
  17649. return this;
  17650. }
  17651. copy( source ) {
  17652. this.array = new source.array.constructor( source.array );
  17653. this.count = source.count;
  17654. this.stride = source.stride;
  17655. this.usage = source.usage;
  17656. return this;
  17657. }
  17658. copyAt( index1, attribute, index2 ) {
  17659. index1 *= this.stride;
  17660. index2 *= attribute.stride;
  17661. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17662. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17663. }
  17664. return this;
  17665. }
  17666. set( value, offset = 0 ) {
  17667. this.array.set( value, offset );
  17668. return this;
  17669. }
  17670. clone( data ) {
  17671. if ( data.arrayBuffers === undefined ) {
  17672. data.arrayBuffers = {};
  17673. }
  17674. if ( this.array.buffer._uuid === undefined ) {
  17675. this.array.buffer._uuid = generateUUID();
  17676. }
  17677. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17678. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17679. }
  17680. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17681. const ib = new this.constructor( array, this.stride );
  17682. ib.setUsage( this.usage );
  17683. return ib;
  17684. }
  17685. onUpload( callback ) {
  17686. this.onUploadCallback = callback;
  17687. return this;
  17688. }
  17689. toJSON( data ) {
  17690. if ( data.arrayBuffers === undefined ) {
  17691. data.arrayBuffers = {};
  17692. }
  17693. // generate UUID for array buffer if necessary
  17694. if ( this.array.buffer._uuid === undefined ) {
  17695. this.array.buffer._uuid = generateUUID();
  17696. }
  17697. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17698. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  17699. }
  17700. //
  17701. return {
  17702. uuid: this.uuid,
  17703. buffer: this.array.buffer._uuid,
  17704. type: this.array.constructor.name,
  17705. stride: this.stride
  17706. };
  17707. }
  17708. }
  17709. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  17710. const _vector$6 = /*@__PURE__*/ new Vector3();
  17711. class InterleavedBufferAttribute {
  17712. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17713. this.name = '';
  17714. this.data = interleavedBuffer;
  17715. this.itemSize = itemSize;
  17716. this.offset = offset;
  17717. this.normalized = normalized === true;
  17718. }
  17719. get count() {
  17720. return this.data.count;
  17721. }
  17722. get array() {
  17723. return this.data.array;
  17724. }
  17725. set needsUpdate( value ) {
  17726. this.data.needsUpdate = value;
  17727. }
  17728. applyMatrix4( m ) {
  17729. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17730. _vector$6.x = this.getX( i );
  17731. _vector$6.y = this.getY( i );
  17732. _vector$6.z = this.getZ( i );
  17733. _vector$6.applyMatrix4( m );
  17734. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17735. }
  17736. return this;
  17737. }
  17738. applyNormalMatrix( m ) {
  17739. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17740. _vector$6.x = this.getX( i );
  17741. _vector$6.y = this.getY( i );
  17742. _vector$6.z = this.getZ( i );
  17743. _vector$6.applyNormalMatrix( m );
  17744. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17745. }
  17746. return this;
  17747. }
  17748. transformDirection( m ) {
  17749. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17750. _vector$6.x = this.getX( i );
  17751. _vector$6.y = this.getY( i );
  17752. _vector$6.z = this.getZ( i );
  17753. _vector$6.transformDirection( m );
  17754. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17755. }
  17756. return this;
  17757. }
  17758. setX( index, x ) {
  17759. this.data.array[ index * this.data.stride + this.offset ] = x;
  17760. return this;
  17761. }
  17762. setY( index, y ) {
  17763. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17764. return this;
  17765. }
  17766. setZ( index, z ) {
  17767. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17768. return this;
  17769. }
  17770. setW( index, w ) {
  17771. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17772. return this;
  17773. }
  17774. getX( index ) {
  17775. return this.data.array[ index * this.data.stride + this.offset ];
  17776. }
  17777. getY( index ) {
  17778. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  17779. }
  17780. getZ( index ) {
  17781. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  17782. }
  17783. getW( index ) {
  17784. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  17785. }
  17786. setXY( index, x, y ) {
  17787. index = index * this.data.stride + this.offset;
  17788. this.data.array[ index + 0 ] = x;
  17789. this.data.array[ index + 1 ] = y;
  17790. return this;
  17791. }
  17792. setXYZ( index, x, y, z ) {
  17793. index = index * this.data.stride + this.offset;
  17794. this.data.array[ index + 0 ] = x;
  17795. this.data.array[ index + 1 ] = y;
  17796. this.data.array[ index + 2 ] = z;
  17797. return this;
  17798. }
  17799. setXYZW( index, x, y, z, w ) {
  17800. index = index * this.data.stride + this.offset;
  17801. this.data.array[ index + 0 ] = x;
  17802. this.data.array[ index + 1 ] = y;
  17803. this.data.array[ index + 2 ] = z;
  17804. this.data.array[ index + 3 ] = w;
  17805. return this;
  17806. }
  17807. clone( data ) {
  17808. if ( data === undefined ) {
  17809. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  17810. const array = [];
  17811. for ( let i = 0; i < this.count; i ++ ) {
  17812. const index = i * this.data.stride + this.offset;
  17813. for ( let j = 0; j < this.itemSize; j ++ ) {
  17814. array.push( this.data.array[ index + j ] );
  17815. }
  17816. }
  17817. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17818. } else {
  17819. if ( data.interleavedBuffers === undefined ) {
  17820. data.interleavedBuffers = {};
  17821. }
  17822. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17823. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17824. }
  17825. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17826. }
  17827. }
  17828. toJSON( data ) {
  17829. if ( data === undefined ) {
  17830. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  17831. const array = [];
  17832. for ( let i = 0; i < this.count; i ++ ) {
  17833. const index = i * this.data.stride + this.offset;
  17834. for ( let j = 0; j < this.itemSize; j ++ ) {
  17835. array.push( this.data.array[ index + j ] );
  17836. }
  17837. }
  17838. // deinterleave data and save it as an ordinary buffer attribute for now
  17839. return {
  17840. itemSize: this.itemSize,
  17841. type: this.array.constructor.name,
  17842. array: array,
  17843. normalized: this.normalized
  17844. };
  17845. } else {
  17846. // save as true interlaved attribtue
  17847. if ( data.interleavedBuffers === undefined ) {
  17848. data.interleavedBuffers = {};
  17849. }
  17850. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17851. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17852. }
  17853. return {
  17854. isInterleavedBufferAttribute: true,
  17855. itemSize: this.itemSize,
  17856. data: this.data.uuid,
  17857. offset: this.offset,
  17858. normalized: this.normalized
  17859. };
  17860. }
  17861. }
  17862. }
  17863. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  17864. /**
  17865. * parameters = {
  17866. * color: <hex>,
  17867. * map: new THREE.Texture( <Image> ),
  17868. * alphaMap: new THREE.Texture( <Image> ),
  17869. * rotation: <float>,
  17870. * sizeAttenuation: <bool>
  17871. * }
  17872. */
  17873. class SpriteMaterial extends Material {
  17874. constructor( parameters ) {
  17875. super();
  17876. this.type = 'SpriteMaterial';
  17877. this.color = new Color( 0xffffff );
  17878. this.map = null;
  17879. this.alphaMap = null;
  17880. this.rotation = 0;
  17881. this.sizeAttenuation = true;
  17882. this.transparent = true;
  17883. this.setValues( parameters );
  17884. }
  17885. copy( source ) {
  17886. super.copy( source );
  17887. this.color.copy( source.color );
  17888. this.map = source.map;
  17889. this.alphaMap = source.alphaMap;
  17890. this.rotation = source.rotation;
  17891. this.sizeAttenuation = source.sizeAttenuation;
  17892. return this;
  17893. }
  17894. }
  17895. SpriteMaterial.prototype.isSpriteMaterial = true;
  17896. let _geometry;
  17897. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17898. const _worldScale = /*@__PURE__*/ new Vector3();
  17899. const _mvPosition = /*@__PURE__*/ new Vector3();
  17900. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17901. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17902. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17903. const _vA = /*@__PURE__*/ new Vector3();
  17904. const _vB = /*@__PURE__*/ new Vector3();
  17905. const _vC = /*@__PURE__*/ new Vector3();
  17906. const _uvA = /*@__PURE__*/ new Vector2();
  17907. const _uvB = /*@__PURE__*/ new Vector2();
  17908. const _uvC = /*@__PURE__*/ new Vector2();
  17909. class Sprite extends Object3D {
  17910. constructor( material ) {
  17911. super();
  17912. this.type = 'Sprite';
  17913. if ( _geometry === undefined ) {
  17914. _geometry = new BufferGeometry();
  17915. const float32Array = new Float32Array( [
  17916. - 0.5, - 0.5, 0, 0, 0,
  17917. 0.5, - 0.5, 0, 1, 0,
  17918. 0.5, 0.5, 0, 1, 1,
  17919. - 0.5, 0.5, 0, 0, 1
  17920. ] );
  17921. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17922. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17923. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17924. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17925. }
  17926. this.geometry = _geometry;
  17927. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17928. this.center = new Vector2( 0.5, 0.5 );
  17929. }
  17930. raycast( raycaster, intersects ) {
  17931. if ( raycaster.camera === null ) {
  17932. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17933. }
  17934. _worldScale.setFromMatrixScale( this.matrixWorld );
  17935. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17936. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17937. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17938. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17939. _worldScale.multiplyScalar( - _mvPosition.z );
  17940. }
  17941. const rotation = this.material.rotation;
  17942. let sin, cos;
  17943. if ( rotation !== 0 ) {
  17944. cos = Math.cos( rotation );
  17945. sin = Math.sin( rotation );
  17946. }
  17947. const center = this.center;
  17948. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17949. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17950. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17951. _uvA.set( 0, 0 );
  17952. _uvB.set( 1, 0 );
  17953. _uvC.set( 1, 1 );
  17954. // check first triangle
  17955. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17956. if ( intersect === null ) {
  17957. // check second triangle
  17958. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17959. _uvB.set( 0, 1 );
  17960. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17961. if ( intersect === null ) {
  17962. return;
  17963. }
  17964. }
  17965. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17966. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17967. intersects.push( {
  17968. distance: distance,
  17969. point: _intersectPoint.clone(),
  17970. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17971. face: null,
  17972. object: this
  17973. } );
  17974. }
  17975. copy( source ) {
  17976. super.copy( source );
  17977. if ( source.center !== undefined ) this.center.copy( source.center );
  17978. this.material = source.material;
  17979. return this;
  17980. }
  17981. }
  17982. Sprite.prototype.isSprite = true;
  17983. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17984. // compute position in camera space
  17985. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17986. // to check if rotation is not zero
  17987. if ( sin !== undefined ) {
  17988. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17989. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17990. } else {
  17991. _rotatedPosition.copy( _alignedPosition );
  17992. }
  17993. vertexPosition.copy( mvPosition );
  17994. vertexPosition.x += _rotatedPosition.x;
  17995. vertexPosition.y += _rotatedPosition.y;
  17996. // transform to world space
  17997. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17998. }
  17999. const _v1$2 = /*@__PURE__*/ new Vector3();
  18000. const _v2$1 = /*@__PURE__*/ new Vector3();
  18001. class LOD extends Object3D {
  18002. constructor() {
  18003. super();
  18004. this._currentLevel = 0;
  18005. this.type = 'LOD';
  18006. Object.defineProperties( this, {
  18007. levels: {
  18008. enumerable: true,
  18009. value: []
  18010. },
  18011. isLOD: {
  18012. value: true,
  18013. }
  18014. } );
  18015. this.autoUpdate = true;
  18016. }
  18017. copy( source ) {
  18018. super.copy( source, false );
  18019. const levels = source.levels;
  18020. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18021. const level = levels[ i ];
  18022. this.addLevel( level.object.clone(), level.distance );
  18023. }
  18024. this.autoUpdate = source.autoUpdate;
  18025. return this;
  18026. }
  18027. addLevel( object, distance = 0 ) {
  18028. distance = Math.abs( distance );
  18029. const levels = this.levels;
  18030. let l;
  18031. for ( l = 0; l < levels.length; l ++ ) {
  18032. if ( distance < levels[ l ].distance ) {
  18033. break;
  18034. }
  18035. }
  18036. levels.splice( l, 0, { distance: distance, object: object } );
  18037. this.add( object );
  18038. return this;
  18039. }
  18040. getCurrentLevel() {
  18041. return this._currentLevel;
  18042. }
  18043. getObjectForDistance( distance ) {
  18044. const levels = this.levels;
  18045. if ( levels.length > 0 ) {
  18046. let i, l;
  18047. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18048. if ( distance < levels[ i ].distance ) {
  18049. break;
  18050. }
  18051. }
  18052. return levels[ i - 1 ].object;
  18053. }
  18054. return null;
  18055. }
  18056. raycast( raycaster, intersects ) {
  18057. const levels = this.levels;
  18058. if ( levels.length > 0 ) {
  18059. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18060. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18061. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18062. }
  18063. }
  18064. update( camera ) {
  18065. const levels = this.levels;
  18066. if ( levels.length > 1 ) {
  18067. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18068. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18069. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18070. levels[ 0 ].object.visible = true;
  18071. let i, l;
  18072. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18073. if ( distance >= levels[ i ].distance ) {
  18074. levels[ i - 1 ].object.visible = false;
  18075. levels[ i ].object.visible = true;
  18076. } else {
  18077. break;
  18078. }
  18079. }
  18080. this._currentLevel = i - 1;
  18081. for ( ; i < l; i ++ ) {
  18082. levels[ i ].object.visible = false;
  18083. }
  18084. }
  18085. }
  18086. toJSON( meta ) {
  18087. const data = super.toJSON( meta );
  18088. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18089. data.object.levels = [];
  18090. const levels = this.levels;
  18091. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18092. const level = levels[ i ];
  18093. data.object.levels.push( {
  18094. object: level.object.uuid,
  18095. distance: level.distance
  18096. } );
  18097. }
  18098. return data;
  18099. }
  18100. }
  18101. const _basePosition = /*@__PURE__*/ new Vector3();
  18102. const _skinIndex = /*@__PURE__*/ new Vector4();
  18103. const _skinWeight = /*@__PURE__*/ new Vector4();
  18104. const _vector$5 = /*@__PURE__*/ new Vector3();
  18105. const _matrix = /*@__PURE__*/ new Matrix4();
  18106. class SkinnedMesh extends Mesh {
  18107. constructor( geometry, material ) {
  18108. super( geometry, material );
  18109. this.type = 'SkinnedMesh';
  18110. this.bindMode = 'attached';
  18111. this.bindMatrix = new Matrix4();
  18112. this.bindMatrixInverse = new Matrix4();
  18113. }
  18114. copy( source ) {
  18115. super.copy( source );
  18116. this.bindMode = source.bindMode;
  18117. this.bindMatrix.copy( source.bindMatrix );
  18118. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18119. this.skeleton = source.skeleton;
  18120. return this;
  18121. }
  18122. bind( skeleton, bindMatrix ) {
  18123. this.skeleton = skeleton;
  18124. if ( bindMatrix === undefined ) {
  18125. this.updateMatrixWorld( true );
  18126. this.skeleton.calculateInverses();
  18127. bindMatrix = this.matrixWorld;
  18128. }
  18129. this.bindMatrix.copy( bindMatrix );
  18130. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18131. }
  18132. pose() {
  18133. this.skeleton.pose();
  18134. }
  18135. normalizeSkinWeights() {
  18136. const vector = new Vector4();
  18137. const skinWeight = this.geometry.attributes.skinWeight;
  18138. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18139. vector.x = skinWeight.getX( i );
  18140. vector.y = skinWeight.getY( i );
  18141. vector.z = skinWeight.getZ( i );
  18142. vector.w = skinWeight.getW( i );
  18143. const scale = 1.0 / vector.manhattanLength();
  18144. if ( scale !== Infinity ) {
  18145. vector.multiplyScalar( scale );
  18146. } else {
  18147. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18148. }
  18149. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18150. }
  18151. }
  18152. updateMatrixWorld( force ) {
  18153. super.updateMatrixWorld( force );
  18154. if ( this.bindMode === 'attached' ) {
  18155. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18156. } else if ( this.bindMode === 'detached' ) {
  18157. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18158. } else {
  18159. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18160. }
  18161. }
  18162. boneTransform( index, target ) {
  18163. const skeleton = this.skeleton;
  18164. const geometry = this.geometry;
  18165. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18166. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18167. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  18168. target.set( 0, 0, 0 );
  18169. for ( let i = 0; i < 4; i ++ ) {
  18170. const weight = _skinWeight.getComponent( i );
  18171. if ( weight !== 0 ) {
  18172. const boneIndex = _skinIndex.getComponent( i );
  18173. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18174. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18175. }
  18176. }
  18177. return target.applyMatrix4( this.bindMatrixInverse );
  18178. }
  18179. }
  18180. SkinnedMesh.prototype.isSkinnedMesh = true;
  18181. class Bone extends Object3D {
  18182. constructor() {
  18183. super();
  18184. this.type = 'Bone';
  18185. }
  18186. }
  18187. Bone.prototype.isBone = true;
  18188. class DataTexture extends Texture {
  18189. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18190. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18191. this.image = { data: data, width: width, height: height };
  18192. this.magFilter = magFilter;
  18193. this.minFilter = minFilter;
  18194. this.generateMipmaps = false;
  18195. this.flipY = false;
  18196. this.unpackAlignment = 1;
  18197. this.needsUpdate = true;
  18198. }
  18199. }
  18200. DataTexture.prototype.isDataTexture = true;
  18201. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18202. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18203. class Skeleton {
  18204. constructor( bones = [], boneInverses = [] ) {
  18205. this.uuid = generateUUID();
  18206. this.bones = bones.slice( 0 );
  18207. this.boneInverses = boneInverses;
  18208. this.boneMatrices = null;
  18209. this.boneTexture = null;
  18210. this.boneTextureSize = 0;
  18211. this.frame = - 1;
  18212. this.init();
  18213. }
  18214. init() {
  18215. const bones = this.bones;
  18216. const boneInverses = this.boneInverses;
  18217. this.boneMatrices = new Float32Array( bones.length * 16 );
  18218. // calculate inverse bone matrices if necessary
  18219. if ( boneInverses.length === 0 ) {
  18220. this.calculateInverses();
  18221. } else {
  18222. // handle special case
  18223. if ( bones.length !== boneInverses.length ) {
  18224. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18225. this.boneInverses = [];
  18226. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18227. this.boneInverses.push( new Matrix4() );
  18228. }
  18229. }
  18230. }
  18231. }
  18232. calculateInverses() {
  18233. this.boneInverses.length = 0;
  18234. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18235. const inverse = new Matrix4();
  18236. if ( this.bones[ i ] ) {
  18237. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18238. }
  18239. this.boneInverses.push( inverse );
  18240. }
  18241. }
  18242. pose() {
  18243. // recover the bind-time world matrices
  18244. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18245. const bone = this.bones[ i ];
  18246. if ( bone ) {
  18247. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18248. }
  18249. }
  18250. // compute the local matrices, positions, rotations and scales
  18251. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18252. const bone = this.bones[ i ];
  18253. if ( bone ) {
  18254. if ( bone.parent && bone.parent.isBone ) {
  18255. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18256. bone.matrix.multiply( bone.matrixWorld );
  18257. } else {
  18258. bone.matrix.copy( bone.matrixWorld );
  18259. }
  18260. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18261. }
  18262. }
  18263. }
  18264. update() {
  18265. const bones = this.bones;
  18266. const boneInverses = this.boneInverses;
  18267. const boneMatrices = this.boneMatrices;
  18268. const boneTexture = this.boneTexture;
  18269. // flatten bone matrices to array
  18270. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18271. // compute the offset between the current and the original transform
  18272. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18273. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18274. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18275. }
  18276. if ( boneTexture !== null ) {
  18277. boneTexture.needsUpdate = true;
  18278. }
  18279. }
  18280. clone() {
  18281. return new Skeleton( this.bones, this.boneInverses );
  18282. }
  18283. computeBoneTexture() {
  18284. // layout (1 matrix = 4 pixels)
  18285. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18286. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18287. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18288. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18289. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18290. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18291. size = ceilPowerOfTwo( size );
  18292. size = Math.max( size, 4 );
  18293. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18294. boneMatrices.set( this.boneMatrices ); // copy current values
  18295. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18296. this.boneMatrices = boneMatrices;
  18297. this.boneTexture = boneTexture;
  18298. this.boneTextureSize = size;
  18299. return this;
  18300. }
  18301. getBoneByName( name ) {
  18302. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18303. const bone = this.bones[ i ];
  18304. if ( bone.name === name ) {
  18305. return bone;
  18306. }
  18307. }
  18308. return undefined;
  18309. }
  18310. dispose( ) {
  18311. if ( this.boneTexture !== null ) {
  18312. this.boneTexture.dispose();
  18313. this.boneTexture = null;
  18314. }
  18315. }
  18316. fromJSON( json, bones ) {
  18317. this.uuid = json.uuid;
  18318. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18319. const uuid = json.bones[ i ];
  18320. let bone = bones[ uuid ];
  18321. if ( bone === undefined ) {
  18322. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18323. bone = new Bone();
  18324. }
  18325. this.bones.push( bone );
  18326. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18327. }
  18328. this.init();
  18329. return this;
  18330. }
  18331. toJSON() {
  18332. const data = {
  18333. metadata: {
  18334. version: 4.5,
  18335. type: 'Skeleton',
  18336. generator: 'Skeleton.toJSON'
  18337. },
  18338. bones: [],
  18339. boneInverses: []
  18340. };
  18341. data.uuid = this.uuid;
  18342. const bones = this.bones;
  18343. const boneInverses = this.boneInverses;
  18344. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18345. const bone = bones[ i ];
  18346. data.bones.push( bone.uuid );
  18347. const boneInverse = boneInverses[ i ];
  18348. data.boneInverses.push( boneInverse.toArray() );
  18349. }
  18350. return data;
  18351. }
  18352. }
  18353. class InstancedBufferAttribute extends BufferAttribute {
  18354. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18355. if ( typeof normalized === 'number' ) {
  18356. meshPerAttribute = normalized;
  18357. normalized = false;
  18358. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  18359. }
  18360. super( array, itemSize, normalized );
  18361. this.meshPerAttribute = meshPerAttribute;
  18362. }
  18363. copy( source ) {
  18364. super.copy( source );
  18365. this.meshPerAttribute = source.meshPerAttribute;
  18366. return this;
  18367. }
  18368. toJSON() {
  18369. const data = super.toJSON();
  18370. data.meshPerAttribute = this.meshPerAttribute;
  18371. data.isInstancedBufferAttribute = true;
  18372. return data;
  18373. }
  18374. }
  18375. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  18376. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18377. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18378. const _instanceIntersects = [];
  18379. const _mesh = /*@__PURE__*/ new Mesh();
  18380. class InstancedMesh extends Mesh {
  18381. constructor( geometry, material, count ) {
  18382. super( geometry, material );
  18383. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18384. this.instanceColor = null;
  18385. this.count = count;
  18386. this.frustumCulled = false;
  18387. }
  18388. copy( source ) {
  18389. super.copy( source );
  18390. this.instanceMatrix.copy( source.instanceMatrix );
  18391. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18392. this.count = source.count;
  18393. return this;
  18394. }
  18395. getColorAt( index, color ) {
  18396. color.fromArray( this.instanceColor.array, index * 3 );
  18397. }
  18398. getMatrixAt( index, matrix ) {
  18399. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18400. }
  18401. raycast( raycaster, intersects ) {
  18402. const matrixWorld = this.matrixWorld;
  18403. const raycastTimes = this.count;
  18404. _mesh.geometry = this.geometry;
  18405. _mesh.material = this.material;
  18406. if ( _mesh.material === undefined ) return;
  18407. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18408. // calculate the world matrix for each instance
  18409. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18410. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18411. // the mesh represents this single instance
  18412. _mesh.matrixWorld = _instanceWorldMatrix;
  18413. _mesh.raycast( raycaster, _instanceIntersects );
  18414. // process the result of raycast
  18415. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18416. const intersect = _instanceIntersects[ i ];
  18417. intersect.instanceId = instanceId;
  18418. intersect.object = this;
  18419. intersects.push( intersect );
  18420. }
  18421. _instanceIntersects.length = 0;
  18422. }
  18423. }
  18424. setColorAt( index, color ) {
  18425. if ( this.instanceColor === null ) {
  18426. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18427. }
  18428. color.toArray( this.instanceColor.array, index * 3 );
  18429. }
  18430. setMatrixAt( index, matrix ) {
  18431. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18432. }
  18433. updateMorphTargets() {
  18434. }
  18435. dispose() {
  18436. this.dispatchEvent( { type: 'dispose' } );
  18437. }
  18438. }
  18439. InstancedMesh.prototype.isInstancedMesh = true;
  18440. /**
  18441. * parameters = {
  18442. * color: <hex>,
  18443. * opacity: <float>,
  18444. *
  18445. * linewidth: <float>,
  18446. * linecap: "round",
  18447. * linejoin: "round"
  18448. * }
  18449. */
  18450. class LineBasicMaterial extends Material {
  18451. constructor( parameters ) {
  18452. super();
  18453. this.type = 'LineBasicMaterial';
  18454. this.color = new Color( 0xffffff );
  18455. this.linewidth = 1;
  18456. this.linecap = 'round';
  18457. this.linejoin = 'round';
  18458. this.setValues( parameters );
  18459. }
  18460. copy( source ) {
  18461. super.copy( source );
  18462. this.color.copy( source.color );
  18463. this.linewidth = source.linewidth;
  18464. this.linecap = source.linecap;
  18465. this.linejoin = source.linejoin;
  18466. return this;
  18467. }
  18468. }
  18469. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  18470. const _start$1 = /*@__PURE__*/ new Vector3();
  18471. const _end$1 = /*@__PURE__*/ new Vector3();
  18472. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18473. const _ray$1 = /*@__PURE__*/ new Ray();
  18474. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18475. class Line extends Object3D {
  18476. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18477. super();
  18478. this.type = 'Line';
  18479. this.geometry = geometry;
  18480. this.material = material;
  18481. this.updateMorphTargets();
  18482. }
  18483. copy( source ) {
  18484. super.copy( source );
  18485. this.material = source.material;
  18486. this.geometry = source.geometry;
  18487. return this;
  18488. }
  18489. computeLineDistances() {
  18490. const geometry = this.geometry;
  18491. if ( geometry.isBufferGeometry ) {
  18492. // we assume non-indexed geometry
  18493. if ( geometry.index === null ) {
  18494. const positionAttribute = geometry.attributes.position;
  18495. const lineDistances = [ 0 ];
  18496. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18497. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18498. _end$1.fromBufferAttribute( positionAttribute, i );
  18499. lineDistances[ i ] = lineDistances[ i - 1 ];
  18500. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18501. }
  18502. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18503. } else {
  18504. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18505. }
  18506. } else if ( geometry.isGeometry ) {
  18507. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18508. }
  18509. return this;
  18510. }
  18511. raycast( raycaster, intersects ) {
  18512. const geometry = this.geometry;
  18513. const matrixWorld = this.matrixWorld;
  18514. const threshold = raycaster.params.Line.threshold;
  18515. const drawRange = geometry.drawRange;
  18516. // Checking boundingSphere distance to ray
  18517. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18518. _sphere$1.copy( geometry.boundingSphere );
  18519. _sphere$1.applyMatrix4( matrixWorld );
  18520. _sphere$1.radius += threshold;
  18521. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18522. //
  18523. _inverseMatrix$1.copy( matrixWorld ).invert();
  18524. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18525. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18526. const localThresholdSq = localThreshold * localThreshold;
  18527. const vStart = new Vector3();
  18528. const vEnd = new Vector3();
  18529. const interSegment = new Vector3();
  18530. const interRay = new Vector3();
  18531. const step = this.isLineSegments ? 2 : 1;
  18532. if ( geometry.isBufferGeometry ) {
  18533. const index = geometry.index;
  18534. const attributes = geometry.attributes;
  18535. const positionAttribute = attributes.position;
  18536. if ( index !== null ) {
  18537. const start = Math.max( 0, drawRange.start );
  18538. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18539. for ( let i = start, l = end - 1; i < l; i += step ) {
  18540. const a = index.getX( i );
  18541. const b = index.getX( i + 1 );
  18542. vStart.fromBufferAttribute( positionAttribute, a );
  18543. vEnd.fromBufferAttribute( positionAttribute, b );
  18544. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18545. if ( distSq > localThresholdSq ) continue;
  18546. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18547. const distance = raycaster.ray.origin.distanceTo( interRay );
  18548. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18549. intersects.push( {
  18550. distance: distance,
  18551. // What do we want? intersection point on the ray or on the segment??
  18552. // point: raycaster.ray.at( distance ),
  18553. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18554. index: i,
  18555. face: null,
  18556. faceIndex: null,
  18557. object: this
  18558. } );
  18559. }
  18560. } else {
  18561. const start = Math.max( 0, drawRange.start );
  18562. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18563. for ( let i = start, l = end - 1; i < l; i += step ) {
  18564. vStart.fromBufferAttribute( positionAttribute, i );
  18565. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18566. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18567. if ( distSq > localThresholdSq ) continue;
  18568. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18569. const distance = raycaster.ray.origin.distanceTo( interRay );
  18570. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18571. intersects.push( {
  18572. distance: distance,
  18573. // What do we want? intersection point on the ray or on the segment??
  18574. // point: raycaster.ray.at( distance ),
  18575. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18576. index: i,
  18577. face: null,
  18578. faceIndex: null,
  18579. object: this
  18580. } );
  18581. }
  18582. }
  18583. } else if ( geometry.isGeometry ) {
  18584. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18585. }
  18586. }
  18587. updateMorphTargets() {
  18588. const geometry = this.geometry;
  18589. if ( geometry.isBufferGeometry ) {
  18590. const morphAttributes = geometry.morphAttributes;
  18591. const keys = Object.keys( morphAttributes );
  18592. if ( keys.length > 0 ) {
  18593. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18594. if ( morphAttribute !== undefined ) {
  18595. this.morphTargetInfluences = [];
  18596. this.morphTargetDictionary = {};
  18597. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18598. const name = morphAttribute[ m ].name || String( m );
  18599. this.morphTargetInfluences.push( 0 );
  18600. this.morphTargetDictionary[ name ] = m;
  18601. }
  18602. }
  18603. }
  18604. } else {
  18605. const morphTargets = geometry.morphTargets;
  18606. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  18607. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18608. }
  18609. }
  18610. }
  18611. }
  18612. Line.prototype.isLine = true;
  18613. const _start = /*@__PURE__*/ new Vector3();
  18614. const _end = /*@__PURE__*/ new Vector3();
  18615. class LineSegments extends Line {
  18616. constructor( geometry, material ) {
  18617. super( geometry, material );
  18618. this.type = 'LineSegments';
  18619. }
  18620. computeLineDistances() {
  18621. const geometry = this.geometry;
  18622. if ( geometry.isBufferGeometry ) {
  18623. // we assume non-indexed geometry
  18624. if ( geometry.index === null ) {
  18625. const positionAttribute = geometry.attributes.position;
  18626. const lineDistances = [];
  18627. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18628. _start.fromBufferAttribute( positionAttribute, i );
  18629. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18630. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18631. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18632. }
  18633. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18634. } else {
  18635. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18636. }
  18637. } else if ( geometry.isGeometry ) {
  18638. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18639. }
  18640. return this;
  18641. }
  18642. }
  18643. LineSegments.prototype.isLineSegments = true;
  18644. class LineLoop extends Line {
  18645. constructor( geometry, material ) {
  18646. super( geometry, material );
  18647. this.type = 'LineLoop';
  18648. }
  18649. }
  18650. LineLoop.prototype.isLineLoop = true;
  18651. /**
  18652. * parameters = {
  18653. * color: <hex>,
  18654. * opacity: <float>,
  18655. * map: new THREE.Texture( <Image> ),
  18656. * alphaMap: new THREE.Texture( <Image> ),
  18657. *
  18658. * size: <float>,
  18659. * sizeAttenuation: <bool>
  18660. *
  18661. * }
  18662. */
  18663. class PointsMaterial extends Material {
  18664. constructor( parameters ) {
  18665. super();
  18666. this.type = 'PointsMaterial';
  18667. this.color = new Color( 0xffffff );
  18668. this.map = null;
  18669. this.alphaMap = null;
  18670. this.size = 1;
  18671. this.sizeAttenuation = true;
  18672. this.setValues( parameters );
  18673. }
  18674. copy( source ) {
  18675. super.copy( source );
  18676. this.color.copy( source.color );
  18677. this.map = source.map;
  18678. this.alphaMap = source.alphaMap;
  18679. this.size = source.size;
  18680. this.sizeAttenuation = source.sizeAttenuation;
  18681. return this;
  18682. }
  18683. }
  18684. PointsMaterial.prototype.isPointsMaterial = true;
  18685. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18686. const _ray = /*@__PURE__*/ new Ray();
  18687. const _sphere = /*@__PURE__*/ new Sphere();
  18688. const _position$2 = /*@__PURE__*/ new Vector3();
  18689. class Points extends Object3D {
  18690. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18691. super();
  18692. this.type = 'Points';
  18693. this.geometry = geometry;
  18694. this.material = material;
  18695. this.updateMorphTargets();
  18696. }
  18697. copy( source ) {
  18698. super.copy( source );
  18699. this.material = source.material;
  18700. this.geometry = source.geometry;
  18701. return this;
  18702. }
  18703. raycast( raycaster, intersects ) {
  18704. const geometry = this.geometry;
  18705. const matrixWorld = this.matrixWorld;
  18706. const threshold = raycaster.params.Points.threshold;
  18707. const drawRange = geometry.drawRange;
  18708. // Checking boundingSphere distance to ray
  18709. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18710. _sphere.copy( geometry.boundingSphere );
  18711. _sphere.applyMatrix4( matrixWorld );
  18712. _sphere.radius += threshold;
  18713. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18714. //
  18715. _inverseMatrix.copy( matrixWorld ).invert();
  18716. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18717. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18718. const localThresholdSq = localThreshold * localThreshold;
  18719. if ( geometry.isBufferGeometry ) {
  18720. const index = geometry.index;
  18721. const attributes = geometry.attributes;
  18722. const positionAttribute = attributes.position;
  18723. if ( index !== null ) {
  18724. const start = Math.max( 0, drawRange.start );
  18725. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18726. for ( let i = start, il = end; i < il; i ++ ) {
  18727. const a = index.getX( i );
  18728. _position$2.fromBufferAttribute( positionAttribute, a );
  18729. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18730. }
  18731. } else {
  18732. const start = Math.max( 0, drawRange.start );
  18733. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18734. for ( let i = start, l = end; i < l; i ++ ) {
  18735. _position$2.fromBufferAttribute( positionAttribute, i );
  18736. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18737. }
  18738. }
  18739. } else {
  18740. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18741. }
  18742. }
  18743. updateMorphTargets() {
  18744. const geometry = this.geometry;
  18745. if ( geometry.isBufferGeometry ) {
  18746. const morphAttributes = geometry.morphAttributes;
  18747. const keys = Object.keys( morphAttributes );
  18748. if ( keys.length > 0 ) {
  18749. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18750. if ( morphAttribute !== undefined ) {
  18751. this.morphTargetInfluences = [];
  18752. this.morphTargetDictionary = {};
  18753. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18754. const name = morphAttribute[ m ].name || String( m );
  18755. this.morphTargetInfluences.push( 0 );
  18756. this.morphTargetDictionary[ name ] = m;
  18757. }
  18758. }
  18759. }
  18760. } else {
  18761. const morphTargets = geometry.morphTargets;
  18762. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  18763. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18764. }
  18765. }
  18766. }
  18767. }
  18768. Points.prototype.isPoints = true;
  18769. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18770. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18771. if ( rayPointDistanceSq < localThresholdSq ) {
  18772. const intersectPoint = new Vector3();
  18773. _ray.closestPointToPoint( point, intersectPoint );
  18774. intersectPoint.applyMatrix4( matrixWorld );
  18775. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18776. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18777. intersects.push( {
  18778. distance: distance,
  18779. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18780. point: intersectPoint,
  18781. index: index,
  18782. face: null,
  18783. object: object
  18784. } );
  18785. }
  18786. }
  18787. class VideoTexture extends Texture {
  18788. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18789. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18790. this.format = format !== undefined ? format : RGBFormat;
  18791. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18792. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18793. this.generateMipmaps = false;
  18794. const scope = this;
  18795. function updateVideo() {
  18796. scope.needsUpdate = true;
  18797. video.requestVideoFrameCallback( updateVideo );
  18798. }
  18799. if ( 'requestVideoFrameCallback' in video ) {
  18800. video.requestVideoFrameCallback( updateVideo );
  18801. }
  18802. }
  18803. clone() {
  18804. return new this.constructor( this.image ).copy( this );
  18805. }
  18806. update() {
  18807. const video = this.image;
  18808. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18809. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18810. this.needsUpdate = true;
  18811. }
  18812. }
  18813. }
  18814. VideoTexture.prototype.isVideoTexture = true;
  18815. class CompressedTexture extends Texture {
  18816. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18817. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18818. this.image = { width: width, height: height };
  18819. this.mipmaps = mipmaps;
  18820. // no flipping for cube textures
  18821. // (also flipping doesn't work for compressed textures )
  18822. this.flipY = false;
  18823. // can't generate mipmaps for compressed textures
  18824. // mips must be embedded in DDS files
  18825. this.generateMipmaps = false;
  18826. }
  18827. }
  18828. CompressedTexture.prototype.isCompressedTexture = true;
  18829. class CanvasTexture extends Texture {
  18830. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18831. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18832. this.needsUpdate = true;
  18833. }
  18834. }
  18835. CanvasTexture.prototype.isCanvasTexture = true;
  18836. class DepthTexture extends Texture {
  18837. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  18838. format = format !== undefined ? format : DepthFormat;
  18839. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  18840. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  18841. }
  18842. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  18843. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  18844. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18845. this.image = { width: width, height: height };
  18846. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18847. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18848. this.flipY = false;
  18849. this.generateMipmaps = false;
  18850. }
  18851. }
  18852. DepthTexture.prototype.isDepthTexture = true;
  18853. class CircleGeometry extends BufferGeometry {
  18854. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18855. super();
  18856. this.type = 'CircleGeometry';
  18857. this.parameters = {
  18858. radius: radius,
  18859. segments: segments,
  18860. thetaStart: thetaStart,
  18861. thetaLength: thetaLength
  18862. };
  18863. segments = Math.max( 3, segments );
  18864. // buffers
  18865. const indices = [];
  18866. const vertices = [];
  18867. const normals = [];
  18868. const uvs = [];
  18869. // helper variables
  18870. const vertex = new Vector3();
  18871. const uv = new Vector2();
  18872. // center point
  18873. vertices.push( 0, 0, 0 );
  18874. normals.push( 0, 0, 1 );
  18875. uvs.push( 0.5, 0.5 );
  18876. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  18877. const segment = thetaStart + s / segments * thetaLength;
  18878. // vertex
  18879. vertex.x = radius * Math.cos( segment );
  18880. vertex.y = radius * Math.sin( segment );
  18881. vertices.push( vertex.x, vertex.y, vertex.z );
  18882. // normal
  18883. normals.push( 0, 0, 1 );
  18884. // uvs
  18885. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  18886. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  18887. uvs.push( uv.x, uv.y );
  18888. }
  18889. // indices
  18890. for ( let i = 1; i <= segments; i ++ ) {
  18891. indices.push( i, i + 1, 0 );
  18892. }
  18893. // build geometry
  18894. this.setIndex( indices );
  18895. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18896. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18897. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18898. }
  18899. static fromJSON( data ) {
  18900. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  18901. }
  18902. }
  18903. class CylinderGeometry extends BufferGeometry {
  18904. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18905. super();
  18906. this.type = 'CylinderGeometry';
  18907. this.parameters = {
  18908. radiusTop: radiusTop,
  18909. radiusBottom: radiusBottom,
  18910. height: height,
  18911. radialSegments: radialSegments,
  18912. heightSegments: heightSegments,
  18913. openEnded: openEnded,
  18914. thetaStart: thetaStart,
  18915. thetaLength: thetaLength
  18916. };
  18917. const scope = this;
  18918. radialSegments = Math.floor( radialSegments );
  18919. heightSegments = Math.floor( heightSegments );
  18920. // buffers
  18921. const indices = [];
  18922. const vertices = [];
  18923. const normals = [];
  18924. const uvs = [];
  18925. // helper variables
  18926. let index = 0;
  18927. const indexArray = [];
  18928. const halfHeight = height / 2;
  18929. let groupStart = 0;
  18930. // generate geometry
  18931. generateTorso();
  18932. if ( openEnded === false ) {
  18933. if ( radiusTop > 0 ) generateCap( true );
  18934. if ( radiusBottom > 0 ) generateCap( false );
  18935. }
  18936. // build geometry
  18937. this.setIndex( indices );
  18938. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18939. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18940. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18941. function generateTorso() {
  18942. const normal = new Vector3();
  18943. const vertex = new Vector3();
  18944. let groupCount = 0;
  18945. // this will be used to calculate the normal
  18946. const slope = ( radiusBottom - radiusTop ) / height;
  18947. // generate vertices, normals and uvs
  18948. for ( let y = 0; y <= heightSegments; y ++ ) {
  18949. const indexRow = [];
  18950. const v = y / heightSegments;
  18951. // calculate the radius of the current row
  18952. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18953. for ( let x = 0; x <= radialSegments; x ++ ) {
  18954. const u = x / radialSegments;
  18955. const theta = u * thetaLength + thetaStart;
  18956. const sinTheta = Math.sin( theta );
  18957. const cosTheta = Math.cos( theta );
  18958. // vertex
  18959. vertex.x = radius * sinTheta;
  18960. vertex.y = - v * height + halfHeight;
  18961. vertex.z = radius * cosTheta;
  18962. vertices.push( vertex.x, vertex.y, vertex.z );
  18963. // normal
  18964. normal.set( sinTheta, slope, cosTheta ).normalize();
  18965. normals.push( normal.x, normal.y, normal.z );
  18966. // uv
  18967. uvs.push( u, 1 - v );
  18968. // save index of vertex in respective row
  18969. indexRow.push( index ++ );
  18970. }
  18971. // now save vertices of the row in our index array
  18972. indexArray.push( indexRow );
  18973. }
  18974. // generate indices
  18975. for ( let x = 0; x < radialSegments; x ++ ) {
  18976. for ( let y = 0; y < heightSegments; y ++ ) {
  18977. // we use the index array to access the correct indices
  18978. const a = indexArray[ y ][ x ];
  18979. const b = indexArray[ y + 1 ][ x ];
  18980. const c = indexArray[ y + 1 ][ x + 1 ];
  18981. const d = indexArray[ y ][ x + 1 ];
  18982. // faces
  18983. indices.push( a, b, d );
  18984. indices.push( b, c, d );
  18985. // update group counter
  18986. groupCount += 6;
  18987. }
  18988. }
  18989. // add a group to the geometry. this will ensure multi material support
  18990. scope.addGroup( groupStart, groupCount, 0 );
  18991. // calculate new start value for groups
  18992. groupStart += groupCount;
  18993. }
  18994. function generateCap( top ) {
  18995. // save the index of the first center vertex
  18996. const centerIndexStart = index;
  18997. const uv = new Vector2();
  18998. const vertex = new Vector3();
  18999. let groupCount = 0;
  19000. const radius = ( top === true ) ? radiusTop : radiusBottom;
  19001. const sign = ( top === true ) ? 1 : - 1;
  19002. // first we generate the center vertex data of the cap.
  19003. // because the geometry needs one set of uvs per face,
  19004. // we must generate a center vertex per face/segment
  19005. for ( let x = 1; x <= radialSegments; x ++ ) {
  19006. // vertex
  19007. vertices.push( 0, halfHeight * sign, 0 );
  19008. // normal
  19009. normals.push( 0, sign, 0 );
  19010. // uv
  19011. uvs.push( 0.5, 0.5 );
  19012. // increase index
  19013. index ++;
  19014. }
  19015. // save the index of the last center vertex
  19016. const centerIndexEnd = index;
  19017. // now we generate the surrounding vertices, normals and uvs
  19018. for ( let x = 0; x <= radialSegments; x ++ ) {
  19019. const u = x / radialSegments;
  19020. const theta = u * thetaLength + thetaStart;
  19021. const cosTheta = Math.cos( theta );
  19022. const sinTheta = Math.sin( theta );
  19023. // vertex
  19024. vertex.x = radius * sinTheta;
  19025. vertex.y = halfHeight * sign;
  19026. vertex.z = radius * cosTheta;
  19027. vertices.push( vertex.x, vertex.y, vertex.z );
  19028. // normal
  19029. normals.push( 0, sign, 0 );
  19030. // uv
  19031. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19032. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19033. uvs.push( uv.x, uv.y );
  19034. // increase index
  19035. index ++;
  19036. }
  19037. // generate indices
  19038. for ( let x = 0; x < radialSegments; x ++ ) {
  19039. const c = centerIndexStart + x;
  19040. const i = centerIndexEnd + x;
  19041. if ( top === true ) {
  19042. // face top
  19043. indices.push( i, i + 1, c );
  19044. } else {
  19045. // face bottom
  19046. indices.push( i + 1, i, c );
  19047. }
  19048. groupCount += 3;
  19049. }
  19050. // add a group to the geometry. this will ensure multi material support
  19051. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19052. // calculate new start value for groups
  19053. groupStart += groupCount;
  19054. }
  19055. }
  19056. static fromJSON( data ) {
  19057. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19058. }
  19059. }
  19060. class ConeGeometry extends CylinderGeometry {
  19061. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19062. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19063. this.type = 'ConeGeometry';
  19064. this.parameters = {
  19065. radius: radius,
  19066. height: height,
  19067. radialSegments: radialSegments,
  19068. heightSegments: heightSegments,
  19069. openEnded: openEnded,
  19070. thetaStart: thetaStart,
  19071. thetaLength: thetaLength
  19072. };
  19073. }
  19074. static fromJSON( data ) {
  19075. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19076. }
  19077. }
  19078. class PolyhedronGeometry extends BufferGeometry {
  19079. constructor( vertices, indices, radius = 1, detail = 0 ) {
  19080. super();
  19081. this.type = 'PolyhedronGeometry';
  19082. this.parameters = {
  19083. vertices: vertices,
  19084. indices: indices,
  19085. radius: radius,
  19086. detail: detail
  19087. };
  19088. // default buffer data
  19089. const vertexBuffer = [];
  19090. const uvBuffer = [];
  19091. // the subdivision creates the vertex buffer data
  19092. subdivide( detail );
  19093. // all vertices should lie on a conceptual sphere with a given radius
  19094. applyRadius( radius );
  19095. // finally, create the uv data
  19096. generateUVs();
  19097. // build non-indexed geometry
  19098. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19099. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19100. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19101. if ( detail === 0 ) {
  19102. this.computeVertexNormals(); // flat normals
  19103. } else {
  19104. this.normalizeNormals(); // smooth normals
  19105. }
  19106. // helper functions
  19107. function subdivide( detail ) {
  19108. const a = new Vector3();
  19109. const b = new Vector3();
  19110. const c = new Vector3();
  19111. // iterate over all faces and apply a subdivison with the given detail value
  19112. for ( let i = 0; i < indices.length; i += 3 ) {
  19113. // get the vertices of the face
  19114. getVertexByIndex( indices[ i + 0 ], a );
  19115. getVertexByIndex( indices[ i + 1 ], b );
  19116. getVertexByIndex( indices[ i + 2 ], c );
  19117. // perform subdivision
  19118. subdivideFace( a, b, c, detail );
  19119. }
  19120. }
  19121. function subdivideFace( a, b, c, detail ) {
  19122. const cols = detail + 1;
  19123. // we use this multidimensional array as a data structure for creating the subdivision
  19124. const v = [];
  19125. // construct all of the vertices for this subdivision
  19126. for ( let i = 0; i <= cols; i ++ ) {
  19127. v[ i ] = [];
  19128. const aj = a.clone().lerp( c, i / cols );
  19129. const bj = b.clone().lerp( c, i / cols );
  19130. const rows = cols - i;
  19131. for ( let j = 0; j <= rows; j ++ ) {
  19132. if ( j === 0 && i === cols ) {
  19133. v[ i ][ j ] = aj;
  19134. } else {
  19135. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19136. }
  19137. }
  19138. }
  19139. // construct all of the faces
  19140. for ( let i = 0; i < cols; i ++ ) {
  19141. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19142. const k = Math.floor( j / 2 );
  19143. if ( j % 2 === 0 ) {
  19144. pushVertex( v[ i ][ k + 1 ] );
  19145. pushVertex( v[ i + 1 ][ k ] );
  19146. pushVertex( v[ i ][ k ] );
  19147. } else {
  19148. pushVertex( v[ i ][ k + 1 ] );
  19149. pushVertex( v[ i + 1 ][ k + 1 ] );
  19150. pushVertex( v[ i + 1 ][ k ] );
  19151. }
  19152. }
  19153. }
  19154. }
  19155. function applyRadius( radius ) {
  19156. const vertex = new Vector3();
  19157. // iterate over the entire buffer and apply the radius to each vertex
  19158. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19159. vertex.x = vertexBuffer[ i + 0 ];
  19160. vertex.y = vertexBuffer[ i + 1 ];
  19161. vertex.z = vertexBuffer[ i + 2 ];
  19162. vertex.normalize().multiplyScalar( radius );
  19163. vertexBuffer[ i + 0 ] = vertex.x;
  19164. vertexBuffer[ i + 1 ] = vertex.y;
  19165. vertexBuffer[ i + 2 ] = vertex.z;
  19166. }
  19167. }
  19168. function generateUVs() {
  19169. const vertex = new Vector3();
  19170. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19171. vertex.x = vertexBuffer[ i + 0 ];
  19172. vertex.y = vertexBuffer[ i + 1 ];
  19173. vertex.z = vertexBuffer[ i + 2 ];
  19174. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19175. const v = inclination( vertex ) / Math.PI + 0.5;
  19176. uvBuffer.push( u, 1 - v );
  19177. }
  19178. correctUVs();
  19179. correctSeam();
  19180. }
  19181. function correctSeam() {
  19182. // handle case when face straddles the seam, see #3269
  19183. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  19184. // uv data of a single face
  19185. const x0 = uvBuffer[ i + 0 ];
  19186. const x1 = uvBuffer[ i + 2 ];
  19187. const x2 = uvBuffer[ i + 4 ];
  19188. const max = Math.max( x0, x1, x2 );
  19189. const min = Math.min( x0, x1, x2 );
  19190. // 0.9 is somewhat arbitrary
  19191. if ( max > 0.9 && min < 0.1 ) {
  19192. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19193. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19194. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19195. }
  19196. }
  19197. }
  19198. function pushVertex( vertex ) {
  19199. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19200. }
  19201. function getVertexByIndex( index, vertex ) {
  19202. const stride = index * 3;
  19203. vertex.x = vertices[ stride + 0 ];
  19204. vertex.y = vertices[ stride + 1 ];
  19205. vertex.z = vertices[ stride + 2 ];
  19206. }
  19207. function correctUVs() {
  19208. const a = new Vector3();
  19209. const b = new Vector3();
  19210. const c = new Vector3();
  19211. const centroid = new Vector3();
  19212. const uvA = new Vector2();
  19213. const uvB = new Vector2();
  19214. const uvC = new Vector2();
  19215. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19216. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19217. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19218. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19219. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19220. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19221. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19222. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19223. const azi = azimuth( centroid );
  19224. correctUV( uvA, j + 0, a, azi );
  19225. correctUV( uvB, j + 2, b, azi );
  19226. correctUV( uvC, j + 4, c, azi );
  19227. }
  19228. }
  19229. function correctUV( uv, stride, vector, azimuth ) {
  19230. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19231. uvBuffer[ stride ] = uv.x - 1;
  19232. }
  19233. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19234. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19235. }
  19236. }
  19237. // Angle around the Y axis, counter-clockwise when looking from above.
  19238. function azimuth( vector ) {
  19239. return Math.atan2( vector.z, - vector.x );
  19240. }
  19241. // Angle above the XZ plane.
  19242. function inclination( vector ) {
  19243. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19244. }
  19245. }
  19246. static fromJSON( data ) {
  19247. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  19248. }
  19249. }
  19250. class DodecahedronGeometry extends PolyhedronGeometry {
  19251. constructor( radius = 1, detail = 0 ) {
  19252. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19253. const r = 1 / t;
  19254. const vertices = [
  19255. // (±1, ±1, ±1)
  19256. - 1, - 1, - 1, - 1, - 1, 1,
  19257. - 1, 1, - 1, - 1, 1, 1,
  19258. 1, - 1, - 1, 1, - 1, 1,
  19259. 1, 1, - 1, 1, 1, 1,
  19260. // (0, ±1/φ, ±φ)
  19261. 0, - r, - t, 0, - r, t,
  19262. 0, r, - t, 0, r, t,
  19263. // (±1/φ, ±φ, 0)
  19264. - r, - t, 0, - r, t, 0,
  19265. r, - t, 0, r, t, 0,
  19266. // (±φ, 0, ±1/φ)
  19267. - t, 0, - r, t, 0, - r,
  19268. - t, 0, r, t, 0, r
  19269. ];
  19270. const indices = [
  19271. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19272. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19273. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19274. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19275. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19276. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19277. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19278. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19279. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19280. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19281. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19282. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19283. ];
  19284. super( vertices, indices, radius, detail );
  19285. this.type = 'DodecahedronGeometry';
  19286. this.parameters = {
  19287. radius: radius,
  19288. detail: detail
  19289. };
  19290. }
  19291. static fromJSON( data ) {
  19292. return new DodecahedronGeometry( data.radius, data.detail );
  19293. }
  19294. }
  19295. const _v0 = new Vector3();
  19296. const _v1$1 = new Vector3();
  19297. const _normal = new Vector3();
  19298. const _triangle = new Triangle();
  19299. class EdgesGeometry extends BufferGeometry {
  19300. constructor( geometry, thresholdAngle ) {
  19301. super();
  19302. this.type = 'EdgesGeometry';
  19303. this.parameters = {
  19304. thresholdAngle: thresholdAngle
  19305. };
  19306. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  19307. if ( geometry.isGeometry === true ) {
  19308. console.error( 'THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  19309. return;
  19310. }
  19311. const precisionPoints = 4;
  19312. const precision = Math.pow( 10, precisionPoints );
  19313. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  19314. const indexAttr = geometry.getIndex();
  19315. const positionAttr = geometry.getAttribute( 'position' );
  19316. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19317. const indexArr = [ 0, 0, 0 ];
  19318. const vertKeys = [ 'a', 'b', 'c' ];
  19319. const hashes = new Array( 3 );
  19320. const edgeData = {};
  19321. const vertices = [];
  19322. for ( let i = 0; i < indexCount; i += 3 ) {
  19323. if ( indexAttr ) {
  19324. indexArr[ 0 ] = indexAttr.getX( i );
  19325. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  19326. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  19327. } else {
  19328. indexArr[ 0 ] = i;
  19329. indexArr[ 1 ] = i + 1;
  19330. indexArr[ 2 ] = i + 2;
  19331. }
  19332. const { a, b, c } = _triangle;
  19333. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  19334. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  19335. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  19336. _triangle.getNormal( _normal );
  19337. // create hashes for the edge from the vertices
  19338. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  19339. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  19340. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  19341. // skip degenerate triangles
  19342. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  19343. continue;
  19344. }
  19345. // iterate over every edge
  19346. for ( let j = 0; j < 3; j ++ ) {
  19347. // get the first and next vertex making up the edge
  19348. const jNext = ( j + 1 ) % 3;
  19349. const vecHash0 = hashes[ j ];
  19350. const vecHash1 = hashes[ jNext ];
  19351. const v0 = _triangle[ vertKeys[ j ] ];
  19352. const v1 = _triangle[ vertKeys[ jNext ] ];
  19353. const hash = `${ vecHash0 }_${ vecHash1 }`;
  19354. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  19355. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  19356. // if we found a sibling edge add it into the vertex array if
  19357. // it meets the angle threshold and delete the edge from the map.
  19358. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  19359. vertices.push( v0.x, v0.y, v0.z );
  19360. vertices.push( v1.x, v1.y, v1.z );
  19361. }
  19362. edgeData[ reverseHash ] = null;
  19363. } else if ( ! ( hash in edgeData ) ) {
  19364. // if we've already got an edge here then skip adding a new one
  19365. edgeData[ hash ] = {
  19366. index0: indexArr[ j ],
  19367. index1: indexArr[ jNext ],
  19368. normal: _normal.clone(),
  19369. };
  19370. }
  19371. }
  19372. }
  19373. // iterate over all remaining, unmatched edges and add them to the vertex array
  19374. for ( const key in edgeData ) {
  19375. if ( edgeData[ key ] ) {
  19376. const { index0, index1 } = edgeData[ key ];
  19377. _v0.fromBufferAttribute( positionAttr, index0 );
  19378. _v1$1.fromBufferAttribute( positionAttr, index1 );
  19379. vertices.push( _v0.x, _v0.y, _v0.z );
  19380. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  19381. }
  19382. }
  19383. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19384. }
  19385. }
  19386. /**
  19387. * Extensible curve object.
  19388. *
  19389. * Some common of curve methods:
  19390. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19391. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19392. * .getPoints(), .getSpacedPoints()
  19393. * .getLength()
  19394. * .updateArcLengths()
  19395. *
  19396. * This following curves inherit from THREE.Curve:
  19397. *
  19398. * -- 2D curves --
  19399. * THREE.ArcCurve
  19400. * THREE.CubicBezierCurve
  19401. * THREE.EllipseCurve
  19402. * THREE.LineCurve
  19403. * THREE.QuadraticBezierCurve
  19404. * THREE.SplineCurve
  19405. *
  19406. * -- 3D curves --
  19407. * THREE.CatmullRomCurve3
  19408. * THREE.CubicBezierCurve3
  19409. * THREE.LineCurve3
  19410. * THREE.QuadraticBezierCurve3
  19411. *
  19412. * A series of curves can be represented as a THREE.CurvePath.
  19413. *
  19414. **/
  19415. class Curve {
  19416. constructor() {
  19417. this.type = 'Curve';
  19418. this.arcLengthDivisions = 200;
  19419. }
  19420. // Virtual base class method to overwrite and implement in subclasses
  19421. // - t [0 .. 1]
  19422. getPoint( /* t, optionalTarget */ ) {
  19423. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19424. return null;
  19425. }
  19426. // Get point at relative position in curve according to arc length
  19427. // - u [0 .. 1]
  19428. getPointAt( u, optionalTarget ) {
  19429. const t = this.getUtoTmapping( u );
  19430. return this.getPoint( t, optionalTarget );
  19431. }
  19432. // Get sequence of points using getPoint( t )
  19433. getPoints( divisions = 5 ) {
  19434. const points = [];
  19435. for ( let d = 0; d <= divisions; d ++ ) {
  19436. points.push( this.getPoint( d / divisions ) );
  19437. }
  19438. return points;
  19439. }
  19440. // Get sequence of points using getPointAt( u )
  19441. getSpacedPoints( divisions = 5 ) {
  19442. const points = [];
  19443. for ( let d = 0; d <= divisions; d ++ ) {
  19444. points.push( this.getPointAt( d / divisions ) );
  19445. }
  19446. return points;
  19447. }
  19448. // Get total curve arc length
  19449. getLength() {
  19450. const lengths = this.getLengths();
  19451. return lengths[ lengths.length - 1 ];
  19452. }
  19453. // Get list of cumulative segment lengths
  19454. getLengths( divisions = this.arcLengthDivisions ) {
  19455. if ( this.cacheArcLengths &&
  19456. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19457. ! this.needsUpdate ) {
  19458. return this.cacheArcLengths;
  19459. }
  19460. this.needsUpdate = false;
  19461. const cache = [];
  19462. let current, last = this.getPoint( 0 );
  19463. let sum = 0;
  19464. cache.push( 0 );
  19465. for ( let p = 1; p <= divisions; p ++ ) {
  19466. current = this.getPoint( p / divisions );
  19467. sum += current.distanceTo( last );
  19468. cache.push( sum );
  19469. last = current;
  19470. }
  19471. this.cacheArcLengths = cache;
  19472. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19473. }
  19474. updateArcLengths() {
  19475. this.needsUpdate = true;
  19476. this.getLengths();
  19477. }
  19478. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19479. getUtoTmapping( u, distance ) {
  19480. const arcLengths = this.getLengths();
  19481. let i = 0;
  19482. const il = arcLengths.length;
  19483. let targetArcLength; // The targeted u distance value to get
  19484. if ( distance ) {
  19485. targetArcLength = distance;
  19486. } else {
  19487. targetArcLength = u * arcLengths[ il - 1 ];
  19488. }
  19489. // binary search for the index with largest value smaller than target u distance
  19490. let low = 0, high = il - 1, comparison;
  19491. while ( low <= high ) {
  19492. 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
  19493. comparison = arcLengths[ i ] - targetArcLength;
  19494. if ( comparison < 0 ) {
  19495. low = i + 1;
  19496. } else if ( comparison > 0 ) {
  19497. high = i - 1;
  19498. } else {
  19499. high = i;
  19500. break;
  19501. // DONE
  19502. }
  19503. }
  19504. i = high;
  19505. if ( arcLengths[ i ] === targetArcLength ) {
  19506. return i / ( il - 1 );
  19507. }
  19508. // we could get finer grain at lengths, or use simple interpolation between two points
  19509. const lengthBefore = arcLengths[ i ];
  19510. const lengthAfter = arcLengths[ i + 1 ];
  19511. const segmentLength = lengthAfter - lengthBefore;
  19512. // determine where we are between the 'before' and 'after' points
  19513. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19514. // add that fractional amount to t
  19515. const t = ( i + segmentFraction ) / ( il - 1 );
  19516. return t;
  19517. }
  19518. // Returns a unit vector tangent at t
  19519. // In case any sub curve does not implement its tangent derivation,
  19520. // 2 points a small delta apart will be used to find its gradient
  19521. // which seems to give a reasonable approximation
  19522. getTangent( t, optionalTarget ) {
  19523. const delta = 0.0001;
  19524. let t1 = t - delta;
  19525. let t2 = t + delta;
  19526. // Capping in case of danger
  19527. if ( t1 < 0 ) t1 = 0;
  19528. if ( t2 > 1 ) t2 = 1;
  19529. const pt1 = this.getPoint( t1 );
  19530. const pt2 = this.getPoint( t2 );
  19531. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19532. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19533. return tangent;
  19534. }
  19535. getTangentAt( u, optionalTarget ) {
  19536. const t = this.getUtoTmapping( u );
  19537. return this.getTangent( t, optionalTarget );
  19538. }
  19539. computeFrenetFrames( segments, closed ) {
  19540. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19541. const normal = new Vector3();
  19542. const tangents = [];
  19543. const normals = [];
  19544. const binormals = [];
  19545. const vec = new Vector3();
  19546. const mat = new Matrix4();
  19547. // compute the tangent vectors for each segment on the curve
  19548. for ( let i = 0; i <= segments; i ++ ) {
  19549. const u = i / segments;
  19550. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19551. tangents[ i ].normalize();
  19552. }
  19553. // select an initial normal vector perpendicular to the first tangent vector,
  19554. // and in the direction of the minimum tangent xyz component
  19555. normals[ 0 ] = new Vector3();
  19556. binormals[ 0 ] = new Vector3();
  19557. let min = Number.MAX_VALUE;
  19558. const tx = Math.abs( tangents[ 0 ].x );
  19559. const ty = Math.abs( tangents[ 0 ].y );
  19560. const tz = Math.abs( tangents[ 0 ].z );
  19561. if ( tx <= min ) {
  19562. min = tx;
  19563. normal.set( 1, 0, 0 );
  19564. }
  19565. if ( ty <= min ) {
  19566. min = ty;
  19567. normal.set( 0, 1, 0 );
  19568. }
  19569. if ( tz <= min ) {
  19570. normal.set( 0, 0, 1 );
  19571. }
  19572. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19573. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19574. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19575. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19576. for ( let i = 1; i <= segments; i ++ ) {
  19577. normals[ i ] = normals[ i - 1 ].clone();
  19578. binormals[ i ] = binormals[ i - 1 ].clone();
  19579. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19580. if ( vec.length() > Number.EPSILON ) {
  19581. vec.normalize();
  19582. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19583. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19584. }
  19585. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19586. }
  19587. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19588. if ( closed === true ) {
  19589. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19590. theta /= segments;
  19591. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19592. theta = - theta;
  19593. }
  19594. for ( let i = 1; i <= segments; i ++ ) {
  19595. // twist a little...
  19596. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19597. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19598. }
  19599. }
  19600. return {
  19601. tangents: tangents,
  19602. normals: normals,
  19603. binormals: binormals
  19604. };
  19605. }
  19606. clone() {
  19607. return new this.constructor().copy( this );
  19608. }
  19609. copy( source ) {
  19610. this.arcLengthDivisions = source.arcLengthDivisions;
  19611. return this;
  19612. }
  19613. toJSON() {
  19614. const data = {
  19615. metadata: {
  19616. version: 4.5,
  19617. type: 'Curve',
  19618. generator: 'Curve.toJSON'
  19619. }
  19620. };
  19621. data.arcLengthDivisions = this.arcLengthDivisions;
  19622. data.type = this.type;
  19623. return data;
  19624. }
  19625. fromJSON( json ) {
  19626. this.arcLengthDivisions = json.arcLengthDivisions;
  19627. return this;
  19628. }
  19629. }
  19630. class EllipseCurve extends Curve {
  19631. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19632. super();
  19633. this.type = 'EllipseCurve';
  19634. this.aX = aX;
  19635. this.aY = aY;
  19636. this.xRadius = xRadius;
  19637. this.yRadius = yRadius;
  19638. this.aStartAngle = aStartAngle;
  19639. this.aEndAngle = aEndAngle;
  19640. this.aClockwise = aClockwise;
  19641. this.aRotation = aRotation;
  19642. }
  19643. getPoint( t, optionalTarget ) {
  19644. const point = optionalTarget || new Vector2();
  19645. const twoPi = Math.PI * 2;
  19646. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19647. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19648. // ensures that deltaAngle is 0 .. 2 PI
  19649. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19650. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19651. if ( deltaAngle < Number.EPSILON ) {
  19652. if ( samePoints ) {
  19653. deltaAngle = 0;
  19654. } else {
  19655. deltaAngle = twoPi;
  19656. }
  19657. }
  19658. if ( this.aClockwise === true && ! samePoints ) {
  19659. if ( deltaAngle === twoPi ) {
  19660. deltaAngle = - twoPi;
  19661. } else {
  19662. deltaAngle = deltaAngle - twoPi;
  19663. }
  19664. }
  19665. const angle = this.aStartAngle + t * deltaAngle;
  19666. let x = this.aX + this.xRadius * Math.cos( angle );
  19667. let y = this.aY + this.yRadius * Math.sin( angle );
  19668. if ( this.aRotation !== 0 ) {
  19669. const cos = Math.cos( this.aRotation );
  19670. const sin = Math.sin( this.aRotation );
  19671. const tx = x - this.aX;
  19672. const ty = y - this.aY;
  19673. // Rotate the point about the center of the ellipse.
  19674. x = tx * cos - ty * sin + this.aX;
  19675. y = tx * sin + ty * cos + this.aY;
  19676. }
  19677. return point.set( x, y );
  19678. }
  19679. copy( source ) {
  19680. super.copy( source );
  19681. this.aX = source.aX;
  19682. this.aY = source.aY;
  19683. this.xRadius = source.xRadius;
  19684. this.yRadius = source.yRadius;
  19685. this.aStartAngle = source.aStartAngle;
  19686. this.aEndAngle = source.aEndAngle;
  19687. this.aClockwise = source.aClockwise;
  19688. this.aRotation = source.aRotation;
  19689. return this;
  19690. }
  19691. toJSON() {
  19692. const data = super.toJSON();
  19693. data.aX = this.aX;
  19694. data.aY = this.aY;
  19695. data.xRadius = this.xRadius;
  19696. data.yRadius = this.yRadius;
  19697. data.aStartAngle = this.aStartAngle;
  19698. data.aEndAngle = this.aEndAngle;
  19699. data.aClockwise = this.aClockwise;
  19700. data.aRotation = this.aRotation;
  19701. return data;
  19702. }
  19703. fromJSON( json ) {
  19704. super.fromJSON( json );
  19705. this.aX = json.aX;
  19706. this.aY = json.aY;
  19707. this.xRadius = json.xRadius;
  19708. this.yRadius = json.yRadius;
  19709. this.aStartAngle = json.aStartAngle;
  19710. this.aEndAngle = json.aEndAngle;
  19711. this.aClockwise = json.aClockwise;
  19712. this.aRotation = json.aRotation;
  19713. return this;
  19714. }
  19715. }
  19716. EllipseCurve.prototype.isEllipseCurve = true;
  19717. class ArcCurve extends EllipseCurve {
  19718. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19719. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19720. this.type = 'ArcCurve';
  19721. }
  19722. }
  19723. ArcCurve.prototype.isArcCurve = true;
  19724. /**
  19725. * Centripetal CatmullRom Curve - which is useful for avoiding
  19726. * cusps and self-intersections in non-uniform catmull rom curves.
  19727. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19728. *
  19729. * curve.type accepts centripetal(default), chordal and catmullrom
  19730. * curve.tension is used for catmullrom which defaults to 0.5
  19731. */
  19732. /*
  19733. Based on an optimized c++ solution in
  19734. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19735. - http://ideone.com/NoEbVM
  19736. This CubicPoly class could be used for reusing some variables and calculations,
  19737. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19738. which can be placed in CurveUtils.
  19739. */
  19740. function CubicPoly() {
  19741. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19742. /*
  19743. * Compute coefficients for a cubic polynomial
  19744. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19745. * such that
  19746. * p(0) = x0, p(1) = x1
  19747. * and
  19748. * p'(0) = t0, p'(1) = t1.
  19749. */
  19750. function init( x0, x1, t0, t1 ) {
  19751. c0 = x0;
  19752. c1 = t0;
  19753. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19754. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19755. }
  19756. return {
  19757. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19758. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19759. },
  19760. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19761. // compute tangents when parameterized in [t1,t2]
  19762. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19763. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19764. // rescale tangents for parametrization in [0,1]
  19765. t1 *= dt1;
  19766. t2 *= dt1;
  19767. init( x1, x2, t1, t2 );
  19768. },
  19769. calc: function ( t ) {
  19770. const t2 = t * t;
  19771. const t3 = t2 * t;
  19772. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19773. }
  19774. };
  19775. }
  19776. //
  19777. const tmp = new Vector3();
  19778. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  19779. class CatmullRomCurve3 extends Curve {
  19780. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19781. super();
  19782. this.type = 'CatmullRomCurve3';
  19783. this.points = points;
  19784. this.closed = closed;
  19785. this.curveType = curveType;
  19786. this.tension = tension;
  19787. }
  19788. getPoint( t, optionalTarget = new Vector3() ) {
  19789. const point = optionalTarget;
  19790. const points = this.points;
  19791. const l = points.length;
  19792. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19793. let intPoint = Math.floor( p );
  19794. let weight = p - intPoint;
  19795. if ( this.closed ) {
  19796. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19797. } else if ( weight === 0 && intPoint === l - 1 ) {
  19798. intPoint = l - 2;
  19799. weight = 1;
  19800. }
  19801. let p0, p3; // 4 points (p1 & p2 defined below)
  19802. if ( this.closed || intPoint > 0 ) {
  19803. p0 = points[ ( intPoint - 1 ) % l ];
  19804. } else {
  19805. // extrapolate first point
  19806. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19807. p0 = tmp;
  19808. }
  19809. const p1 = points[ intPoint % l ];
  19810. const p2 = points[ ( intPoint + 1 ) % l ];
  19811. if ( this.closed || intPoint + 2 < l ) {
  19812. p3 = points[ ( intPoint + 2 ) % l ];
  19813. } else {
  19814. // extrapolate last point
  19815. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19816. p3 = tmp;
  19817. }
  19818. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19819. // init Centripetal / Chordal Catmull-Rom
  19820. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19821. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19822. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19823. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19824. // safety check for repeated points
  19825. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19826. if ( dt0 < 1e-4 ) dt0 = dt1;
  19827. if ( dt2 < 1e-4 ) dt2 = dt1;
  19828. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19829. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19830. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19831. } else if ( this.curveType === 'catmullrom' ) {
  19832. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19833. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19834. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19835. }
  19836. point.set(
  19837. px.calc( weight ),
  19838. py.calc( weight ),
  19839. pz.calc( weight )
  19840. );
  19841. return point;
  19842. }
  19843. copy( source ) {
  19844. super.copy( source );
  19845. this.points = [];
  19846. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19847. const point = source.points[ i ];
  19848. this.points.push( point.clone() );
  19849. }
  19850. this.closed = source.closed;
  19851. this.curveType = source.curveType;
  19852. this.tension = source.tension;
  19853. return this;
  19854. }
  19855. toJSON() {
  19856. const data = super.toJSON();
  19857. data.points = [];
  19858. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19859. const point = this.points[ i ];
  19860. data.points.push( point.toArray() );
  19861. }
  19862. data.closed = this.closed;
  19863. data.curveType = this.curveType;
  19864. data.tension = this.tension;
  19865. return data;
  19866. }
  19867. fromJSON( json ) {
  19868. super.fromJSON( json );
  19869. this.points = [];
  19870. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19871. const point = json.points[ i ];
  19872. this.points.push( new Vector3().fromArray( point ) );
  19873. }
  19874. this.closed = json.closed;
  19875. this.curveType = json.curveType;
  19876. this.tension = json.tension;
  19877. return this;
  19878. }
  19879. }
  19880. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  19881. /**
  19882. * Bezier Curves formulas obtained from
  19883. * http://en.wikipedia.org/wiki/Bézier_curve
  19884. */
  19885. function CatmullRom( t, p0, p1, p2, p3 ) {
  19886. const v0 = ( p2 - p0 ) * 0.5;
  19887. const v1 = ( p3 - p1 ) * 0.5;
  19888. const t2 = t * t;
  19889. const t3 = t * t2;
  19890. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19891. }
  19892. //
  19893. function QuadraticBezierP0( t, p ) {
  19894. const k = 1 - t;
  19895. return k * k * p;
  19896. }
  19897. function QuadraticBezierP1( t, p ) {
  19898. return 2 * ( 1 - t ) * t * p;
  19899. }
  19900. function QuadraticBezierP2( t, p ) {
  19901. return t * t * p;
  19902. }
  19903. function QuadraticBezier( t, p0, p1, p2 ) {
  19904. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19905. QuadraticBezierP2( t, p2 );
  19906. }
  19907. //
  19908. function CubicBezierP0( t, p ) {
  19909. const k = 1 - t;
  19910. return k * k * k * p;
  19911. }
  19912. function CubicBezierP1( t, p ) {
  19913. const k = 1 - t;
  19914. return 3 * k * k * t * p;
  19915. }
  19916. function CubicBezierP2( t, p ) {
  19917. return 3 * ( 1 - t ) * t * t * p;
  19918. }
  19919. function CubicBezierP3( t, p ) {
  19920. return t * t * t * p;
  19921. }
  19922. function CubicBezier( t, p0, p1, p2, p3 ) {
  19923. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19924. CubicBezierP3( t, p3 );
  19925. }
  19926. class CubicBezierCurve extends Curve {
  19927. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19928. super();
  19929. this.type = 'CubicBezierCurve';
  19930. this.v0 = v0;
  19931. this.v1 = v1;
  19932. this.v2 = v2;
  19933. this.v3 = v3;
  19934. }
  19935. getPoint( t, optionalTarget = new Vector2() ) {
  19936. const point = optionalTarget;
  19937. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19938. point.set(
  19939. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19940. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19941. );
  19942. return point;
  19943. }
  19944. copy( source ) {
  19945. super.copy( source );
  19946. this.v0.copy( source.v0 );
  19947. this.v1.copy( source.v1 );
  19948. this.v2.copy( source.v2 );
  19949. this.v3.copy( source.v3 );
  19950. return this;
  19951. }
  19952. toJSON() {
  19953. const data = super.toJSON();
  19954. data.v0 = this.v0.toArray();
  19955. data.v1 = this.v1.toArray();
  19956. data.v2 = this.v2.toArray();
  19957. data.v3 = this.v3.toArray();
  19958. return data;
  19959. }
  19960. fromJSON( json ) {
  19961. super.fromJSON( json );
  19962. this.v0.fromArray( json.v0 );
  19963. this.v1.fromArray( json.v1 );
  19964. this.v2.fromArray( json.v2 );
  19965. this.v3.fromArray( json.v3 );
  19966. return this;
  19967. }
  19968. }
  19969. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  19970. class CubicBezierCurve3 extends Curve {
  19971. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19972. super();
  19973. this.type = 'CubicBezierCurve3';
  19974. this.v0 = v0;
  19975. this.v1 = v1;
  19976. this.v2 = v2;
  19977. this.v3 = v3;
  19978. }
  19979. getPoint( t, optionalTarget = new Vector3() ) {
  19980. const point = optionalTarget;
  19981. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19982. point.set(
  19983. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19984. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19985. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19986. );
  19987. return point;
  19988. }
  19989. copy( source ) {
  19990. super.copy( source );
  19991. this.v0.copy( source.v0 );
  19992. this.v1.copy( source.v1 );
  19993. this.v2.copy( source.v2 );
  19994. this.v3.copy( source.v3 );
  19995. return this;
  19996. }
  19997. toJSON() {
  19998. const data = super.toJSON();
  19999. data.v0 = this.v0.toArray();
  20000. data.v1 = this.v1.toArray();
  20001. data.v2 = this.v2.toArray();
  20002. data.v3 = this.v3.toArray();
  20003. return data;
  20004. }
  20005. fromJSON( json ) {
  20006. super.fromJSON( json );
  20007. this.v0.fromArray( json.v0 );
  20008. this.v1.fromArray( json.v1 );
  20009. this.v2.fromArray( json.v2 );
  20010. this.v3.fromArray( json.v3 );
  20011. return this;
  20012. }
  20013. }
  20014. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  20015. class LineCurve extends Curve {
  20016. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  20017. super();
  20018. this.type = 'LineCurve';
  20019. this.v1 = v1;
  20020. this.v2 = v2;
  20021. }
  20022. getPoint( t, optionalTarget = new Vector2() ) {
  20023. const point = optionalTarget;
  20024. if ( t === 1 ) {
  20025. point.copy( this.v2 );
  20026. } else {
  20027. point.copy( this.v2 ).sub( this.v1 );
  20028. point.multiplyScalar( t ).add( this.v1 );
  20029. }
  20030. return point;
  20031. }
  20032. // Line curve is linear, so we can overwrite default getPointAt
  20033. getPointAt( u, optionalTarget ) {
  20034. return this.getPoint( u, optionalTarget );
  20035. }
  20036. getTangent( t, optionalTarget ) {
  20037. const tangent = optionalTarget || new Vector2();
  20038. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  20039. return tangent;
  20040. }
  20041. copy( source ) {
  20042. super.copy( source );
  20043. this.v1.copy( source.v1 );
  20044. this.v2.copy( source.v2 );
  20045. return this;
  20046. }
  20047. toJSON() {
  20048. const data = super.toJSON();
  20049. data.v1 = this.v1.toArray();
  20050. data.v2 = this.v2.toArray();
  20051. return data;
  20052. }
  20053. fromJSON( json ) {
  20054. super.fromJSON( json );
  20055. this.v1.fromArray( json.v1 );
  20056. this.v2.fromArray( json.v2 );
  20057. return this;
  20058. }
  20059. }
  20060. LineCurve.prototype.isLineCurve = true;
  20061. class LineCurve3 extends Curve {
  20062. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  20063. super();
  20064. this.type = 'LineCurve3';
  20065. this.isLineCurve3 = true;
  20066. this.v1 = v1;
  20067. this.v2 = v2;
  20068. }
  20069. getPoint( t, optionalTarget = new Vector3() ) {
  20070. const point = optionalTarget;
  20071. if ( t === 1 ) {
  20072. point.copy( this.v2 );
  20073. } else {
  20074. point.copy( this.v2 ).sub( this.v1 );
  20075. point.multiplyScalar( t ).add( this.v1 );
  20076. }
  20077. return point;
  20078. }
  20079. // Line curve is linear, so we can overwrite default getPointAt
  20080. getPointAt( u, optionalTarget ) {
  20081. return this.getPoint( u, optionalTarget );
  20082. }
  20083. copy( source ) {
  20084. super.copy( source );
  20085. this.v1.copy( source.v1 );
  20086. this.v2.copy( source.v2 );
  20087. return this;
  20088. }
  20089. toJSON() {
  20090. const data = super.toJSON();
  20091. data.v1 = this.v1.toArray();
  20092. data.v2 = this.v2.toArray();
  20093. return data;
  20094. }
  20095. fromJSON( json ) {
  20096. super.fromJSON( json );
  20097. this.v1.fromArray( json.v1 );
  20098. this.v2.fromArray( json.v2 );
  20099. return this;
  20100. }
  20101. }
  20102. class QuadraticBezierCurve extends Curve {
  20103. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  20104. super();
  20105. this.type = 'QuadraticBezierCurve';
  20106. this.v0 = v0;
  20107. this.v1 = v1;
  20108. this.v2 = v2;
  20109. }
  20110. getPoint( t, optionalTarget = new Vector2() ) {
  20111. const point = optionalTarget;
  20112. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20113. point.set(
  20114. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20115. QuadraticBezier( t, v0.y, v1.y, v2.y )
  20116. );
  20117. return point;
  20118. }
  20119. copy( source ) {
  20120. super.copy( source );
  20121. this.v0.copy( source.v0 );
  20122. this.v1.copy( source.v1 );
  20123. this.v2.copy( source.v2 );
  20124. return this;
  20125. }
  20126. toJSON() {
  20127. const data = super.toJSON();
  20128. data.v0 = this.v0.toArray();
  20129. data.v1 = this.v1.toArray();
  20130. data.v2 = this.v2.toArray();
  20131. return data;
  20132. }
  20133. fromJSON( json ) {
  20134. super.fromJSON( json );
  20135. this.v0.fromArray( json.v0 );
  20136. this.v1.fromArray( json.v1 );
  20137. this.v2.fromArray( json.v2 );
  20138. return this;
  20139. }
  20140. }
  20141. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  20142. class QuadraticBezierCurve3 extends Curve {
  20143. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  20144. super();
  20145. this.type = 'QuadraticBezierCurve3';
  20146. this.v0 = v0;
  20147. this.v1 = v1;
  20148. this.v2 = v2;
  20149. }
  20150. getPoint( t, optionalTarget = new Vector3() ) {
  20151. const point = optionalTarget;
  20152. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20153. point.set(
  20154. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20155. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  20156. QuadraticBezier( t, v0.z, v1.z, v2.z )
  20157. );
  20158. return point;
  20159. }
  20160. copy( source ) {
  20161. super.copy( source );
  20162. this.v0.copy( source.v0 );
  20163. this.v1.copy( source.v1 );
  20164. this.v2.copy( source.v2 );
  20165. return this;
  20166. }
  20167. toJSON() {
  20168. const data = super.toJSON();
  20169. data.v0 = this.v0.toArray();
  20170. data.v1 = this.v1.toArray();
  20171. data.v2 = this.v2.toArray();
  20172. return data;
  20173. }
  20174. fromJSON( json ) {
  20175. super.fromJSON( json );
  20176. this.v0.fromArray( json.v0 );
  20177. this.v1.fromArray( json.v1 );
  20178. this.v2.fromArray( json.v2 );
  20179. return this;
  20180. }
  20181. }
  20182. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  20183. class SplineCurve extends Curve {
  20184. constructor( points = [] ) {
  20185. super();
  20186. this.type = 'SplineCurve';
  20187. this.points = points;
  20188. }
  20189. getPoint( t, optionalTarget = new Vector2() ) {
  20190. const point = optionalTarget;
  20191. const points = this.points;
  20192. const p = ( points.length - 1 ) * t;
  20193. const intPoint = Math.floor( p );
  20194. const weight = p - intPoint;
  20195. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20196. const p1 = points[ intPoint ];
  20197. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20198. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20199. point.set(
  20200. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  20201. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  20202. );
  20203. return point;
  20204. }
  20205. copy( source ) {
  20206. super.copy( source );
  20207. this.points = [];
  20208. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  20209. const point = source.points[ i ];
  20210. this.points.push( point.clone() );
  20211. }
  20212. return this;
  20213. }
  20214. toJSON() {
  20215. const data = super.toJSON();
  20216. data.points = [];
  20217. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20218. const point = this.points[ i ];
  20219. data.points.push( point.toArray() );
  20220. }
  20221. return data;
  20222. }
  20223. fromJSON( json ) {
  20224. super.fromJSON( json );
  20225. this.points = [];
  20226. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20227. const point = json.points[ i ];
  20228. this.points.push( new Vector2().fromArray( point ) );
  20229. }
  20230. return this;
  20231. }
  20232. }
  20233. SplineCurve.prototype.isSplineCurve = true;
  20234. var Curves = /*#__PURE__*/Object.freeze({
  20235. __proto__: null,
  20236. ArcCurve: ArcCurve,
  20237. CatmullRomCurve3: CatmullRomCurve3,
  20238. CubicBezierCurve: CubicBezierCurve,
  20239. CubicBezierCurve3: CubicBezierCurve3,
  20240. EllipseCurve: EllipseCurve,
  20241. LineCurve: LineCurve,
  20242. LineCurve3: LineCurve3,
  20243. QuadraticBezierCurve: QuadraticBezierCurve,
  20244. QuadraticBezierCurve3: QuadraticBezierCurve3,
  20245. SplineCurve: SplineCurve
  20246. });
  20247. /**
  20248. * Port from https://github.com/mapbox/earcut (v2.2.2)
  20249. */
  20250. const Earcut = {
  20251. triangulate: function ( data, holeIndices, dim = 2 ) {
  20252. const hasHoles = holeIndices && holeIndices.length;
  20253. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20254. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20255. const triangles = [];
  20256. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20257. let minX, minY, maxX, maxY, x, y, invSize;
  20258. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20259. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20260. if ( data.length > 80 * dim ) {
  20261. minX = maxX = data[ 0 ];
  20262. minY = maxY = data[ 1 ];
  20263. for ( let i = dim; i < outerLen; i += dim ) {
  20264. x = data[ i ];
  20265. y = data[ i + 1 ];
  20266. if ( x < minX ) minX = x;
  20267. if ( y < minY ) minY = y;
  20268. if ( x > maxX ) maxX = x;
  20269. if ( y > maxY ) maxY = y;
  20270. }
  20271. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20272. invSize = Math.max( maxX - minX, maxY - minY );
  20273. invSize = invSize !== 0 ? 1 / invSize : 0;
  20274. }
  20275. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20276. return triangles;
  20277. }
  20278. };
  20279. // create a circular doubly linked list from polygon points in the specified winding order
  20280. function linkedList( data, start, end, dim, clockwise ) {
  20281. let i, last;
  20282. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20283. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20284. } else {
  20285. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20286. }
  20287. if ( last && equals( last, last.next ) ) {
  20288. removeNode( last );
  20289. last = last.next;
  20290. }
  20291. return last;
  20292. }
  20293. // eliminate colinear or duplicate points
  20294. function filterPoints( start, end ) {
  20295. if ( ! start ) return start;
  20296. if ( ! end ) end = start;
  20297. let p = start,
  20298. again;
  20299. do {
  20300. again = false;
  20301. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20302. removeNode( p );
  20303. p = end = p.prev;
  20304. if ( p === p.next ) break;
  20305. again = true;
  20306. } else {
  20307. p = p.next;
  20308. }
  20309. } while ( again || p !== end );
  20310. return end;
  20311. }
  20312. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20313. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20314. if ( ! ear ) return;
  20315. // interlink polygon nodes in z-order
  20316. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20317. let stop = ear,
  20318. prev, next;
  20319. // iterate through ears, slicing them one by one
  20320. while ( ear.prev !== ear.next ) {
  20321. prev = ear.prev;
  20322. next = ear.next;
  20323. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20324. // cut off the triangle
  20325. triangles.push( prev.i / dim );
  20326. triangles.push( ear.i / dim );
  20327. triangles.push( next.i / dim );
  20328. removeNode( ear );
  20329. // skipping the next vertex leads to less sliver triangles
  20330. ear = next.next;
  20331. stop = next.next;
  20332. continue;
  20333. }
  20334. ear = next;
  20335. // if we looped through the whole remaining polygon and can't find any more ears
  20336. if ( ear === stop ) {
  20337. // try filtering points and slicing again
  20338. if ( ! pass ) {
  20339. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20340. // if this didn't work, try curing all small self-intersections locally
  20341. } else if ( pass === 1 ) {
  20342. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20343. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20344. // as a last resort, try splitting the remaining polygon into two
  20345. } else if ( pass === 2 ) {
  20346. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20347. }
  20348. break;
  20349. }
  20350. }
  20351. }
  20352. // check whether a polygon node forms a valid ear with adjacent nodes
  20353. function isEar( ear ) {
  20354. const a = ear.prev,
  20355. b = ear,
  20356. c = ear.next;
  20357. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20358. // now make sure we don't have other points inside the potential ear
  20359. let p = ear.next.next;
  20360. while ( p !== ear.prev ) {
  20361. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20362. area( p.prev, p, p.next ) >= 0 ) return false;
  20363. p = p.next;
  20364. }
  20365. return true;
  20366. }
  20367. function isEarHashed( ear, minX, minY, invSize ) {
  20368. const a = ear.prev,
  20369. b = ear,
  20370. c = ear.next;
  20371. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20372. // triangle bbox; min & max are calculated like this for speed
  20373. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20374. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20375. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20376. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20377. // z-order range for the current triangle bbox;
  20378. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20379. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20380. let p = ear.prevZ,
  20381. n = ear.nextZ;
  20382. // look for points inside the triangle in both directions
  20383. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20384. if ( p !== ear.prev && p !== ear.next &&
  20385. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20386. area( p.prev, p, p.next ) >= 0 ) return false;
  20387. p = p.prevZ;
  20388. if ( n !== ear.prev && n !== ear.next &&
  20389. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20390. area( n.prev, n, n.next ) >= 0 ) return false;
  20391. n = n.nextZ;
  20392. }
  20393. // look for remaining points in decreasing z-order
  20394. while ( p && p.z >= minZ ) {
  20395. if ( p !== ear.prev && p !== ear.next &&
  20396. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20397. area( p.prev, p, p.next ) >= 0 ) return false;
  20398. p = p.prevZ;
  20399. }
  20400. // look for remaining points in increasing z-order
  20401. while ( n && n.z <= maxZ ) {
  20402. if ( n !== ear.prev && n !== ear.next &&
  20403. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20404. area( n.prev, n, n.next ) >= 0 ) return false;
  20405. n = n.nextZ;
  20406. }
  20407. return true;
  20408. }
  20409. // go through all polygon nodes and cure small local self-intersections
  20410. function cureLocalIntersections( start, triangles, dim ) {
  20411. let p = start;
  20412. do {
  20413. const a = p.prev,
  20414. b = p.next.next;
  20415. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20416. triangles.push( a.i / dim );
  20417. triangles.push( p.i / dim );
  20418. triangles.push( b.i / dim );
  20419. // remove two nodes involved
  20420. removeNode( p );
  20421. removeNode( p.next );
  20422. p = start = b;
  20423. }
  20424. p = p.next;
  20425. } while ( p !== start );
  20426. return filterPoints( p );
  20427. }
  20428. // try splitting polygon into two and triangulate them independently
  20429. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20430. // look for a valid diagonal that divides the polygon into two
  20431. let a = start;
  20432. do {
  20433. let b = a.next.next;
  20434. while ( b !== a.prev ) {
  20435. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20436. // split the polygon in two by the diagonal
  20437. let c = splitPolygon( a, b );
  20438. // filter colinear points around the cuts
  20439. a = filterPoints( a, a.next );
  20440. c = filterPoints( c, c.next );
  20441. // run earcut on each half
  20442. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20443. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20444. return;
  20445. }
  20446. b = b.next;
  20447. }
  20448. a = a.next;
  20449. } while ( a !== start );
  20450. }
  20451. // link every hole into the outer loop, producing a single-ring polygon without holes
  20452. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20453. const queue = [];
  20454. let i, len, start, end, list;
  20455. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20456. start = holeIndices[ i ] * dim;
  20457. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20458. list = linkedList( data, start, end, dim, false );
  20459. if ( list === list.next ) list.steiner = true;
  20460. queue.push( getLeftmost( list ) );
  20461. }
  20462. queue.sort( compareX );
  20463. // process holes from left to right
  20464. for ( i = 0; i < queue.length; i ++ ) {
  20465. eliminateHole( queue[ i ], outerNode );
  20466. outerNode = filterPoints( outerNode, outerNode.next );
  20467. }
  20468. return outerNode;
  20469. }
  20470. function compareX( a, b ) {
  20471. return a.x - b.x;
  20472. }
  20473. // find a bridge between vertices that connects hole with an outer ring and and link it
  20474. function eliminateHole( hole, outerNode ) {
  20475. outerNode = findHoleBridge( hole, outerNode );
  20476. if ( outerNode ) {
  20477. const b = splitPolygon( outerNode, hole );
  20478. // filter collinear points around the cuts
  20479. filterPoints( outerNode, outerNode.next );
  20480. filterPoints( b, b.next );
  20481. }
  20482. }
  20483. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20484. function findHoleBridge( hole, outerNode ) {
  20485. let p = outerNode;
  20486. const hx = hole.x;
  20487. const hy = hole.y;
  20488. let qx = - Infinity, m;
  20489. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20490. // segment's endpoint with lesser x will be potential connection point
  20491. do {
  20492. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20493. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20494. if ( x <= hx && x > qx ) {
  20495. qx = x;
  20496. if ( x === hx ) {
  20497. if ( hy === p.y ) return p;
  20498. if ( hy === p.next.y ) return p.next;
  20499. }
  20500. m = p.x < p.next.x ? p : p.next;
  20501. }
  20502. }
  20503. p = p.next;
  20504. } while ( p !== outerNode );
  20505. if ( ! m ) return null;
  20506. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  20507. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20508. // if there are no points found, we have a valid connection;
  20509. // otherwise choose the point of the minimum angle with the ray as connection point
  20510. const stop = m,
  20511. mx = m.x,
  20512. my = m.y;
  20513. let tanMin = Infinity, tan;
  20514. p = m;
  20515. do {
  20516. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20517. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20518. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20519. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20520. m = p;
  20521. tanMin = tan;
  20522. }
  20523. }
  20524. p = p.next;
  20525. } while ( p !== stop );
  20526. return m;
  20527. }
  20528. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20529. function sectorContainsSector( m, p ) {
  20530. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20531. }
  20532. // interlink polygon nodes in z-order
  20533. function indexCurve( start, minX, minY, invSize ) {
  20534. let p = start;
  20535. do {
  20536. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20537. p.prevZ = p.prev;
  20538. p.nextZ = p.next;
  20539. p = p.next;
  20540. } while ( p !== start );
  20541. p.prevZ.nextZ = null;
  20542. p.prevZ = null;
  20543. sortLinked( p );
  20544. }
  20545. // Simon Tatham's linked list merge sort algorithm
  20546. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20547. function sortLinked( list ) {
  20548. let i, p, q, e, tail, numMerges, pSize, qSize,
  20549. inSize = 1;
  20550. do {
  20551. p = list;
  20552. list = null;
  20553. tail = null;
  20554. numMerges = 0;
  20555. while ( p ) {
  20556. numMerges ++;
  20557. q = p;
  20558. pSize = 0;
  20559. for ( i = 0; i < inSize; i ++ ) {
  20560. pSize ++;
  20561. q = q.nextZ;
  20562. if ( ! q ) break;
  20563. }
  20564. qSize = inSize;
  20565. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20566. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20567. e = p;
  20568. p = p.nextZ;
  20569. pSize --;
  20570. } else {
  20571. e = q;
  20572. q = q.nextZ;
  20573. qSize --;
  20574. }
  20575. if ( tail ) tail.nextZ = e;
  20576. else list = e;
  20577. e.prevZ = tail;
  20578. tail = e;
  20579. }
  20580. p = q;
  20581. }
  20582. tail.nextZ = null;
  20583. inSize *= 2;
  20584. } while ( numMerges > 1 );
  20585. return list;
  20586. }
  20587. // z-order of a point given coords and inverse of the longer side of data bbox
  20588. function zOrder( x, y, minX, minY, invSize ) {
  20589. // coords are transformed into non-negative 15-bit integer range
  20590. x = 32767 * ( x - minX ) * invSize;
  20591. y = 32767 * ( y - minY ) * invSize;
  20592. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20593. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20594. x = ( x | ( x << 2 ) ) & 0x33333333;
  20595. x = ( x | ( x << 1 ) ) & 0x55555555;
  20596. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20597. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20598. y = ( y | ( y << 2 ) ) & 0x33333333;
  20599. y = ( y | ( y << 1 ) ) & 0x55555555;
  20600. return x | ( y << 1 );
  20601. }
  20602. // find the leftmost node of a polygon ring
  20603. function getLeftmost( start ) {
  20604. let p = start,
  20605. leftmost = start;
  20606. do {
  20607. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20608. p = p.next;
  20609. } while ( p !== start );
  20610. return leftmost;
  20611. }
  20612. // check if a point lies within a convex triangle
  20613. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20614. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20615. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20616. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20617. }
  20618. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20619. function isValidDiagonal( a, b ) {
  20620. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20621. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20622. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20623. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20624. }
  20625. // signed area of a triangle
  20626. function area( p, q, r ) {
  20627. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20628. }
  20629. // check if two points are equal
  20630. function equals( p1, p2 ) {
  20631. return p1.x === p2.x && p1.y === p2.y;
  20632. }
  20633. // check if two segments intersect
  20634. function intersects( p1, q1, p2, q2 ) {
  20635. const o1 = sign( area( p1, q1, p2 ) );
  20636. const o2 = sign( area( p1, q1, q2 ) );
  20637. const o3 = sign( area( p2, q2, p1 ) );
  20638. const o4 = sign( area( p2, q2, q1 ) );
  20639. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20640. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20641. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20642. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20643. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20644. return false;
  20645. }
  20646. // for collinear points p, q, r, check if point q lies on segment pr
  20647. function onSegment( p, q, r ) {
  20648. 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 );
  20649. }
  20650. function sign( num ) {
  20651. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20652. }
  20653. // check if a polygon diagonal intersects any polygon segments
  20654. function intersectsPolygon( a, b ) {
  20655. let p = a;
  20656. do {
  20657. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20658. intersects( p, p.next, a, b ) ) return true;
  20659. p = p.next;
  20660. } while ( p !== a );
  20661. return false;
  20662. }
  20663. // check if a polygon diagonal is locally inside the polygon
  20664. function locallyInside( a, b ) {
  20665. return area( a.prev, a, a.next ) < 0 ?
  20666. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20667. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20668. }
  20669. // check if the middle point of a polygon diagonal is inside the polygon
  20670. function middleInside( a, b ) {
  20671. let p = a,
  20672. inside = false;
  20673. const px = ( a.x + b.x ) / 2,
  20674. py = ( a.y + b.y ) / 2;
  20675. do {
  20676. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20677. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20678. inside = ! inside;
  20679. p = p.next;
  20680. } while ( p !== a );
  20681. return inside;
  20682. }
  20683. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20684. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20685. function splitPolygon( a, b ) {
  20686. const a2 = new Node( a.i, a.x, a.y ),
  20687. b2 = new Node( b.i, b.x, b.y ),
  20688. an = a.next,
  20689. bp = b.prev;
  20690. a.next = b;
  20691. b.prev = a;
  20692. a2.next = an;
  20693. an.prev = a2;
  20694. b2.next = a2;
  20695. a2.prev = b2;
  20696. bp.next = b2;
  20697. b2.prev = bp;
  20698. return b2;
  20699. }
  20700. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20701. function insertNode( i, x, y, last ) {
  20702. const p = new Node( i, x, y );
  20703. if ( ! last ) {
  20704. p.prev = p;
  20705. p.next = p;
  20706. } else {
  20707. p.next = last.next;
  20708. p.prev = last;
  20709. last.next.prev = p;
  20710. last.next = p;
  20711. }
  20712. return p;
  20713. }
  20714. function removeNode( p ) {
  20715. p.next.prev = p.prev;
  20716. p.prev.next = p.next;
  20717. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20718. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20719. }
  20720. function Node( i, x, y ) {
  20721. // vertex index in coordinates array
  20722. this.i = i;
  20723. // vertex coordinates
  20724. this.x = x;
  20725. this.y = y;
  20726. // previous and next vertex nodes in a polygon ring
  20727. this.prev = null;
  20728. this.next = null;
  20729. // z-order curve value
  20730. this.z = null;
  20731. // previous and next nodes in z-order
  20732. this.prevZ = null;
  20733. this.nextZ = null;
  20734. // indicates whether this is a steiner point
  20735. this.steiner = false;
  20736. }
  20737. function signedArea( data, start, end, dim ) {
  20738. let sum = 0;
  20739. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20740. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20741. j = i;
  20742. }
  20743. return sum;
  20744. }
  20745. class ShapeUtils {
  20746. // calculate area of the contour polygon
  20747. static area( contour ) {
  20748. const n = contour.length;
  20749. let a = 0.0;
  20750. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20751. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20752. }
  20753. return a * 0.5;
  20754. }
  20755. static isClockWise( pts ) {
  20756. return ShapeUtils.area( pts ) < 0;
  20757. }
  20758. static triangulateShape( contour, holes ) {
  20759. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20760. const holeIndices = []; // array of hole indices
  20761. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20762. removeDupEndPts( contour );
  20763. addContour( vertices, contour );
  20764. //
  20765. let holeIndex = contour.length;
  20766. holes.forEach( removeDupEndPts );
  20767. for ( let i = 0; i < holes.length; i ++ ) {
  20768. holeIndices.push( holeIndex );
  20769. holeIndex += holes[ i ].length;
  20770. addContour( vertices, holes[ i ] );
  20771. }
  20772. //
  20773. const triangles = Earcut.triangulate( vertices, holeIndices );
  20774. //
  20775. for ( let i = 0; i < triangles.length; i += 3 ) {
  20776. faces.push( triangles.slice( i, i + 3 ) );
  20777. }
  20778. return faces;
  20779. }
  20780. }
  20781. function removeDupEndPts( points ) {
  20782. const l = points.length;
  20783. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20784. points.pop();
  20785. }
  20786. }
  20787. function addContour( vertices, contour ) {
  20788. for ( let i = 0; i < contour.length; i ++ ) {
  20789. vertices.push( contour[ i ].x );
  20790. vertices.push( contour[ i ].y );
  20791. }
  20792. }
  20793. /**
  20794. * Creates extruded geometry from a path shape.
  20795. *
  20796. * parameters = {
  20797. *
  20798. * curveSegments: <int>, // number of points on the curves
  20799. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20800. * depth: <float>, // Depth to extrude the shape
  20801. *
  20802. * bevelEnabled: <bool>, // turn on bevel
  20803. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20804. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20805. * bevelOffset: <float>, // how far from shape outline does bevel start
  20806. * bevelSegments: <int>, // number of bevel layers
  20807. *
  20808. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20809. *
  20810. * UVGenerator: <Object> // object that provides UV generator functions
  20811. *
  20812. * }
  20813. */
  20814. class ExtrudeGeometry extends BufferGeometry {
  20815. constructor( shapes, options ) {
  20816. super();
  20817. this.type = 'ExtrudeGeometry';
  20818. this.parameters = {
  20819. shapes: shapes,
  20820. options: options
  20821. };
  20822. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20823. const scope = this;
  20824. const verticesArray = [];
  20825. const uvArray = [];
  20826. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20827. const shape = shapes[ i ];
  20828. addShape( shape );
  20829. }
  20830. // build geometry
  20831. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20832. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20833. this.computeVertexNormals();
  20834. // functions
  20835. function addShape( shape ) {
  20836. const placeholder = [];
  20837. // options
  20838. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20839. const steps = options.steps !== undefined ? options.steps : 1;
  20840. let depth = options.depth !== undefined ? options.depth : 100;
  20841. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20842. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  20843. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  20844. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20845. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20846. const extrudePath = options.extrudePath;
  20847. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20848. // deprecated options
  20849. if ( options.amount !== undefined ) {
  20850. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  20851. depth = options.amount;
  20852. }
  20853. //
  20854. let extrudePts, extrudeByPath = false;
  20855. let splineTube, binormal, normal, position2;
  20856. if ( extrudePath ) {
  20857. extrudePts = extrudePath.getSpacedPoints( steps );
  20858. extrudeByPath = true;
  20859. bevelEnabled = false; // bevels not supported for path extrusion
  20860. // SETUP TNB variables
  20861. // TODO1 - have a .isClosed in spline?
  20862. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20863. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20864. binormal = new Vector3();
  20865. normal = new Vector3();
  20866. position2 = new Vector3();
  20867. }
  20868. // Safeguards if bevels are not enabled
  20869. if ( ! bevelEnabled ) {
  20870. bevelSegments = 0;
  20871. bevelThickness = 0;
  20872. bevelSize = 0;
  20873. bevelOffset = 0;
  20874. }
  20875. // Variables initialization
  20876. const shapePoints = shape.extractPoints( curveSegments );
  20877. let vertices = shapePoints.shape;
  20878. const holes = shapePoints.holes;
  20879. const reverse = ! ShapeUtils.isClockWise( vertices );
  20880. if ( reverse ) {
  20881. vertices = vertices.reverse();
  20882. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20883. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20884. const ahole = holes[ h ];
  20885. if ( ShapeUtils.isClockWise( ahole ) ) {
  20886. holes[ h ] = ahole.reverse();
  20887. }
  20888. }
  20889. }
  20890. const faces = ShapeUtils.triangulateShape( vertices, holes );
  20891. /* Vertices */
  20892. const contour = vertices; // vertices has all points but contour has only points of circumference
  20893. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20894. const ahole = holes[ h ];
  20895. vertices = vertices.concat( ahole );
  20896. }
  20897. function scalePt2( pt, vec, size ) {
  20898. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  20899. return vec.clone().multiplyScalar( size ).add( pt );
  20900. }
  20901. const vlen = vertices.length, flen = faces.length;
  20902. // Find directions for point movement
  20903. function getBevelVec( inPt, inPrev, inNext ) {
  20904. // computes for inPt the corresponding point inPt' on a new contour
  20905. // shifted by 1 unit (length of normalized vector) to the left
  20906. // if we walk along contour clockwise, this new contour is outside the old one
  20907. //
  20908. // inPt' is the intersection of the two lines parallel to the two
  20909. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20910. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20911. // good reading for geometry algorithms (here: line-line intersection)
  20912. // http://geomalgorithms.com/a05-_intersect-1.html
  20913. const v_prev_x = inPt.x - inPrev.x,
  20914. v_prev_y = inPt.y - inPrev.y;
  20915. const v_next_x = inNext.x - inPt.x,
  20916. v_next_y = inNext.y - inPt.y;
  20917. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20918. // check for collinear edges
  20919. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20920. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20921. // not collinear
  20922. // length of vectors for normalizing
  20923. const v_prev_len = Math.sqrt( v_prev_lensq );
  20924. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20925. // shift adjacent points by unit vectors to the left
  20926. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20927. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20928. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20929. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20930. // scaling factor for v_prev to intersection point
  20931. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20932. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20933. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20934. // vector from inPt to intersection point
  20935. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20936. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20937. // Don't normalize!, otherwise sharp corners become ugly
  20938. // but prevent crazy spikes
  20939. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20940. if ( v_trans_lensq <= 2 ) {
  20941. return new Vector2( v_trans_x, v_trans_y );
  20942. } else {
  20943. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20944. }
  20945. } else {
  20946. // handle special case of collinear edges
  20947. let direction_eq = false; // assumes: opposite
  20948. if ( v_prev_x > Number.EPSILON ) {
  20949. if ( v_next_x > Number.EPSILON ) {
  20950. direction_eq = true;
  20951. }
  20952. } else {
  20953. if ( v_prev_x < - Number.EPSILON ) {
  20954. if ( v_next_x < - Number.EPSILON ) {
  20955. direction_eq = true;
  20956. }
  20957. } else {
  20958. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20959. direction_eq = true;
  20960. }
  20961. }
  20962. }
  20963. if ( direction_eq ) {
  20964. // console.log("Warning: lines are a straight sequence");
  20965. v_trans_x = - v_prev_y;
  20966. v_trans_y = v_prev_x;
  20967. shrink_by = Math.sqrt( v_prev_lensq );
  20968. } else {
  20969. // console.log("Warning: lines are a straight spike");
  20970. v_trans_x = v_prev_x;
  20971. v_trans_y = v_prev_y;
  20972. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20973. }
  20974. }
  20975. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20976. }
  20977. const contourMovements = [];
  20978. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20979. if ( j === il ) j = 0;
  20980. if ( k === il ) k = 0;
  20981. // (j)---(i)---(k)
  20982. // console.log('i,j,k', i, j , k)
  20983. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20984. }
  20985. const holesMovements = [];
  20986. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20987. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20988. const ahole = holes[ h ];
  20989. oneHoleMovements = [];
  20990. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20991. if ( j === il ) j = 0;
  20992. if ( k === il ) k = 0;
  20993. // (j)---(i)---(k)
  20994. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20995. }
  20996. holesMovements.push( oneHoleMovements );
  20997. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20998. }
  20999. // Loop bevelSegments, 1 for the front, 1 for the back
  21000. for ( let b = 0; b < bevelSegments; b ++ ) {
  21001. //for ( b = bevelSegments; b > 0; b -- ) {
  21002. const t = b / bevelSegments;
  21003. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21004. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21005. // contract shape
  21006. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21007. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21008. v( vert.x, vert.y, - z );
  21009. }
  21010. // expand holes
  21011. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21012. const ahole = holes[ h ];
  21013. oneHoleMovements = holesMovements[ h ];
  21014. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21015. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21016. v( vert.x, vert.y, - z );
  21017. }
  21018. }
  21019. }
  21020. const bs = bevelSize + bevelOffset;
  21021. // Back facing vertices
  21022. for ( let i = 0; i < vlen; i ++ ) {
  21023. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21024. if ( ! extrudeByPath ) {
  21025. v( vert.x, vert.y, 0 );
  21026. } else {
  21027. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21028. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21029. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21030. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21031. v( position2.x, position2.y, position2.z );
  21032. }
  21033. }
  21034. // Add stepped vertices...
  21035. // Including front facing vertices
  21036. for ( let s = 1; s <= steps; s ++ ) {
  21037. for ( let i = 0; i < vlen; i ++ ) {
  21038. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21039. if ( ! extrudeByPath ) {
  21040. v( vert.x, vert.y, depth / steps * s );
  21041. } else {
  21042. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21043. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21044. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21045. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21046. v( position2.x, position2.y, position2.z );
  21047. }
  21048. }
  21049. }
  21050. // Add bevel segments planes
  21051. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21052. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21053. const t = b / bevelSegments;
  21054. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21055. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21056. // contract shape
  21057. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21058. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21059. v( vert.x, vert.y, depth + z );
  21060. }
  21061. // expand holes
  21062. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21063. const ahole = holes[ h ];
  21064. oneHoleMovements = holesMovements[ h ];
  21065. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21066. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21067. if ( ! extrudeByPath ) {
  21068. v( vert.x, vert.y, depth + z );
  21069. } else {
  21070. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21071. }
  21072. }
  21073. }
  21074. }
  21075. /* Faces */
  21076. // Top and bottom faces
  21077. buildLidFaces();
  21078. // Sides faces
  21079. buildSideFaces();
  21080. ///// Internal functions
  21081. function buildLidFaces() {
  21082. const start = verticesArray.length / 3;
  21083. if ( bevelEnabled ) {
  21084. let layer = 0; // steps + 1
  21085. let offset = vlen * layer;
  21086. // Bottom faces
  21087. for ( let i = 0; i < flen; i ++ ) {
  21088. const face = faces[ i ];
  21089. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21090. }
  21091. layer = steps + bevelSegments * 2;
  21092. offset = vlen * layer;
  21093. // Top faces
  21094. for ( let i = 0; i < flen; i ++ ) {
  21095. const face = faces[ i ];
  21096. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21097. }
  21098. } else {
  21099. // Bottom faces
  21100. for ( let i = 0; i < flen; i ++ ) {
  21101. const face = faces[ i ];
  21102. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21103. }
  21104. // Top faces
  21105. for ( let i = 0; i < flen; i ++ ) {
  21106. const face = faces[ i ];
  21107. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21108. }
  21109. }
  21110. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21111. }
  21112. // Create faces for the z-sides of the shape
  21113. function buildSideFaces() {
  21114. const start = verticesArray.length / 3;
  21115. let layeroffset = 0;
  21116. sidewalls( contour, layeroffset );
  21117. layeroffset += contour.length;
  21118. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21119. const ahole = holes[ h ];
  21120. sidewalls( ahole, layeroffset );
  21121. //, true
  21122. layeroffset += ahole.length;
  21123. }
  21124. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21125. }
  21126. function sidewalls( contour, layeroffset ) {
  21127. let i = contour.length;
  21128. while ( -- i >= 0 ) {
  21129. const j = i;
  21130. let k = i - 1;
  21131. if ( k < 0 ) k = contour.length - 1;
  21132. //console.log('b', i,j, i-1, k,vertices.length);
  21133. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21134. const slen1 = vlen * s;
  21135. const slen2 = vlen * ( s + 1 );
  21136. const a = layeroffset + j + slen1,
  21137. b = layeroffset + k + slen1,
  21138. c = layeroffset + k + slen2,
  21139. d = layeroffset + j + slen2;
  21140. f4( a, b, c, d );
  21141. }
  21142. }
  21143. }
  21144. function v( x, y, z ) {
  21145. placeholder.push( x );
  21146. placeholder.push( y );
  21147. placeholder.push( z );
  21148. }
  21149. function f3( a, b, c ) {
  21150. addVertex( a );
  21151. addVertex( b );
  21152. addVertex( c );
  21153. const nextIndex = verticesArray.length / 3;
  21154. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21155. addUV( uvs[ 0 ] );
  21156. addUV( uvs[ 1 ] );
  21157. addUV( uvs[ 2 ] );
  21158. }
  21159. function f4( a, b, c, d ) {
  21160. addVertex( a );
  21161. addVertex( b );
  21162. addVertex( d );
  21163. addVertex( b );
  21164. addVertex( c );
  21165. addVertex( d );
  21166. const nextIndex = verticesArray.length / 3;
  21167. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21168. addUV( uvs[ 0 ] );
  21169. addUV( uvs[ 1 ] );
  21170. addUV( uvs[ 3 ] );
  21171. addUV( uvs[ 1 ] );
  21172. addUV( uvs[ 2 ] );
  21173. addUV( uvs[ 3 ] );
  21174. }
  21175. function addVertex( index ) {
  21176. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21177. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21178. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21179. }
  21180. function addUV( vector2 ) {
  21181. uvArray.push( vector2.x );
  21182. uvArray.push( vector2.y );
  21183. }
  21184. }
  21185. }
  21186. toJSON() {
  21187. const data = super.toJSON();
  21188. const shapes = this.parameters.shapes;
  21189. const options = this.parameters.options;
  21190. return toJSON$1( shapes, options, data );
  21191. }
  21192. static fromJSON( data, shapes ) {
  21193. const geometryShapes = [];
  21194. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21195. const shape = shapes[ data.shapes[ j ] ];
  21196. geometryShapes.push( shape );
  21197. }
  21198. const extrudePath = data.options.extrudePath;
  21199. if ( extrudePath !== undefined ) {
  21200. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21201. }
  21202. return new ExtrudeGeometry( geometryShapes, data.options );
  21203. }
  21204. }
  21205. const WorldUVGenerator = {
  21206. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21207. const a_x = vertices[ indexA * 3 ];
  21208. const a_y = vertices[ indexA * 3 + 1 ];
  21209. const b_x = vertices[ indexB * 3 ];
  21210. const b_y = vertices[ indexB * 3 + 1 ];
  21211. const c_x = vertices[ indexC * 3 ];
  21212. const c_y = vertices[ indexC * 3 + 1 ];
  21213. return [
  21214. new Vector2( a_x, a_y ),
  21215. new Vector2( b_x, b_y ),
  21216. new Vector2( c_x, c_y )
  21217. ];
  21218. },
  21219. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21220. const a_x = vertices[ indexA * 3 ];
  21221. const a_y = vertices[ indexA * 3 + 1 ];
  21222. const a_z = vertices[ indexA * 3 + 2 ];
  21223. const b_x = vertices[ indexB * 3 ];
  21224. const b_y = vertices[ indexB * 3 + 1 ];
  21225. const b_z = vertices[ indexB * 3 + 2 ];
  21226. const c_x = vertices[ indexC * 3 ];
  21227. const c_y = vertices[ indexC * 3 + 1 ];
  21228. const c_z = vertices[ indexC * 3 + 2 ];
  21229. const d_x = vertices[ indexD * 3 ];
  21230. const d_y = vertices[ indexD * 3 + 1 ];
  21231. const d_z = vertices[ indexD * 3 + 2 ];
  21232. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21233. return [
  21234. new Vector2( a_x, 1 - a_z ),
  21235. new Vector2( b_x, 1 - b_z ),
  21236. new Vector2( c_x, 1 - c_z ),
  21237. new Vector2( d_x, 1 - d_z )
  21238. ];
  21239. } else {
  21240. return [
  21241. new Vector2( a_y, 1 - a_z ),
  21242. new Vector2( b_y, 1 - b_z ),
  21243. new Vector2( c_y, 1 - c_z ),
  21244. new Vector2( d_y, 1 - d_z )
  21245. ];
  21246. }
  21247. }
  21248. };
  21249. function toJSON$1( shapes, options, data ) {
  21250. data.shapes = [];
  21251. if ( Array.isArray( shapes ) ) {
  21252. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21253. const shape = shapes[ i ];
  21254. data.shapes.push( shape.uuid );
  21255. }
  21256. } else {
  21257. data.shapes.push( shapes.uuid );
  21258. }
  21259. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21260. return data;
  21261. }
  21262. class IcosahedronGeometry extends PolyhedronGeometry {
  21263. constructor( radius = 1, detail = 0 ) {
  21264. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21265. const vertices = [
  21266. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21267. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21268. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21269. ];
  21270. const indices = [
  21271. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21272. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21273. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21274. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21275. ];
  21276. super( vertices, indices, radius, detail );
  21277. this.type = 'IcosahedronGeometry';
  21278. this.parameters = {
  21279. radius: radius,
  21280. detail: detail
  21281. };
  21282. }
  21283. static fromJSON( data ) {
  21284. return new IcosahedronGeometry( data.radius, data.detail );
  21285. }
  21286. }
  21287. class LatheGeometry extends BufferGeometry {
  21288. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  21289. super();
  21290. this.type = 'LatheGeometry';
  21291. this.parameters = {
  21292. points: points,
  21293. segments: segments,
  21294. phiStart: phiStart,
  21295. phiLength: phiLength
  21296. };
  21297. segments = Math.floor( segments );
  21298. // clamp phiLength so it's in range of [ 0, 2PI ]
  21299. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21300. // buffers
  21301. const indices = [];
  21302. const vertices = [];
  21303. const uvs = [];
  21304. // helper variables
  21305. const inverseSegments = 1.0 / segments;
  21306. const vertex = new Vector3();
  21307. const uv = new Vector2();
  21308. // generate vertices and uvs
  21309. for ( let i = 0; i <= segments; i ++ ) {
  21310. const phi = phiStart + i * inverseSegments * phiLength;
  21311. const sin = Math.sin( phi );
  21312. const cos = Math.cos( phi );
  21313. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21314. // vertex
  21315. vertex.x = points[ j ].x * sin;
  21316. vertex.y = points[ j ].y;
  21317. vertex.z = points[ j ].x * cos;
  21318. vertices.push( vertex.x, vertex.y, vertex.z );
  21319. // uv
  21320. uv.x = i / segments;
  21321. uv.y = j / ( points.length - 1 );
  21322. uvs.push( uv.x, uv.y );
  21323. }
  21324. }
  21325. // indices
  21326. for ( let i = 0; i < segments; i ++ ) {
  21327. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  21328. const base = j + i * points.length;
  21329. const a = base;
  21330. const b = base + points.length;
  21331. const c = base + points.length + 1;
  21332. const d = base + 1;
  21333. // faces
  21334. indices.push( a, b, d );
  21335. indices.push( b, c, d );
  21336. }
  21337. }
  21338. // build geometry
  21339. this.setIndex( indices );
  21340. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21341. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21342. // generate normals
  21343. this.computeVertexNormals();
  21344. // if the geometry is closed, we need to average the normals along the seam.
  21345. // because the corresponding vertices are identical (but still have different UVs).
  21346. if ( phiLength === Math.PI * 2 ) {
  21347. const normals = this.attributes.normal.array;
  21348. const n1 = new Vector3();
  21349. const n2 = new Vector3();
  21350. const n = new Vector3();
  21351. // this is the buffer offset for the last line of vertices
  21352. const base = segments * points.length * 3;
  21353. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  21354. // select the normal of the vertex in the first line
  21355. n1.x = normals[ j + 0 ];
  21356. n1.y = normals[ j + 1 ];
  21357. n1.z = normals[ j + 2 ];
  21358. // select the normal of the vertex in the last line
  21359. n2.x = normals[ base + j + 0 ];
  21360. n2.y = normals[ base + j + 1 ];
  21361. n2.z = normals[ base + j + 2 ];
  21362. // average normals
  21363. n.addVectors( n1, n2 ).normalize();
  21364. // assign the new values to both normals
  21365. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  21366. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  21367. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  21368. }
  21369. }
  21370. }
  21371. static fromJSON( data ) {
  21372. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  21373. }
  21374. }
  21375. class OctahedronGeometry extends PolyhedronGeometry {
  21376. constructor( radius = 1, detail = 0 ) {
  21377. const vertices = [
  21378. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21379. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21380. ];
  21381. const indices = [
  21382. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21383. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21384. 1, 3, 4, 1, 4, 2
  21385. ];
  21386. super( vertices, indices, radius, detail );
  21387. this.type = 'OctahedronGeometry';
  21388. this.parameters = {
  21389. radius: radius,
  21390. detail: detail
  21391. };
  21392. }
  21393. static fromJSON( data ) {
  21394. return new OctahedronGeometry( data.radius, data.detail );
  21395. }
  21396. }
  21397. /**
  21398. * Parametric Surfaces Geometry
  21399. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  21400. */
  21401. class ParametricGeometry extends BufferGeometry {
  21402. constructor( func, slices, stacks ) {
  21403. super();
  21404. this.type = 'ParametricGeometry';
  21405. this.parameters = {
  21406. func: func,
  21407. slices: slices,
  21408. stacks: stacks
  21409. };
  21410. // buffers
  21411. const indices = [];
  21412. const vertices = [];
  21413. const normals = [];
  21414. const uvs = [];
  21415. const EPS = 0.00001;
  21416. const normal = new Vector3();
  21417. const p0 = new Vector3(), p1 = new Vector3();
  21418. const pu = new Vector3(), pv = new Vector3();
  21419. if ( func.length < 3 ) {
  21420. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  21421. }
  21422. // generate vertices, normals and uvs
  21423. const sliceCount = slices + 1;
  21424. for ( let i = 0; i <= stacks; i ++ ) {
  21425. const v = i / stacks;
  21426. for ( let j = 0; j <= slices; j ++ ) {
  21427. const u = j / slices;
  21428. // vertex
  21429. func( u, v, p0 );
  21430. vertices.push( p0.x, p0.y, p0.z );
  21431. // normal
  21432. // approximate tangent vectors via finite differences
  21433. if ( u - EPS >= 0 ) {
  21434. func( u - EPS, v, p1 );
  21435. pu.subVectors( p0, p1 );
  21436. } else {
  21437. func( u + EPS, v, p1 );
  21438. pu.subVectors( p1, p0 );
  21439. }
  21440. if ( v - EPS >= 0 ) {
  21441. func( u, v - EPS, p1 );
  21442. pv.subVectors( p0, p1 );
  21443. } else {
  21444. func( u, v + EPS, p1 );
  21445. pv.subVectors( p1, p0 );
  21446. }
  21447. // cross product of tangent vectors returns surface normal
  21448. normal.crossVectors( pu, pv ).normalize();
  21449. normals.push( normal.x, normal.y, normal.z );
  21450. // uv
  21451. uvs.push( u, v );
  21452. }
  21453. }
  21454. // generate indices
  21455. for ( let i = 0; i < stacks; i ++ ) {
  21456. for ( let j = 0; j < slices; j ++ ) {
  21457. const a = i * sliceCount + j;
  21458. const b = i * sliceCount + j + 1;
  21459. const c = ( i + 1 ) * sliceCount + j + 1;
  21460. const d = ( i + 1 ) * sliceCount + j;
  21461. // faces one and two
  21462. indices.push( a, b, d );
  21463. indices.push( b, c, d );
  21464. }
  21465. }
  21466. // build geometry
  21467. this.setIndex( indices );
  21468. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21469. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21470. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21471. }
  21472. }
  21473. class RingGeometry extends BufferGeometry {
  21474. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21475. super();
  21476. this.type = 'RingGeometry';
  21477. this.parameters = {
  21478. innerRadius: innerRadius,
  21479. outerRadius: outerRadius,
  21480. thetaSegments: thetaSegments,
  21481. phiSegments: phiSegments,
  21482. thetaStart: thetaStart,
  21483. thetaLength: thetaLength
  21484. };
  21485. thetaSegments = Math.max( 3, thetaSegments );
  21486. phiSegments = Math.max( 1, phiSegments );
  21487. // buffers
  21488. const indices = [];
  21489. const vertices = [];
  21490. const normals = [];
  21491. const uvs = [];
  21492. // some helper variables
  21493. let radius = innerRadius;
  21494. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21495. const vertex = new Vector3();
  21496. const uv = new Vector2();
  21497. // generate vertices, normals and uvs
  21498. for ( let j = 0; j <= phiSegments; j ++ ) {
  21499. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21500. // values are generate from the inside of the ring to the outside
  21501. const segment = thetaStart + i / thetaSegments * thetaLength;
  21502. // vertex
  21503. vertex.x = radius * Math.cos( segment );
  21504. vertex.y = radius * Math.sin( segment );
  21505. vertices.push( vertex.x, vertex.y, vertex.z );
  21506. // normal
  21507. normals.push( 0, 0, 1 );
  21508. // uv
  21509. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21510. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21511. uvs.push( uv.x, uv.y );
  21512. }
  21513. // increase the radius for next row of vertices
  21514. radius += radiusStep;
  21515. }
  21516. // indices
  21517. for ( let j = 0; j < phiSegments; j ++ ) {
  21518. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21519. for ( let i = 0; i < thetaSegments; i ++ ) {
  21520. const segment = i + thetaSegmentLevel;
  21521. const a = segment;
  21522. const b = segment + thetaSegments + 1;
  21523. const c = segment + thetaSegments + 2;
  21524. const d = segment + 1;
  21525. // faces
  21526. indices.push( a, b, d );
  21527. indices.push( b, c, d );
  21528. }
  21529. }
  21530. // build geometry
  21531. this.setIndex( indices );
  21532. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21533. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21534. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21535. }
  21536. static fromJSON( data ) {
  21537. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21538. }
  21539. }
  21540. class ShapeGeometry extends BufferGeometry {
  21541. constructor( shapes, curveSegments = 12 ) {
  21542. super();
  21543. this.type = 'ShapeGeometry';
  21544. this.parameters = {
  21545. shapes: shapes,
  21546. curveSegments: curveSegments
  21547. };
  21548. // buffers
  21549. const indices = [];
  21550. const vertices = [];
  21551. const normals = [];
  21552. const uvs = [];
  21553. // helper variables
  21554. let groupStart = 0;
  21555. let groupCount = 0;
  21556. // allow single and array values for "shapes" parameter
  21557. if ( Array.isArray( shapes ) === false ) {
  21558. addShape( shapes );
  21559. } else {
  21560. for ( let i = 0; i < shapes.length; i ++ ) {
  21561. addShape( shapes[ i ] );
  21562. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21563. groupStart += groupCount;
  21564. groupCount = 0;
  21565. }
  21566. }
  21567. // build geometry
  21568. this.setIndex( indices );
  21569. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21570. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21571. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21572. // helper functions
  21573. function addShape( shape ) {
  21574. const indexOffset = vertices.length / 3;
  21575. const points = shape.extractPoints( curveSegments );
  21576. let shapeVertices = points.shape;
  21577. const shapeHoles = points.holes;
  21578. // check direction of vertices
  21579. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21580. shapeVertices = shapeVertices.reverse();
  21581. }
  21582. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21583. const shapeHole = shapeHoles[ i ];
  21584. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21585. shapeHoles[ i ] = shapeHole.reverse();
  21586. }
  21587. }
  21588. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21589. // join vertices of inner and outer paths to a single array
  21590. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21591. const shapeHole = shapeHoles[ i ];
  21592. shapeVertices = shapeVertices.concat( shapeHole );
  21593. }
  21594. // vertices, normals, uvs
  21595. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21596. const vertex = shapeVertices[ i ];
  21597. vertices.push( vertex.x, vertex.y, 0 );
  21598. normals.push( 0, 0, 1 );
  21599. uvs.push( vertex.x, vertex.y ); // world uvs
  21600. }
  21601. // incides
  21602. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21603. const face = faces[ i ];
  21604. const a = face[ 0 ] + indexOffset;
  21605. const b = face[ 1 ] + indexOffset;
  21606. const c = face[ 2 ] + indexOffset;
  21607. indices.push( a, b, c );
  21608. groupCount += 3;
  21609. }
  21610. }
  21611. }
  21612. toJSON() {
  21613. const data = super.toJSON();
  21614. const shapes = this.parameters.shapes;
  21615. return toJSON( shapes, data );
  21616. }
  21617. static fromJSON( data, shapes ) {
  21618. const geometryShapes = [];
  21619. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21620. const shape = shapes[ data.shapes[ j ] ];
  21621. geometryShapes.push( shape );
  21622. }
  21623. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21624. }
  21625. }
  21626. function toJSON( shapes, data ) {
  21627. data.shapes = [];
  21628. if ( Array.isArray( shapes ) ) {
  21629. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21630. const shape = shapes[ i ];
  21631. data.shapes.push( shape.uuid );
  21632. }
  21633. } else {
  21634. data.shapes.push( shapes.uuid );
  21635. }
  21636. return data;
  21637. }
  21638. class SphereGeometry extends BufferGeometry {
  21639. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21640. super();
  21641. this.type = 'SphereGeometry';
  21642. this.parameters = {
  21643. radius: radius,
  21644. widthSegments: widthSegments,
  21645. heightSegments: heightSegments,
  21646. phiStart: phiStart,
  21647. phiLength: phiLength,
  21648. thetaStart: thetaStart,
  21649. thetaLength: thetaLength
  21650. };
  21651. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21652. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21653. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21654. let index = 0;
  21655. const grid = [];
  21656. const vertex = new Vector3();
  21657. const normal = new Vector3();
  21658. // buffers
  21659. const indices = [];
  21660. const vertices = [];
  21661. const normals = [];
  21662. const uvs = [];
  21663. // generate vertices, normals and uvs
  21664. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21665. const verticesRow = [];
  21666. const v = iy / heightSegments;
  21667. // special case for the poles
  21668. let uOffset = 0;
  21669. if ( iy == 0 && thetaStart == 0 ) {
  21670. uOffset = 0.5 / widthSegments;
  21671. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21672. uOffset = - 0.5 / widthSegments;
  21673. }
  21674. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21675. const u = ix / widthSegments;
  21676. // vertex
  21677. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21678. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21679. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21680. vertices.push( vertex.x, vertex.y, vertex.z );
  21681. // normal
  21682. normal.copy( vertex ).normalize();
  21683. normals.push( normal.x, normal.y, normal.z );
  21684. // uv
  21685. uvs.push( u + uOffset, 1 - v );
  21686. verticesRow.push( index ++ );
  21687. }
  21688. grid.push( verticesRow );
  21689. }
  21690. // indices
  21691. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21692. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21693. const a = grid[ iy ][ ix + 1 ];
  21694. const b = grid[ iy ][ ix ];
  21695. const c = grid[ iy + 1 ][ ix ];
  21696. const d = grid[ iy + 1 ][ ix + 1 ];
  21697. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21698. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21699. }
  21700. }
  21701. // build geometry
  21702. this.setIndex( indices );
  21703. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21704. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21705. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21706. }
  21707. static fromJSON( data ) {
  21708. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21709. }
  21710. }
  21711. class TetrahedronGeometry extends PolyhedronGeometry {
  21712. constructor( radius = 1, detail = 0 ) {
  21713. const vertices = [
  21714. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21715. ];
  21716. const indices = [
  21717. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21718. ];
  21719. super( vertices, indices, radius, detail );
  21720. this.type = 'TetrahedronGeometry';
  21721. this.parameters = {
  21722. radius: radius,
  21723. detail: detail
  21724. };
  21725. }
  21726. static fromJSON( data ) {
  21727. return new TetrahedronGeometry( data.radius, data.detail );
  21728. }
  21729. }
  21730. /**
  21731. * Text = 3D Text
  21732. *
  21733. * parameters = {
  21734. * font: <THREE.Font>, // font
  21735. *
  21736. * size: <float>, // size of the text
  21737. * height: <float>, // thickness to extrude text
  21738. * curveSegments: <int>, // number of points on the curves
  21739. *
  21740. * bevelEnabled: <bool>, // turn on bevel
  21741. * bevelThickness: <float>, // how deep into text bevel goes
  21742. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  21743. * bevelOffset: <float> // how far from text outline does bevel start
  21744. * }
  21745. */
  21746. class TextGeometry extends ExtrudeGeometry {
  21747. constructor( text, parameters = {} ) {
  21748. const font = parameters.font;
  21749. if ( ! ( font && font.isFont ) ) {
  21750. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  21751. return new BufferGeometry();
  21752. }
  21753. const shapes = font.generateShapes( text, parameters.size );
  21754. // translate parameters to ExtrudeGeometry API
  21755. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  21756. // defaults
  21757. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21758. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21759. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21760. super( shapes, parameters );
  21761. this.type = 'TextGeometry';
  21762. }
  21763. }
  21764. class TorusGeometry extends BufferGeometry {
  21765. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  21766. super();
  21767. this.type = 'TorusGeometry';
  21768. this.parameters = {
  21769. radius: radius,
  21770. tube: tube,
  21771. radialSegments: radialSegments,
  21772. tubularSegments: tubularSegments,
  21773. arc: arc
  21774. };
  21775. radialSegments = Math.floor( radialSegments );
  21776. tubularSegments = Math.floor( tubularSegments );
  21777. // buffers
  21778. const indices = [];
  21779. const vertices = [];
  21780. const normals = [];
  21781. const uvs = [];
  21782. // helper variables
  21783. const center = new Vector3();
  21784. const vertex = new Vector3();
  21785. const normal = new Vector3();
  21786. // generate vertices, normals and uvs
  21787. for ( let j = 0; j <= radialSegments; j ++ ) {
  21788. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21789. const u = i / tubularSegments * arc;
  21790. const v = j / radialSegments * Math.PI * 2;
  21791. // vertex
  21792. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21793. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21794. vertex.z = tube * Math.sin( v );
  21795. vertices.push( vertex.x, vertex.y, vertex.z );
  21796. // normal
  21797. center.x = radius * Math.cos( u );
  21798. center.y = radius * Math.sin( u );
  21799. normal.subVectors( vertex, center ).normalize();
  21800. normals.push( normal.x, normal.y, normal.z );
  21801. // uv
  21802. uvs.push( i / tubularSegments );
  21803. uvs.push( j / radialSegments );
  21804. }
  21805. }
  21806. // generate indices
  21807. for ( let j = 1; j <= radialSegments; j ++ ) {
  21808. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21809. // indices
  21810. const a = ( tubularSegments + 1 ) * j + i - 1;
  21811. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21812. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21813. const d = ( tubularSegments + 1 ) * j + i;
  21814. // faces
  21815. indices.push( a, b, d );
  21816. indices.push( b, c, d );
  21817. }
  21818. }
  21819. // build geometry
  21820. this.setIndex( indices );
  21821. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21822. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21823. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21824. }
  21825. static fromJSON( data ) {
  21826. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21827. }
  21828. }
  21829. class TorusKnotGeometry extends BufferGeometry {
  21830. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21831. super();
  21832. this.type = 'TorusKnotGeometry';
  21833. this.parameters = {
  21834. radius: radius,
  21835. tube: tube,
  21836. tubularSegments: tubularSegments,
  21837. radialSegments: radialSegments,
  21838. p: p,
  21839. q: q
  21840. };
  21841. tubularSegments = Math.floor( tubularSegments );
  21842. radialSegments = Math.floor( radialSegments );
  21843. // buffers
  21844. const indices = [];
  21845. const vertices = [];
  21846. const normals = [];
  21847. const uvs = [];
  21848. // helper variables
  21849. const vertex = new Vector3();
  21850. const normal = new Vector3();
  21851. const P1 = new Vector3();
  21852. const P2 = new Vector3();
  21853. const B = new Vector3();
  21854. const T = new Vector3();
  21855. const N = new Vector3();
  21856. // generate vertices, normals and uvs
  21857. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21858. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  21859. const u = i / tubularSegments * p * Math.PI * 2;
  21860. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21861. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21862. calculatePositionOnCurve( u, p, q, radius, P1 );
  21863. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21864. // calculate orthonormal basis
  21865. T.subVectors( P2, P1 );
  21866. N.addVectors( P2, P1 );
  21867. B.crossVectors( T, N );
  21868. N.crossVectors( B, T );
  21869. // normalize B, N. T can be ignored, we don't use it
  21870. B.normalize();
  21871. N.normalize();
  21872. for ( let j = 0; j <= radialSegments; ++ j ) {
  21873. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21874. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21875. const v = j / radialSegments * Math.PI * 2;
  21876. const cx = - tube * Math.cos( v );
  21877. const cy = tube * Math.sin( v );
  21878. // now calculate the final vertex position.
  21879. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  21880. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21881. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21882. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21883. vertices.push( vertex.x, vertex.y, vertex.z );
  21884. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21885. normal.subVectors( vertex, P1 ).normalize();
  21886. normals.push( normal.x, normal.y, normal.z );
  21887. // uv
  21888. uvs.push( i / tubularSegments );
  21889. uvs.push( j / radialSegments );
  21890. }
  21891. }
  21892. // generate indices
  21893. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21894. for ( let i = 1; i <= radialSegments; i ++ ) {
  21895. // indices
  21896. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21897. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21898. const c = ( radialSegments + 1 ) * j + i;
  21899. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21900. // faces
  21901. indices.push( a, b, d );
  21902. indices.push( b, c, d );
  21903. }
  21904. }
  21905. // build geometry
  21906. this.setIndex( indices );
  21907. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21908. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21909. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21910. // this function calculates the current position on the torus curve
  21911. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21912. const cu = Math.cos( u );
  21913. const su = Math.sin( u );
  21914. const quOverP = q / p * u;
  21915. const cs = Math.cos( quOverP );
  21916. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21917. position.y = radius * ( 2 + cs ) * su * 0.5;
  21918. position.z = radius * Math.sin( quOverP ) * 0.5;
  21919. }
  21920. }
  21921. static fromJSON( data ) {
  21922. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21923. }
  21924. }
  21925. class TubeGeometry extends BufferGeometry {
  21926. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  21927. super();
  21928. this.type = 'TubeGeometry';
  21929. this.parameters = {
  21930. path: path,
  21931. tubularSegments: tubularSegments,
  21932. radius: radius,
  21933. radialSegments: radialSegments,
  21934. closed: closed
  21935. };
  21936. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21937. // expose internals
  21938. this.tangents = frames.tangents;
  21939. this.normals = frames.normals;
  21940. this.binormals = frames.binormals;
  21941. // helper variables
  21942. const vertex = new Vector3();
  21943. const normal = new Vector3();
  21944. const uv = new Vector2();
  21945. let P = new Vector3();
  21946. // buffer
  21947. const vertices = [];
  21948. const normals = [];
  21949. const uvs = [];
  21950. const indices = [];
  21951. // create buffer data
  21952. generateBufferData();
  21953. // build geometry
  21954. this.setIndex( indices );
  21955. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21956. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21957. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21958. // functions
  21959. function generateBufferData() {
  21960. for ( let i = 0; i < tubularSegments; i ++ ) {
  21961. generateSegment( i );
  21962. }
  21963. // if the geometry is not closed, generate the last row of vertices and normals
  21964. // at the regular position on the given path
  21965. //
  21966. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21967. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21968. // uvs are generated in a separate function.
  21969. // this makes it easy compute correct values for closed geometries
  21970. generateUVs();
  21971. // finally create faces
  21972. generateIndices();
  21973. }
  21974. function generateSegment( i ) {
  21975. // we use getPointAt to sample evenly distributed points from the given path
  21976. P = path.getPointAt( i / tubularSegments, P );
  21977. // retrieve corresponding normal and binormal
  21978. const N = frames.normals[ i ];
  21979. const B = frames.binormals[ i ];
  21980. // generate normals and vertices for the current segment
  21981. for ( let j = 0; j <= radialSegments; j ++ ) {
  21982. const v = j / radialSegments * Math.PI * 2;
  21983. const sin = Math.sin( v );
  21984. const cos = - Math.cos( v );
  21985. // normal
  21986. normal.x = ( cos * N.x + sin * B.x );
  21987. normal.y = ( cos * N.y + sin * B.y );
  21988. normal.z = ( cos * N.z + sin * B.z );
  21989. normal.normalize();
  21990. normals.push( normal.x, normal.y, normal.z );
  21991. // vertex
  21992. vertex.x = P.x + radius * normal.x;
  21993. vertex.y = P.y + radius * normal.y;
  21994. vertex.z = P.z + radius * normal.z;
  21995. vertices.push( vertex.x, vertex.y, vertex.z );
  21996. }
  21997. }
  21998. function generateIndices() {
  21999. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22000. for ( let i = 1; i <= radialSegments; i ++ ) {
  22001. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22002. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22003. const c = ( radialSegments + 1 ) * j + i;
  22004. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22005. // faces
  22006. indices.push( a, b, d );
  22007. indices.push( b, c, d );
  22008. }
  22009. }
  22010. }
  22011. function generateUVs() {
  22012. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22013. for ( let j = 0; j <= radialSegments; j ++ ) {
  22014. uv.x = i / tubularSegments;
  22015. uv.y = j / radialSegments;
  22016. uvs.push( uv.x, uv.y );
  22017. }
  22018. }
  22019. }
  22020. }
  22021. toJSON() {
  22022. const data = super.toJSON();
  22023. data.path = this.parameters.path.toJSON();
  22024. return data;
  22025. }
  22026. static fromJSON( data ) {
  22027. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22028. // User defined curves or instances of CurvePath will not be deserialized.
  22029. return new TubeGeometry(
  22030. new Curves[ data.path.type ]().fromJSON( data.path ),
  22031. data.tubularSegments,
  22032. data.radius,
  22033. data.radialSegments,
  22034. data.closed
  22035. );
  22036. }
  22037. }
  22038. class WireframeGeometry extends BufferGeometry {
  22039. constructor( geometry ) {
  22040. super();
  22041. this.type = 'WireframeGeometry';
  22042. if ( geometry.isGeometry === true ) {
  22043. console.error( 'THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  22044. return;
  22045. }
  22046. // buffer
  22047. const vertices = [];
  22048. const edges = new Set();
  22049. // helper variables
  22050. const start = new Vector3();
  22051. const end = new Vector3();
  22052. if ( geometry.index !== null ) {
  22053. // indexed BufferGeometry
  22054. const position = geometry.attributes.position;
  22055. const indices = geometry.index;
  22056. let groups = geometry.groups;
  22057. if ( groups.length === 0 ) {
  22058. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22059. }
  22060. // create a data structure that contains all eges without duplicates
  22061. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22062. const group = groups[ o ];
  22063. const groupStart = group.start;
  22064. const groupCount = group.count;
  22065. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22066. for ( let j = 0; j < 3; j ++ ) {
  22067. const index1 = indices.getX( i + j );
  22068. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22069. start.fromBufferAttribute( position, index1 );
  22070. end.fromBufferAttribute( position, index2 );
  22071. if ( isUniqueEdge( start, end, edges ) === true ) {
  22072. vertices.push( start.x, start.y, start.z );
  22073. vertices.push( end.x, end.y, end.z );
  22074. }
  22075. }
  22076. }
  22077. }
  22078. } else {
  22079. // non-indexed BufferGeometry
  22080. const position = geometry.attributes.position;
  22081. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22082. for ( let j = 0; j < 3; j ++ ) {
  22083. // three edges per triangle, an edge is represented as (index1, index2)
  22084. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22085. const index1 = 3 * i + j;
  22086. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22087. start.fromBufferAttribute( position, index1 );
  22088. end.fromBufferAttribute( position, index2 );
  22089. if ( isUniqueEdge( start, end, edges ) === true ) {
  22090. vertices.push( start.x, start.y, start.z );
  22091. vertices.push( end.x, end.y, end.z );
  22092. }
  22093. }
  22094. }
  22095. }
  22096. // build geometry
  22097. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22098. }
  22099. }
  22100. function isUniqueEdge( start, end, edges ) {
  22101. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22102. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22103. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22104. return false;
  22105. } else {
  22106. edges.add( hash1, hash2 );
  22107. return true;
  22108. }
  22109. }
  22110. var Geometries = /*#__PURE__*/Object.freeze({
  22111. __proto__: null,
  22112. BoxGeometry: BoxGeometry,
  22113. BoxBufferGeometry: BoxGeometry,
  22114. CircleGeometry: CircleGeometry,
  22115. CircleBufferGeometry: CircleGeometry,
  22116. ConeGeometry: ConeGeometry,
  22117. ConeBufferGeometry: ConeGeometry,
  22118. CylinderGeometry: CylinderGeometry,
  22119. CylinderBufferGeometry: CylinderGeometry,
  22120. DodecahedronGeometry: DodecahedronGeometry,
  22121. DodecahedronBufferGeometry: DodecahedronGeometry,
  22122. EdgesGeometry: EdgesGeometry,
  22123. ExtrudeGeometry: ExtrudeGeometry,
  22124. ExtrudeBufferGeometry: ExtrudeGeometry,
  22125. IcosahedronGeometry: IcosahedronGeometry,
  22126. IcosahedronBufferGeometry: IcosahedronGeometry,
  22127. LatheGeometry: LatheGeometry,
  22128. LatheBufferGeometry: LatheGeometry,
  22129. OctahedronGeometry: OctahedronGeometry,
  22130. OctahedronBufferGeometry: OctahedronGeometry,
  22131. ParametricGeometry: ParametricGeometry,
  22132. ParametricBufferGeometry: ParametricGeometry,
  22133. PlaneGeometry: PlaneGeometry,
  22134. PlaneBufferGeometry: PlaneGeometry,
  22135. PolyhedronGeometry: PolyhedronGeometry,
  22136. PolyhedronBufferGeometry: PolyhedronGeometry,
  22137. RingGeometry: RingGeometry,
  22138. RingBufferGeometry: RingGeometry,
  22139. ShapeGeometry: ShapeGeometry,
  22140. ShapeBufferGeometry: ShapeGeometry,
  22141. SphereGeometry: SphereGeometry,
  22142. SphereBufferGeometry: SphereGeometry,
  22143. TetrahedronGeometry: TetrahedronGeometry,
  22144. TetrahedronBufferGeometry: TetrahedronGeometry,
  22145. TextGeometry: TextGeometry,
  22146. TextBufferGeometry: TextGeometry,
  22147. TorusGeometry: TorusGeometry,
  22148. TorusBufferGeometry: TorusGeometry,
  22149. TorusKnotGeometry: TorusKnotGeometry,
  22150. TorusKnotBufferGeometry: TorusKnotGeometry,
  22151. TubeGeometry: TubeGeometry,
  22152. TubeBufferGeometry: TubeGeometry,
  22153. WireframeGeometry: WireframeGeometry
  22154. });
  22155. /**
  22156. * parameters = {
  22157. * color: <THREE.Color>
  22158. * }
  22159. */
  22160. class ShadowMaterial extends Material {
  22161. constructor( parameters ) {
  22162. super();
  22163. this.type = 'ShadowMaterial';
  22164. this.color = new Color( 0x000000 );
  22165. this.transparent = true;
  22166. this.setValues( parameters );
  22167. }
  22168. copy( source ) {
  22169. super.copy( source );
  22170. this.color.copy( source.color );
  22171. return this;
  22172. }
  22173. }
  22174. ShadowMaterial.prototype.isShadowMaterial = true;
  22175. /**
  22176. * parameters = {
  22177. * color: <hex>,
  22178. * roughness: <float>,
  22179. * metalness: <float>,
  22180. * opacity: <float>,
  22181. *
  22182. * map: new THREE.Texture( <Image> ),
  22183. *
  22184. * lightMap: new THREE.Texture( <Image> ),
  22185. * lightMapIntensity: <float>
  22186. *
  22187. * aoMap: new THREE.Texture( <Image> ),
  22188. * aoMapIntensity: <float>
  22189. *
  22190. * emissive: <hex>,
  22191. * emissiveIntensity: <float>
  22192. * emissiveMap: new THREE.Texture( <Image> ),
  22193. *
  22194. * bumpMap: new THREE.Texture( <Image> ),
  22195. * bumpScale: <float>,
  22196. *
  22197. * normalMap: new THREE.Texture( <Image> ),
  22198. * normalMapType: THREE.TangentSpaceNormalMap,
  22199. * normalScale: <Vector2>,
  22200. *
  22201. * displacementMap: new THREE.Texture( <Image> ),
  22202. * displacementScale: <float>,
  22203. * displacementBias: <float>,
  22204. *
  22205. * roughnessMap: new THREE.Texture( <Image> ),
  22206. *
  22207. * metalnessMap: new THREE.Texture( <Image> ),
  22208. *
  22209. * alphaMap: new THREE.Texture( <Image> ),
  22210. *
  22211. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22212. * envMapIntensity: <float>
  22213. *
  22214. * refractionRatio: <float>,
  22215. *
  22216. * wireframe: <boolean>,
  22217. * wireframeLinewidth: <float>,
  22218. *
  22219. * flatShading: <bool>
  22220. * }
  22221. */
  22222. class MeshStandardMaterial extends Material {
  22223. constructor( parameters ) {
  22224. super();
  22225. this.defines = { 'STANDARD': '' };
  22226. this.type = 'MeshStandardMaterial';
  22227. this.color = new Color( 0xffffff ); // diffuse
  22228. this.roughness = 1.0;
  22229. this.metalness = 0.0;
  22230. this.map = null;
  22231. this.lightMap = null;
  22232. this.lightMapIntensity = 1.0;
  22233. this.aoMap = null;
  22234. this.aoMapIntensity = 1.0;
  22235. this.emissive = new Color( 0x000000 );
  22236. this.emissiveIntensity = 1.0;
  22237. this.emissiveMap = null;
  22238. this.bumpMap = null;
  22239. this.bumpScale = 1;
  22240. this.normalMap = null;
  22241. this.normalMapType = TangentSpaceNormalMap;
  22242. this.normalScale = new Vector2( 1, 1 );
  22243. this.displacementMap = null;
  22244. this.displacementScale = 1;
  22245. this.displacementBias = 0;
  22246. this.roughnessMap = null;
  22247. this.metalnessMap = null;
  22248. this.alphaMap = null;
  22249. this.envMap = null;
  22250. this.envMapIntensity = 1.0;
  22251. this.refractionRatio = 0.98;
  22252. this.wireframe = false;
  22253. this.wireframeLinewidth = 1;
  22254. this.wireframeLinecap = 'round';
  22255. this.wireframeLinejoin = 'round';
  22256. this.flatShading = false;
  22257. this.setValues( parameters );
  22258. }
  22259. copy( source ) {
  22260. super.copy( source );
  22261. this.defines = { 'STANDARD': '' };
  22262. this.color.copy( source.color );
  22263. this.roughness = source.roughness;
  22264. this.metalness = source.metalness;
  22265. this.map = source.map;
  22266. this.lightMap = source.lightMap;
  22267. this.lightMapIntensity = source.lightMapIntensity;
  22268. this.aoMap = source.aoMap;
  22269. this.aoMapIntensity = source.aoMapIntensity;
  22270. this.emissive.copy( source.emissive );
  22271. this.emissiveMap = source.emissiveMap;
  22272. this.emissiveIntensity = source.emissiveIntensity;
  22273. this.bumpMap = source.bumpMap;
  22274. this.bumpScale = source.bumpScale;
  22275. this.normalMap = source.normalMap;
  22276. this.normalMapType = source.normalMapType;
  22277. this.normalScale.copy( source.normalScale );
  22278. this.displacementMap = source.displacementMap;
  22279. this.displacementScale = source.displacementScale;
  22280. this.displacementBias = source.displacementBias;
  22281. this.roughnessMap = source.roughnessMap;
  22282. this.metalnessMap = source.metalnessMap;
  22283. this.alphaMap = source.alphaMap;
  22284. this.envMap = source.envMap;
  22285. this.envMapIntensity = source.envMapIntensity;
  22286. this.refractionRatio = source.refractionRatio;
  22287. this.wireframe = source.wireframe;
  22288. this.wireframeLinewidth = source.wireframeLinewidth;
  22289. this.wireframeLinecap = source.wireframeLinecap;
  22290. this.wireframeLinejoin = source.wireframeLinejoin;
  22291. this.flatShading = source.flatShading;
  22292. return this;
  22293. }
  22294. }
  22295. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  22296. /**
  22297. * parameters = {
  22298. * clearcoat: <float>,
  22299. * clearcoatMap: new THREE.Texture( <Image> ),
  22300. * clearcoatRoughness: <float>,
  22301. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  22302. * clearcoatNormalScale: <Vector2>,
  22303. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  22304. *
  22305. * ior: <float>,
  22306. * reflectivity: <float>,
  22307. *
  22308. * sheenTint: <Color>,
  22309. *
  22310. * transmission: <float>,
  22311. * transmissionMap: new THREE.Texture( <Image> ),
  22312. *
  22313. * thickness: <float>,
  22314. * thicknessMap: new THREE.Texture( <Image> ),
  22315. * attenuationDistance: <float>,
  22316. * attenuationTint: <Color>,
  22317. *
  22318. * specularIntensity: <float>,
  22319. * specularIntensityhMap: new THREE.Texture( <Image> ),
  22320. * specularTint: <Color>,
  22321. * specularTintMap: new THREE.Texture( <Image> )
  22322. * }
  22323. */
  22324. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22325. constructor( parameters ) {
  22326. super();
  22327. this.defines = {
  22328. 'STANDARD': '',
  22329. 'PHYSICAL': ''
  22330. };
  22331. this.type = 'MeshPhysicalMaterial';
  22332. this.clearcoatMap = null;
  22333. this.clearcoatRoughness = 0.0;
  22334. this.clearcoatRoughnessMap = null;
  22335. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22336. this.clearcoatNormalMap = null;
  22337. this.ior = 1.5;
  22338. Object.defineProperty( this, 'reflectivity', {
  22339. get: function () {
  22340. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22341. },
  22342. set: function ( reflectivity ) {
  22343. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22344. }
  22345. } );
  22346. this.sheenTint = new Color( 0x000000 );
  22347. this.transmission = 0.0;
  22348. this.transmissionMap = null;
  22349. this.thickness = 0.01;
  22350. this.thicknessMap = null;
  22351. this.attenuationDistance = 0.0;
  22352. this.attenuationTint = new Color( 1, 1, 1 );
  22353. this.specularIntensity = 1.0;
  22354. this.specularIntensityMap = null;
  22355. this.specularTint = new Color( 1, 1, 1 );
  22356. this.specularTintMap = null;
  22357. this._clearcoat = 0;
  22358. this._transmission = 0;
  22359. this.setValues( parameters );
  22360. }
  22361. get clearcoat() {
  22362. return this._clearcoat;
  22363. }
  22364. set clearcoat( value ) {
  22365. if ( this._clearcoat > 0 !== value > 0 ) {
  22366. this.version ++;
  22367. }
  22368. this._clearcoat = value;
  22369. }
  22370. get transmission() {
  22371. return this._transmission;
  22372. }
  22373. set transmission( value ) {
  22374. if ( this._transmission > 0 !== value > 0 ) {
  22375. this.version ++;
  22376. }
  22377. this._transmission = value;
  22378. }
  22379. copy( source ) {
  22380. super.copy( source );
  22381. this.defines = {
  22382. 'STANDARD': '',
  22383. 'PHYSICAL': ''
  22384. };
  22385. this.clearcoat = source.clearcoat;
  22386. this.clearcoatMap = source.clearcoatMap;
  22387. this.clearcoatRoughness = source.clearcoatRoughness;
  22388. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22389. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22390. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22391. this.ior = source.ior;
  22392. this.sheenTint.copy( source.sheenTint );
  22393. this.transmission = source.transmission;
  22394. this.transmissionMap = source.transmissionMap;
  22395. this.thickness = source.thickness;
  22396. this.thicknessMap = source.thicknessMap;
  22397. this.attenuationDistance = source.attenuationDistance;
  22398. this.attenuationTint.copy( source.attenuationTint );
  22399. this.specularIntensity = source.specularIntensity;
  22400. this.specularIntensityMap = source.specularIntensityMap;
  22401. this.specularTint.copy( source.specularTint );
  22402. this.specularTintMap = source.specularTintMap;
  22403. return this;
  22404. }
  22405. }
  22406. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  22407. /**
  22408. * parameters = {
  22409. * color: <hex>,
  22410. * specular: <hex>,
  22411. * shininess: <float>,
  22412. * opacity: <float>,
  22413. *
  22414. * map: new THREE.Texture( <Image> ),
  22415. *
  22416. * lightMap: new THREE.Texture( <Image> ),
  22417. * lightMapIntensity: <float>
  22418. *
  22419. * aoMap: new THREE.Texture( <Image> ),
  22420. * aoMapIntensity: <float>
  22421. *
  22422. * emissive: <hex>,
  22423. * emissiveIntensity: <float>
  22424. * emissiveMap: new THREE.Texture( <Image> ),
  22425. *
  22426. * bumpMap: new THREE.Texture( <Image> ),
  22427. * bumpScale: <float>,
  22428. *
  22429. * normalMap: new THREE.Texture( <Image> ),
  22430. * normalMapType: THREE.TangentSpaceNormalMap,
  22431. * normalScale: <Vector2>,
  22432. *
  22433. * displacementMap: new THREE.Texture( <Image> ),
  22434. * displacementScale: <float>,
  22435. * displacementBias: <float>,
  22436. *
  22437. * specularMap: new THREE.Texture( <Image> ),
  22438. *
  22439. * alphaMap: new THREE.Texture( <Image> ),
  22440. *
  22441. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22442. * combine: THREE.MultiplyOperation,
  22443. * reflectivity: <float>,
  22444. * refractionRatio: <float>,
  22445. *
  22446. * wireframe: <boolean>,
  22447. * wireframeLinewidth: <float>,
  22448. *
  22449. * flatShading: <bool>
  22450. * }
  22451. */
  22452. class MeshPhongMaterial extends Material {
  22453. constructor( parameters ) {
  22454. super();
  22455. this.type = 'MeshPhongMaterial';
  22456. this.color = new Color( 0xffffff ); // diffuse
  22457. this.specular = new Color( 0x111111 );
  22458. this.shininess = 30;
  22459. this.map = null;
  22460. this.lightMap = null;
  22461. this.lightMapIntensity = 1.0;
  22462. this.aoMap = null;
  22463. this.aoMapIntensity = 1.0;
  22464. this.emissive = new Color( 0x000000 );
  22465. this.emissiveIntensity = 1.0;
  22466. this.emissiveMap = null;
  22467. this.bumpMap = null;
  22468. this.bumpScale = 1;
  22469. this.normalMap = null;
  22470. this.normalMapType = TangentSpaceNormalMap;
  22471. this.normalScale = new Vector2( 1, 1 );
  22472. this.displacementMap = null;
  22473. this.displacementScale = 1;
  22474. this.displacementBias = 0;
  22475. this.specularMap = null;
  22476. this.alphaMap = null;
  22477. this.envMap = null;
  22478. this.combine = MultiplyOperation;
  22479. this.reflectivity = 1;
  22480. this.refractionRatio = 0.98;
  22481. this.wireframe = false;
  22482. this.wireframeLinewidth = 1;
  22483. this.wireframeLinecap = 'round';
  22484. this.wireframeLinejoin = 'round';
  22485. this.flatShading = false;
  22486. this.setValues( parameters );
  22487. }
  22488. copy( source ) {
  22489. super.copy( source );
  22490. this.color.copy( source.color );
  22491. this.specular.copy( source.specular );
  22492. this.shininess = source.shininess;
  22493. this.map = source.map;
  22494. this.lightMap = source.lightMap;
  22495. this.lightMapIntensity = source.lightMapIntensity;
  22496. this.aoMap = source.aoMap;
  22497. this.aoMapIntensity = source.aoMapIntensity;
  22498. this.emissive.copy( source.emissive );
  22499. this.emissiveMap = source.emissiveMap;
  22500. this.emissiveIntensity = source.emissiveIntensity;
  22501. this.bumpMap = source.bumpMap;
  22502. this.bumpScale = source.bumpScale;
  22503. this.normalMap = source.normalMap;
  22504. this.normalMapType = source.normalMapType;
  22505. this.normalScale.copy( source.normalScale );
  22506. this.displacementMap = source.displacementMap;
  22507. this.displacementScale = source.displacementScale;
  22508. this.displacementBias = source.displacementBias;
  22509. this.specularMap = source.specularMap;
  22510. this.alphaMap = source.alphaMap;
  22511. this.envMap = source.envMap;
  22512. this.combine = source.combine;
  22513. this.reflectivity = source.reflectivity;
  22514. this.refractionRatio = source.refractionRatio;
  22515. this.wireframe = source.wireframe;
  22516. this.wireframeLinewidth = source.wireframeLinewidth;
  22517. this.wireframeLinecap = source.wireframeLinecap;
  22518. this.wireframeLinejoin = source.wireframeLinejoin;
  22519. this.flatShading = source.flatShading;
  22520. return this;
  22521. }
  22522. }
  22523. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  22524. /**
  22525. * parameters = {
  22526. * color: <hex>,
  22527. *
  22528. * map: new THREE.Texture( <Image> ),
  22529. * gradientMap: new THREE.Texture( <Image> ),
  22530. *
  22531. * lightMap: new THREE.Texture( <Image> ),
  22532. * lightMapIntensity: <float>
  22533. *
  22534. * aoMap: new THREE.Texture( <Image> ),
  22535. * aoMapIntensity: <float>
  22536. *
  22537. * emissive: <hex>,
  22538. * emissiveIntensity: <float>
  22539. * emissiveMap: new THREE.Texture( <Image> ),
  22540. *
  22541. * bumpMap: new THREE.Texture( <Image> ),
  22542. * bumpScale: <float>,
  22543. *
  22544. * normalMap: new THREE.Texture( <Image> ),
  22545. * normalMapType: THREE.TangentSpaceNormalMap,
  22546. * normalScale: <Vector2>,
  22547. *
  22548. * displacementMap: new THREE.Texture( <Image> ),
  22549. * displacementScale: <float>,
  22550. * displacementBias: <float>,
  22551. *
  22552. * alphaMap: new THREE.Texture( <Image> ),
  22553. *
  22554. * wireframe: <boolean>,
  22555. * wireframeLinewidth: <float>,
  22556. *
  22557. * }
  22558. */
  22559. class MeshToonMaterial extends Material {
  22560. constructor( parameters ) {
  22561. super();
  22562. this.defines = { 'TOON': '' };
  22563. this.type = 'MeshToonMaterial';
  22564. this.color = new Color( 0xffffff );
  22565. this.map = null;
  22566. this.gradientMap = null;
  22567. this.lightMap = null;
  22568. this.lightMapIntensity = 1.0;
  22569. this.aoMap = null;
  22570. this.aoMapIntensity = 1.0;
  22571. this.emissive = new Color( 0x000000 );
  22572. this.emissiveIntensity = 1.0;
  22573. this.emissiveMap = null;
  22574. this.bumpMap = null;
  22575. this.bumpScale = 1;
  22576. this.normalMap = null;
  22577. this.normalMapType = TangentSpaceNormalMap;
  22578. this.normalScale = new Vector2( 1, 1 );
  22579. this.displacementMap = null;
  22580. this.displacementScale = 1;
  22581. this.displacementBias = 0;
  22582. this.alphaMap = null;
  22583. this.wireframe = false;
  22584. this.wireframeLinewidth = 1;
  22585. this.wireframeLinecap = 'round';
  22586. this.wireframeLinejoin = 'round';
  22587. this.setValues( parameters );
  22588. }
  22589. copy( source ) {
  22590. super.copy( source );
  22591. this.color.copy( source.color );
  22592. this.map = source.map;
  22593. this.gradientMap = source.gradientMap;
  22594. this.lightMap = source.lightMap;
  22595. this.lightMapIntensity = source.lightMapIntensity;
  22596. this.aoMap = source.aoMap;
  22597. this.aoMapIntensity = source.aoMapIntensity;
  22598. this.emissive.copy( source.emissive );
  22599. this.emissiveMap = source.emissiveMap;
  22600. this.emissiveIntensity = source.emissiveIntensity;
  22601. this.bumpMap = source.bumpMap;
  22602. this.bumpScale = source.bumpScale;
  22603. this.normalMap = source.normalMap;
  22604. this.normalMapType = source.normalMapType;
  22605. this.normalScale.copy( source.normalScale );
  22606. this.displacementMap = source.displacementMap;
  22607. this.displacementScale = source.displacementScale;
  22608. this.displacementBias = source.displacementBias;
  22609. this.alphaMap = source.alphaMap;
  22610. this.wireframe = source.wireframe;
  22611. this.wireframeLinewidth = source.wireframeLinewidth;
  22612. this.wireframeLinecap = source.wireframeLinecap;
  22613. this.wireframeLinejoin = source.wireframeLinejoin;
  22614. return this;
  22615. }
  22616. }
  22617. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  22618. /**
  22619. * parameters = {
  22620. * opacity: <float>,
  22621. *
  22622. * bumpMap: new THREE.Texture( <Image> ),
  22623. * bumpScale: <float>,
  22624. *
  22625. * normalMap: new THREE.Texture( <Image> ),
  22626. * normalMapType: THREE.TangentSpaceNormalMap,
  22627. * normalScale: <Vector2>,
  22628. *
  22629. * displacementMap: new THREE.Texture( <Image> ),
  22630. * displacementScale: <float>,
  22631. * displacementBias: <float>,
  22632. *
  22633. * wireframe: <boolean>,
  22634. * wireframeLinewidth: <float>
  22635. *
  22636. * flatShading: <bool>
  22637. * }
  22638. */
  22639. class MeshNormalMaterial extends Material {
  22640. constructor( parameters ) {
  22641. super();
  22642. this.type = 'MeshNormalMaterial';
  22643. this.bumpMap = null;
  22644. this.bumpScale = 1;
  22645. this.normalMap = null;
  22646. this.normalMapType = TangentSpaceNormalMap;
  22647. this.normalScale = new Vector2( 1, 1 );
  22648. this.displacementMap = null;
  22649. this.displacementScale = 1;
  22650. this.displacementBias = 0;
  22651. this.wireframe = false;
  22652. this.wireframeLinewidth = 1;
  22653. this.fog = false;
  22654. this.flatShading = false;
  22655. this.setValues( parameters );
  22656. }
  22657. copy( source ) {
  22658. super.copy( source );
  22659. this.bumpMap = source.bumpMap;
  22660. this.bumpScale = source.bumpScale;
  22661. this.normalMap = source.normalMap;
  22662. this.normalMapType = source.normalMapType;
  22663. this.normalScale.copy( source.normalScale );
  22664. this.displacementMap = source.displacementMap;
  22665. this.displacementScale = source.displacementScale;
  22666. this.displacementBias = source.displacementBias;
  22667. this.wireframe = source.wireframe;
  22668. this.wireframeLinewidth = source.wireframeLinewidth;
  22669. this.flatShading = source.flatShading;
  22670. return this;
  22671. }
  22672. }
  22673. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22674. /**
  22675. * parameters = {
  22676. * color: <hex>,
  22677. * opacity: <float>,
  22678. *
  22679. * map: new THREE.Texture( <Image> ),
  22680. *
  22681. * lightMap: new THREE.Texture( <Image> ),
  22682. * lightMapIntensity: <float>
  22683. *
  22684. * aoMap: new THREE.Texture( <Image> ),
  22685. * aoMapIntensity: <float>
  22686. *
  22687. * emissive: <hex>,
  22688. * emissiveIntensity: <float>
  22689. * emissiveMap: new THREE.Texture( <Image> ),
  22690. *
  22691. * specularMap: new THREE.Texture( <Image> ),
  22692. *
  22693. * alphaMap: new THREE.Texture( <Image> ),
  22694. *
  22695. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22696. * combine: THREE.Multiply,
  22697. * reflectivity: <float>,
  22698. * refractionRatio: <float>,
  22699. *
  22700. * wireframe: <boolean>,
  22701. * wireframeLinewidth: <float>,
  22702. *
  22703. * }
  22704. */
  22705. class MeshLambertMaterial extends Material {
  22706. constructor( parameters ) {
  22707. super();
  22708. this.type = 'MeshLambertMaterial';
  22709. this.color = new Color( 0xffffff ); // diffuse
  22710. this.map = null;
  22711. this.lightMap = null;
  22712. this.lightMapIntensity = 1.0;
  22713. this.aoMap = null;
  22714. this.aoMapIntensity = 1.0;
  22715. this.emissive = new Color( 0x000000 );
  22716. this.emissiveIntensity = 1.0;
  22717. this.emissiveMap = null;
  22718. this.specularMap = null;
  22719. this.alphaMap = null;
  22720. this.envMap = null;
  22721. this.combine = MultiplyOperation;
  22722. this.reflectivity = 1;
  22723. this.refractionRatio = 0.98;
  22724. this.wireframe = false;
  22725. this.wireframeLinewidth = 1;
  22726. this.wireframeLinecap = 'round';
  22727. this.wireframeLinejoin = 'round';
  22728. this.setValues( parameters );
  22729. }
  22730. copy( source ) {
  22731. super.copy( source );
  22732. this.color.copy( source.color );
  22733. this.map = source.map;
  22734. this.lightMap = source.lightMap;
  22735. this.lightMapIntensity = source.lightMapIntensity;
  22736. this.aoMap = source.aoMap;
  22737. this.aoMapIntensity = source.aoMapIntensity;
  22738. this.emissive.copy( source.emissive );
  22739. this.emissiveMap = source.emissiveMap;
  22740. this.emissiveIntensity = source.emissiveIntensity;
  22741. this.specularMap = source.specularMap;
  22742. this.alphaMap = source.alphaMap;
  22743. this.envMap = source.envMap;
  22744. this.combine = source.combine;
  22745. this.reflectivity = source.reflectivity;
  22746. this.refractionRatio = source.refractionRatio;
  22747. this.wireframe = source.wireframe;
  22748. this.wireframeLinewidth = source.wireframeLinewidth;
  22749. this.wireframeLinecap = source.wireframeLinecap;
  22750. this.wireframeLinejoin = source.wireframeLinejoin;
  22751. return this;
  22752. }
  22753. }
  22754. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22755. /**
  22756. * parameters = {
  22757. * color: <hex>,
  22758. * opacity: <float>,
  22759. *
  22760. * matcap: new THREE.Texture( <Image> ),
  22761. *
  22762. * map: new THREE.Texture( <Image> ),
  22763. *
  22764. * bumpMap: new THREE.Texture( <Image> ),
  22765. * bumpScale: <float>,
  22766. *
  22767. * normalMap: new THREE.Texture( <Image> ),
  22768. * normalMapType: THREE.TangentSpaceNormalMap,
  22769. * normalScale: <Vector2>,
  22770. *
  22771. * displacementMap: new THREE.Texture( <Image> ),
  22772. * displacementScale: <float>,
  22773. * displacementBias: <float>,
  22774. *
  22775. * alphaMap: new THREE.Texture( <Image> ),
  22776. *
  22777. * flatShading: <bool>
  22778. * }
  22779. */
  22780. class MeshMatcapMaterial extends Material {
  22781. constructor( parameters ) {
  22782. super();
  22783. this.defines = { 'MATCAP': '' };
  22784. this.type = 'MeshMatcapMaterial';
  22785. this.color = new Color( 0xffffff ); // diffuse
  22786. this.matcap = null;
  22787. this.map = null;
  22788. this.bumpMap = null;
  22789. this.bumpScale = 1;
  22790. this.normalMap = null;
  22791. this.normalMapType = TangentSpaceNormalMap;
  22792. this.normalScale = new Vector2( 1, 1 );
  22793. this.displacementMap = null;
  22794. this.displacementScale = 1;
  22795. this.displacementBias = 0;
  22796. this.alphaMap = null;
  22797. this.flatShading = false;
  22798. this.setValues( parameters );
  22799. }
  22800. copy( source ) {
  22801. super.copy( source );
  22802. this.defines = { 'MATCAP': '' };
  22803. this.color.copy( source.color );
  22804. this.matcap = source.matcap;
  22805. this.map = source.map;
  22806. this.bumpMap = source.bumpMap;
  22807. this.bumpScale = source.bumpScale;
  22808. this.normalMap = source.normalMap;
  22809. this.normalMapType = source.normalMapType;
  22810. this.normalScale.copy( source.normalScale );
  22811. this.displacementMap = source.displacementMap;
  22812. this.displacementScale = source.displacementScale;
  22813. this.displacementBias = source.displacementBias;
  22814. this.alphaMap = source.alphaMap;
  22815. this.flatShading = source.flatShading;
  22816. return this;
  22817. }
  22818. }
  22819. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  22820. /**
  22821. * parameters = {
  22822. * color: <hex>,
  22823. * opacity: <float>,
  22824. *
  22825. * linewidth: <float>,
  22826. *
  22827. * scale: <float>,
  22828. * dashSize: <float>,
  22829. * gapSize: <float>
  22830. * }
  22831. */
  22832. class LineDashedMaterial extends LineBasicMaterial {
  22833. constructor( parameters ) {
  22834. super();
  22835. this.type = 'LineDashedMaterial';
  22836. this.scale = 1;
  22837. this.dashSize = 3;
  22838. this.gapSize = 1;
  22839. this.setValues( parameters );
  22840. }
  22841. copy( source ) {
  22842. super.copy( source );
  22843. this.scale = source.scale;
  22844. this.dashSize = source.dashSize;
  22845. this.gapSize = source.gapSize;
  22846. return this;
  22847. }
  22848. }
  22849. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22850. var Materials = /*#__PURE__*/Object.freeze({
  22851. __proto__: null,
  22852. ShadowMaterial: ShadowMaterial,
  22853. SpriteMaterial: SpriteMaterial,
  22854. RawShaderMaterial: RawShaderMaterial,
  22855. ShaderMaterial: ShaderMaterial,
  22856. PointsMaterial: PointsMaterial,
  22857. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22858. MeshStandardMaterial: MeshStandardMaterial,
  22859. MeshPhongMaterial: MeshPhongMaterial,
  22860. MeshToonMaterial: MeshToonMaterial,
  22861. MeshNormalMaterial: MeshNormalMaterial,
  22862. MeshLambertMaterial: MeshLambertMaterial,
  22863. MeshDepthMaterial: MeshDepthMaterial,
  22864. MeshDistanceMaterial: MeshDistanceMaterial,
  22865. MeshBasicMaterial: MeshBasicMaterial,
  22866. MeshMatcapMaterial: MeshMatcapMaterial,
  22867. LineDashedMaterial: LineDashedMaterial,
  22868. LineBasicMaterial: LineBasicMaterial,
  22869. Material: Material
  22870. });
  22871. const AnimationUtils = {
  22872. // same as Array.prototype.slice, but also works on typed arrays
  22873. arraySlice: function ( array, from, to ) {
  22874. if ( AnimationUtils.isTypedArray( array ) ) {
  22875. // in ios9 array.subarray(from, undefined) will return empty array
  22876. // but array.subarray(from) or array.subarray(from, len) is correct
  22877. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22878. }
  22879. return array.slice( from, to );
  22880. },
  22881. // converts an array to a specific type
  22882. convertArray: function ( array, type, forceClone ) {
  22883. if ( ! array || // let 'undefined' and 'null' pass
  22884. ! forceClone && array.constructor === type ) return array;
  22885. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22886. return new type( array ); // create typed array
  22887. }
  22888. return Array.prototype.slice.call( array ); // create Array
  22889. },
  22890. isTypedArray: function ( object ) {
  22891. return ArrayBuffer.isView( object ) &&
  22892. ! ( object instanceof DataView );
  22893. },
  22894. // returns an array by which times and values can be sorted
  22895. getKeyframeOrder: function ( times ) {
  22896. function compareTime( i, j ) {
  22897. return times[ i ] - times[ j ];
  22898. }
  22899. const n = times.length;
  22900. const result = new Array( n );
  22901. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22902. result.sort( compareTime );
  22903. return result;
  22904. },
  22905. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22906. sortedArray: function ( values, stride, order ) {
  22907. const nValues = values.length;
  22908. const result = new values.constructor( nValues );
  22909. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22910. const srcOffset = order[ i ] * stride;
  22911. for ( let j = 0; j !== stride; ++ j ) {
  22912. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22913. }
  22914. }
  22915. return result;
  22916. },
  22917. // function for parsing AOS keyframe formats
  22918. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  22919. let i = 1, key = jsonKeys[ 0 ];
  22920. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22921. key = jsonKeys[ i ++ ];
  22922. }
  22923. if ( key === undefined ) return; // no data
  22924. let value = key[ valuePropertyName ];
  22925. if ( value === undefined ) return; // no data
  22926. if ( Array.isArray( value ) ) {
  22927. do {
  22928. value = key[ valuePropertyName ];
  22929. if ( value !== undefined ) {
  22930. times.push( key.time );
  22931. values.push.apply( values, value ); // push all elements
  22932. }
  22933. key = jsonKeys[ i ++ ];
  22934. } while ( key !== undefined );
  22935. } else if ( value.toArray !== undefined ) {
  22936. // ...assume THREE.Math-ish
  22937. do {
  22938. value = key[ valuePropertyName ];
  22939. if ( value !== undefined ) {
  22940. times.push( key.time );
  22941. value.toArray( values, values.length );
  22942. }
  22943. key = jsonKeys[ i ++ ];
  22944. } while ( key !== undefined );
  22945. } else {
  22946. // otherwise push as-is
  22947. do {
  22948. value = key[ valuePropertyName ];
  22949. if ( value !== undefined ) {
  22950. times.push( key.time );
  22951. values.push( value );
  22952. }
  22953. key = jsonKeys[ i ++ ];
  22954. } while ( key !== undefined );
  22955. }
  22956. },
  22957. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22958. const clip = sourceClip.clone();
  22959. clip.name = name;
  22960. const tracks = [];
  22961. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22962. const track = clip.tracks[ i ];
  22963. const valueSize = track.getValueSize();
  22964. const times = [];
  22965. const values = [];
  22966. for ( let j = 0; j < track.times.length; ++ j ) {
  22967. const frame = track.times[ j ] * fps;
  22968. if ( frame < startFrame || frame >= endFrame ) continue;
  22969. times.push( track.times[ j ] );
  22970. for ( let k = 0; k < valueSize; ++ k ) {
  22971. values.push( track.values[ j * valueSize + k ] );
  22972. }
  22973. }
  22974. if ( times.length === 0 ) continue;
  22975. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  22976. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  22977. tracks.push( track );
  22978. }
  22979. clip.tracks = tracks;
  22980. // find minimum .times value across all tracks in the trimmed clip
  22981. let minStartTime = Infinity;
  22982. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22983. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22984. minStartTime = clip.tracks[ i ].times[ 0 ];
  22985. }
  22986. }
  22987. // shift all tracks such that clip begins at t=0
  22988. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22989. clip.tracks[ i ].shift( - 1 * minStartTime );
  22990. }
  22991. clip.resetDuration();
  22992. return clip;
  22993. },
  22994. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22995. if ( fps <= 0 ) fps = 30;
  22996. const numTracks = referenceClip.tracks.length;
  22997. const referenceTime = referenceFrame / fps;
  22998. // Make each track's values relative to the values at the reference frame
  22999. for ( let i = 0; i < numTracks; ++ i ) {
  23000. const referenceTrack = referenceClip.tracks[ i ];
  23001. const referenceTrackType = referenceTrack.ValueTypeName;
  23002. // Skip this track if it's non-numeric
  23003. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23004. // Find the track in the target clip whose name and type matches the reference track
  23005. const targetTrack = targetClip.tracks.find( function ( track ) {
  23006. return track.name === referenceTrack.name
  23007. && track.ValueTypeName === referenceTrackType;
  23008. } );
  23009. if ( targetTrack === undefined ) continue;
  23010. let referenceOffset = 0;
  23011. const referenceValueSize = referenceTrack.getValueSize();
  23012. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23013. referenceOffset = referenceValueSize / 3;
  23014. }
  23015. let targetOffset = 0;
  23016. const targetValueSize = targetTrack.getValueSize();
  23017. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23018. targetOffset = targetValueSize / 3;
  23019. }
  23020. const lastIndex = referenceTrack.times.length - 1;
  23021. let referenceValue;
  23022. // Find the value to subtract out of the track
  23023. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23024. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23025. const startIndex = referenceOffset;
  23026. const endIndex = referenceValueSize - referenceOffset;
  23027. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  23028. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23029. // Reference frame is after the last keyframe, so just use the last keyframe
  23030. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23031. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23032. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  23033. } else {
  23034. // Interpolate to the reference value
  23035. const interpolant = referenceTrack.createInterpolant();
  23036. const startIndex = referenceOffset;
  23037. const endIndex = referenceValueSize - referenceOffset;
  23038. interpolant.evaluate( referenceTime );
  23039. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23040. }
  23041. // Conjugate the quaternion
  23042. if ( referenceTrackType === 'quaternion' ) {
  23043. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23044. referenceQuat.toArray( referenceValue );
  23045. }
  23046. // Subtract the reference value from all of the track values
  23047. const numTimes = targetTrack.times.length;
  23048. for ( let j = 0; j < numTimes; ++ j ) {
  23049. const valueStart = j * targetValueSize + targetOffset;
  23050. if ( referenceTrackType === 'quaternion' ) {
  23051. // Multiply the conjugate for quaternion track types
  23052. Quaternion.multiplyQuaternionsFlat(
  23053. targetTrack.values,
  23054. valueStart,
  23055. referenceValue,
  23056. 0,
  23057. targetTrack.values,
  23058. valueStart
  23059. );
  23060. } else {
  23061. const valueEnd = targetValueSize - targetOffset * 2;
  23062. // Subtract each value for all other numeric track types
  23063. for ( let k = 0; k < valueEnd; ++ k ) {
  23064. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23065. }
  23066. }
  23067. }
  23068. }
  23069. targetClip.blendMode = AdditiveAnimationBlendMode;
  23070. return targetClip;
  23071. }
  23072. };
  23073. /**
  23074. * Abstract base class of interpolants over parametric samples.
  23075. *
  23076. * The parameter domain is one dimensional, typically the time or a path
  23077. * along a curve defined by the data.
  23078. *
  23079. * The sample values can have any dimensionality and derived classes may
  23080. * apply special interpretations to the data.
  23081. *
  23082. * This class provides the interval seek in a Template Method, deferring
  23083. * the actual interpolation to derived classes.
  23084. *
  23085. * Time complexity is O(1) for linear access crossing at most two points
  23086. * and O(log N) for random access, where N is the number of positions.
  23087. *
  23088. * References:
  23089. *
  23090. * http://www.oodesign.com/template-method-pattern.html
  23091. *
  23092. */
  23093. class Interpolant {
  23094. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23095. this.parameterPositions = parameterPositions;
  23096. this._cachedIndex = 0;
  23097. this.resultBuffer = resultBuffer !== undefined ?
  23098. resultBuffer : new sampleValues.constructor( sampleSize );
  23099. this.sampleValues = sampleValues;
  23100. this.valueSize = sampleSize;
  23101. this.settings = null;
  23102. this.DefaultSettings_ = {};
  23103. }
  23104. evaluate( t ) {
  23105. const pp = this.parameterPositions;
  23106. let i1 = this._cachedIndex,
  23107. t1 = pp[ i1 ],
  23108. t0 = pp[ i1 - 1 ];
  23109. validate_interval: {
  23110. seek: {
  23111. let right;
  23112. linear_scan: {
  23113. //- See http://jsperf.com/comparison-to-undefined/3
  23114. //- slower code:
  23115. //-
  23116. //- if ( t >= t1 || t1 === undefined ) {
  23117. forward_scan: if ( ! ( t < t1 ) ) {
  23118. for ( let giveUpAt = i1 + 2; ; ) {
  23119. if ( t1 === undefined ) {
  23120. if ( t < t0 ) break forward_scan;
  23121. // after end
  23122. i1 = pp.length;
  23123. this._cachedIndex = i1;
  23124. return this.afterEnd_( i1 - 1, t, t0 );
  23125. }
  23126. if ( i1 === giveUpAt ) break; // this loop
  23127. t0 = t1;
  23128. t1 = pp[ ++ i1 ];
  23129. if ( t < t1 ) {
  23130. // we have arrived at the sought interval
  23131. break seek;
  23132. }
  23133. }
  23134. // prepare binary search on the right side of the index
  23135. right = pp.length;
  23136. break linear_scan;
  23137. }
  23138. //- slower code:
  23139. //- if ( t < t0 || t0 === undefined ) {
  23140. if ( ! ( t >= t0 ) ) {
  23141. // looping?
  23142. const t1global = pp[ 1 ];
  23143. if ( t < t1global ) {
  23144. i1 = 2; // + 1, using the scan for the details
  23145. t0 = t1global;
  23146. }
  23147. // linear reverse scan
  23148. for ( let giveUpAt = i1 - 2; ; ) {
  23149. if ( t0 === undefined ) {
  23150. // before start
  23151. this._cachedIndex = 0;
  23152. return this.beforeStart_( 0, t, t1 );
  23153. }
  23154. if ( i1 === giveUpAt ) break; // this loop
  23155. t1 = t0;
  23156. t0 = pp[ -- i1 - 1 ];
  23157. if ( t >= t0 ) {
  23158. // we have arrived at the sought interval
  23159. break seek;
  23160. }
  23161. }
  23162. // prepare binary search on the left side of the index
  23163. right = i1;
  23164. i1 = 0;
  23165. break linear_scan;
  23166. }
  23167. // the interval is valid
  23168. break validate_interval;
  23169. } // linear scan
  23170. // binary search
  23171. while ( i1 < right ) {
  23172. const mid = ( i1 + right ) >>> 1;
  23173. if ( t < pp[ mid ] ) {
  23174. right = mid;
  23175. } else {
  23176. i1 = mid + 1;
  23177. }
  23178. }
  23179. t1 = pp[ i1 ];
  23180. t0 = pp[ i1 - 1 ];
  23181. // check boundary cases, again
  23182. if ( t0 === undefined ) {
  23183. this._cachedIndex = 0;
  23184. return this.beforeStart_( 0, t, t1 );
  23185. }
  23186. if ( t1 === undefined ) {
  23187. i1 = pp.length;
  23188. this._cachedIndex = i1;
  23189. return this.afterEnd_( i1 - 1, t0, t );
  23190. }
  23191. } // seek
  23192. this._cachedIndex = i1;
  23193. this.intervalChanged_( i1, t0, t1 );
  23194. } // validate_interval
  23195. return this.interpolate_( i1, t0, t, t1 );
  23196. }
  23197. getSettings_() {
  23198. return this.settings || this.DefaultSettings_;
  23199. }
  23200. copySampleValue_( index ) {
  23201. // copies a sample value to the result buffer
  23202. const result = this.resultBuffer,
  23203. values = this.sampleValues,
  23204. stride = this.valueSize,
  23205. offset = index * stride;
  23206. for ( let i = 0; i !== stride; ++ i ) {
  23207. result[ i ] = values[ offset + i ];
  23208. }
  23209. return result;
  23210. }
  23211. // Template methods for derived classes:
  23212. interpolate_( /* i1, t0, t, t1 */ ) {
  23213. throw new Error( 'call to abstract method' );
  23214. // implementations shall return this.resultBuffer
  23215. }
  23216. intervalChanged_( /* i1, t0, t1 */ ) {
  23217. // empty
  23218. }
  23219. }
  23220. // ALIAS DEFINITIONS
  23221. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  23222. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  23223. /**
  23224. * Fast and simple cubic spline interpolant.
  23225. *
  23226. * It was derived from a Hermitian construction setting the first derivative
  23227. * at each sample position to the linear slope between neighboring positions
  23228. * over their parameter interval.
  23229. */
  23230. class CubicInterpolant extends Interpolant {
  23231. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23232. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23233. this._weightPrev = - 0;
  23234. this._offsetPrev = - 0;
  23235. this._weightNext = - 0;
  23236. this._offsetNext = - 0;
  23237. this.DefaultSettings_ = {
  23238. endingStart: ZeroCurvatureEnding,
  23239. endingEnd: ZeroCurvatureEnding
  23240. };
  23241. }
  23242. intervalChanged_( i1, t0, t1 ) {
  23243. const pp = this.parameterPositions;
  23244. let iPrev = i1 - 2,
  23245. iNext = i1 + 1,
  23246. tPrev = pp[ iPrev ],
  23247. tNext = pp[ iNext ];
  23248. if ( tPrev === undefined ) {
  23249. switch ( this.getSettings_().endingStart ) {
  23250. case ZeroSlopeEnding:
  23251. // f'(t0) = 0
  23252. iPrev = i1;
  23253. tPrev = 2 * t0 - t1;
  23254. break;
  23255. case WrapAroundEnding:
  23256. // use the other end of the curve
  23257. iPrev = pp.length - 2;
  23258. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23259. break;
  23260. default: // ZeroCurvatureEnding
  23261. // f''(t0) = 0 a.k.a. Natural Spline
  23262. iPrev = i1;
  23263. tPrev = t1;
  23264. }
  23265. }
  23266. if ( tNext === undefined ) {
  23267. switch ( this.getSettings_().endingEnd ) {
  23268. case ZeroSlopeEnding:
  23269. // f'(tN) = 0
  23270. iNext = i1;
  23271. tNext = 2 * t1 - t0;
  23272. break;
  23273. case WrapAroundEnding:
  23274. // use the other end of the curve
  23275. iNext = 1;
  23276. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23277. break;
  23278. default: // ZeroCurvatureEnding
  23279. // f''(tN) = 0, a.k.a. Natural Spline
  23280. iNext = i1 - 1;
  23281. tNext = t0;
  23282. }
  23283. }
  23284. const halfDt = ( t1 - t0 ) * 0.5,
  23285. stride = this.valueSize;
  23286. this._weightPrev = halfDt / ( t0 - tPrev );
  23287. this._weightNext = halfDt / ( tNext - t1 );
  23288. this._offsetPrev = iPrev * stride;
  23289. this._offsetNext = iNext * stride;
  23290. }
  23291. interpolate_( i1, t0, t, t1 ) {
  23292. const result = this.resultBuffer,
  23293. values = this.sampleValues,
  23294. stride = this.valueSize,
  23295. o1 = i1 * stride, o0 = o1 - stride,
  23296. oP = this._offsetPrev, oN = this._offsetNext,
  23297. wP = this._weightPrev, wN = this._weightNext,
  23298. p = ( t - t0 ) / ( t1 - t0 ),
  23299. pp = p * p,
  23300. ppp = pp * p;
  23301. // evaluate polynomials
  23302. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23303. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23304. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23305. const sN = wN * ppp - wN * pp;
  23306. // combine data linearly
  23307. for ( let i = 0; i !== stride; ++ i ) {
  23308. result[ i ] =
  23309. sP * values[ oP + i ] +
  23310. s0 * values[ o0 + i ] +
  23311. s1 * values[ o1 + i ] +
  23312. sN * values[ oN + i ];
  23313. }
  23314. return result;
  23315. }
  23316. }
  23317. class LinearInterpolant extends Interpolant {
  23318. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23319. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23320. }
  23321. interpolate_( i1, t0, t, t1 ) {
  23322. const result = this.resultBuffer,
  23323. values = this.sampleValues,
  23324. stride = this.valueSize,
  23325. offset1 = i1 * stride,
  23326. offset0 = offset1 - stride,
  23327. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23328. weight0 = 1 - weight1;
  23329. for ( let i = 0; i !== stride; ++ i ) {
  23330. result[ i ] =
  23331. values[ offset0 + i ] * weight0 +
  23332. values[ offset1 + i ] * weight1;
  23333. }
  23334. return result;
  23335. }
  23336. }
  23337. /**
  23338. *
  23339. * Interpolant that evaluates to the sample value at the position preceeding
  23340. * the parameter.
  23341. */
  23342. class DiscreteInterpolant extends Interpolant {
  23343. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23344. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23345. }
  23346. interpolate_( i1 /*, t0, t, t1 */ ) {
  23347. return this.copySampleValue_( i1 - 1 );
  23348. }
  23349. }
  23350. class KeyframeTrack {
  23351. constructor( name, times, values, interpolation ) {
  23352. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23353. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23354. this.name = name;
  23355. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  23356. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  23357. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23358. }
  23359. // Serialization (in static context, because of constructor invocation
  23360. // and automatic invocation of .toJSON):
  23361. static toJSON( track ) {
  23362. const trackType = track.constructor;
  23363. let json;
  23364. // derived classes can define a static toJSON method
  23365. if ( trackType.toJSON !== this.toJSON ) {
  23366. json = trackType.toJSON( track );
  23367. } else {
  23368. // by default, we assume the data can be serialized as-is
  23369. json = {
  23370. 'name': track.name,
  23371. 'times': AnimationUtils.convertArray( track.times, Array ),
  23372. 'values': AnimationUtils.convertArray( track.values, Array )
  23373. };
  23374. const interpolation = track.getInterpolation();
  23375. if ( interpolation !== track.DefaultInterpolation ) {
  23376. json.interpolation = interpolation;
  23377. }
  23378. }
  23379. json.type = track.ValueTypeName; // mandatory
  23380. return json;
  23381. }
  23382. InterpolantFactoryMethodDiscrete( result ) {
  23383. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23384. }
  23385. InterpolantFactoryMethodLinear( result ) {
  23386. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23387. }
  23388. InterpolantFactoryMethodSmooth( result ) {
  23389. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23390. }
  23391. setInterpolation( interpolation ) {
  23392. let factoryMethod;
  23393. switch ( interpolation ) {
  23394. case InterpolateDiscrete:
  23395. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23396. break;
  23397. case InterpolateLinear:
  23398. factoryMethod = this.InterpolantFactoryMethodLinear;
  23399. break;
  23400. case InterpolateSmooth:
  23401. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23402. break;
  23403. }
  23404. if ( factoryMethod === undefined ) {
  23405. const message = 'unsupported interpolation for ' +
  23406. this.ValueTypeName + ' keyframe track named ' + this.name;
  23407. if ( this.createInterpolant === undefined ) {
  23408. // fall back to default, unless the default itself is messed up
  23409. if ( interpolation !== this.DefaultInterpolation ) {
  23410. this.setInterpolation( this.DefaultInterpolation );
  23411. } else {
  23412. throw new Error( message ); // fatal, in this case
  23413. }
  23414. }
  23415. console.warn( 'THREE.KeyframeTrack:', message );
  23416. return this;
  23417. }
  23418. this.createInterpolant = factoryMethod;
  23419. return this;
  23420. }
  23421. getInterpolation() {
  23422. switch ( this.createInterpolant ) {
  23423. case this.InterpolantFactoryMethodDiscrete:
  23424. return InterpolateDiscrete;
  23425. case this.InterpolantFactoryMethodLinear:
  23426. return InterpolateLinear;
  23427. case this.InterpolantFactoryMethodSmooth:
  23428. return InterpolateSmooth;
  23429. }
  23430. }
  23431. getValueSize() {
  23432. return this.values.length / this.times.length;
  23433. }
  23434. // move all keyframes either forwards or backwards in time
  23435. shift( timeOffset ) {
  23436. if ( timeOffset !== 0.0 ) {
  23437. const times = this.times;
  23438. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23439. times[ i ] += timeOffset;
  23440. }
  23441. }
  23442. return this;
  23443. }
  23444. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23445. scale( timeScale ) {
  23446. if ( timeScale !== 1.0 ) {
  23447. const times = this.times;
  23448. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23449. times[ i ] *= timeScale;
  23450. }
  23451. }
  23452. return this;
  23453. }
  23454. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23455. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23456. trim( startTime, endTime ) {
  23457. const times = this.times,
  23458. nKeys = times.length;
  23459. let from = 0,
  23460. to = nKeys - 1;
  23461. while ( from !== nKeys && times[ from ] < startTime ) {
  23462. ++ from;
  23463. }
  23464. while ( to !== - 1 && times[ to ] > endTime ) {
  23465. -- to;
  23466. }
  23467. ++ to; // inclusive -> exclusive bound
  23468. if ( from !== 0 || to !== nKeys ) {
  23469. // empty tracks are forbidden, so keep at least one keyframe
  23470. if ( from >= to ) {
  23471. to = Math.max( to, 1 );
  23472. from = to - 1;
  23473. }
  23474. const stride = this.getValueSize();
  23475. this.times = AnimationUtils.arraySlice( times, from, to );
  23476. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  23477. }
  23478. return this;
  23479. }
  23480. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23481. validate() {
  23482. let valid = true;
  23483. const valueSize = this.getValueSize();
  23484. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23485. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23486. valid = false;
  23487. }
  23488. const times = this.times,
  23489. values = this.values,
  23490. nKeys = times.length;
  23491. if ( nKeys === 0 ) {
  23492. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23493. valid = false;
  23494. }
  23495. let prevTime = null;
  23496. for ( let i = 0; i !== nKeys; i ++ ) {
  23497. const currTime = times[ i ];
  23498. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23499. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23500. valid = false;
  23501. break;
  23502. }
  23503. if ( prevTime !== null && prevTime > currTime ) {
  23504. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23505. valid = false;
  23506. break;
  23507. }
  23508. prevTime = currTime;
  23509. }
  23510. if ( values !== undefined ) {
  23511. if ( AnimationUtils.isTypedArray( values ) ) {
  23512. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23513. const value = values[ i ];
  23514. if ( isNaN( value ) ) {
  23515. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23516. valid = false;
  23517. break;
  23518. }
  23519. }
  23520. }
  23521. }
  23522. return valid;
  23523. }
  23524. // removes equivalent sequential keys as common in morph target sequences
  23525. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23526. optimize() {
  23527. // times or values may be shared with other tracks, so overwriting is unsafe
  23528. const times = AnimationUtils.arraySlice( this.times ),
  23529. values = AnimationUtils.arraySlice( this.values ),
  23530. stride = this.getValueSize(),
  23531. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23532. lastIndex = times.length - 1;
  23533. let writeIndex = 1;
  23534. for ( let i = 1; i < lastIndex; ++ i ) {
  23535. let keep = false;
  23536. const time = times[ i ];
  23537. const timeNext = times[ i + 1 ];
  23538. // remove adjacent keyframes scheduled at the same time
  23539. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23540. if ( ! smoothInterpolation ) {
  23541. // remove unnecessary keyframes same as their neighbors
  23542. const offset = i * stride,
  23543. offsetP = offset - stride,
  23544. offsetN = offset + stride;
  23545. for ( let j = 0; j !== stride; ++ j ) {
  23546. const value = values[ offset + j ];
  23547. if ( value !== values[ offsetP + j ] ||
  23548. value !== values[ offsetN + j ] ) {
  23549. keep = true;
  23550. break;
  23551. }
  23552. }
  23553. } else {
  23554. keep = true;
  23555. }
  23556. }
  23557. // in-place compaction
  23558. if ( keep ) {
  23559. if ( i !== writeIndex ) {
  23560. times[ writeIndex ] = times[ i ];
  23561. const readOffset = i * stride,
  23562. writeOffset = writeIndex * stride;
  23563. for ( let j = 0; j !== stride; ++ j ) {
  23564. values[ writeOffset + j ] = values[ readOffset + j ];
  23565. }
  23566. }
  23567. ++ writeIndex;
  23568. }
  23569. }
  23570. // flush last keyframe (compaction looks ahead)
  23571. if ( lastIndex > 0 ) {
  23572. times[ writeIndex ] = times[ lastIndex ];
  23573. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23574. values[ writeOffset + j ] = values[ readOffset + j ];
  23575. }
  23576. ++ writeIndex;
  23577. }
  23578. if ( writeIndex !== times.length ) {
  23579. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  23580. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  23581. } else {
  23582. this.times = times;
  23583. this.values = values;
  23584. }
  23585. return this;
  23586. }
  23587. clone() {
  23588. const times = AnimationUtils.arraySlice( this.times, 0 );
  23589. const values = AnimationUtils.arraySlice( this.values, 0 );
  23590. const TypedKeyframeTrack = this.constructor;
  23591. const track = new TypedKeyframeTrack( this.name, times, values );
  23592. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23593. track.createInterpolant = this.createInterpolant;
  23594. return track;
  23595. }
  23596. }
  23597. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23598. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23599. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23600. /**
  23601. * A Track of Boolean keyframe values.
  23602. */
  23603. class BooleanKeyframeTrack extends KeyframeTrack {}
  23604. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23605. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23606. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23607. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23608. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23609. /**
  23610. * A Track of keyframe values that represent color.
  23611. */
  23612. class ColorKeyframeTrack extends KeyframeTrack {}
  23613. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23614. /**
  23615. * A Track of numeric keyframe values.
  23616. */
  23617. class NumberKeyframeTrack extends KeyframeTrack {}
  23618. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23619. /**
  23620. * Spherical linear unit quaternion interpolant.
  23621. */
  23622. class QuaternionLinearInterpolant extends Interpolant {
  23623. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23624. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23625. }
  23626. interpolate_( i1, t0, t, t1 ) {
  23627. const result = this.resultBuffer,
  23628. values = this.sampleValues,
  23629. stride = this.valueSize,
  23630. alpha = ( t - t0 ) / ( t1 - t0 );
  23631. let offset = i1 * stride;
  23632. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23633. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23634. }
  23635. return result;
  23636. }
  23637. }
  23638. /**
  23639. * A Track of quaternion keyframe values.
  23640. */
  23641. class QuaternionKeyframeTrack extends KeyframeTrack {
  23642. InterpolantFactoryMethodLinear( result ) {
  23643. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23644. }
  23645. }
  23646. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23647. // ValueBufferType is inherited
  23648. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23649. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23650. /**
  23651. * A Track that interpolates Strings
  23652. */
  23653. class StringKeyframeTrack extends KeyframeTrack {}
  23654. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23655. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23656. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23657. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23658. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23659. /**
  23660. * A Track of vectored keyframe values.
  23661. */
  23662. class VectorKeyframeTrack extends KeyframeTrack {}
  23663. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23664. class AnimationClip {
  23665. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23666. this.name = name;
  23667. this.tracks = tracks;
  23668. this.duration = duration;
  23669. this.blendMode = blendMode;
  23670. this.uuid = generateUUID();
  23671. // this means it should figure out its duration by scanning the tracks
  23672. if ( this.duration < 0 ) {
  23673. this.resetDuration();
  23674. }
  23675. }
  23676. static parse( json ) {
  23677. const tracks = [],
  23678. jsonTracks = json.tracks,
  23679. frameTime = 1.0 / ( json.fps || 1.0 );
  23680. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23681. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23682. }
  23683. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23684. clip.uuid = json.uuid;
  23685. return clip;
  23686. }
  23687. static toJSON( clip ) {
  23688. const tracks = [],
  23689. clipTracks = clip.tracks;
  23690. const json = {
  23691. 'name': clip.name,
  23692. 'duration': clip.duration,
  23693. 'tracks': tracks,
  23694. 'uuid': clip.uuid,
  23695. 'blendMode': clip.blendMode
  23696. };
  23697. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23698. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23699. }
  23700. return json;
  23701. }
  23702. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23703. const numMorphTargets = morphTargetSequence.length;
  23704. const tracks = [];
  23705. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23706. let times = [];
  23707. let values = [];
  23708. times.push(
  23709. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23710. i,
  23711. ( i + 1 ) % numMorphTargets );
  23712. values.push( 0, 1, 0 );
  23713. const order = AnimationUtils.getKeyframeOrder( times );
  23714. times = AnimationUtils.sortedArray( times, 1, order );
  23715. values = AnimationUtils.sortedArray( values, 1, order );
  23716. // if there is a key at the first frame, duplicate it as the
  23717. // last frame as well for perfect loop.
  23718. if ( ! noLoop && times[ 0 ] === 0 ) {
  23719. times.push( numMorphTargets );
  23720. values.push( values[ 0 ] );
  23721. }
  23722. tracks.push(
  23723. new NumberKeyframeTrack(
  23724. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23725. times, values
  23726. ).scale( 1.0 / fps ) );
  23727. }
  23728. return new this( name, - 1, tracks );
  23729. }
  23730. static findByName( objectOrClipArray, name ) {
  23731. let clipArray = objectOrClipArray;
  23732. if ( ! Array.isArray( objectOrClipArray ) ) {
  23733. const o = objectOrClipArray;
  23734. clipArray = o.geometry && o.geometry.animations || o.animations;
  23735. }
  23736. for ( let i = 0; i < clipArray.length; i ++ ) {
  23737. if ( clipArray[ i ].name === name ) {
  23738. return clipArray[ i ];
  23739. }
  23740. }
  23741. return null;
  23742. }
  23743. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23744. const animationToMorphTargets = {};
  23745. // tested with https://regex101.com/ on trick sequences
  23746. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23747. const pattern = /^([\w-]*?)([\d]+)$/;
  23748. // sort morph target names into animation groups based
  23749. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23750. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23751. const morphTarget = morphTargets[ i ];
  23752. const parts = morphTarget.name.match( pattern );
  23753. if ( parts && parts.length > 1 ) {
  23754. const name = parts[ 1 ];
  23755. let animationMorphTargets = animationToMorphTargets[ name ];
  23756. if ( ! animationMorphTargets ) {
  23757. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23758. }
  23759. animationMorphTargets.push( morphTarget );
  23760. }
  23761. }
  23762. const clips = [];
  23763. for ( const name in animationToMorphTargets ) {
  23764. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23765. }
  23766. return clips;
  23767. }
  23768. // parse the animation.hierarchy format
  23769. static parseAnimation( animation, bones ) {
  23770. if ( ! animation ) {
  23771. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23772. return null;
  23773. }
  23774. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23775. // only return track if there are actually keys.
  23776. if ( animationKeys.length !== 0 ) {
  23777. const times = [];
  23778. const values = [];
  23779. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  23780. // empty keys are filtered out, so check again
  23781. if ( times.length !== 0 ) {
  23782. destTracks.push( new trackType( trackName, times, values ) );
  23783. }
  23784. }
  23785. };
  23786. const tracks = [];
  23787. const clipName = animation.name || 'default';
  23788. const fps = animation.fps || 30;
  23789. const blendMode = animation.blendMode;
  23790. // automatic length determination in AnimationClip.
  23791. let duration = animation.length || - 1;
  23792. const hierarchyTracks = animation.hierarchy || [];
  23793. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23794. const animationKeys = hierarchyTracks[ h ].keys;
  23795. // skip empty tracks
  23796. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23797. // process morph targets
  23798. if ( animationKeys[ 0 ].morphTargets ) {
  23799. // figure out all morph targets used in this track
  23800. const morphTargetNames = {};
  23801. let k;
  23802. for ( k = 0; k < animationKeys.length; k ++ ) {
  23803. if ( animationKeys[ k ].morphTargets ) {
  23804. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23805. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23806. }
  23807. }
  23808. }
  23809. // create a track for each morph target with all zero
  23810. // morphTargetInfluences except for the keys in which
  23811. // the morphTarget is named.
  23812. for ( const morphTargetName in morphTargetNames ) {
  23813. const times = [];
  23814. const values = [];
  23815. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23816. const animationKey = animationKeys[ k ];
  23817. times.push( animationKey.time );
  23818. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23819. }
  23820. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23821. }
  23822. duration = morphTargetNames.length * ( fps || 1.0 );
  23823. } else {
  23824. // ...assume skeletal animation
  23825. const boneName = '.bones[' + bones[ h ].name + ']';
  23826. addNonemptyTrack(
  23827. VectorKeyframeTrack, boneName + '.position',
  23828. animationKeys, 'pos', tracks );
  23829. addNonemptyTrack(
  23830. QuaternionKeyframeTrack, boneName + '.quaternion',
  23831. animationKeys, 'rot', tracks );
  23832. addNonemptyTrack(
  23833. VectorKeyframeTrack, boneName + '.scale',
  23834. animationKeys, 'scl', tracks );
  23835. }
  23836. }
  23837. if ( tracks.length === 0 ) {
  23838. return null;
  23839. }
  23840. const clip = new this( clipName, duration, tracks, blendMode );
  23841. return clip;
  23842. }
  23843. resetDuration() {
  23844. const tracks = this.tracks;
  23845. let duration = 0;
  23846. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23847. const track = this.tracks[ i ];
  23848. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23849. }
  23850. this.duration = duration;
  23851. return this;
  23852. }
  23853. trim() {
  23854. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23855. this.tracks[ i ].trim( 0, this.duration );
  23856. }
  23857. return this;
  23858. }
  23859. validate() {
  23860. let valid = true;
  23861. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23862. valid = valid && this.tracks[ i ].validate();
  23863. }
  23864. return valid;
  23865. }
  23866. optimize() {
  23867. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23868. this.tracks[ i ].optimize();
  23869. }
  23870. return this;
  23871. }
  23872. clone() {
  23873. const tracks = [];
  23874. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23875. tracks.push( this.tracks[ i ].clone() );
  23876. }
  23877. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23878. }
  23879. toJSON() {
  23880. return this.constructor.toJSON( this );
  23881. }
  23882. }
  23883. function getTrackTypeForValueTypeName( typeName ) {
  23884. switch ( typeName.toLowerCase() ) {
  23885. case 'scalar':
  23886. case 'double':
  23887. case 'float':
  23888. case 'number':
  23889. case 'integer':
  23890. return NumberKeyframeTrack;
  23891. case 'vector':
  23892. case 'vector2':
  23893. case 'vector3':
  23894. case 'vector4':
  23895. return VectorKeyframeTrack;
  23896. case 'color':
  23897. return ColorKeyframeTrack;
  23898. case 'quaternion':
  23899. return QuaternionKeyframeTrack;
  23900. case 'bool':
  23901. case 'boolean':
  23902. return BooleanKeyframeTrack;
  23903. case 'string':
  23904. return StringKeyframeTrack;
  23905. }
  23906. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23907. }
  23908. function parseKeyframeTrack( json ) {
  23909. if ( json.type === undefined ) {
  23910. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23911. }
  23912. const trackType = getTrackTypeForValueTypeName( json.type );
  23913. if ( json.times === undefined ) {
  23914. const times = [], values = [];
  23915. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23916. json.times = times;
  23917. json.values = values;
  23918. }
  23919. // derived classes can define a static parse method
  23920. if ( trackType.parse !== undefined ) {
  23921. return trackType.parse( json );
  23922. } else {
  23923. // by default, we assume a constructor compatible with the base
  23924. return new trackType( json.name, json.times, json.values, json.interpolation );
  23925. }
  23926. }
  23927. const Cache = {
  23928. enabled: false,
  23929. files: {},
  23930. add: function ( key, file ) {
  23931. if ( this.enabled === false ) return;
  23932. // console.log( 'THREE.Cache', 'Adding key:', key );
  23933. this.files[ key ] = file;
  23934. },
  23935. get: function ( key ) {
  23936. if ( this.enabled === false ) return;
  23937. // console.log( 'THREE.Cache', 'Checking key:', key );
  23938. return this.files[ key ];
  23939. },
  23940. remove: function ( key ) {
  23941. delete this.files[ key ];
  23942. },
  23943. clear: function () {
  23944. this.files = {};
  23945. }
  23946. };
  23947. class LoadingManager {
  23948. constructor( onLoad, onProgress, onError ) {
  23949. const scope = this;
  23950. let isLoading = false;
  23951. let itemsLoaded = 0;
  23952. let itemsTotal = 0;
  23953. let urlModifier = undefined;
  23954. const handlers = [];
  23955. // Refer to #5689 for the reason why we don't set .onStart
  23956. // in the constructor
  23957. this.onStart = undefined;
  23958. this.onLoad = onLoad;
  23959. this.onProgress = onProgress;
  23960. this.onError = onError;
  23961. this.itemStart = function ( url ) {
  23962. itemsTotal ++;
  23963. if ( isLoading === false ) {
  23964. if ( scope.onStart !== undefined ) {
  23965. scope.onStart( url, itemsLoaded, itemsTotal );
  23966. }
  23967. }
  23968. isLoading = true;
  23969. };
  23970. this.itemEnd = function ( url ) {
  23971. itemsLoaded ++;
  23972. if ( scope.onProgress !== undefined ) {
  23973. scope.onProgress( url, itemsLoaded, itemsTotal );
  23974. }
  23975. if ( itemsLoaded === itemsTotal ) {
  23976. isLoading = false;
  23977. if ( scope.onLoad !== undefined ) {
  23978. scope.onLoad();
  23979. }
  23980. }
  23981. };
  23982. this.itemError = function ( url ) {
  23983. if ( scope.onError !== undefined ) {
  23984. scope.onError( url );
  23985. }
  23986. };
  23987. this.resolveURL = function ( url ) {
  23988. if ( urlModifier ) {
  23989. return urlModifier( url );
  23990. }
  23991. return url;
  23992. };
  23993. this.setURLModifier = function ( transform ) {
  23994. urlModifier = transform;
  23995. return this;
  23996. };
  23997. this.addHandler = function ( regex, loader ) {
  23998. handlers.push( regex, loader );
  23999. return this;
  24000. };
  24001. this.removeHandler = function ( regex ) {
  24002. const index = handlers.indexOf( regex );
  24003. if ( index !== - 1 ) {
  24004. handlers.splice( index, 2 );
  24005. }
  24006. return this;
  24007. };
  24008. this.getHandler = function ( file ) {
  24009. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24010. const regex = handlers[ i ];
  24011. const loader = handlers[ i + 1 ];
  24012. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24013. if ( regex.test( file ) ) {
  24014. return loader;
  24015. }
  24016. }
  24017. return null;
  24018. };
  24019. }
  24020. }
  24021. const DefaultLoadingManager = new LoadingManager();
  24022. class Loader {
  24023. constructor( manager ) {
  24024. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24025. this.crossOrigin = 'anonymous';
  24026. this.withCredentials = false;
  24027. this.path = '';
  24028. this.resourcePath = '';
  24029. this.requestHeader = {};
  24030. }
  24031. load( /* url, onLoad, onProgress, onError */ ) {}
  24032. loadAsync( url, onProgress ) {
  24033. const scope = this;
  24034. return new Promise( function ( resolve, reject ) {
  24035. scope.load( url, resolve, onProgress, reject );
  24036. } );
  24037. }
  24038. parse( /* data */ ) {}
  24039. setCrossOrigin( crossOrigin ) {
  24040. this.crossOrigin = crossOrigin;
  24041. return this;
  24042. }
  24043. setWithCredentials( value ) {
  24044. this.withCredentials = value;
  24045. return this;
  24046. }
  24047. setPath( path ) {
  24048. this.path = path;
  24049. return this;
  24050. }
  24051. setResourcePath( resourcePath ) {
  24052. this.resourcePath = resourcePath;
  24053. return this;
  24054. }
  24055. setRequestHeader( requestHeader ) {
  24056. this.requestHeader = requestHeader;
  24057. return this;
  24058. }
  24059. }
  24060. const loading = {};
  24061. class FileLoader extends Loader {
  24062. constructor( manager ) {
  24063. super( manager );
  24064. }
  24065. load( url, onLoad, onProgress, onError ) {
  24066. if ( url === undefined ) url = '';
  24067. if ( this.path !== undefined ) url = this.path + url;
  24068. url = this.manager.resolveURL( url );
  24069. const scope = this;
  24070. const cached = Cache.get( url );
  24071. if ( cached !== undefined ) {
  24072. scope.manager.itemStart( url );
  24073. setTimeout( function () {
  24074. if ( onLoad ) onLoad( cached );
  24075. scope.manager.itemEnd( url );
  24076. }, 0 );
  24077. return cached;
  24078. }
  24079. // Check if request is duplicate
  24080. if ( loading[ url ] !== undefined ) {
  24081. loading[ url ].push( {
  24082. onLoad: onLoad,
  24083. onProgress: onProgress,
  24084. onError: onError
  24085. } );
  24086. return;
  24087. }
  24088. // Check for data: URI
  24089. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  24090. const dataUriRegexResult = url.match( dataUriRegex );
  24091. let request;
  24092. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  24093. if ( dataUriRegexResult ) {
  24094. const mimeType = dataUriRegexResult[ 1 ];
  24095. const isBase64 = !! dataUriRegexResult[ 2 ];
  24096. let data = dataUriRegexResult[ 3 ];
  24097. data = decodeURIComponent( data );
  24098. if ( isBase64 ) data = atob( data );
  24099. try {
  24100. let response;
  24101. const responseType = ( this.responseType || '' ).toLowerCase();
  24102. switch ( responseType ) {
  24103. case 'arraybuffer':
  24104. case 'blob':
  24105. const view = new Uint8Array( data.length );
  24106. for ( let i = 0; i < data.length; i ++ ) {
  24107. view[ i ] = data.charCodeAt( i );
  24108. }
  24109. if ( responseType === 'blob' ) {
  24110. response = new Blob( [ view.buffer ], { type: mimeType } );
  24111. } else {
  24112. response = view.buffer;
  24113. }
  24114. break;
  24115. case 'document':
  24116. const parser = new DOMParser();
  24117. response = parser.parseFromString( data, mimeType );
  24118. break;
  24119. case 'json':
  24120. response = JSON.parse( data );
  24121. break;
  24122. default: // 'text' or other
  24123. response = data;
  24124. break;
  24125. }
  24126. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  24127. setTimeout( function () {
  24128. if ( onLoad ) onLoad( response );
  24129. scope.manager.itemEnd( url );
  24130. }, 0 );
  24131. } catch ( error ) {
  24132. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  24133. setTimeout( function () {
  24134. if ( onError ) onError( error );
  24135. scope.manager.itemError( url );
  24136. scope.manager.itemEnd( url );
  24137. }, 0 );
  24138. }
  24139. } else {
  24140. // Initialise array for duplicate requests
  24141. loading[ url ] = [];
  24142. loading[ url ].push( {
  24143. onLoad: onLoad,
  24144. onProgress: onProgress,
  24145. onError: onError
  24146. } );
  24147. request = new XMLHttpRequest();
  24148. request.open( 'GET', url, true );
  24149. request.addEventListener( 'load', function ( event ) {
  24150. const response = this.response;
  24151. const callbacks = loading[ url ];
  24152. delete loading[ url ];
  24153. if ( this.status === 200 || this.status === 0 ) {
  24154. // Some browsers return HTTP Status 0 when using non-http protocol
  24155. // e.g. 'file://' or 'data://'. Handle as success.
  24156. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24157. // Add to cache only on HTTP success, so that we do not cache
  24158. // error response bodies as proper responses to requests.
  24159. Cache.add( url, response );
  24160. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24161. const callback = callbacks[ i ];
  24162. if ( callback.onLoad ) callback.onLoad( response );
  24163. }
  24164. scope.manager.itemEnd( url );
  24165. } else {
  24166. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24167. const callback = callbacks[ i ];
  24168. if ( callback.onError ) callback.onError( event );
  24169. }
  24170. scope.manager.itemError( url );
  24171. scope.manager.itemEnd( url );
  24172. }
  24173. }, false );
  24174. request.addEventListener( 'progress', function ( event ) {
  24175. const callbacks = loading[ url ];
  24176. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24177. const callback = callbacks[ i ];
  24178. if ( callback.onProgress ) callback.onProgress( event );
  24179. }
  24180. }, false );
  24181. request.addEventListener( 'error', function ( event ) {
  24182. const callbacks = loading[ url ];
  24183. delete loading[ url ];
  24184. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24185. const callback = callbacks[ i ];
  24186. if ( callback.onError ) callback.onError( event );
  24187. }
  24188. scope.manager.itemError( url );
  24189. scope.manager.itemEnd( url );
  24190. }, false );
  24191. request.addEventListener( 'abort', function ( event ) {
  24192. const callbacks = loading[ url ];
  24193. delete loading[ url ];
  24194. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24195. const callback = callbacks[ i ];
  24196. if ( callback.onError ) callback.onError( event );
  24197. }
  24198. scope.manager.itemError( url );
  24199. scope.manager.itemEnd( url );
  24200. }, false );
  24201. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  24202. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  24203. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  24204. for ( const header in this.requestHeader ) {
  24205. request.setRequestHeader( header, this.requestHeader[ header ] );
  24206. }
  24207. request.send( null );
  24208. }
  24209. scope.manager.itemStart( url );
  24210. return request;
  24211. }
  24212. setResponseType( value ) {
  24213. this.responseType = value;
  24214. return this;
  24215. }
  24216. setMimeType( value ) {
  24217. this.mimeType = value;
  24218. return this;
  24219. }
  24220. }
  24221. class AnimationLoader extends Loader {
  24222. constructor( manager ) {
  24223. super( manager );
  24224. }
  24225. load( url, onLoad, onProgress, onError ) {
  24226. const scope = this;
  24227. const loader = new FileLoader( this.manager );
  24228. loader.setPath( this.path );
  24229. loader.setRequestHeader( this.requestHeader );
  24230. loader.setWithCredentials( this.withCredentials );
  24231. loader.load( url, function ( text ) {
  24232. try {
  24233. onLoad( scope.parse( JSON.parse( text ) ) );
  24234. } catch ( e ) {
  24235. if ( onError ) {
  24236. onError( e );
  24237. } else {
  24238. console.error( e );
  24239. }
  24240. scope.manager.itemError( url );
  24241. }
  24242. }, onProgress, onError );
  24243. }
  24244. parse( json ) {
  24245. const animations = [];
  24246. for ( let i = 0; i < json.length; i ++ ) {
  24247. const clip = AnimationClip.parse( json[ i ] );
  24248. animations.push( clip );
  24249. }
  24250. return animations;
  24251. }
  24252. }
  24253. /**
  24254. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24255. *
  24256. * Sub classes have to implement the parse() method which will be used in load().
  24257. */
  24258. class CompressedTextureLoader extends Loader {
  24259. constructor( manager ) {
  24260. super( manager );
  24261. }
  24262. load( url, onLoad, onProgress, onError ) {
  24263. const scope = this;
  24264. const images = [];
  24265. const texture = new CompressedTexture();
  24266. const loader = new FileLoader( this.manager );
  24267. loader.setPath( this.path );
  24268. loader.setResponseType( 'arraybuffer' );
  24269. loader.setRequestHeader( this.requestHeader );
  24270. loader.setWithCredentials( scope.withCredentials );
  24271. let loaded = 0;
  24272. function loadTexture( i ) {
  24273. loader.load( url[ i ], function ( buffer ) {
  24274. const texDatas = scope.parse( buffer, true );
  24275. images[ i ] = {
  24276. width: texDatas.width,
  24277. height: texDatas.height,
  24278. format: texDatas.format,
  24279. mipmaps: texDatas.mipmaps
  24280. };
  24281. loaded += 1;
  24282. if ( loaded === 6 ) {
  24283. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24284. texture.image = images;
  24285. texture.format = texDatas.format;
  24286. texture.needsUpdate = true;
  24287. if ( onLoad ) onLoad( texture );
  24288. }
  24289. }, onProgress, onError );
  24290. }
  24291. if ( Array.isArray( url ) ) {
  24292. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24293. loadTexture( i );
  24294. }
  24295. } else {
  24296. // compressed cubemap texture stored in a single DDS file
  24297. loader.load( url, function ( buffer ) {
  24298. const texDatas = scope.parse( buffer, true );
  24299. if ( texDatas.isCubemap ) {
  24300. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24301. for ( let f = 0; f < faces; f ++ ) {
  24302. images[ f ] = { mipmaps: [] };
  24303. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24304. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24305. images[ f ].format = texDatas.format;
  24306. images[ f ].width = texDatas.width;
  24307. images[ f ].height = texDatas.height;
  24308. }
  24309. }
  24310. texture.image = images;
  24311. } else {
  24312. texture.image.width = texDatas.width;
  24313. texture.image.height = texDatas.height;
  24314. texture.mipmaps = texDatas.mipmaps;
  24315. }
  24316. if ( texDatas.mipmapCount === 1 ) {
  24317. texture.minFilter = LinearFilter;
  24318. }
  24319. texture.format = texDatas.format;
  24320. texture.needsUpdate = true;
  24321. if ( onLoad ) onLoad( texture );
  24322. }, onProgress, onError );
  24323. }
  24324. return texture;
  24325. }
  24326. }
  24327. class ImageLoader extends Loader {
  24328. constructor( manager ) {
  24329. super( manager );
  24330. }
  24331. load( url, onLoad, onProgress, onError ) {
  24332. if ( this.path !== undefined ) url = this.path + url;
  24333. url = this.manager.resolveURL( url );
  24334. const scope = this;
  24335. const cached = Cache.get( url );
  24336. if ( cached !== undefined ) {
  24337. scope.manager.itemStart( url );
  24338. setTimeout( function () {
  24339. if ( onLoad ) onLoad( cached );
  24340. scope.manager.itemEnd( url );
  24341. }, 0 );
  24342. return cached;
  24343. }
  24344. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  24345. function onImageLoad() {
  24346. image.removeEventListener( 'load', onImageLoad, false );
  24347. image.removeEventListener( 'error', onImageError, false );
  24348. Cache.add( url, this );
  24349. if ( onLoad ) onLoad( this );
  24350. scope.manager.itemEnd( url );
  24351. }
  24352. function onImageError( event ) {
  24353. image.removeEventListener( 'load', onImageLoad, false );
  24354. image.removeEventListener( 'error', onImageError, false );
  24355. if ( onError ) onError( event );
  24356. scope.manager.itemError( url );
  24357. scope.manager.itemEnd( url );
  24358. }
  24359. image.addEventListener( 'load', onImageLoad, false );
  24360. image.addEventListener( 'error', onImageError, false );
  24361. if ( url.substr( 0, 5 ) !== 'data:' ) {
  24362. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24363. }
  24364. scope.manager.itemStart( url );
  24365. image.src = url;
  24366. return image;
  24367. }
  24368. }
  24369. class CubeTextureLoader extends Loader {
  24370. constructor( manager ) {
  24371. super( manager );
  24372. }
  24373. load( urls, onLoad, onProgress, onError ) {
  24374. const texture = new CubeTexture();
  24375. const loader = new ImageLoader( this.manager );
  24376. loader.setCrossOrigin( this.crossOrigin );
  24377. loader.setPath( this.path );
  24378. let loaded = 0;
  24379. function loadTexture( i ) {
  24380. loader.load( urls[ i ], function ( image ) {
  24381. texture.images[ i ] = image;
  24382. loaded ++;
  24383. if ( loaded === 6 ) {
  24384. texture.needsUpdate = true;
  24385. if ( onLoad ) onLoad( texture );
  24386. }
  24387. }, undefined, onError );
  24388. }
  24389. for ( let i = 0; i < urls.length; ++ i ) {
  24390. loadTexture( i );
  24391. }
  24392. return texture;
  24393. }
  24394. }
  24395. /**
  24396. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24397. *
  24398. * Sub classes have to implement the parse() method which will be used in load().
  24399. */
  24400. class DataTextureLoader extends Loader {
  24401. constructor( manager ) {
  24402. super( manager );
  24403. }
  24404. load( url, onLoad, onProgress, onError ) {
  24405. const scope = this;
  24406. const texture = new DataTexture();
  24407. const loader = new FileLoader( this.manager );
  24408. loader.setResponseType( 'arraybuffer' );
  24409. loader.setRequestHeader( this.requestHeader );
  24410. loader.setPath( this.path );
  24411. loader.setWithCredentials( scope.withCredentials );
  24412. loader.load( url, function ( buffer ) {
  24413. const texData = scope.parse( buffer );
  24414. if ( ! texData ) return;
  24415. if ( texData.image !== undefined ) {
  24416. texture.image = texData.image;
  24417. } else if ( texData.data !== undefined ) {
  24418. texture.image.width = texData.width;
  24419. texture.image.height = texData.height;
  24420. texture.image.data = texData.data;
  24421. }
  24422. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24423. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24424. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24425. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24426. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24427. if ( texData.encoding !== undefined ) {
  24428. texture.encoding = texData.encoding;
  24429. }
  24430. if ( texData.flipY !== undefined ) {
  24431. texture.flipY = texData.flipY;
  24432. }
  24433. if ( texData.format !== undefined ) {
  24434. texture.format = texData.format;
  24435. }
  24436. if ( texData.type !== undefined ) {
  24437. texture.type = texData.type;
  24438. }
  24439. if ( texData.mipmaps !== undefined ) {
  24440. texture.mipmaps = texData.mipmaps;
  24441. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24442. }
  24443. if ( texData.mipmapCount === 1 ) {
  24444. texture.minFilter = LinearFilter;
  24445. }
  24446. if ( texData.generateMipmaps !== undefined ) {
  24447. texture.generateMipmaps = texData.generateMipmaps;
  24448. }
  24449. texture.needsUpdate = true;
  24450. if ( onLoad ) onLoad( texture, texData );
  24451. }, onProgress, onError );
  24452. return texture;
  24453. }
  24454. }
  24455. class TextureLoader extends Loader {
  24456. constructor( manager ) {
  24457. super( manager );
  24458. }
  24459. load( url, onLoad, onProgress, onError ) {
  24460. const texture = new Texture();
  24461. const loader = new ImageLoader( this.manager );
  24462. loader.setCrossOrigin( this.crossOrigin );
  24463. loader.setPath( this.path );
  24464. loader.load( url, function ( image ) {
  24465. texture.image = image;
  24466. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  24467. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  24468. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  24469. texture.needsUpdate = true;
  24470. if ( onLoad !== undefined ) {
  24471. onLoad( texture );
  24472. }
  24473. }, onProgress, onError );
  24474. return texture;
  24475. }
  24476. }
  24477. /**************************************************************
  24478. * Curved Path - a curve path is simply a array of connected
  24479. * curves, but retains the api of a curve
  24480. **************************************************************/
  24481. class CurvePath extends Curve {
  24482. constructor() {
  24483. super();
  24484. this.type = 'CurvePath';
  24485. this.curves = [];
  24486. this.autoClose = false; // Automatically closes the path
  24487. }
  24488. add( curve ) {
  24489. this.curves.push( curve );
  24490. }
  24491. closePath() {
  24492. // Add a line curve if start and end of lines are not connected
  24493. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24494. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24495. if ( ! startPoint.equals( endPoint ) ) {
  24496. this.curves.push( new LineCurve( endPoint, startPoint ) );
  24497. }
  24498. }
  24499. // To get accurate point with reference to
  24500. // entire path distance at time t,
  24501. // following has to be done:
  24502. // 1. Length of each sub path have to be known
  24503. // 2. Locate and identify type of curve
  24504. // 3. Get t for the curve
  24505. // 4. Return curve.getPointAt(t')
  24506. getPoint( t ) {
  24507. const d = t * this.getLength();
  24508. const curveLengths = this.getCurveLengths();
  24509. let i = 0;
  24510. // To think about boundaries points.
  24511. while ( i < curveLengths.length ) {
  24512. if ( curveLengths[ i ] >= d ) {
  24513. const diff = curveLengths[ i ] - d;
  24514. const curve = this.curves[ i ];
  24515. const segmentLength = curve.getLength();
  24516. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24517. return curve.getPointAt( u );
  24518. }
  24519. i ++;
  24520. }
  24521. return null;
  24522. // loop where sum != 0, sum > d , sum+1 <d
  24523. }
  24524. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24525. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24526. // getPoint() depends on getLength
  24527. getLength() {
  24528. const lens = this.getCurveLengths();
  24529. return lens[ lens.length - 1 ];
  24530. }
  24531. // cacheLengths must be recalculated.
  24532. updateArcLengths() {
  24533. this.needsUpdate = true;
  24534. this.cacheLengths = null;
  24535. this.getCurveLengths();
  24536. }
  24537. // Compute lengths and cache them
  24538. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24539. getCurveLengths() {
  24540. // We use cache values if curves and cache array are same length
  24541. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24542. return this.cacheLengths;
  24543. }
  24544. // Get length of sub-curve
  24545. // Push sums into cached array
  24546. const lengths = [];
  24547. let sums = 0;
  24548. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24549. sums += this.curves[ i ].getLength();
  24550. lengths.push( sums );
  24551. }
  24552. this.cacheLengths = lengths;
  24553. return lengths;
  24554. }
  24555. getSpacedPoints( divisions = 40 ) {
  24556. const points = [];
  24557. for ( let i = 0; i <= divisions; i ++ ) {
  24558. points.push( this.getPoint( i / divisions ) );
  24559. }
  24560. if ( this.autoClose ) {
  24561. points.push( points[ 0 ] );
  24562. }
  24563. return points;
  24564. }
  24565. getPoints( divisions = 12 ) {
  24566. const points = [];
  24567. let last;
  24568. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24569. const curve = curves[ i ];
  24570. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  24571. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  24572. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  24573. : divisions;
  24574. const pts = curve.getPoints( resolution );
  24575. for ( let j = 0; j < pts.length; j ++ ) {
  24576. const point = pts[ j ];
  24577. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24578. points.push( point );
  24579. last = point;
  24580. }
  24581. }
  24582. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24583. points.push( points[ 0 ] );
  24584. }
  24585. return points;
  24586. }
  24587. copy( source ) {
  24588. super.copy( source );
  24589. this.curves = [];
  24590. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24591. const curve = source.curves[ i ];
  24592. this.curves.push( curve.clone() );
  24593. }
  24594. this.autoClose = source.autoClose;
  24595. return this;
  24596. }
  24597. toJSON() {
  24598. const data = super.toJSON();
  24599. data.autoClose = this.autoClose;
  24600. data.curves = [];
  24601. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24602. const curve = this.curves[ i ];
  24603. data.curves.push( curve.toJSON() );
  24604. }
  24605. return data;
  24606. }
  24607. fromJSON( json ) {
  24608. super.fromJSON( json );
  24609. this.autoClose = json.autoClose;
  24610. this.curves = [];
  24611. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24612. const curve = json.curves[ i ];
  24613. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24614. }
  24615. return this;
  24616. }
  24617. }
  24618. class Path extends CurvePath {
  24619. constructor( points ) {
  24620. super();
  24621. this.type = 'Path';
  24622. this.currentPoint = new Vector2();
  24623. if ( points ) {
  24624. this.setFromPoints( points );
  24625. }
  24626. }
  24627. setFromPoints( points ) {
  24628. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24629. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24630. this.lineTo( points[ i ].x, points[ i ].y );
  24631. }
  24632. return this;
  24633. }
  24634. moveTo( x, y ) {
  24635. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24636. return this;
  24637. }
  24638. lineTo( x, y ) {
  24639. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24640. this.curves.push( curve );
  24641. this.currentPoint.set( x, y );
  24642. return this;
  24643. }
  24644. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24645. const curve = new QuadraticBezierCurve(
  24646. this.currentPoint.clone(),
  24647. new Vector2( aCPx, aCPy ),
  24648. new Vector2( aX, aY )
  24649. );
  24650. this.curves.push( curve );
  24651. this.currentPoint.set( aX, aY );
  24652. return this;
  24653. }
  24654. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24655. const curve = new CubicBezierCurve(
  24656. this.currentPoint.clone(),
  24657. new Vector2( aCP1x, aCP1y ),
  24658. new Vector2( aCP2x, aCP2y ),
  24659. new Vector2( aX, aY )
  24660. );
  24661. this.curves.push( curve );
  24662. this.currentPoint.set( aX, aY );
  24663. return this;
  24664. }
  24665. splineThru( pts /*Array of Vector*/ ) {
  24666. const npts = [ this.currentPoint.clone() ].concat( pts );
  24667. const curve = new SplineCurve( npts );
  24668. this.curves.push( curve );
  24669. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24670. return this;
  24671. }
  24672. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24673. const x0 = this.currentPoint.x;
  24674. const y0 = this.currentPoint.y;
  24675. this.absarc( aX + x0, aY + y0, aRadius,
  24676. aStartAngle, aEndAngle, aClockwise );
  24677. return this;
  24678. }
  24679. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24680. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24681. return this;
  24682. }
  24683. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24684. const x0 = this.currentPoint.x;
  24685. const y0 = this.currentPoint.y;
  24686. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24687. return this;
  24688. }
  24689. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24690. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24691. if ( this.curves.length > 0 ) {
  24692. // if a previous curve is present, attempt to join
  24693. const firstPoint = curve.getPoint( 0 );
  24694. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24695. this.lineTo( firstPoint.x, firstPoint.y );
  24696. }
  24697. }
  24698. this.curves.push( curve );
  24699. const lastPoint = curve.getPoint( 1 );
  24700. this.currentPoint.copy( lastPoint );
  24701. return this;
  24702. }
  24703. copy( source ) {
  24704. super.copy( source );
  24705. this.currentPoint.copy( source.currentPoint );
  24706. return this;
  24707. }
  24708. toJSON() {
  24709. const data = super.toJSON();
  24710. data.currentPoint = this.currentPoint.toArray();
  24711. return data;
  24712. }
  24713. fromJSON( json ) {
  24714. super.fromJSON( json );
  24715. this.currentPoint.fromArray( json.currentPoint );
  24716. return this;
  24717. }
  24718. }
  24719. class Shape extends Path {
  24720. constructor( points ) {
  24721. super( points );
  24722. this.uuid = generateUUID();
  24723. this.type = 'Shape';
  24724. this.holes = [];
  24725. }
  24726. getPointsHoles( divisions ) {
  24727. const holesPts = [];
  24728. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24729. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24730. }
  24731. return holesPts;
  24732. }
  24733. // get points of shape and holes (keypoints based on segments parameter)
  24734. extractPoints( divisions ) {
  24735. return {
  24736. shape: this.getPoints( divisions ),
  24737. holes: this.getPointsHoles( divisions )
  24738. };
  24739. }
  24740. copy( source ) {
  24741. super.copy( source );
  24742. this.holes = [];
  24743. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24744. const hole = source.holes[ i ];
  24745. this.holes.push( hole.clone() );
  24746. }
  24747. return this;
  24748. }
  24749. toJSON() {
  24750. const data = super.toJSON();
  24751. data.uuid = this.uuid;
  24752. data.holes = [];
  24753. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24754. const hole = this.holes[ i ];
  24755. data.holes.push( hole.toJSON() );
  24756. }
  24757. return data;
  24758. }
  24759. fromJSON( json ) {
  24760. super.fromJSON( json );
  24761. this.uuid = json.uuid;
  24762. this.holes = [];
  24763. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24764. const hole = json.holes[ i ];
  24765. this.holes.push( new Path().fromJSON( hole ) );
  24766. }
  24767. return this;
  24768. }
  24769. }
  24770. class Light extends Object3D {
  24771. constructor( color, intensity = 1 ) {
  24772. super();
  24773. this.type = 'Light';
  24774. this.color = new Color( color );
  24775. this.intensity = intensity;
  24776. }
  24777. dispose() {
  24778. // Empty here in base class; some subclasses override.
  24779. }
  24780. copy( source ) {
  24781. super.copy( source );
  24782. this.color.copy( source.color );
  24783. this.intensity = source.intensity;
  24784. return this;
  24785. }
  24786. toJSON( meta ) {
  24787. const data = super.toJSON( meta );
  24788. data.object.color = this.color.getHex();
  24789. data.object.intensity = this.intensity;
  24790. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24791. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24792. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24793. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24794. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24795. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24796. return data;
  24797. }
  24798. }
  24799. Light.prototype.isLight = true;
  24800. class HemisphereLight extends Light {
  24801. constructor( skyColor, groundColor, intensity ) {
  24802. super( skyColor, intensity );
  24803. this.type = 'HemisphereLight';
  24804. this.position.copy( Object3D.DefaultUp );
  24805. this.updateMatrix();
  24806. this.groundColor = new Color( groundColor );
  24807. }
  24808. copy( source ) {
  24809. Light.prototype.copy.call( this, source );
  24810. this.groundColor.copy( source.groundColor );
  24811. return this;
  24812. }
  24813. }
  24814. HemisphereLight.prototype.isHemisphereLight = true;
  24815. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24816. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24817. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24818. class LightShadow {
  24819. constructor( camera ) {
  24820. this.camera = camera;
  24821. this.bias = 0;
  24822. this.normalBias = 0;
  24823. this.radius = 1;
  24824. this.blurSamples = 8;
  24825. this.mapSize = new Vector2( 512, 512 );
  24826. this.map = null;
  24827. this.mapPass = null;
  24828. this.matrix = new Matrix4();
  24829. this.autoUpdate = true;
  24830. this.needsUpdate = false;
  24831. this._frustum = new Frustum();
  24832. this._frameExtents = new Vector2( 1, 1 );
  24833. this._viewportCount = 1;
  24834. this._viewports = [
  24835. new Vector4( 0, 0, 1, 1 )
  24836. ];
  24837. }
  24838. getViewportCount() {
  24839. return this._viewportCount;
  24840. }
  24841. getFrustum() {
  24842. return this._frustum;
  24843. }
  24844. updateMatrices( light ) {
  24845. const shadowCamera = this.camera;
  24846. const shadowMatrix = this.matrix;
  24847. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24848. shadowCamera.position.copy( _lightPositionWorld$1 );
  24849. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24850. shadowCamera.lookAt( _lookTarget$1 );
  24851. shadowCamera.updateMatrixWorld();
  24852. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24853. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24854. shadowMatrix.set(
  24855. 0.5, 0.0, 0.0, 0.5,
  24856. 0.0, 0.5, 0.0, 0.5,
  24857. 0.0, 0.0, 0.5, 0.5,
  24858. 0.0, 0.0, 0.0, 1.0
  24859. );
  24860. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  24861. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  24862. }
  24863. getViewport( viewportIndex ) {
  24864. return this._viewports[ viewportIndex ];
  24865. }
  24866. getFrameExtents() {
  24867. return this._frameExtents;
  24868. }
  24869. dispose() {
  24870. if ( this.map ) {
  24871. this.map.dispose();
  24872. }
  24873. if ( this.mapPass ) {
  24874. this.mapPass.dispose();
  24875. }
  24876. }
  24877. copy( source ) {
  24878. this.camera = source.camera.clone();
  24879. this.bias = source.bias;
  24880. this.radius = source.radius;
  24881. this.mapSize.copy( source.mapSize );
  24882. return this;
  24883. }
  24884. clone() {
  24885. return new this.constructor().copy( this );
  24886. }
  24887. toJSON() {
  24888. const object = {};
  24889. if ( this.bias !== 0 ) object.bias = this.bias;
  24890. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24891. if ( this.radius !== 1 ) object.radius = this.radius;
  24892. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24893. object.camera = this.camera.toJSON( false ).object;
  24894. delete object.camera.matrix;
  24895. return object;
  24896. }
  24897. }
  24898. class SpotLightShadow extends LightShadow {
  24899. constructor() {
  24900. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24901. this.focus = 1;
  24902. }
  24903. updateMatrices( light ) {
  24904. const camera = this.camera;
  24905. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24906. const aspect = this.mapSize.width / this.mapSize.height;
  24907. const far = light.distance || camera.far;
  24908. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24909. camera.fov = fov;
  24910. camera.aspect = aspect;
  24911. camera.far = far;
  24912. camera.updateProjectionMatrix();
  24913. }
  24914. super.updateMatrices( light );
  24915. }
  24916. copy( source ) {
  24917. super.copy( source );
  24918. this.focus = source.focus;
  24919. return this;
  24920. }
  24921. }
  24922. SpotLightShadow.prototype.isSpotLightShadow = true;
  24923. class SpotLight extends Light {
  24924. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  24925. super( color, intensity );
  24926. this.type = 'SpotLight';
  24927. this.position.copy( Object3D.DefaultUp );
  24928. this.updateMatrix();
  24929. this.target = new Object3D();
  24930. this.distance = distance;
  24931. this.angle = angle;
  24932. this.penumbra = penumbra;
  24933. this.decay = decay; // for physically correct lights, should be 2.
  24934. this.shadow = new SpotLightShadow();
  24935. }
  24936. get power() {
  24937. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24938. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24939. return this.intensity * Math.PI;
  24940. }
  24941. set power( power ) {
  24942. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24943. this.intensity = power / Math.PI;
  24944. }
  24945. dispose() {
  24946. this.shadow.dispose();
  24947. }
  24948. copy( source ) {
  24949. super.copy( source );
  24950. this.distance = source.distance;
  24951. this.angle = source.angle;
  24952. this.penumbra = source.penumbra;
  24953. this.decay = source.decay;
  24954. this.target = source.target.clone();
  24955. this.shadow = source.shadow.clone();
  24956. return this;
  24957. }
  24958. }
  24959. SpotLight.prototype.isSpotLight = true;
  24960. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24961. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24962. const _lookTarget = /*@__PURE__*/ new Vector3();
  24963. class PointLightShadow extends LightShadow {
  24964. constructor() {
  24965. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24966. this._frameExtents = new Vector2( 4, 2 );
  24967. this._viewportCount = 6;
  24968. this._viewports = [
  24969. // These viewports map a cube-map onto a 2D texture with the
  24970. // following orientation:
  24971. //
  24972. // xzXZ
  24973. // y Y
  24974. //
  24975. // X - Positive x direction
  24976. // x - Negative x direction
  24977. // Y - Positive y direction
  24978. // y - Negative y direction
  24979. // Z - Positive z direction
  24980. // z - Negative z direction
  24981. // positive X
  24982. new Vector4( 2, 1, 1, 1 ),
  24983. // negative X
  24984. new Vector4( 0, 1, 1, 1 ),
  24985. // positive Z
  24986. new Vector4( 3, 1, 1, 1 ),
  24987. // negative Z
  24988. new Vector4( 1, 1, 1, 1 ),
  24989. // positive Y
  24990. new Vector4( 3, 0, 1, 1 ),
  24991. // negative Y
  24992. new Vector4( 1, 0, 1, 1 )
  24993. ];
  24994. this._cubeDirections = [
  24995. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24996. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24997. ];
  24998. this._cubeUps = [
  24999. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  25000. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  25001. ];
  25002. }
  25003. updateMatrices( light, viewportIndex = 0 ) {
  25004. const camera = this.camera;
  25005. const shadowMatrix = this.matrix;
  25006. const far = light.distance || camera.far;
  25007. if ( far !== camera.far ) {
  25008. camera.far = far;
  25009. camera.updateProjectionMatrix();
  25010. }
  25011. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  25012. camera.position.copy( _lightPositionWorld );
  25013. _lookTarget.copy( camera.position );
  25014. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  25015. camera.up.copy( this._cubeUps[ viewportIndex ] );
  25016. camera.lookAt( _lookTarget );
  25017. camera.updateMatrixWorld();
  25018. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  25019. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  25020. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  25021. }
  25022. }
  25023. PointLightShadow.prototype.isPointLightShadow = true;
  25024. class PointLight extends Light {
  25025. constructor( color, intensity, distance = 0, decay = 1 ) {
  25026. super( color, intensity );
  25027. this.type = 'PointLight';
  25028. this.distance = distance;
  25029. this.decay = decay; // for physically correct lights, should be 2.
  25030. this.shadow = new PointLightShadow();
  25031. }
  25032. get power() {
  25033. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25034. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25035. return this.intensity * 4 * Math.PI;
  25036. }
  25037. set power( power ) {
  25038. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25039. this.intensity = power / ( 4 * Math.PI );
  25040. }
  25041. dispose() {
  25042. this.shadow.dispose();
  25043. }
  25044. copy( source ) {
  25045. super.copy( source );
  25046. this.distance = source.distance;
  25047. this.decay = source.decay;
  25048. this.shadow = source.shadow.clone();
  25049. return this;
  25050. }
  25051. }
  25052. PointLight.prototype.isPointLight = true;
  25053. class DirectionalLightShadow extends LightShadow {
  25054. constructor() {
  25055. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25056. }
  25057. }
  25058. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  25059. class DirectionalLight extends Light {
  25060. constructor( color, intensity ) {
  25061. super( color, intensity );
  25062. this.type = 'DirectionalLight';
  25063. this.position.copy( Object3D.DefaultUp );
  25064. this.updateMatrix();
  25065. this.target = new Object3D();
  25066. this.shadow = new DirectionalLightShadow();
  25067. }
  25068. dispose() {
  25069. this.shadow.dispose();
  25070. }
  25071. copy( source ) {
  25072. super.copy( source );
  25073. this.target = source.target.clone();
  25074. this.shadow = source.shadow.clone();
  25075. return this;
  25076. }
  25077. }
  25078. DirectionalLight.prototype.isDirectionalLight = true;
  25079. class AmbientLight extends Light {
  25080. constructor( color, intensity ) {
  25081. super( color, intensity );
  25082. this.type = 'AmbientLight';
  25083. }
  25084. }
  25085. AmbientLight.prototype.isAmbientLight = true;
  25086. class RectAreaLight extends Light {
  25087. constructor( color, intensity, width = 10, height = 10 ) {
  25088. super( color, intensity );
  25089. this.type = 'RectAreaLight';
  25090. this.width = width;
  25091. this.height = height;
  25092. }
  25093. get power() {
  25094. // compute the light's luminous power (in lumens) from its intensity (in nits)
  25095. return this.intensity * this.width * this.height * Math.PI;
  25096. }
  25097. set power( power ) {
  25098. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  25099. this.intensity = power / ( this.width * this.height * Math.PI );
  25100. }
  25101. copy( source ) {
  25102. super.copy( source );
  25103. this.width = source.width;
  25104. this.height = source.height;
  25105. return this;
  25106. }
  25107. toJSON( meta ) {
  25108. const data = super.toJSON( meta );
  25109. data.object.width = this.width;
  25110. data.object.height = this.height;
  25111. return data;
  25112. }
  25113. }
  25114. RectAreaLight.prototype.isRectAreaLight = true;
  25115. /**
  25116. * Primary reference:
  25117. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25118. *
  25119. * Secondary reference:
  25120. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25121. */
  25122. // 3-band SH defined by 9 coefficients
  25123. class SphericalHarmonics3 {
  25124. constructor() {
  25125. this.coefficients = [];
  25126. for ( let i = 0; i < 9; i ++ ) {
  25127. this.coefficients.push( new Vector3() );
  25128. }
  25129. }
  25130. set( coefficients ) {
  25131. for ( let i = 0; i < 9; i ++ ) {
  25132. this.coefficients[ i ].copy( coefficients[ i ] );
  25133. }
  25134. return this;
  25135. }
  25136. zero() {
  25137. for ( let i = 0; i < 9; i ++ ) {
  25138. this.coefficients[ i ].set( 0, 0, 0 );
  25139. }
  25140. return this;
  25141. }
  25142. // get the radiance in the direction of the normal
  25143. // target is a Vector3
  25144. getAt( normal, target ) {
  25145. // normal is assumed to be unit length
  25146. const x = normal.x, y = normal.y, z = normal.z;
  25147. const coeff = this.coefficients;
  25148. // band 0
  25149. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25150. // band 1
  25151. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25152. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25153. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25154. // band 2
  25155. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25156. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25157. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25158. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25159. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25160. return target;
  25161. }
  25162. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25163. // target is a Vector3
  25164. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25165. getIrradianceAt( normal, target ) {
  25166. // normal is assumed to be unit length
  25167. const x = normal.x, y = normal.y, z = normal.z;
  25168. const coeff = this.coefficients;
  25169. // band 0
  25170. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25171. // band 1
  25172. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25173. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25174. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25175. // band 2
  25176. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25177. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25178. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25179. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25180. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25181. return target;
  25182. }
  25183. add( sh ) {
  25184. for ( let i = 0; i < 9; i ++ ) {
  25185. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25186. }
  25187. return this;
  25188. }
  25189. addScaledSH( sh, s ) {
  25190. for ( let i = 0; i < 9; i ++ ) {
  25191. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25192. }
  25193. return this;
  25194. }
  25195. scale( s ) {
  25196. for ( let i = 0; i < 9; i ++ ) {
  25197. this.coefficients[ i ].multiplyScalar( s );
  25198. }
  25199. return this;
  25200. }
  25201. lerp( sh, alpha ) {
  25202. for ( let i = 0; i < 9; i ++ ) {
  25203. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25204. }
  25205. return this;
  25206. }
  25207. equals( sh ) {
  25208. for ( let i = 0; i < 9; i ++ ) {
  25209. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25210. return false;
  25211. }
  25212. }
  25213. return true;
  25214. }
  25215. copy( sh ) {
  25216. return this.set( sh.coefficients );
  25217. }
  25218. clone() {
  25219. return new this.constructor().copy( this );
  25220. }
  25221. fromArray( array, offset = 0 ) {
  25222. const coefficients = this.coefficients;
  25223. for ( let i = 0; i < 9; i ++ ) {
  25224. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25225. }
  25226. return this;
  25227. }
  25228. toArray( array = [], offset = 0 ) {
  25229. const coefficients = this.coefficients;
  25230. for ( let i = 0; i < 9; i ++ ) {
  25231. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25232. }
  25233. return array;
  25234. }
  25235. // evaluate the basis functions
  25236. // shBasis is an Array[ 9 ]
  25237. static getBasisAt( normal, shBasis ) {
  25238. // normal is assumed to be unit length
  25239. const x = normal.x, y = normal.y, z = normal.z;
  25240. // band 0
  25241. shBasis[ 0 ] = 0.282095;
  25242. // band 1
  25243. shBasis[ 1 ] = 0.488603 * y;
  25244. shBasis[ 2 ] = 0.488603 * z;
  25245. shBasis[ 3 ] = 0.488603 * x;
  25246. // band 2
  25247. shBasis[ 4 ] = 1.092548 * x * y;
  25248. shBasis[ 5 ] = 1.092548 * y * z;
  25249. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25250. shBasis[ 7 ] = 1.092548 * x * z;
  25251. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25252. }
  25253. }
  25254. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  25255. class LightProbe extends Light {
  25256. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25257. super( undefined, intensity );
  25258. this.sh = sh;
  25259. }
  25260. copy( source ) {
  25261. super.copy( source );
  25262. this.sh.copy( source.sh );
  25263. return this;
  25264. }
  25265. fromJSON( json ) {
  25266. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25267. this.sh.fromArray( json.sh );
  25268. return this;
  25269. }
  25270. toJSON( meta ) {
  25271. const data = super.toJSON( meta );
  25272. data.object.sh = this.sh.toArray();
  25273. return data;
  25274. }
  25275. }
  25276. LightProbe.prototype.isLightProbe = true;
  25277. class MaterialLoader extends Loader {
  25278. constructor( manager ) {
  25279. super( manager );
  25280. this.textures = {};
  25281. }
  25282. load( url, onLoad, onProgress, onError ) {
  25283. const scope = this;
  25284. const loader = new FileLoader( scope.manager );
  25285. loader.setPath( scope.path );
  25286. loader.setRequestHeader( scope.requestHeader );
  25287. loader.setWithCredentials( scope.withCredentials );
  25288. loader.load( url, function ( text ) {
  25289. try {
  25290. onLoad( scope.parse( JSON.parse( text ) ) );
  25291. } catch ( e ) {
  25292. if ( onError ) {
  25293. onError( e );
  25294. } else {
  25295. console.error( e );
  25296. }
  25297. scope.manager.itemError( url );
  25298. }
  25299. }, onProgress, onError );
  25300. }
  25301. parse( json ) {
  25302. const textures = this.textures;
  25303. function getTexture( name ) {
  25304. if ( textures[ name ] === undefined ) {
  25305. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25306. }
  25307. return textures[ name ];
  25308. }
  25309. const material = new Materials[ json.type ]();
  25310. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25311. if ( json.name !== undefined ) material.name = json.name;
  25312. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25313. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25314. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25315. if ( json.sheenTint !== undefined ) material.sheenTint = new Color().setHex( json.sheenTint );
  25316. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25317. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25318. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25319. if ( json.specularTint !== undefined && material.specularTint !== undefined ) material.specularTint.setHex( json.specularTint );
  25320. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25321. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25322. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25323. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25324. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25325. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25326. if ( json.attenuationTint !== undefined && material.attenuationTint !== undefined ) material.attenuationTint.setHex( json.attenuationTint );
  25327. if ( json.fog !== undefined ) material.fog = json.fog;
  25328. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25329. if ( json.blending !== undefined ) material.blending = json.blending;
  25330. if ( json.combine !== undefined ) material.combine = json.combine;
  25331. if ( json.side !== undefined ) material.side = json.side;
  25332. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25333. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25334. if ( json.format !== undefined ) material.format = json.format;
  25335. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25336. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25337. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25338. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25339. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25340. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25341. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25342. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25343. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25344. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25345. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25346. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25347. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25348. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25349. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25350. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25351. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25352. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25353. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25354. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25355. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25356. if ( json.scale !== undefined ) material.scale = json.scale;
  25357. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25358. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25359. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25360. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25361. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25362. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25363. if ( json.visible !== undefined ) material.visible = json.visible;
  25364. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25365. if ( json.userData !== undefined ) material.userData = json.userData;
  25366. if ( json.vertexColors !== undefined ) {
  25367. if ( typeof json.vertexColors === 'number' ) {
  25368. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25369. } else {
  25370. material.vertexColors = json.vertexColors;
  25371. }
  25372. }
  25373. // Shader Material
  25374. if ( json.uniforms !== undefined ) {
  25375. for ( const name in json.uniforms ) {
  25376. const uniform = json.uniforms[ name ];
  25377. material.uniforms[ name ] = {};
  25378. switch ( uniform.type ) {
  25379. case 't':
  25380. material.uniforms[ name ].value = getTexture( uniform.value );
  25381. break;
  25382. case 'c':
  25383. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25384. break;
  25385. case 'v2':
  25386. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25387. break;
  25388. case 'v3':
  25389. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25390. break;
  25391. case 'v4':
  25392. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25393. break;
  25394. case 'm3':
  25395. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25396. break;
  25397. case 'm4':
  25398. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25399. break;
  25400. default:
  25401. material.uniforms[ name ].value = uniform.value;
  25402. }
  25403. }
  25404. }
  25405. if ( json.defines !== undefined ) material.defines = json.defines;
  25406. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25407. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25408. if ( json.extensions !== undefined ) {
  25409. for ( const key in json.extensions ) {
  25410. material.extensions[ key ] = json.extensions[ key ];
  25411. }
  25412. }
  25413. // Deprecated
  25414. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  25415. // for PointsMaterial
  25416. if ( json.size !== undefined ) material.size = json.size;
  25417. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25418. // maps
  25419. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25420. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25421. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25422. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25423. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25424. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25425. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25426. if ( json.normalScale !== undefined ) {
  25427. let normalScale = json.normalScale;
  25428. if ( Array.isArray( normalScale ) === false ) {
  25429. // Blender exporter used to export a scalar. See #7459
  25430. normalScale = [ normalScale, normalScale ];
  25431. }
  25432. material.normalScale = new Vector2().fromArray( normalScale );
  25433. }
  25434. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25435. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25436. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25437. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25438. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25439. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25440. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25441. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25442. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25443. if ( json.specularTintMap !== undefined ) material.specularTintMap = getTexture( json.specularTintMap );
  25444. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25445. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25446. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25447. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25448. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25449. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25450. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25451. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25452. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25453. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25454. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25455. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25456. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25457. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25458. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25459. return material;
  25460. }
  25461. setTextures( value ) {
  25462. this.textures = value;
  25463. return this;
  25464. }
  25465. }
  25466. class LoaderUtils {
  25467. static decodeText( array ) {
  25468. if ( typeof TextDecoder !== 'undefined' ) {
  25469. return new TextDecoder().decode( array );
  25470. }
  25471. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25472. // throws a "maximum call stack size exceeded" error for large arrays.
  25473. let s = '';
  25474. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25475. // Implicitly assumes little-endian.
  25476. s += String.fromCharCode( array[ i ] );
  25477. }
  25478. try {
  25479. // merges multi-byte utf-8 characters.
  25480. return decodeURIComponent( escape( s ) );
  25481. } catch ( e ) { // see #16358
  25482. return s;
  25483. }
  25484. }
  25485. static extractUrlBase( url ) {
  25486. const index = url.lastIndexOf( '/' );
  25487. if ( index === - 1 ) return './';
  25488. return url.substr( 0, index + 1 );
  25489. }
  25490. }
  25491. class InstancedBufferGeometry extends BufferGeometry {
  25492. constructor() {
  25493. super();
  25494. this.type = 'InstancedBufferGeometry';
  25495. this.instanceCount = Infinity;
  25496. }
  25497. copy( source ) {
  25498. super.copy( source );
  25499. this.instanceCount = source.instanceCount;
  25500. return this;
  25501. }
  25502. clone() {
  25503. return new this.constructor().copy( this );
  25504. }
  25505. toJSON() {
  25506. const data = super.toJSON( this );
  25507. data.instanceCount = this.instanceCount;
  25508. data.isInstancedBufferGeometry = true;
  25509. return data;
  25510. }
  25511. }
  25512. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  25513. class BufferGeometryLoader extends Loader {
  25514. constructor( manager ) {
  25515. super( manager );
  25516. }
  25517. load( url, onLoad, onProgress, onError ) {
  25518. const scope = this;
  25519. const loader = new FileLoader( scope.manager );
  25520. loader.setPath( scope.path );
  25521. loader.setRequestHeader( scope.requestHeader );
  25522. loader.setWithCredentials( scope.withCredentials );
  25523. loader.load( url, function ( text ) {
  25524. try {
  25525. onLoad( scope.parse( JSON.parse( text ) ) );
  25526. } catch ( e ) {
  25527. if ( onError ) {
  25528. onError( e );
  25529. } else {
  25530. console.error( e );
  25531. }
  25532. scope.manager.itemError( url );
  25533. }
  25534. }, onProgress, onError );
  25535. }
  25536. parse( json ) {
  25537. const interleavedBufferMap = {};
  25538. const arrayBufferMap = {};
  25539. function getInterleavedBuffer( json, uuid ) {
  25540. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25541. const interleavedBuffers = json.interleavedBuffers;
  25542. const interleavedBuffer = interleavedBuffers[ uuid ];
  25543. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25544. const array = getTypedArray( interleavedBuffer.type, buffer );
  25545. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25546. ib.uuid = interleavedBuffer.uuid;
  25547. interleavedBufferMap[ uuid ] = ib;
  25548. return ib;
  25549. }
  25550. function getArrayBuffer( json, uuid ) {
  25551. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25552. const arrayBuffers = json.arrayBuffers;
  25553. const arrayBuffer = arrayBuffers[ uuid ];
  25554. const ab = new Uint32Array( arrayBuffer ).buffer;
  25555. arrayBufferMap[ uuid ] = ab;
  25556. return ab;
  25557. }
  25558. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25559. const index = json.data.index;
  25560. if ( index !== undefined ) {
  25561. const typedArray = getTypedArray( index.type, index.array );
  25562. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25563. }
  25564. const attributes = json.data.attributes;
  25565. for ( const key in attributes ) {
  25566. const attribute = attributes[ key ];
  25567. let bufferAttribute;
  25568. if ( attribute.isInterleavedBufferAttribute ) {
  25569. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25570. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25571. } else {
  25572. const typedArray = getTypedArray( attribute.type, attribute.array );
  25573. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25574. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25575. }
  25576. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25577. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25578. if ( attribute.updateRange !== undefined ) {
  25579. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25580. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25581. }
  25582. geometry.setAttribute( key, bufferAttribute );
  25583. }
  25584. const morphAttributes = json.data.morphAttributes;
  25585. if ( morphAttributes ) {
  25586. for ( const key in morphAttributes ) {
  25587. const attributeArray = morphAttributes[ key ];
  25588. const array = [];
  25589. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25590. const attribute = attributeArray[ i ];
  25591. let bufferAttribute;
  25592. if ( attribute.isInterleavedBufferAttribute ) {
  25593. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25594. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25595. } else {
  25596. const typedArray = getTypedArray( attribute.type, attribute.array );
  25597. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25598. }
  25599. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25600. array.push( bufferAttribute );
  25601. }
  25602. geometry.morphAttributes[ key ] = array;
  25603. }
  25604. }
  25605. const morphTargetsRelative = json.data.morphTargetsRelative;
  25606. if ( morphTargetsRelative ) {
  25607. geometry.morphTargetsRelative = true;
  25608. }
  25609. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25610. if ( groups !== undefined ) {
  25611. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25612. const group = groups[ i ];
  25613. geometry.addGroup( group.start, group.count, group.materialIndex );
  25614. }
  25615. }
  25616. const boundingSphere = json.data.boundingSphere;
  25617. if ( boundingSphere !== undefined ) {
  25618. const center = new Vector3();
  25619. if ( boundingSphere.center !== undefined ) {
  25620. center.fromArray( boundingSphere.center );
  25621. }
  25622. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25623. }
  25624. if ( json.name ) geometry.name = json.name;
  25625. if ( json.userData ) geometry.userData = json.userData;
  25626. return geometry;
  25627. }
  25628. }
  25629. class ObjectLoader extends Loader {
  25630. constructor( manager ) {
  25631. super( manager );
  25632. }
  25633. load( url, onLoad, onProgress, onError ) {
  25634. const scope = this;
  25635. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25636. this.resourcePath = this.resourcePath || path;
  25637. const loader = new FileLoader( this.manager );
  25638. loader.setPath( this.path );
  25639. loader.setRequestHeader( this.requestHeader );
  25640. loader.setWithCredentials( this.withCredentials );
  25641. loader.load( url, function ( text ) {
  25642. let json = null;
  25643. try {
  25644. json = JSON.parse( text );
  25645. } catch ( error ) {
  25646. if ( onError !== undefined ) onError( error );
  25647. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25648. return;
  25649. }
  25650. const metadata = json.metadata;
  25651. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25652. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25653. return;
  25654. }
  25655. scope.parse( json, onLoad );
  25656. }, onProgress, onError );
  25657. }
  25658. async loadAsync( url, onProgress ) {
  25659. const scope = this;
  25660. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25661. this.resourcePath = this.resourcePath || path;
  25662. const loader = new FileLoader( this.manager );
  25663. loader.setPath( this.path );
  25664. loader.setRequestHeader( this.requestHeader );
  25665. loader.setWithCredentials( this.withCredentials );
  25666. const text = await loader.loadAsync( url, onProgress );
  25667. const json = JSON.parse( text );
  25668. const metadata = json.metadata;
  25669. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25670. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25671. }
  25672. return await scope.parseAsync( json );
  25673. }
  25674. parse( json, onLoad ) {
  25675. const animations = this.parseAnimations( json.animations );
  25676. const shapes = this.parseShapes( json.shapes );
  25677. const geometries = this.parseGeometries( json.geometries, shapes );
  25678. const images = this.parseImages( json.images, function () {
  25679. if ( onLoad !== undefined ) onLoad( object );
  25680. } );
  25681. const textures = this.parseTextures( json.textures, images );
  25682. const materials = this.parseMaterials( json.materials, textures );
  25683. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25684. const skeletons = this.parseSkeletons( json.skeletons, object );
  25685. this.bindSkeletons( object, skeletons );
  25686. //
  25687. if ( onLoad !== undefined ) {
  25688. let hasImages = false;
  25689. for ( const uuid in images ) {
  25690. if ( images[ uuid ] instanceof HTMLImageElement ) {
  25691. hasImages = true;
  25692. break;
  25693. }
  25694. }
  25695. if ( hasImages === false ) onLoad( object );
  25696. }
  25697. return object;
  25698. }
  25699. async parseAsync( json ) {
  25700. const animations = this.parseAnimations( json.animations );
  25701. const shapes = this.parseShapes( json.shapes );
  25702. const geometries = this.parseGeometries( json.geometries, shapes );
  25703. const images = await this.parseImagesAsync( json.images );
  25704. const textures = this.parseTextures( json.textures, images );
  25705. const materials = this.parseMaterials( json.materials, textures );
  25706. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25707. const skeletons = this.parseSkeletons( json.skeletons, object );
  25708. this.bindSkeletons( object, skeletons );
  25709. return object;
  25710. }
  25711. parseShapes( json ) {
  25712. const shapes = {};
  25713. if ( json !== undefined ) {
  25714. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25715. const shape = new Shape().fromJSON( json[ i ] );
  25716. shapes[ shape.uuid ] = shape;
  25717. }
  25718. }
  25719. return shapes;
  25720. }
  25721. parseSkeletons( json, object ) {
  25722. const skeletons = {};
  25723. const bones = {};
  25724. // generate bone lookup table
  25725. object.traverse( function ( child ) {
  25726. if ( child.isBone ) bones[ child.uuid ] = child;
  25727. } );
  25728. // create skeletons
  25729. if ( json !== undefined ) {
  25730. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25731. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25732. skeletons[ skeleton.uuid ] = skeleton;
  25733. }
  25734. }
  25735. return skeletons;
  25736. }
  25737. parseGeometries( json, shapes ) {
  25738. const geometries = {};
  25739. if ( json !== undefined ) {
  25740. const bufferGeometryLoader = new BufferGeometryLoader();
  25741. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25742. let geometry;
  25743. const data = json[ i ];
  25744. switch ( data.type ) {
  25745. case 'BufferGeometry':
  25746. case 'InstancedBufferGeometry':
  25747. geometry = bufferGeometryLoader.parse( data );
  25748. break;
  25749. case 'Geometry':
  25750. console.error( 'THREE.ObjectLoader: The legacy Geometry type is no longer supported.' );
  25751. break;
  25752. default:
  25753. if ( data.type in Geometries ) {
  25754. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25755. } else {
  25756. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25757. }
  25758. }
  25759. geometry.uuid = data.uuid;
  25760. if ( data.name !== undefined ) geometry.name = data.name;
  25761. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25762. geometries[ data.uuid ] = geometry;
  25763. }
  25764. }
  25765. return geometries;
  25766. }
  25767. parseMaterials( json, textures ) {
  25768. const cache = {}; // MultiMaterial
  25769. const materials = {};
  25770. if ( json !== undefined ) {
  25771. const loader = new MaterialLoader();
  25772. loader.setTextures( textures );
  25773. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25774. const data = json[ i ];
  25775. if ( data.type === 'MultiMaterial' ) {
  25776. // Deprecated
  25777. const array = [];
  25778. for ( let j = 0; j < data.materials.length; j ++ ) {
  25779. const material = data.materials[ j ];
  25780. if ( cache[ material.uuid ] === undefined ) {
  25781. cache[ material.uuid ] = loader.parse( material );
  25782. }
  25783. array.push( cache[ material.uuid ] );
  25784. }
  25785. materials[ data.uuid ] = array;
  25786. } else {
  25787. if ( cache[ data.uuid ] === undefined ) {
  25788. cache[ data.uuid ] = loader.parse( data );
  25789. }
  25790. materials[ data.uuid ] = cache[ data.uuid ];
  25791. }
  25792. }
  25793. }
  25794. return materials;
  25795. }
  25796. parseAnimations( json ) {
  25797. const animations = {};
  25798. if ( json !== undefined ) {
  25799. for ( let i = 0; i < json.length; i ++ ) {
  25800. const data = json[ i ];
  25801. const clip = AnimationClip.parse( data );
  25802. animations[ clip.uuid ] = clip;
  25803. }
  25804. }
  25805. return animations;
  25806. }
  25807. parseImages( json, onLoad ) {
  25808. const scope = this;
  25809. const images = {};
  25810. let loader;
  25811. function loadImage( url ) {
  25812. scope.manager.itemStart( url );
  25813. return loader.load( url, function () {
  25814. scope.manager.itemEnd( url );
  25815. }, undefined, function () {
  25816. scope.manager.itemError( url );
  25817. scope.manager.itemEnd( url );
  25818. } );
  25819. }
  25820. function deserializeImage( image ) {
  25821. if ( typeof image === 'string' ) {
  25822. const url = image;
  25823. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25824. return loadImage( path );
  25825. } else {
  25826. if ( image.data ) {
  25827. return {
  25828. data: getTypedArray( image.type, image.data ),
  25829. width: image.width,
  25830. height: image.height
  25831. };
  25832. } else {
  25833. return null;
  25834. }
  25835. }
  25836. }
  25837. if ( json !== undefined && json.length > 0 ) {
  25838. const manager = new LoadingManager( onLoad );
  25839. loader = new ImageLoader( manager );
  25840. loader.setCrossOrigin( this.crossOrigin );
  25841. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25842. const image = json[ i ];
  25843. const url = image.url;
  25844. if ( Array.isArray( url ) ) {
  25845. // load array of images e.g CubeTexture
  25846. images[ image.uuid ] = [];
  25847. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25848. const currentUrl = url[ j ];
  25849. const deserializedImage = deserializeImage( currentUrl );
  25850. if ( deserializedImage !== null ) {
  25851. if ( deserializedImage instanceof HTMLImageElement ) {
  25852. images[ image.uuid ].push( deserializedImage );
  25853. } else {
  25854. // special case: handle array of data textures for cube textures
  25855. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25856. }
  25857. }
  25858. }
  25859. } else {
  25860. // load single image
  25861. const deserializedImage = deserializeImage( image.url );
  25862. if ( deserializedImage !== null ) {
  25863. images[ image.uuid ] = deserializedImage;
  25864. }
  25865. }
  25866. }
  25867. }
  25868. return images;
  25869. }
  25870. async parseImagesAsync( json ) {
  25871. const scope = this;
  25872. const images = {};
  25873. let loader;
  25874. async function deserializeImage( image ) {
  25875. if ( typeof image === 'string' ) {
  25876. const url = image;
  25877. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25878. return await loader.loadAsync( path );
  25879. } else {
  25880. if ( image.data ) {
  25881. return {
  25882. data: getTypedArray( image.type, image.data ),
  25883. width: image.width,
  25884. height: image.height
  25885. };
  25886. } else {
  25887. return null;
  25888. }
  25889. }
  25890. }
  25891. if ( json !== undefined && json.length > 0 ) {
  25892. loader = new ImageLoader( this.manager );
  25893. loader.setCrossOrigin( this.crossOrigin );
  25894. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25895. const image = json[ i ];
  25896. const url = image.url;
  25897. if ( Array.isArray( url ) ) {
  25898. // load array of images e.g CubeTexture
  25899. images[ image.uuid ] = [];
  25900. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25901. const currentUrl = url[ j ];
  25902. const deserializedImage = await deserializeImage( currentUrl );
  25903. if ( deserializedImage !== null ) {
  25904. if ( deserializedImage instanceof HTMLImageElement ) {
  25905. images[ image.uuid ].push( deserializedImage );
  25906. } else {
  25907. // special case: handle array of data textures for cube textures
  25908. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25909. }
  25910. }
  25911. }
  25912. } else {
  25913. // load single image
  25914. const deserializedImage = await deserializeImage( image.url );
  25915. if ( deserializedImage !== null ) {
  25916. images[ image.uuid ] = deserializedImage;
  25917. }
  25918. }
  25919. }
  25920. }
  25921. return images;
  25922. }
  25923. parseTextures( json, images ) {
  25924. function parseConstant( value, type ) {
  25925. if ( typeof value === 'number' ) return value;
  25926. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25927. return type[ value ];
  25928. }
  25929. const textures = {};
  25930. if ( json !== undefined ) {
  25931. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25932. const data = json[ i ];
  25933. if ( data.image === undefined ) {
  25934. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25935. }
  25936. if ( images[ data.image ] === undefined ) {
  25937. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25938. }
  25939. let texture;
  25940. const image = images[ data.image ];
  25941. if ( Array.isArray( image ) ) {
  25942. texture = new CubeTexture( image );
  25943. if ( image.length === 6 ) texture.needsUpdate = true;
  25944. } else {
  25945. if ( image && image.data ) {
  25946. texture = new DataTexture( image.data, image.width, image.height );
  25947. } else {
  25948. texture = new Texture( image );
  25949. }
  25950. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25951. }
  25952. texture.uuid = data.uuid;
  25953. if ( data.name !== undefined ) texture.name = data.name;
  25954. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25955. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25956. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25957. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25958. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25959. if ( data.wrap !== undefined ) {
  25960. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25961. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25962. }
  25963. if ( data.format !== undefined ) texture.format = data.format;
  25964. if ( data.type !== undefined ) texture.type = data.type;
  25965. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25966. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25967. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25968. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25969. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25970. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25971. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25972. textures[ data.uuid ] = texture;
  25973. }
  25974. }
  25975. return textures;
  25976. }
  25977. parseObject( data, geometries, materials, textures, animations ) {
  25978. let object;
  25979. function getGeometry( name ) {
  25980. if ( geometries[ name ] === undefined ) {
  25981. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25982. }
  25983. return geometries[ name ];
  25984. }
  25985. function getMaterial( name ) {
  25986. if ( name === undefined ) return undefined;
  25987. if ( Array.isArray( name ) ) {
  25988. const array = [];
  25989. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25990. const uuid = name[ i ];
  25991. if ( materials[ uuid ] === undefined ) {
  25992. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25993. }
  25994. array.push( materials[ uuid ] );
  25995. }
  25996. return array;
  25997. }
  25998. if ( materials[ name ] === undefined ) {
  25999. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26000. }
  26001. return materials[ name ];
  26002. }
  26003. function getTexture( uuid ) {
  26004. if ( textures[ uuid ] === undefined ) {
  26005. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  26006. }
  26007. return textures[ uuid ];
  26008. }
  26009. let geometry, material;
  26010. switch ( data.type ) {
  26011. case 'Scene':
  26012. object = new Scene();
  26013. if ( data.background !== undefined ) {
  26014. if ( Number.isInteger( data.background ) ) {
  26015. object.background = new Color( data.background );
  26016. } else {
  26017. object.background = getTexture( data.background );
  26018. }
  26019. }
  26020. if ( data.environment !== undefined ) {
  26021. object.environment = getTexture( data.environment );
  26022. }
  26023. if ( data.fog !== undefined ) {
  26024. if ( data.fog.type === 'Fog' ) {
  26025. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26026. } else if ( data.fog.type === 'FogExp2' ) {
  26027. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26028. }
  26029. }
  26030. break;
  26031. case 'PerspectiveCamera':
  26032. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26033. if ( data.focus !== undefined ) object.focus = data.focus;
  26034. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26035. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26036. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26037. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26038. break;
  26039. case 'OrthographicCamera':
  26040. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26041. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26042. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26043. break;
  26044. case 'AmbientLight':
  26045. object = new AmbientLight( data.color, data.intensity );
  26046. break;
  26047. case 'DirectionalLight':
  26048. object = new DirectionalLight( data.color, data.intensity );
  26049. break;
  26050. case 'PointLight':
  26051. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26052. break;
  26053. case 'RectAreaLight':
  26054. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26055. break;
  26056. case 'SpotLight':
  26057. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26058. break;
  26059. case 'HemisphereLight':
  26060. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26061. break;
  26062. case 'LightProbe':
  26063. object = new LightProbe().fromJSON( data );
  26064. break;
  26065. case 'SkinnedMesh':
  26066. geometry = getGeometry( data.geometry );
  26067. material = getMaterial( data.material );
  26068. object = new SkinnedMesh( geometry, material );
  26069. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  26070. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  26071. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  26072. break;
  26073. case 'Mesh':
  26074. geometry = getGeometry( data.geometry );
  26075. material = getMaterial( data.material );
  26076. object = new Mesh( geometry, material );
  26077. break;
  26078. case 'InstancedMesh':
  26079. geometry = getGeometry( data.geometry );
  26080. material = getMaterial( data.material );
  26081. const count = data.count;
  26082. const instanceMatrix = data.instanceMatrix;
  26083. const instanceColor = data.instanceColor;
  26084. object = new InstancedMesh( geometry, material, count );
  26085. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  26086. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  26087. break;
  26088. case 'LOD':
  26089. object = new LOD();
  26090. break;
  26091. case 'Line':
  26092. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  26093. break;
  26094. case 'LineLoop':
  26095. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26096. break;
  26097. case 'LineSegments':
  26098. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26099. break;
  26100. case 'PointCloud':
  26101. case 'Points':
  26102. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26103. break;
  26104. case 'Sprite':
  26105. object = new Sprite( getMaterial( data.material ) );
  26106. break;
  26107. case 'Group':
  26108. object = new Group();
  26109. break;
  26110. case 'Bone':
  26111. object = new Bone();
  26112. break;
  26113. default:
  26114. object = new Object3D();
  26115. }
  26116. object.uuid = data.uuid;
  26117. if ( data.name !== undefined ) object.name = data.name;
  26118. if ( data.matrix !== undefined ) {
  26119. object.matrix.fromArray( data.matrix );
  26120. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26121. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26122. } else {
  26123. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26124. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26125. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26126. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26127. }
  26128. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26129. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26130. if ( data.shadow ) {
  26131. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26132. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26133. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26134. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26135. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26136. }
  26137. if ( data.visible !== undefined ) object.visible = data.visible;
  26138. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26139. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26140. if ( data.userData !== undefined ) object.userData = data.userData;
  26141. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26142. if ( data.children !== undefined ) {
  26143. const children = data.children;
  26144. for ( let i = 0; i < children.length; i ++ ) {
  26145. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26146. }
  26147. }
  26148. if ( data.animations !== undefined ) {
  26149. const objectAnimations = data.animations;
  26150. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26151. const uuid = objectAnimations[ i ];
  26152. object.animations.push( animations[ uuid ] );
  26153. }
  26154. }
  26155. if ( data.type === 'LOD' ) {
  26156. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26157. const levels = data.levels;
  26158. for ( let l = 0; l < levels.length; l ++ ) {
  26159. const level = levels[ l ];
  26160. const child = object.getObjectByProperty( 'uuid', level.object );
  26161. if ( child !== undefined ) {
  26162. object.addLevel( child, level.distance );
  26163. }
  26164. }
  26165. }
  26166. return object;
  26167. }
  26168. bindSkeletons( object, skeletons ) {
  26169. if ( Object.keys( skeletons ).length === 0 ) return;
  26170. object.traverse( function ( child ) {
  26171. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26172. const skeleton = skeletons[ child.skeleton ];
  26173. if ( skeleton === undefined ) {
  26174. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26175. } else {
  26176. child.bind( skeleton, child.bindMatrix );
  26177. }
  26178. }
  26179. } );
  26180. }
  26181. /* DEPRECATED */
  26182. setTexturePath( value ) {
  26183. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  26184. return this.setResourcePath( value );
  26185. }
  26186. }
  26187. const TEXTURE_MAPPING = {
  26188. UVMapping: UVMapping,
  26189. CubeReflectionMapping: CubeReflectionMapping,
  26190. CubeRefractionMapping: CubeRefractionMapping,
  26191. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26192. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26193. CubeUVReflectionMapping: CubeUVReflectionMapping,
  26194. CubeUVRefractionMapping: CubeUVRefractionMapping
  26195. };
  26196. const TEXTURE_WRAPPING = {
  26197. RepeatWrapping: RepeatWrapping,
  26198. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26199. MirroredRepeatWrapping: MirroredRepeatWrapping
  26200. };
  26201. const TEXTURE_FILTER = {
  26202. NearestFilter: NearestFilter,
  26203. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26204. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26205. LinearFilter: LinearFilter,
  26206. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26207. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26208. };
  26209. class ImageBitmapLoader extends Loader {
  26210. constructor( manager ) {
  26211. super( manager );
  26212. if ( typeof createImageBitmap === 'undefined' ) {
  26213. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26214. }
  26215. if ( typeof fetch === 'undefined' ) {
  26216. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26217. }
  26218. this.options = { premultiplyAlpha: 'none' };
  26219. }
  26220. setOptions( options ) {
  26221. this.options = options;
  26222. return this;
  26223. }
  26224. load( url, onLoad, onProgress, onError ) {
  26225. if ( url === undefined ) url = '';
  26226. if ( this.path !== undefined ) url = this.path + url;
  26227. url = this.manager.resolveURL( url );
  26228. const scope = this;
  26229. const cached = Cache.get( url );
  26230. if ( cached !== undefined ) {
  26231. scope.manager.itemStart( url );
  26232. setTimeout( function () {
  26233. if ( onLoad ) onLoad( cached );
  26234. scope.manager.itemEnd( url );
  26235. }, 0 );
  26236. return cached;
  26237. }
  26238. const fetchOptions = {};
  26239. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26240. fetchOptions.headers = this.requestHeader;
  26241. fetch( url, fetchOptions ).then( function ( res ) {
  26242. return res.blob();
  26243. } ).then( function ( blob ) {
  26244. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26245. } ).then( function ( imageBitmap ) {
  26246. Cache.add( url, imageBitmap );
  26247. if ( onLoad ) onLoad( imageBitmap );
  26248. scope.manager.itemEnd( url );
  26249. } ).catch( function ( e ) {
  26250. if ( onError ) onError( e );
  26251. scope.manager.itemError( url );
  26252. scope.manager.itemEnd( url );
  26253. } );
  26254. scope.manager.itemStart( url );
  26255. }
  26256. }
  26257. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  26258. class ShapePath {
  26259. constructor() {
  26260. this.type = 'ShapePath';
  26261. this.color = new Color();
  26262. this.subPaths = [];
  26263. this.currentPath = null;
  26264. }
  26265. moveTo( x, y ) {
  26266. this.currentPath = new Path();
  26267. this.subPaths.push( this.currentPath );
  26268. this.currentPath.moveTo( x, y );
  26269. return this;
  26270. }
  26271. lineTo( x, y ) {
  26272. this.currentPath.lineTo( x, y );
  26273. return this;
  26274. }
  26275. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  26276. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  26277. return this;
  26278. }
  26279. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  26280. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  26281. return this;
  26282. }
  26283. splineThru( pts ) {
  26284. this.currentPath.splineThru( pts );
  26285. return this;
  26286. }
  26287. toShapes( isCCW, noHoles ) {
  26288. function toShapesNoHoles( inSubpaths ) {
  26289. const shapes = [];
  26290. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  26291. const tmpPath = inSubpaths[ i ];
  26292. const tmpShape = new Shape();
  26293. tmpShape.curves = tmpPath.curves;
  26294. shapes.push( tmpShape );
  26295. }
  26296. return shapes;
  26297. }
  26298. function isPointInsidePolygon( inPt, inPolygon ) {
  26299. const polyLen = inPolygon.length;
  26300. // inPt on polygon contour => immediate success or
  26301. // toggling of inside/outside at every single! intersection point of an edge
  26302. // with the horizontal line through inPt, left of inPt
  26303. // not counting lowerY endpoints of edges and whole edges on that line
  26304. let inside = false;
  26305. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  26306. let edgeLowPt = inPolygon[ p ];
  26307. let edgeHighPt = inPolygon[ q ];
  26308. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  26309. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  26310. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  26311. // not parallel
  26312. if ( edgeDy < 0 ) {
  26313. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  26314. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  26315. }
  26316. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  26317. if ( inPt.y === edgeLowPt.y ) {
  26318. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  26319. // continue; // no intersection or edgeLowPt => doesn't count !!!
  26320. } else {
  26321. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  26322. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  26323. if ( perpEdge < 0 ) continue;
  26324. inside = ! inside; // true intersection left of inPt
  26325. }
  26326. } else {
  26327. // parallel or collinear
  26328. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  26329. // edge lies on the same horizontal line as inPt
  26330. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  26331. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  26332. // continue;
  26333. }
  26334. }
  26335. return inside;
  26336. }
  26337. const isClockWise = ShapeUtils.isClockWise;
  26338. const subPaths = this.subPaths;
  26339. if ( subPaths.length === 0 ) return [];
  26340. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  26341. let solid, tmpPath, tmpShape;
  26342. const shapes = [];
  26343. if ( subPaths.length === 1 ) {
  26344. tmpPath = subPaths[ 0 ];
  26345. tmpShape = new Shape();
  26346. tmpShape.curves = tmpPath.curves;
  26347. shapes.push( tmpShape );
  26348. return shapes;
  26349. }
  26350. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  26351. holesFirst = isCCW ? ! holesFirst : holesFirst;
  26352. // console.log("Holes first", holesFirst);
  26353. const betterShapeHoles = [];
  26354. const newShapes = [];
  26355. let newShapeHoles = [];
  26356. let mainIdx = 0;
  26357. let tmpPoints;
  26358. newShapes[ mainIdx ] = undefined;
  26359. newShapeHoles[ mainIdx ] = [];
  26360. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  26361. tmpPath = subPaths[ i ];
  26362. tmpPoints = tmpPath.getPoints();
  26363. solid = isClockWise( tmpPoints );
  26364. solid = isCCW ? ! solid : solid;
  26365. if ( solid ) {
  26366. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  26367. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  26368. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  26369. if ( holesFirst ) mainIdx ++;
  26370. newShapeHoles[ mainIdx ] = [];
  26371. //console.log('cw', i);
  26372. } else {
  26373. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  26374. //console.log('ccw', i);
  26375. }
  26376. }
  26377. // only Holes? -> probably all Shapes with wrong orientation
  26378. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  26379. if ( newShapes.length > 1 ) {
  26380. let ambiguous = false;
  26381. const toChange = [];
  26382. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  26383. betterShapeHoles[ sIdx ] = [];
  26384. }
  26385. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  26386. const sho = newShapeHoles[ sIdx ];
  26387. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  26388. const ho = sho[ hIdx ];
  26389. let hole_unassigned = true;
  26390. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  26391. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  26392. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  26393. if ( hole_unassigned ) {
  26394. hole_unassigned = false;
  26395. betterShapeHoles[ s2Idx ].push( ho );
  26396. } else {
  26397. ambiguous = true;
  26398. }
  26399. }
  26400. }
  26401. if ( hole_unassigned ) {
  26402. betterShapeHoles[ sIdx ].push( ho );
  26403. }
  26404. }
  26405. }
  26406. // console.log("ambiguous: ", ambiguous);
  26407. if ( toChange.length > 0 ) {
  26408. // console.log("to change: ", toChange);
  26409. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  26410. }
  26411. }
  26412. let tmpHoles;
  26413. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  26414. tmpShape = newShapes[ i ].s;
  26415. shapes.push( tmpShape );
  26416. tmpHoles = newShapeHoles[ i ];
  26417. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  26418. tmpShape.holes.push( tmpHoles[ j ].h );
  26419. }
  26420. }
  26421. //console.log("shape", shapes);
  26422. return shapes;
  26423. }
  26424. }
  26425. class Font {
  26426. constructor( data ) {
  26427. this.type = 'Font';
  26428. this.data = data;
  26429. }
  26430. generateShapes( text, size = 100 ) {
  26431. const shapes = [];
  26432. const paths = createPaths( text, size, this.data );
  26433. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  26434. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  26435. }
  26436. return shapes;
  26437. }
  26438. }
  26439. function createPaths( text, size, data ) {
  26440. const chars = Array.from( text );
  26441. const scale = size / data.resolution;
  26442. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  26443. const paths = [];
  26444. let offsetX = 0, offsetY = 0;
  26445. for ( let i = 0; i < chars.length; i ++ ) {
  26446. const char = chars[ i ];
  26447. if ( char === '\n' ) {
  26448. offsetX = 0;
  26449. offsetY -= line_height;
  26450. } else {
  26451. const ret = createPath( char, scale, offsetX, offsetY, data );
  26452. offsetX += ret.offsetX;
  26453. paths.push( ret.path );
  26454. }
  26455. }
  26456. return paths;
  26457. }
  26458. function createPath( char, scale, offsetX, offsetY, data ) {
  26459. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  26460. if ( ! glyph ) {
  26461. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  26462. return;
  26463. }
  26464. const path = new ShapePath();
  26465. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  26466. if ( glyph.o ) {
  26467. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  26468. for ( let i = 0, l = outline.length; i < l; ) {
  26469. const action = outline[ i ++ ];
  26470. switch ( action ) {
  26471. case 'm': // moveTo
  26472. x = outline[ i ++ ] * scale + offsetX;
  26473. y = outline[ i ++ ] * scale + offsetY;
  26474. path.moveTo( x, y );
  26475. break;
  26476. case 'l': // lineTo
  26477. x = outline[ i ++ ] * scale + offsetX;
  26478. y = outline[ i ++ ] * scale + offsetY;
  26479. path.lineTo( x, y );
  26480. break;
  26481. case 'q': // quadraticCurveTo
  26482. cpx = outline[ i ++ ] * scale + offsetX;
  26483. cpy = outline[ i ++ ] * scale + offsetY;
  26484. cpx1 = outline[ i ++ ] * scale + offsetX;
  26485. cpy1 = outline[ i ++ ] * scale + offsetY;
  26486. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  26487. break;
  26488. case 'b': // bezierCurveTo
  26489. cpx = outline[ i ++ ] * scale + offsetX;
  26490. cpy = outline[ i ++ ] * scale + offsetY;
  26491. cpx1 = outline[ i ++ ] * scale + offsetX;
  26492. cpy1 = outline[ i ++ ] * scale + offsetY;
  26493. cpx2 = outline[ i ++ ] * scale + offsetX;
  26494. cpy2 = outline[ i ++ ] * scale + offsetY;
  26495. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  26496. break;
  26497. }
  26498. }
  26499. }
  26500. return { offsetX: glyph.ha * scale, path: path };
  26501. }
  26502. Font.prototype.isFont = true;
  26503. class FontLoader extends Loader {
  26504. constructor( manager ) {
  26505. super( manager );
  26506. }
  26507. load( url, onLoad, onProgress, onError ) {
  26508. const scope = this;
  26509. const loader = new FileLoader( this.manager );
  26510. loader.setPath( this.path );
  26511. loader.setRequestHeader( this.requestHeader );
  26512. loader.setWithCredentials( scope.withCredentials );
  26513. loader.load( url, function ( text ) {
  26514. let json;
  26515. try {
  26516. json = JSON.parse( text );
  26517. } catch ( e ) {
  26518. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  26519. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  26520. }
  26521. const font = scope.parse( json );
  26522. if ( onLoad ) onLoad( font );
  26523. }, onProgress, onError );
  26524. }
  26525. parse( json ) {
  26526. return new Font( json );
  26527. }
  26528. }
  26529. let _context;
  26530. const AudioContext = {
  26531. getContext: function () {
  26532. if ( _context === undefined ) {
  26533. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26534. }
  26535. return _context;
  26536. },
  26537. setContext: function ( value ) {
  26538. _context = value;
  26539. }
  26540. };
  26541. class AudioLoader extends Loader {
  26542. constructor( manager ) {
  26543. super( manager );
  26544. }
  26545. load( url, onLoad, onProgress, onError ) {
  26546. const scope = this;
  26547. const loader = new FileLoader( this.manager );
  26548. loader.setResponseType( 'arraybuffer' );
  26549. loader.setPath( this.path );
  26550. loader.setRequestHeader( this.requestHeader );
  26551. loader.setWithCredentials( this.withCredentials );
  26552. loader.load( url, function ( buffer ) {
  26553. try {
  26554. // Create a copy of the buffer. The `decodeAudioData` method
  26555. // detaches the buffer when complete, preventing reuse.
  26556. const bufferCopy = buffer.slice( 0 );
  26557. const context = AudioContext.getContext();
  26558. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26559. onLoad( audioBuffer );
  26560. } );
  26561. } catch ( e ) {
  26562. if ( onError ) {
  26563. onError( e );
  26564. } else {
  26565. console.error( e );
  26566. }
  26567. scope.manager.itemError( url );
  26568. }
  26569. }, onProgress, onError );
  26570. }
  26571. }
  26572. class HemisphereLightProbe extends LightProbe {
  26573. constructor( skyColor, groundColor, intensity = 1 ) {
  26574. super( undefined, intensity );
  26575. const color1 = new Color().set( skyColor );
  26576. const color2 = new Color().set( groundColor );
  26577. const sky = new Vector3( color1.r, color1.g, color1.b );
  26578. const ground = new Vector3( color2.r, color2.g, color2.b );
  26579. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26580. const c0 = Math.sqrt( Math.PI );
  26581. const c1 = c0 * Math.sqrt( 0.75 );
  26582. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26583. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26584. }
  26585. }
  26586. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  26587. class AmbientLightProbe extends LightProbe {
  26588. constructor( color, intensity = 1 ) {
  26589. super( undefined, intensity );
  26590. const color1 = new Color().set( color );
  26591. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26592. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26593. }
  26594. }
  26595. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  26596. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26597. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26598. class StereoCamera {
  26599. constructor() {
  26600. this.type = 'StereoCamera';
  26601. this.aspect = 1;
  26602. this.eyeSep = 0.064;
  26603. this.cameraL = new PerspectiveCamera();
  26604. this.cameraL.layers.enable( 1 );
  26605. this.cameraL.matrixAutoUpdate = false;
  26606. this.cameraR = new PerspectiveCamera();
  26607. this.cameraR.layers.enable( 2 );
  26608. this.cameraR.matrixAutoUpdate = false;
  26609. this._cache = {
  26610. focus: null,
  26611. fov: null,
  26612. aspect: null,
  26613. near: null,
  26614. far: null,
  26615. zoom: null,
  26616. eyeSep: null
  26617. };
  26618. }
  26619. update( camera ) {
  26620. const cache = this._cache;
  26621. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26622. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26623. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26624. if ( needsUpdate ) {
  26625. cache.focus = camera.focus;
  26626. cache.fov = camera.fov;
  26627. cache.aspect = camera.aspect * this.aspect;
  26628. cache.near = camera.near;
  26629. cache.far = camera.far;
  26630. cache.zoom = camera.zoom;
  26631. cache.eyeSep = this.eyeSep;
  26632. // Off-axis stereoscopic effect based on
  26633. // http://paulbourke.net/stereographics/stereorender/
  26634. const projectionMatrix = camera.projectionMatrix.clone();
  26635. const eyeSepHalf = cache.eyeSep / 2;
  26636. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26637. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26638. let xmin, xmax;
  26639. // translate xOffset
  26640. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26641. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26642. // for left eye
  26643. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26644. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26645. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26646. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26647. this.cameraL.projectionMatrix.copy( projectionMatrix );
  26648. // for right eye
  26649. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26650. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26651. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26652. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26653. this.cameraR.projectionMatrix.copy( projectionMatrix );
  26654. }
  26655. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26656. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26657. }
  26658. }
  26659. class Clock {
  26660. constructor( autoStart = true ) {
  26661. this.autoStart = autoStart;
  26662. this.startTime = 0;
  26663. this.oldTime = 0;
  26664. this.elapsedTime = 0;
  26665. this.running = false;
  26666. }
  26667. start() {
  26668. this.startTime = now();
  26669. this.oldTime = this.startTime;
  26670. this.elapsedTime = 0;
  26671. this.running = true;
  26672. }
  26673. stop() {
  26674. this.getElapsedTime();
  26675. this.running = false;
  26676. this.autoStart = false;
  26677. }
  26678. getElapsedTime() {
  26679. this.getDelta();
  26680. return this.elapsedTime;
  26681. }
  26682. getDelta() {
  26683. let diff = 0;
  26684. if ( this.autoStart && ! this.running ) {
  26685. this.start();
  26686. return 0;
  26687. }
  26688. if ( this.running ) {
  26689. const newTime = now();
  26690. diff = ( newTime - this.oldTime ) / 1000;
  26691. this.oldTime = newTime;
  26692. this.elapsedTime += diff;
  26693. }
  26694. return diff;
  26695. }
  26696. }
  26697. function now() {
  26698. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26699. }
  26700. const _position$1 = /*@__PURE__*/ new Vector3();
  26701. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26702. const _scale$1 = /*@__PURE__*/ new Vector3();
  26703. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26704. class AudioListener extends Object3D {
  26705. constructor() {
  26706. super();
  26707. this.type = 'AudioListener';
  26708. this.context = AudioContext.getContext();
  26709. this.gain = this.context.createGain();
  26710. this.gain.connect( this.context.destination );
  26711. this.filter = null;
  26712. this.timeDelta = 0;
  26713. // private
  26714. this._clock = new Clock();
  26715. }
  26716. getInput() {
  26717. return this.gain;
  26718. }
  26719. removeFilter() {
  26720. if ( this.filter !== null ) {
  26721. this.gain.disconnect( this.filter );
  26722. this.filter.disconnect( this.context.destination );
  26723. this.gain.connect( this.context.destination );
  26724. this.filter = null;
  26725. }
  26726. return this;
  26727. }
  26728. getFilter() {
  26729. return this.filter;
  26730. }
  26731. setFilter( value ) {
  26732. if ( this.filter !== null ) {
  26733. this.gain.disconnect( this.filter );
  26734. this.filter.disconnect( this.context.destination );
  26735. } else {
  26736. this.gain.disconnect( this.context.destination );
  26737. }
  26738. this.filter = value;
  26739. this.gain.connect( this.filter );
  26740. this.filter.connect( this.context.destination );
  26741. return this;
  26742. }
  26743. getMasterVolume() {
  26744. return this.gain.gain.value;
  26745. }
  26746. setMasterVolume( value ) {
  26747. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26748. return this;
  26749. }
  26750. updateMatrixWorld( force ) {
  26751. super.updateMatrixWorld( force );
  26752. const listener = this.context.listener;
  26753. const up = this.up;
  26754. this.timeDelta = this._clock.getDelta();
  26755. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26756. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26757. if ( listener.positionX ) {
  26758. // code path for Chrome (see #14393)
  26759. const endTime = this.context.currentTime + this.timeDelta;
  26760. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26761. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26762. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26763. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26764. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26765. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26766. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26767. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26768. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26769. } else {
  26770. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26771. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26772. }
  26773. }
  26774. }
  26775. class Audio extends Object3D {
  26776. constructor( listener ) {
  26777. super();
  26778. this.type = 'Audio';
  26779. this.listener = listener;
  26780. this.context = listener.context;
  26781. this.gain = this.context.createGain();
  26782. this.gain.connect( listener.getInput() );
  26783. this.autoplay = false;
  26784. this.buffer = null;
  26785. this.detune = 0;
  26786. this.loop = false;
  26787. this.loopStart = 0;
  26788. this.loopEnd = 0;
  26789. this.offset = 0;
  26790. this.duration = undefined;
  26791. this.playbackRate = 1;
  26792. this.isPlaying = false;
  26793. this.hasPlaybackControl = true;
  26794. this.source = null;
  26795. this.sourceType = 'empty';
  26796. this._startedAt = 0;
  26797. this._progress = 0;
  26798. this._connected = false;
  26799. this.filters = [];
  26800. }
  26801. getOutput() {
  26802. return this.gain;
  26803. }
  26804. setNodeSource( audioNode ) {
  26805. this.hasPlaybackControl = false;
  26806. this.sourceType = 'audioNode';
  26807. this.source = audioNode;
  26808. this.connect();
  26809. return this;
  26810. }
  26811. setMediaElementSource( mediaElement ) {
  26812. this.hasPlaybackControl = false;
  26813. this.sourceType = 'mediaNode';
  26814. this.source = this.context.createMediaElementSource( mediaElement );
  26815. this.connect();
  26816. return this;
  26817. }
  26818. setMediaStreamSource( mediaStream ) {
  26819. this.hasPlaybackControl = false;
  26820. this.sourceType = 'mediaStreamNode';
  26821. this.source = this.context.createMediaStreamSource( mediaStream );
  26822. this.connect();
  26823. return this;
  26824. }
  26825. setBuffer( audioBuffer ) {
  26826. this.buffer = audioBuffer;
  26827. this.sourceType = 'buffer';
  26828. if ( this.autoplay ) this.play();
  26829. return this;
  26830. }
  26831. play( delay = 0 ) {
  26832. if ( this.isPlaying === true ) {
  26833. console.warn( 'THREE.Audio: Audio is already playing.' );
  26834. return;
  26835. }
  26836. if ( this.hasPlaybackControl === false ) {
  26837. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26838. return;
  26839. }
  26840. this._startedAt = this.context.currentTime + delay;
  26841. const source = this.context.createBufferSource();
  26842. source.buffer = this.buffer;
  26843. source.loop = this.loop;
  26844. source.loopStart = this.loopStart;
  26845. source.loopEnd = this.loopEnd;
  26846. source.onended = this.onEnded.bind( this );
  26847. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26848. this.isPlaying = true;
  26849. this.source = source;
  26850. this.setDetune( this.detune );
  26851. this.setPlaybackRate( this.playbackRate );
  26852. return this.connect();
  26853. }
  26854. pause() {
  26855. if ( this.hasPlaybackControl === false ) {
  26856. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26857. return;
  26858. }
  26859. if ( this.isPlaying === true ) {
  26860. // update current progress
  26861. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26862. if ( this.loop === true ) {
  26863. // ensure _progress does not exceed duration with looped audios
  26864. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26865. }
  26866. this.source.stop();
  26867. this.source.onended = null;
  26868. this.isPlaying = false;
  26869. }
  26870. return this;
  26871. }
  26872. stop() {
  26873. if ( this.hasPlaybackControl === false ) {
  26874. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26875. return;
  26876. }
  26877. this._progress = 0;
  26878. this.source.stop();
  26879. this.source.onended = null;
  26880. this.isPlaying = false;
  26881. return this;
  26882. }
  26883. connect() {
  26884. if ( this.filters.length > 0 ) {
  26885. this.source.connect( this.filters[ 0 ] );
  26886. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26887. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26888. }
  26889. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26890. } else {
  26891. this.source.connect( this.getOutput() );
  26892. }
  26893. this._connected = true;
  26894. return this;
  26895. }
  26896. disconnect() {
  26897. if ( this.filters.length > 0 ) {
  26898. this.source.disconnect( this.filters[ 0 ] );
  26899. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26900. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26901. }
  26902. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26903. } else {
  26904. this.source.disconnect( this.getOutput() );
  26905. }
  26906. this._connected = false;
  26907. return this;
  26908. }
  26909. getFilters() {
  26910. return this.filters;
  26911. }
  26912. setFilters( value ) {
  26913. if ( ! value ) value = [];
  26914. if ( this._connected === true ) {
  26915. this.disconnect();
  26916. this.filters = value.slice();
  26917. this.connect();
  26918. } else {
  26919. this.filters = value.slice();
  26920. }
  26921. return this;
  26922. }
  26923. setDetune( value ) {
  26924. this.detune = value;
  26925. if ( this.source.detune === undefined ) return; // only set detune when available
  26926. if ( this.isPlaying === true ) {
  26927. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26928. }
  26929. return this;
  26930. }
  26931. getDetune() {
  26932. return this.detune;
  26933. }
  26934. getFilter() {
  26935. return this.getFilters()[ 0 ];
  26936. }
  26937. setFilter( filter ) {
  26938. return this.setFilters( filter ? [ filter ] : [] );
  26939. }
  26940. setPlaybackRate( value ) {
  26941. if ( this.hasPlaybackControl === false ) {
  26942. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26943. return;
  26944. }
  26945. this.playbackRate = value;
  26946. if ( this.isPlaying === true ) {
  26947. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26948. }
  26949. return this;
  26950. }
  26951. getPlaybackRate() {
  26952. return this.playbackRate;
  26953. }
  26954. onEnded() {
  26955. this.isPlaying = false;
  26956. }
  26957. getLoop() {
  26958. if ( this.hasPlaybackControl === false ) {
  26959. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26960. return false;
  26961. }
  26962. return this.loop;
  26963. }
  26964. setLoop( value ) {
  26965. if ( this.hasPlaybackControl === false ) {
  26966. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26967. return;
  26968. }
  26969. this.loop = value;
  26970. if ( this.isPlaying === true ) {
  26971. this.source.loop = this.loop;
  26972. }
  26973. return this;
  26974. }
  26975. setLoopStart( value ) {
  26976. this.loopStart = value;
  26977. return this;
  26978. }
  26979. setLoopEnd( value ) {
  26980. this.loopEnd = value;
  26981. return this;
  26982. }
  26983. getVolume() {
  26984. return this.gain.gain.value;
  26985. }
  26986. setVolume( value ) {
  26987. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26988. return this;
  26989. }
  26990. }
  26991. const _position = /*@__PURE__*/ new Vector3();
  26992. const _quaternion = /*@__PURE__*/ new Quaternion();
  26993. const _scale = /*@__PURE__*/ new Vector3();
  26994. const _orientation = /*@__PURE__*/ new Vector3();
  26995. class PositionalAudio extends Audio {
  26996. constructor( listener ) {
  26997. super( listener );
  26998. this.panner = this.context.createPanner();
  26999. this.panner.panningModel = 'HRTF';
  27000. this.panner.connect( this.gain );
  27001. }
  27002. getOutput() {
  27003. return this.panner;
  27004. }
  27005. getRefDistance() {
  27006. return this.panner.refDistance;
  27007. }
  27008. setRefDistance( value ) {
  27009. this.panner.refDistance = value;
  27010. return this;
  27011. }
  27012. getRolloffFactor() {
  27013. return this.panner.rolloffFactor;
  27014. }
  27015. setRolloffFactor( value ) {
  27016. this.panner.rolloffFactor = value;
  27017. return this;
  27018. }
  27019. getDistanceModel() {
  27020. return this.panner.distanceModel;
  27021. }
  27022. setDistanceModel( value ) {
  27023. this.panner.distanceModel = value;
  27024. return this;
  27025. }
  27026. getMaxDistance() {
  27027. return this.panner.maxDistance;
  27028. }
  27029. setMaxDistance( value ) {
  27030. this.panner.maxDistance = value;
  27031. return this;
  27032. }
  27033. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  27034. this.panner.coneInnerAngle = coneInnerAngle;
  27035. this.panner.coneOuterAngle = coneOuterAngle;
  27036. this.panner.coneOuterGain = coneOuterGain;
  27037. return this;
  27038. }
  27039. updateMatrixWorld( force ) {
  27040. super.updateMatrixWorld( force );
  27041. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  27042. this.matrixWorld.decompose( _position, _quaternion, _scale );
  27043. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  27044. const panner = this.panner;
  27045. if ( panner.positionX ) {
  27046. // code path for Chrome and Firefox (see #14393)
  27047. const endTime = this.context.currentTime + this.listener.timeDelta;
  27048. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  27049. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  27050. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  27051. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  27052. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  27053. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  27054. } else {
  27055. panner.setPosition( _position.x, _position.y, _position.z );
  27056. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  27057. }
  27058. }
  27059. }
  27060. class AudioAnalyser {
  27061. constructor( audio, fftSize = 2048 ) {
  27062. this.analyser = audio.context.createAnalyser();
  27063. this.analyser.fftSize = fftSize;
  27064. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  27065. audio.getOutput().connect( this.analyser );
  27066. }
  27067. getFrequencyData() {
  27068. this.analyser.getByteFrequencyData( this.data );
  27069. return this.data;
  27070. }
  27071. getAverageFrequency() {
  27072. let value = 0;
  27073. const data = this.getFrequencyData();
  27074. for ( let i = 0; i < data.length; i ++ ) {
  27075. value += data[ i ];
  27076. }
  27077. return value / data.length;
  27078. }
  27079. }
  27080. class PropertyMixer {
  27081. constructor( binding, typeName, valueSize ) {
  27082. this.binding = binding;
  27083. this.valueSize = valueSize;
  27084. let mixFunction,
  27085. mixFunctionAdditive,
  27086. setIdentity;
  27087. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  27088. //
  27089. // interpolators can use .buffer as their .result
  27090. // the data then goes to 'incoming'
  27091. //
  27092. // 'accu0' and 'accu1' are used frame-interleaved for
  27093. // the cumulative result and are compared to detect
  27094. // changes
  27095. //
  27096. // 'orig' stores the original state of the property
  27097. //
  27098. // 'add' is used for additive cumulative results
  27099. //
  27100. // 'work' is optional and is only present for quaternion types. It is used
  27101. // to store intermediate quaternion multiplication results
  27102. switch ( typeName ) {
  27103. case 'quaternion':
  27104. mixFunction = this._slerp;
  27105. mixFunctionAdditive = this._slerpAdditive;
  27106. setIdentity = this._setAdditiveIdentityQuaternion;
  27107. this.buffer = new Float64Array( valueSize * 6 );
  27108. this._workIndex = 5;
  27109. break;
  27110. case 'string':
  27111. case 'bool':
  27112. mixFunction = this._select;
  27113. // Use the regular mix function and for additive on these types,
  27114. // additive is not relevant for non-numeric types
  27115. mixFunctionAdditive = this._select;
  27116. setIdentity = this._setAdditiveIdentityOther;
  27117. this.buffer = new Array( valueSize * 5 );
  27118. break;
  27119. default:
  27120. mixFunction = this._lerp;
  27121. mixFunctionAdditive = this._lerpAdditive;
  27122. setIdentity = this._setAdditiveIdentityNumeric;
  27123. this.buffer = new Float64Array( valueSize * 5 );
  27124. }
  27125. this._mixBufferRegion = mixFunction;
  27126. this._mixBufferRegionAdditive = mixFunctionAdditive;
  27127. this._setIdentity = setIdentity;
  27128. this._origIndex = 3;
  27129. this._addIndex = 4;
  27130. this.cumulativeWeight = 0;
  27131. this.cumulativeWeightAdditive = 0;
  27132. this.useCount = 0;
  27133. this.referenceCount = 0;
  27134. }
  27135. // accumulate data in the 'incoming' region into 'accu<i>'
  27136. accumulate( accuIndex, weight ) {
  27137. // note: happily accumulating nothing when weight = 0, the caller knows
  27138. // the weight and shouldn't have made the call in the first place
  27139. const buffer = this.buffer,
  27140. stride = this.valueSize,
  27141. offset = accuIndex * stride + stride;
  27142. let currentWeight = this.cumulativeWeight;
  27143. if ( currentWeight === 0 ) {
  27144. // accuN := incoming * weight
  27145. for ( let i = 0; i !== stride; ++ i ) {
  27146. buffer[ offset + i ] = buffer[ i ];
  27147. }
  27148. currentWeight = weight;
  27149. } else {
  27150. // accuN := accuN + incoming * weight
  27151. currentWeight += weight;
  27152. const mix = weight / currentWeight;
  27153. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27154. }
  27155. this.cumulativeWeight = currentWeight;
  27156. }
  27157. // accumulate data in the 'incoming' region into 'add'
  27158. accumulateAdditive( weight ) {
  27159. const buffer = this.buffer,
  27160. stride = this.valueSize,
  27161. offset = stride * this._addIndex;
  27162. if ( this.cumulativeWeightAdditive === 0 ) {
  27163. // add = identity
  27164. this._setIdentity();
  27165. }
  27166. // add := add + incoming * weight
  27167. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  27168. this.cumulativeWeightAdditive += weight;
  27169. }
  27170. // apply the state of 'accu<i>' to the binding when accus differ
  27171. apply( accuIndex ) {
  27172. const stride = this.valueSize,
  27173. buffer = this.buffer,
  27174. offset = accuIndex * stride + stride,
  27175. weight = this.cumulativeWeight,
  27176. weightAdditive = this.cumulativeWeightAdditive,
  27177. binding = this.binding;
  27178. this.cumulativeWeight = 0;
  27179. this.cumulativeWeightAdditive = 0;
  27180. if ( weight < 1 ) {
  27181. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27182. const originalValueOffset = stride * this._origIndex;
  27183. this._mixBufferRegion(
  27184. buffer, offset, originalValueOffset, 1 - weight, stride );
  27185. }
  27186. if ( weightAdditive > 0 ) {
  27187. // accuN := accuN + additive accuN
  27188. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  27189. }
  27190. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  27191. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27192. // value has changed -> update scene graph
  27193. binding.setValue( buffer, offset );
  27194. break;
  27195. }
  27196. }
  27197. }
  27198. // remember the state of the bound property and copy it to both accus
  27199. saveOriginalState() {
  27200. const binding = this.binding;
  27201. const buffer = this.buffer,
  27202. stride = this.valueSize,
  27203. originalValueOffset = stride * this._origIndex;
  27204. binding.getValue( buffer, originalValueOffset );
  27205. // accu[0..1] := orig -- initially detect changes against the original
  27206. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27207. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27208. }
  27209. // Add to identity for additive
  27210. this._setIdentity();
  27211. this.cumulativeWeight = 0;
  27212. this.cumulativeWeightAdditive = 0;
  27213. }
  27214. // apply the state previously taken via 'saveOriginalState' to the binding
  27215. restoreOriginalState() {
  27216. const originalValueOffset = this.valueSize * 3;
  27217. this.binding.setValue( this.buffer, originalValueOffset );
  27218. }
  27219. _setAdditiveIdentityNumeric() {
  27220. const startIndex = this._addIndex * this.valueSize;
  27221. const endIndex = startIndex + this.valueSize;
  27222. for ( let i = startIndex; i < endIndex; i ++ ) {
  27223. this.buffer[ i ] = 0;
  27224. }
  27225. }
  27226. _setAdditiveIdentityQuaternion() {
  27227. this._setAdditiveIdentityNumeric();
  27228. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  27229. }
  27230. _setAdditiveIdentityOther() {
  27231. const startIndex = this._origIndex * this.valueSize;
  27232. const targetIndex = this._addIndex * this.valueSize;
  27233. for ( let i = 0; i < this.valueSize; i ++ ) {
  27234. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  27235. }
  27236. }
  27237. // mix functions
  27238. _select( buffer, dstOffset, srcOffset, t, stride ) {
  27239. if ( t >= 0.5 ) {
  27240. for ( let i = 0; i !== stride; ++ i ) {
  27241. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27242. }
  27243. }
  27244. }
  27245. _slerp( buffer, dstOffset, srcOffset, t ) {
  27246. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27247. }
  27248. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27249. const workOffset = this._workIndex * stride;
  27250. // Store result in intermediate buffer offset
  27251. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  27252. // Slerp to the intermediate result
  27253. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  27254. }
  27255. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  27256. const s = 1 - t;
  27257. for ( let i = 0; i !== stride; ++ i ) {
  27258. const j = dstOffset + i;
  27259. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27260. }
  27261. }
  27262. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27263. for ( let i = 0; i !== stride; ++ i ) {
  27264. const j = dstOffset + i;
  27265. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  27266. }
  27267. }
  27268. }
  27269. // Characters [].:/ are reserved for track binding syntax.
  27270. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27271. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27272. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27273. // only latin characters, and the unicode \p{L} is not yet supported. So
  27274. // instead, we exclude reserved characters and match everything else.
  27275. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27276. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27277. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27278. // be matched to parse the rest of the track name.
  27279. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27280. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27281. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27282. // Object on target node, and accessor. May not contain reserved
  27283. // characters. Accessor may contain any character except closing bracket.
  27284. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27285. // Property and accessor. May not contain reserved characters. Accessor may
  27286. // contain any non-bracket characters.
  27287. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27288. const _trackRe = new RegExp( ''
  27289. + '^'
  27290. + _directoryRe
  27291. + _nodeRe
  27292. + _objectRe
  27293. + _propertyRe
  27294. + '$'
  27295. );
  27296. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  27297. class Composite {
  27298. constructor( targetGroup, path, optionalParsedPath ) {
  27299. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27300. this._targetGroup = targetGroup;
  27301. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27302. }
  27303. getValue( array, offset ) {
  27304. this.bind(); // bind all binding
  27305. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27306. binding = this._bindings[ firstValidIndex ];
  27307. // and only call .getValue on the first
  27308. if ( binding !== undefined ) binding.getValue( array, offset );
  27309. }
  27310. setValue( array, offset ) {
  27311. const bindings = this._bindings;
  27312. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27313. bindings[ i ].setValue( array, offset );
  27314. }
  27315. }
  27316. bind() {
  27317. const bindings = this._bindings;
  27318. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27319. bindings[ i ].bind();
  27320. }
  27321. }
  27322. unbind() {
  27323. const bindings = this._bindings;
  27324. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27325. bindings[ i ].unbind();
  27326. }
  27327. }
  27328. }
  27329. // Note: This class uses a State pattern on a per-method basis:
  27330. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27331. // prototype version of these methods with one that represents
  27332. // the bound state. When the property is not found, the methods
  27333. // become no-ops.
  27334. class PropertyBinding {
  27335. constructor( rootNode, path, parsedPath ) {
  27336. this.path = path;
  27337. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27338. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  27339. this.rootNode = rootNode;
  27340. // initial state of these methods that calls 'bind'
  27341. this.getValue = this._getValue_unbound;
  27342. this.setValue = this._setValue_unbound;
  27343. }
  27344. static create( root, path, parsedPath ) {
  27345. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27346. return new PropertyBinding( root, path, parsedPath );
  27347. } else {
  27348. return new PropertyBinding.Composite( root, path, parsedPath );
  27349. }
  27350. }
  27351. /**
  27352. * Replaces spaces with underscores and removes unsupported characters from
  27353. * node names, to ensure compatibility with parseTrackName().
  27354. *
  27355. * @param {string} name Node name to be sanitized.
  27356. * @return {string}
  27357. */
  27358. static sanitizeNodeName( name ) {
  27359. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27360. }
  27361. static parseTrackName( trackName ) {
  27362. const matches = _trackRe.exec( trackName );
  27363. if ( ! matches ) {
  27364. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27365. }
  27366. const results = {
  27367. // directoryName: matches[ 1 ], // (tschw) currently unused
  27368. nodeName: matches[ 2 ],
  27369. objectName: matches[ 3 ],
  27370. objectIndex: matches[ 4 ],
  27371. propertyName: matches[ 5 ], // required
  27372. propertyIndex: matches[ 6 ]
  27373. };
  27374. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27375. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27376. const objectName = results.nodeName.substring( lastDot + 1 );
  27377. // Object names must be checked against an allowlist. Otherwise, there
  27378. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27379. // 'bar' could be the objectName, or part of a nodeName (which can
  27380. // include '.' characters).
  27381. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27382. results.nodeName = results.nodeName.substring( 0, lastDot );
  27383. results.objectName = objectName;
  27384. }
  27385. }
  27386. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27387. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27388. }
  27389. return results;
  27390. }
  27391. static findNode( root, nodeName ) {
  27392. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27393. return root;
  27394. }
  27395. // search into skeleton bones.
  27396. if ( root.skeleton ) {
  27397. const bone = root.skeleton.getBoneByName( nodeName );
  27398. if ( bone !== undefined ) {
  27399. return bone;
  27400. }
  27401. }
  27402. // search into node subtree.
  27403. if ( root.children ) {
  27404. const searchNodeSubtree = function ( children ) {
  27405. for ( let i = 0; i < children.length; i ++ ) {
  27406. const childNode = children[ i ];
  27407. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27408. return childNode;
  27409. }
  27410. const result = searchNodeSubtree( childNode.children );
  27411. if ( result ) return result;
  27412. }
  27413. return null;
  27414. };
  27415. const subTreeNode = searchNodeSubtree( root.children );
  27416. if ( subTreeNode ) {
  27417. return subTreeNode;
  27418. }
  27419. }
  27420. return null;
  27421. }
  27422. // these are used to "bind" a nonexistent property
  27423. _getValue_unavailable() {}
  27424. _setValue_unavailable() {}
  27425. // Getters
  27426. _getValue_direct( buffer, offset ) {
  27427. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27428. }
  27429. _getValue_array( buffer, offset ) {
  27430. const source = this.resolvedProperty;
  27431. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27432. buffer[ offset ++ ] = source[ i ];
  27433. }
  27434. }
  27435. _getValue_arrayElement( buffer, offset ) {
  27436. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27437. }
  27438. _getValue_toArray( buffer, offset ) {
  27439. this.resolvedProperty.toArray( buffer, offset );
  27440. }
  27441. // Direct
  27442. _setValue_direct( buffer, offset ) {
  27443. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27444. }
  27445. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27446. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27447. this.targetObject.needsUpdate = true;
  27448. }
  27449. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27450. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27451. this.targetObject.matrixWorldNeedsUpdate = true;
  27452. }
  27453. // EntireArray
  27454. _setValue_array( buffer, offset ) {
  27455. const dest = this.resolvedProperty;
  27456. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27457. dest[ i ] = buffer[ offset ++ ];
  27458. }
  27459. }
  27460. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27461. const dest = this.resolvedProperty;
  27462. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27463. dest[ i ] = buffer[ offset ++ ];
  27464. }
  27465. this.targetObject.needsUpdate = true;
  27466. }
  27467. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27468. const dest = this.resolvedProperty;
  27469. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27470. dest[ i ] = buffer[ offset ++ ];
  27471. }
  27472. this.targetObject.matrixWorldNeedsUpdate = true;
  27473. }
  27474. // ArrayElement
  27475. _setValue_arrayElement( buffer, offset ) {
  27476. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27477. }
  27478. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27479. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27480. this.targetObject.needsUpdate = true;
  27481. }
  27482. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27483. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27484. this.targetObject.matrixWorldNeedsUpdate = true;
  27485. }
  27486. // HasToFromArray
  27487. _setValue_fromArray( buffer, offset ) {
  27488. this.resolvedProperty.fromArray( buffer, offset );
  27489. }
  27490. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27491. this.resolvedProperty.fromArray( buffer, offset );
  27492. this.targetObject.needsUpdate = true;
  27493. }
  27494. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27495. this.resolvedProperty.fromArray( buffer, offset );
  27496. this.targetObject.matrixWorldNeedsUpdate = true;
  27497. }
  27498. _getValue_unbound( targetArray, offset ) {
  27499. this.bind();
  27500. this.getValue( targetArray, offset );
  27501. }
  27502. _setValue_unbound( sourceArray, offset ) {
  27503. this.bind();
  27504. this.setValue( sourceArray, offset );
  27505. }
  27506. // create getter / setter pair for a property in the scene graph
  27507. bind() {
  27508. let targetObject = this.node;
  27509. const parsedPath = this.parsedPath;
  27510. const objectName = parsedPath.objectName;
  27511. const propertyName = parsedPath.propertyName;
  27512. let propertyIndex = parsedPath.propertyIndex;
  27513. if ( ! targetObject ) {
  27514. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  27515. this.node = targetObject;
  27516. }
  27517. // set fail state so we can just 'return' on error
  27518. this.getValue = this._getValue_unavailable;
  27519. this.setValue = this._setValue_unavailable;
  27520. // ensure there is a value node
  27521. if ( ! targetObject ) {
  27522. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27523. return;
  27524. }
  27525. if ( objectName ) {
  27526. let objectIndex = parsedPath.objectIndex;
  27527. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27528. switch ( objectName ) {
  27529. case 'materials':
  27530. if ( ! targetObject.material ) {
  27531. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27532. return;
  27533. }
  27534. if ( ! targetObject.material.materials ) {
  27535. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27536. return;
  27537. }
  27538. targetObject = targetObject.material.materials;
  27539. break;
  27540. case 'bones':
  27541. if ( ! targetObject.skeleton ) {
  27542. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27543. return;
  27544. }
  27545. // potential future optimization: skip this if propertyIndex is already an integer
  27546. // and convert the integer string to a true integer.
  27547. targetObject = targetObject.skeleton.bones;
  27548. // support resolving morphTarget names into indices.
  27549. for ( let i = 0; i < targetObject.length; i ++ ) {
  27550. if ( targetObject[ i ].name === objectIndex ) {
  27551. objectIndex = i;
  27552. break;
  27553. }
  27554. }
  27555. break;
  27556. default:
  27557. if ( targetObject[ objectName ] === undefined ) {
  27558. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27559. return;
  27560. }
  27561. targetObject = targetObject[ objectName ];
  27562. }
  27563. if ( objectIndex !== undefined ) {
  27564. if ( targetObject[ objectIndex ] === undefined ) {
  27565. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27566. return;
  27567. }
  27568. targetObject = targetObject[ objectIndex ];
  27569. }
  27570. }
  27571. // resolve property
  27572. const nodeProperty = targetObject[ propertyName ];
  27573. if ( nodeProperty === undefined ) {
  27574. const nodeName = parsedPath.nodeName;
  27575. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27576. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27577. return;
  27578. }
  27579. // determine versioning scheme
  27580. let versioning = this.Versioning.None;
  27581. this.targetObject = targetObject;
  27582. if ( targetObject.needsUpdate !== undefined ) { // material
  27583. versioning = this.Versioning.NeedsUpdate;
  27584. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27585. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27586. }
  27587. // determine how the property gets bound
  27588. let bindingType = this.BindingType.Direct;
  27589. if ( propertyIndex !== undefined ) {
  27590. // access a sub element of the property array (only primitives are supported right now)
  27591. if ( propertyName === 'morphTargetInfluences' ) {
  27592. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27593. // support resolving morphTarget names into indices.
  27594. if ( ! targetObject.geometry ) {
  27595. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27596. return;
  27597. }
  27598. if ( targetObject.geometry.isBufferGeometry ) {
  27599. if ( ! targetObject.geometry.morphAttributes ) {
  27600. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27601. return;
  27602. }
  27603. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27604. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27605. }
  27606. } else {
  27607. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  27608. return;
  27609. }
  27610. }
  27611. bindingType = this.BindingType.ArrayElement;
  27612. this.resolvedProperty = nodeProperty;
  27613. this.propertyIndex = propertyIndex;
  27614. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27615. // must use copy for Object3D.Euler/Quaternion
  27616. bindingType = this.BindingType.HasFromToArray;
  27617. this.resolvedProperty = nodeProperty;
  27618. } else if ( Array.isArray( nodeProperty ) ) {
  27619. bindingType = this.BindingType.EntireArray;
  27620. this.resolvedProperty = nodeProperty;
  27621. } else {
  27622. this.propertyName = propertyName;
  27623. }
  27624. // select getter / setter
  27625. this.getValue = this.GetterByBindingType[ bindingType ];
  27626. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27627. }
  27628. unbind() {
  27629. this.node = null;
  27630. // back to the prototype version of getValue / setValue
  27631. // note: avoiding to mutate the shape of 'this' via 'delete'
  27632. this.getValue = this._getValue_unbound;
  27633. this.setValue = this._setValue_unbound;
  27634. }
  27635. }
  27636. PropertyBinding.Composite = Composite;
  27637. PropertyBinding.prototype.BindingType = {
  27638. Direct: 0,
  27639. EntireArray: 1,
  27640. ArrayElement: 2,
  27641. HasFromToArray: 3
  27642. };
  27643. PropertyBinding.prototype.Versioning = {
  27644. None: 0,
  27645. NeedsUpdate: 1,
  27646. MatrixWorldNeedsUpdate: 2
  27647. };
  27648. PropertyBinding.prototype.GetterByBindingType = [
  27649. PropertyBinding.prototype._getValue_direct,
  27650. PropertyBinding.prototype._getValue_array,
  27651. PropertyBinding.prototype._getValue_arrayElement,
  27652. PropertyBinding.prototype._getValue_toArray,
  27653. ];
  27654. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27655. [
  27656. // Direct
  27657. PropertyBinding.prototype._setValue_direct,
  27658. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27659. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27660. ], [
  27661. // EntireArray
  27662. PropertyBinding.prototype._setValue_array,
  27663. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27664. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27665. ], [
  27666. // ArrayElement
  27667. PropertyBinding.prototype._setValue_arrayElement,
  27668. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27669. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27670. ], [
  27671. // HasToFromArray
  27672. PropertyBinding.prototype._setValue_fromArray,
  27673. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27674. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27675. ]
  27676. ];
  27677. /**
  27678. *
  27679. * A group of objects that receives a shared animation state.
  27680. *
  27681. * Usage:
  27682. *
  27683. * - Add objects you would otherwise pass as 'root' to the
  27684. * constructor or the .clipAction method of AnimationMixer.
  27685. *
  27686. * - Instead pass this object as 'root'.
  27687. *
  27688. * - You can also add and remove objects later when the mixer
  27689. * is running.
  27690. *
  27691. * Note:
  27692. *
  27693. * Objects of this class appear as one object to the mixer,
  27694. * so cache control of the individual objects must be done
  27695. * on the group.
  27696. *
  27697. * Limitation:
  27698. *
  27699. * - The animated properties must be compatible among the
  27700. * all objects in the group.
  27701. *
  27702. * - A single property can either be controlled through a
  27703. * target group or directly, but not both.
  27704. */
  27705. class AnimationObjectGroup {
  27706. constructor() {
  27707. this.uuid = generateUUID();
  27708. // cached objects followed by the active ones
  27709. this._objects = Array.prototype.slice.call( arguments );
  27710. this.nCachedObjects_ = 0; // threshold
  27711. // note: read by PropertyBinding.Composite
  27712. const indices = {};
  27713. this._indicesByUUID = indices; // for bookkeeping
  27714. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27715. indices[ arguments[ i ].uuid ] = i;
  27716. }
  27717. this._paths = []; // inside: string
  27718. this._parsedPaths = []; // inside: { we don't care, here }
  27719. this._bindings = []; // inside: Array< PropertyBinding >
  27720. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27721. const scope = this;
  27722. this.stats = {
  27723. objects: {
  27724. get total() {
  27725. return scope._objects.length;
  27726. },
  27727. get inUse() {
  27728. return this.total - scope.nCachedObjects_;
  27729. }
  27730. },
  27731. get bindingsPerObject() {
  27732. return scope._bindings.length;
  27733. }
  27734. };
  27735. }
  27736. add() {
  27737. const objects = this._objects,
  27738. indicesByUUID = this._indicesByUUID,
  27739. paths = this._paths,
  27740. parsedPaths = this._parsedPaths,
  27741. bindings = this._bindings,
  27742. nBindings = bindings.length;
  27743. let knownObject = undefined,
  27744. nObjects = objects.length,
  27745. nCachedObjects = this.nCachedObjects_;
  27746. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27747. const object = arguments[ i ],
  27748. uuid = object.uuid;
  27749. let index = indicesByUUID[ uuid ];
  27750. if ( index === undefined ) {
  27751. // unknown object -> add it to the ACTIVE region
  27752. index = nObjects ++;
  27753. indicesByUUID[ uuid ] = index;
  27754. objects.push( object );
  27755. // accounting is done, now do the same for all bindings
  27756. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27757. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27758. }
  27759. } else if ( index < nCachedObjects ) {
  27760. knownObject = objects[ index ];
  27761. // move existing object to the ACTIVE region
  27762. const firstActiveIndex = -- nCachedObjects,
  27763. lastCachedObject = objects[ firstActiveIndex ];
  27764. indicesByUUID[ lastCachedObject.uuid ] = index;
  27765. objects[ index ] = lastCachedObject;
  27766. indicesByUUID[ uuid ] = firstActiveIndex;
  27767. objects[ firstActiveIndex ] = object;
  27768. // accounting is done, now do the same for all bindings
  27769. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27770. const bindingsForPath = bindings[ j ],
  27771. lastCached = bindingsForPath[ firstActiveIndex ];
  27772. let binding = bindingsForPath[ index ];
  27773. bindingsForPath[ index ] = lastCached;
  27774. if ( binding === undefined ) {
  27775. // since we do not bother to create new bindings
  27776. // for objects that are cached, the binding may
  27777. // or may not exist
  27778. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27779. }
  27780. bindingsForPath[ firstActiveIndex ] = binding;
  27781. }
  27782. } else if ( objects[ index ] !== knownObject ) {
  27783. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27784. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27785. } // else the object is already where we want it to be
  27786. } // for arguments
  27787. this.nCachedObjects_ = nCachedObjects;
  27788. }
  27789. remove() {
  27790. const objects = this._objects,
  27791. indicesByUUID = this._indicesByUUID,
  27792. bindings = this._bindings,
  27793. nBindings = bindings.length;
  27794. let nCachedObjects = this.nCachedObjects_;
  27795. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27796. const object = arguments[ i ],
  27797. uuid = object.uuid,
  27798. index = indicesByUUID[ uuid ];
  27799. if ( index !== undefined && index >= nCachedObjects ) {
  27800. // move existing object into the CACHED region
  27801. const lastCachedIndex = nCachedObjects ++,
  27802. firstActiveObject = objects[ lastCachedIndex ];
  27803. indicesByUUID[ firstActiveObject.uuid ] = index;
  27804. objects[ index ] = firstActiveObject;
  27805. indicesByUUID[ uuid ] = lastCachedIndex;
  27806. objects[ lastCachedIndex ] = object;
  27807. // accounting is done, now do the same for all bindings
  27808. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27809. const bindingsForPath = bindings[ j ],
  27810. firstActive = bindingsForPath[ lastCachedIndex ],
  27811. binding = bindingsForPath[ index ];
  27812. bindingsForPath[ index ] = firstActive;
  27813. bindingsForPath[ lastCachedIndex ] = binding;
  27814. }
  27815. }
  27816. } // for arguments
  27817. this.nCachedObjects_ = nCachedObjects;
  27818. }
  27819. // remove & forget
  27820. uncache() {
  27821. const objects = this._objects,
  27822. indicesByUUID = this._indicesByUUID,
  27823. bindings = this._bindings,
  27824. nBindings = bindings.length;
  27825. let nCachedObjects = this.nCachedObjects_,
  27826. nObjects = objects.length;
  27827. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27828. const object = arguments[ i ],
  27829. uuid = object.uuid,
  27830. index = indicesByUUID[ uuid ];
  27831. if ( index !== undefined ) {
  27832. delete indicesByUUID[ uuid ];
  27833. if ( index < nCachedObjects ) {
  27834. // object is cached, shrink the CACHED region
  27835. const firstActiveIndex = -- nCachedObjects,
  27836. lastCachedObject = objects[ firstActiveIndex ],
  27837. lastIndex = -- nObjects,
  27838. lastObject = objects[ lastIndex ];
  27839. // last cached object takes this object's place
  27840. indicesByUUID[ lastCachedObject.uuid ] = index;
  27841. objects[ index ] = lastCachedObject;
  27842. // last object goes to the activated slot and pop
  27843. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27844. objects[ firstActiveIndex ] = lastObject;
  27845. objects.pop();
  27846. // accounting is done, now do the same for all bindings
  27847. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27848. const bindingsForPath = bindings[ j ],
  27849. lastCached = bindingsForPath[ firstActiveIndex ],
  27850. last = bindingsForPath[ lastIndex ];
  27851. bindingsForPath[ index ] = lastCached;
  27852. bindingsForPath[ firstActiveIndex ] = last;
  27853. bindingsForPath.pop();
  27854. }
  27855. } else {
  27856. // object is active, just swap with the last and pop
  27857. const lastIndex = -- nObjects,
  27858. lastObject = objects[ lastIndex ];
  27859. if ( lastIndex > 0 ) {
  27860. indicesByUUID[ lastObject.uuid ] = index;
  27861. }
  27862. objects[ index ] = lastObject;
  27863. objects.pop();
  27864. // accounting is done, now do the same for all bindings
  27865. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27866. const bindingsForPath = bindings[ j ];
  27867. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27868. bindingsForPath.pop();
  27869. }
  27870. } // cached or active
  27871. } // if object is known
  27872. } // for arguments
  27873. this.nCachedObjects_ = nCachedObjects;
  27874. }
  27875. // Internal interface used by befriended PropertyBinding.Composite:
  27876. subscribe_( path, parsedPath ) {
  27877. // returns an array of bindings for the given path that is changed
  27878. // according to the contained objects in the group
  27879. const indicesByPath = this._bindingsIndicesByPath;
  27880. let index = indicesByPath[ path ];
  27881. const bindings = this._bindings;
  27882. if ( index !== undefined ) return bindings[ index ];
  27883. const paths = this._paths,
  27884. parsedPaths = this._parsedPaths,
  27885. objects = this._objects,
  27886. nObjects = objects.length,
  27887. nCachedObjects = this.nCachedObjects_,
  27888. bindingsForPath = new Array( nObjects );
  27889. index = bindings.length;
  27890. indicesByPath[ path ] = index;
  27891. paths.push( path );
  27892. parsedPaths.push( parsedPath );
  27893. bindings.push( bindingsForPath );
  27894. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27895. const object = objects[ i ];
  27896. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27897. }
  27898. return bindingsForPath;
  27899. }
  27900. unsubscribe_( path ) {
  27901. // tells the group to forget about a property path and no longer
  27902. // update the array previously obtained with 'subscribe_'
  27903. const indicesByPath = this._bindingsIndicesByPath,
  27904. index = indicesByPath[ path ];
  27905. if ( index !== undefined ) {
  27906. const paths = this._paths,
  27907. parsedPaths = this._parsedPaths,
  27908. bindings = this._bindings,
  27909. lastBindingsIndex = bindings.length - 1,
  27910. lastBindings = bindings[ lastBindingsIndex ],
  27911. lastBindingsPath = path[ lastBindingsIndex ];
  27912. indicesByPath[ lastBindingsPath ] = index;
  27913. bindings[ index ] = lastBindings;
  27914. bindings.pop();
  27915. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27916. parsedPaths.pop();
  27917. paths[ index ] = paths[ lastBindingsIndex ];
  27918. paths.pop();
  27919. }
  27920. }
  27921. }
  27922. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  27923. class AnimationAction {
  27924. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27925. this._mixer = mixer;
  27926. this._clip = clip;
  27927. this._localRoot = localRoot;
  27928. this.blendMode = blendMode;
  27929. const tracks = clip.tracks,
  27930. nTracks = tracks.length,
  27931. interpolants = new Array( nTracks );
  27932. const interpolantSettings = {
  27933. endingStart: ZeroCurvatureEnding,
  27934. endingEnd: ZeroCurvatureEnding
  27935. };
  27936. for ( let i = 0; i !== nTracks; ++ i ) {
  27937. const interpolant = tracks[ i ].createInterpolant( null );
  27938. interpolants[ i ] = interpolant;
  27939. interpolant.settings = interpolantSettings;
  27940. }
  27941. this._interpolantSettings = interpolantSettings;
  27942. this._interpolants = interpolants; // bound by the mixer
  27943. // inside: PropertyMixer (managed by the mixer)
  27944. this._propertyBindings = new Array( nTracks );
  27945. this._cacheIndex = null; // for the memory manager
  27946. this._byClipCacheIndex = null; // for the memory manager
  27947. this._timeScaleInterpolant = null;
  27948. this._weightInterpolant = null;
  27949. this.loop = LoopRepeat;
  27950. this._loopCount = - 1;
  27951. // global mixer time when the action is to be started
  27952. // it's set back to 'null' upon start of the action
  27953. this._startTime = null;
  27954. // scaled local time of the action
  27955. // gets clamped or wrapped to 0..clip.duration according to loop
  27956. this.time = 0;
  27957. this.timeScale = 1;
  27958. this._effectiveTimeScale = 1;
  27959. this.weight = 1;
  27960. this._effectiveWeight = 1;
  27961. this.repetitions = Infinity; // no. of repetitions when looping
  27962. this.paused = false; // true -> zero effective time scale
  27963. this.enabled = true; // false -> zero effective weight
  27964. this.clampWhenFinished = false;// keep feeding the last frame?
  27965. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27966. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27967. }
  27968. // State & Scheduling
  27969. play() {
  27970. this._mixer._activateAction( this );
  27971. return this;
  27972. }
  27973. stop() {
  27974. this._mixer._deactivateAction( this );
  27975. return this.reset();
  27976. }
  27977. reset() {
  27978. this.paused = false;
  27979. this.enabled = true;
  27980. this.time = 0; // restart clip
  27981. this._loopCount = - 1;// forget previous loops
  27982. this._startTime = null;// forget scheduling
  27983. return this.stopFading().stopWarping();
  27984. }
  27985. isRunning() {
  27986. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27987. this._startTime === null && this._mixer._isActiveAction( this );
  27988. }
  27989. // return true when play has been called
  27990. isScheduled() {
  27991. return this._mixer._isActiveAction( this );
  27992. }
  27993. startAt( time ) {
  27994. this._startTime = time;
  27995. return this;
  27996. }
  27997. setLoop( mode, repetitions ) {
  27998. this.loop = mode;
  27999. this.repetitions = repetitions;
  28000. return this;
  28001. }
  28002. // Weight
  28003. // set the weight stopping any scheduled fading
  28004. // although .enabled = false yields an effective weight of zero, this
  28005. // method does *not* change .enabled, because it would be confusing
  28006. setEffectiveWeight( weight ) {
  28007. this.weight = weight;
  28008. // note: same logic as when updated at runtime
  28009. this._effectiveWeight = this.enabled ? weight : 0;
  28010. return this.stopFading();
  28011. }
  28012. // return the weight considering fading and .enabled
  28013. getEffectiveWeight() {
  28014. return this._effectiveWeight;
  28015. }
  28016. fadeIn( duration ) {
  28017. return this._scheduleFading( duration, 0, 1 );
  28018. }
  28019. fadeOut( duration ) {
  28020. return this._scheduleFading( duration, 1, 0 );
  28021. }
  28022. crossFadeFrom( fadeOutAction, duration, warp ) {
  28023. fadeOutAction.fadeOut( duration );
  28024. this.fadeIn( duration );
  28025. if ( warp ) {
  28026. const fadeInDuration = this._clip.duration,
  28027. fadeOutDuration = fadeOutAction._clip.duration,
  28028. startEndRatio = fadeOutDuration / fadeInDuration,
  28029. endStartRatio = fadeInDuration / fadeOutDuration;
  28030. fadeOutAction.warp( 1.0, startEndRatio, duration );
  28031. this.warp( endStartRatio, 1.0, duration );
  28032. }
  28033. return this;
  28034. }
  28035. crossFadeTo( fadeInAction, duration, warp ) {
  28036. return fadeInAction.crossFadeFrom( this, duration, warp );
  28037. }
  28038. stopFading() {
  28039. const weightInterpolant = this._weightInterpolant;
  28040. if ( weightInterpolant !== null ) {
  28041. this._weightInterpolant = null;
  28042. this._mixer._takeBackControlInterpolant( weightInterpolant );
  28043. }
  28044. return this;
  28045. }
  28046. // Time Scale Control
  28047. // set the time scale stopping any scheduled warping
  28048. // although .paused = true yields an effective time scale of zero, this
  28049. // method does *not* change .paused, because it would be confusing
  28050. setEffectiveTimeScale( timeScale ) {
  28051. this.timeScale = timeScale;
  28052. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  28053. return this.stopWarping();
  28054. }
  28055. // return the time scale considering warping and .paused
  28056. getEffectiveTimeScale() {
  28057. return this._effectiveTimeScale;
  28058. }
  28059. setDuration( duration ) {
  28060. this.timeScale = this._clip.duration / duration;
  28061. return this.stopWarping();
  28062. }
  28063. syncWith( action ) {
  28064. this.time = action.time;
  28065. this.timeScale = action.timeScale;
  28066. return this.stopWarping();
  28067. }
  28068. halt( duration ) {
  28069. return this.warp( this._effectiveTimeScale, 0, duration );
  28070. }
  28071. warp( startTimeScale, endTimeScale, duration ) {
  28072. const mixer = this._mixer,
  28073. now = mixer.time,
  28074. timeScale = this.timeScale;
  28075. let interpolant = this._timeScaleInterpolant;
  28076. if ( interpolant === null ) {
  28077. interpolant = mixer._lendControlInterpolant();
  28078. this._timeScaleInterpolant = interpolant;
  28079. }
  28080. const times = interpolant.parameterPositions,
  28081. values = interpolant.sampleValues;
  28082. times[ 0 ] = now;
  28083. times[ 1 ] = now + duration;
  28084. values[ 0 ] = startTimeScale / timeScale;
  28085. values[ 1 ] = endTimeScale / timeScale;
  28086. return this;
  28087. }
  28088. stopWarping() {
  28089. const timeScaleInterpolant = this._timeScaleInterpolant;
  28090. if ( timeScaleInterpolant !== null ) {
  28091. this._timeScaleInterpolant = null;
  28092. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  28093. }
  28094. return this;
  28095. }
  28096. // Object Accessors
  28097. getMixer() {
  28098. return this._mixer;
  28099. }
  28100. getClip() {
  28101. return this._clip;
  28102. }
  28103. getRoot() {
  28104. return this._localRoot || this._mixer._root;
  28105. }
  28106. // Interna
  28107. _update( time, deltaTime, timeDirection, accuIndex ) {
  28108. // called by the mixer
  28109. if ( ! this.enabled ) {
  28110. // call ._updateWeight() to update ._effectiveWeight
  28111. this._updateWeight( time );
  28112. return;
  28113. }
  28114. const startTime = this._startTime;
  28115. if ( startTime !== null ) {
  28116. // check for scheduled start of action
  28117. const timeRunning = ( time - startTime ) * timeDirection;
  28118. if ( timeRunning < 0 || timeDirection === 0 ) {
  28119. return; // yet to come / don't decide when delta = 0
  28120. }
  28121. // start
  28122. this._startTime = null; // unschedule
  28123. deltaTime = timeDirection * timeRunning;
  28124. }
  28125. // apply time scale and advance time
  28126. deltaTime *= this._updateTimeScale( time );
  28127. const clipTime = this._updateTime( deltaTime );
  28128. // note: _updateTime may disable the action resulting in
  28129. // an effective weight of 0
  28130. const weight = this._updateWeight( time );
  28131. if ( weight > 0 ) {
  28132. const interpolants = this._interpolants;
  28133. const propertyMixers = this._propertyBindings;
  28134. switch ( this.blendMode ) {
  28135. case AdditiveAnimationBlendMode:
  28136. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28137. interpolants[ j ].evaluate( clipTime );
  28138. propertyMixers[ j ].accumulateAdditive( weight );
  28139. }
  28140. break;
  28141. case NormalAnimationBlendMode:
  28142. default:
  28143. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28144. interpolants[ j ].evaluate( clipTime );
  28145. propertyMixers[ j ].accumulate( accuIndex, weight );
  28146. }
  28147. }
  28148. }
  28149. }
  28150. _updateWeight( time ) {
  28151. let weight = 0;
  28152. if ( this.enabled ) {
  28153. weight = this.weight;
  28154. const interpolant = this._weightInterpolant;
  28155. if ( interpolant !== null ) {
  28156. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28157. weight *= interpolantValue;
  28158. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28159. this.stopFading();
  28160. if ( interpolantValue === 0 ) {
  28161. // faded out, disable
  28162. this.enabled = false;
  28163. }
  28164. }
  28165. }
  28166. }
  28167. this._effectiveWeight = weight;
  28168. return weight;
  28169. }
  28170. _updateTimeScale( time ) {
  28171. let timeScale = 0;
  28172. if ( ! this.paused ) {
  28173. timeScale = this.timeScale;
  28174. const interpolant = this._timeScaleInterpolant;
  28175. if ( interpolant !== null ) {
  28176. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28177. timeScale *= interpolantValue;
  28178. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28179. this.stopWarping();
  28180. if ( timeScale === 0 ) {
  28181. // motion has halted, pause
  28182. this.paused = true;
  28183. } else {
  28184. // warp done - apply final time scale
  28185. this.timeScale = timeScale;
  28186. }
  28187. }
  28188. }
  28189. }
  28190. this._effectiveTimeScale = timeScale;
  28191. return timeScale;
  28192. }
  28193. _updateTime( deltaTime ) {
  28194. const duration = this._clip.duration;
  28195. const loop = this.loop;
  28196. let time = this.time + deltaTime;
  28197. let loopCount = this._loopCount;
  28198. const pingPong = ( loop === LoopPingPong );
  28199. if ( deltaTime === 0 ) {
  28200. if ( loopCount === - 1 ) return time;
  28201. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  28202. }
  28203. if ( loop === LoopOnce ) {
  28204. if ( loopCount === - 1 ) {
  28205. // just started
  28206. this._loopCount = 0;
  28207. this._setEndings( true, true, false );
  28208. }
  28209. handle_stop: {
  28210. if ( time >= duration ) {
  28211. time = duration;
  28212. } else if ( time < 0 ) {
  28213. time = 0;
  28214. } else {
  28215. this.time = time;
  28216. break handle_stop;
  28217. }
  28218. if ( this.clampWhenFinished ) this.paused = true;
  28219. else this.enabled = false;
  28220. this.time = time;
  28221. this._mixer.dispatchEvent( {
  28222. type: 'finished', action: this,
  28223. direction: deltaTime < 0 ? - 1 : 1
  28224. } );
  28225. }
  28226. } else { // repetitive Repeat or PingPong
  28227. if ( loopCount === - 1 ) {
  28228. // just started
  28229. if ( deltaTime >= 0 ) {
  28230. loopCount = 0;
  28231. this._setEndings( true, this.repetitions === 0, pingPong );
  28232. } else {
  28233. // when looping in reverse direction, the initial
  28234. // transition through zero counts as a repetition,
  28235. // so leave loopCount at -1
  28236. this._setEndings( this.repetitions === 0, true, pingPong );
  28237. }
  28238. }
  28239. if ( time >= duration || time < 0 ) {
  28240. // wrap around
  28241. const loopDelta = Math.floor( time / duration ); // signed
  28242. time -= duration * loopDelta;
  28243. loopCount += Math.abs( loopDelta );
  28244. const pending = this.repetitions - loopCount;
  28245. if ( pending <= 0 ) {
  28246. // have to stop (switch state, clamp time, fire event)
  28247. if ( this.clampWhenFinished ) this.paused = true;
  28248. else this.enabled = false;
  28249. time = deltaTime > 0 ? duration : 0;
  28250. this.time = time;
  28251. this._mixer.dispatchEvent( {
  28252. type: 'finished', action: this,
  28253. direction: deltaTime > 0 ? 1 : - 1
  28254. } );
  28255. } else {
  28256. // keep running
  28257. if ( pending === 1 ) {
  28258. // entering the last round
  28259. const atStart = deltaTime < 0;
  28260. this._setEndings( atStart, ! atStart, pingPong );
  28261. } else {
  28262. this._setEndings( false, false, pingPong );
  28263. }
  28264. this._loopCount = loopCount;
  28265. this.time = time;
  28266. this._mixer.dispatchEvent( {
  28267. type: 'loop', action: this, loopDelta: loopDelta
  28268. } );
  28269. }
  28270. } else {
  28271. this.time = time;
  28272. }
  28273. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28274. // invert time for the "pong round"
  28275. return duration - time;
  28276. }
  28277. }
  28278. return time;
  28279. }
  28280. _setEndings( atStart, atEnd, pingPong ) {
  28281. const settings = this._interpolantSettings;
  28282. if ( pingPong ) {
  28283. settings.endingStart = ZeroSlopeEnding;
  28284. settings.endingEnd = ZeroSlopeEnding;
  28285. } else {
  28286. // assuming for LoopOnce atStart == atEnd == true
  28287. if ( atStart ) {
  28288. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28289. } else {
  28290. settings.endingStart = WrapAroundEnding;
  28291. }
  28292. if ( atEnd ) {
  28293. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28294. } else {
  28295. settings.endingEnd = WrapAroundEnding;
  28296. }
  28297. }
  28298. }
  28299. _scheduleFading( duration, weightNow, weightThen ) {
  28300. const mixer = this._mixer, now = mixer.time;
  28301. let interpolant = this._weightInterpolant;
  28302. if ( interpolant === null ) {
  28303. interpolant = mixer._lendControlInterpolant();
  28304. this._weightInterpolant = interpolant;
  28305. }
  28306. const times = interpolant.parameterPositions,
  28307. values = interpolant.sampleValues;
  28308. times[ 0 ] = now;
  28309. values[ 0 ] = weightNow;
  28310. times[ 1 ] = now + duration;
  28311. values[ 1 ] = weightThen;
  28312. return this;
  28313. }
  28314. }
  28315. class AnimationMixer extends EventDispatcher {
  28316. constructor( root ) {
  28317. super();
  28318. this._root = root;
  28319. this._initMemoryManager();
  28320. this._accuIndex = 0;
  28321. this.time = 0;
  28322. this.timeScale = 1.0;
  28323. }
  28324. _bindAction( action, prototypeAction ) {
  28325. const root = action._localRoot || this._root,
  28326. tracks = action._clip.tracks,
  28327. nTracks = tracks.length,
  28328. bindings = action._propertyBindings,
  28329. interpolants = action._interpolants,
  28330. rootUuid = root.uuid,
  28331. bindingsByRoot = this._bindingsByRootAndName;
  28332. let bindingsByName = bindingsByRoot[ rootUuid ];
  28333. if ( bindingsByName === undefined ) {
  28334. bindingsByName = {};
  28335. bindingsByRoot[ rootUuid ] = bindingsByName;
  28336. }
  28337. for ( let i = 0; i !== nTracks; ++ i ) {
  28338. const track = tracks[ i ],
  28339. trackName = track.name;
  28340. let binding = bindingsByName[ trackName ];
  28341. if ( binding !== undefined ) {
  28342. bindings[ i ] = binding;
  28343. } else {
  28344. binding = bindings[ i ];
  28345. if ( binding !== undefined ) {
  28346. // existing binding, make sure the cache knows
  28347. if ( binding._cacheIndex === null ) {
  28348. ++ binding.referenceCount;
  28349. this._addInactiveBinding( binding, rootUuid, trackName );
  28350. }
  28351. continue;
  28352. }
  28353. const path = prototypeAction && prototypeAction.
  28354. _propertyBindings[ i ].binding.parsedPath;
  28355. binding = new PropertyMixer(
  28356. PropertyBinding.create( root, trackName, path ),
  28357. track.ValueTypeName, track.getValueSize() );
  28358. ++ binding.referenceCount;
  28359. this._addInactiveBinding( binding, rootUuid, trackName );
  28360. bindings[ i ] = binding;
  28361. }
  28362. interpolants[ i ].resultBuffer = binding.buffer;
  28363. }
  28364. }
  28365. _activateAction( action ) {
  28366. if ( ! this._isActiveAction( action ) ) {
  28367. if ( action._cacheIndex === null ) {
  28368. // this action has been forgotten by the cache, but the user
  28369. // appears to be still using it -> rebind
  28370. const rootUuid = ( action._localRoot || this._root ).uuid,
  28371. clipUuid = action._clip.uuid,
  28372. actionsForClip = this._actionsByClip[ clipUuid ];
  28373. this._bindAction( action,
  28374. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28375. this._addInactiveAction( action, clipUuid, rootUuid );
  28376. }
  28377. const bindings = action._propertyBindings;
  28378. // increment reference counts / sort out state
  28379. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28380. const binding = bindings[ i ];
  28381. if ( binding.useCount ++ === 0 ) {
  28382. this._lendBinding( binding );
  28383. binding.saveOriginalState();
  28384. }
  28385. }
  28386. this._lendAction( action );
  28387. }
  28388. }
  28389. _deactivateAction( action ) {
  28390. if ( this._isActiveAction( action ) ) {
  28391. const bindings = action._propertyBindings;
  28392. // decrement reference counts / sort out state
  28393. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28394. const binding = bindings[ i ];
  28395. if ( -- binding.useCount === 0 ) {
  28396. binding.restoreOriginalState();
  28397. this._takeBackBinding( binding );
  28398. }
  28399. }
  28400. this._takeBackAction( action );
  28401. }
  28402. }
  28403. // Memory manager
  28404. _initMemoryManager() {
  28405. this._actions = []; // 'nActiveActions' followed by inactive ones
  28406. this._nActiveActions = 0;
  28407. this._actionsByClip = {};
  28408. // inside:
  28409. // {
  28410. // knownActions: Array< AnimationAction > - used as prototypes
  28411. // actionByRoot: AnimationAction - lookup
  28412. // }
  28413. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28414. this._nActiveBindings = 0;
  28415. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28416. this._controlInterpolants = []; // same game as above
  28417. this._nActiveControlInterpolants = 0;
  28418. const scope = this;
  28419. this.stats = {
  28420. actions: {
  28421. get total() {
  28422. return scope._actions.length;
  28423. },
  28424. get inUse() {
  28425. return scope._nActiveActions;
  28426. }
  28427. },
  28428. bindings: {
  28429. get total() {
  28430. return scope._bindings.length;
  28431. },
  28432. get inUse() {
  28433. return scope._nActiveBindings;
  28434. }
  28435. },
  28436. controlInterpolants: {
  28437. get total() {
  28438. return scope._controlInterpolants.length;
  28439. },
  28440. get inUse() {
  28441. return scope._nActiveControlInterpolants;
  28442. }
  28443. }
  28444. };
  28445. }
  28446. // Memory management for AnimationAction objects
  28447. _isActiveAction( action ) {
  28448. const index = action._cacheIndex;
  28449. return index !== null && index < this._nActiveActions;
  28450. }
  28451. _addInactiveAction( action, clipUuid, rootUuid ) {
  28452. const actions = this._actions,
  28453. actionsByClip = this._actionsByClip;
  28454. let actionsForClip = actionsByClip[ clipUuid ];
  28455. if ( actionsForClip === undefined ) {
  28456. actionsForClip = {
  28457. knownActions: [ action ],
  28458. actionByRoot: {}
  28459. };
  28460. action._byClipCacheIndex = 0;
  28461. actionsByClip[ clipUuid ] = actionsForClip;
  28462. } else {
  28463. const knownActions = actionsForClip.knownActions;
  28464. action._byClipCacheIndex = knownActions.length;
  28465. knownActions.push( action );
  28466. }
  28467. action._cacheIndex = actions.length;
  28468. actions.push( action );
  28469. actionsForClip.actionByRoot[ rootUuid ] = action;
  28470. }
  28471. _removeInactiveAction( action ) {
  28472. const actions = this._actions,
  28473. lastInactiveAction = actions[ actions.length - 1 ],
  28474. cacheIndex = action._cacheIndex;
  28475. lastInactiveAction._cacheIndex = cacheIndex;
  28476. actions[ cacheIndex ] = lastInactiveAction;
  28477. actions.pop();
  28478. action._cacheIndex = null;
  28479. const clipUuid = action._clip.uuid,
  28480. actionsByClip = this._actionsByClip,
  28481. actionsForClip = actionsByClip[ clipUuid ],
  28482. knownActionsForClip = actionsForClip.knownActions,
  28483. lastKnownAction =
  28484. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28485. byClipCacheIndex = action._byClipCacheIndex;
  28486. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28487. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28488. knownActionsForClip.pop();
  28489. action._byClipCacheIndex = null;
  28490. const actionByRoot = actionsForClip.actionByRoot,
  28491. rootUuid = ( action._localRoot || this._root ).uuid;
  28492. delete actionByRoot[ rootUuid ];
  28493. if ( knownActionsForClip.length === 0 ) {
  28494. delete actionsByClip[ clipUuid ];
  28495. }
  28496. this._removeInactiveBindingsForAction( action );
  28497. }
  28498. _removeInactiveBindingsForAction( action ) {
  28499. const bindings = action._propertyBindings;
  28500. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28501. const binding = bindings[ i ];
  28502. if ( -- binding.referenceCount === 0 ) {
  28503. this._removeInactiveBinding( binding );
  28504. }
  28505. }
  28506. }
  28507. _lendAction( action ) {
  28508. // [ active actions | inactive actions ]
  28509. // [ active actions >| inactive actions ]
  28510. // s a
  28511. // <-swap->
  28512. // a s
  28513. const actions = this._actions,
  28514. prevIndex = action._cacheIndex,
  28515. lastActiveIndex = this._nActiveActions ++,
  28516. firstInactiveAction = actions[ lastActiveIndex ];
  28517. action._cacheIndex = lastActiveIndex;
  28518. actions[ lastActiveIndex ] = action;
  28519. firstInactiveAction._cacheIndex = prevIndex;
  28520. actions[ prevIndex ] = firstInactiveAction;
  28521. }
  28522. _takeBackAction( action ) {
  28523. // [ active actions | inactive actions ]
  28524. // [ active actions |< inactive actions ]
  28525. // a s
  28526. // <-swap->
  28527. // s a
  28528. const actions = this._actions,
  28529. prevIndex = action._cacheIndex,
  28530. firstInactiveIndex = -- this._nActiveActions,
  28531. lastActiveAction = actions[ firstInactiveIndex ];
  28532. action._cacheIndex = firstInactiveIndex;
  28533. actions[ firstInactiveIndex ] = action;
  28534. lastActiveAction._cacheIndex = prevIndex;
  28535. actions[ prevIndex ] = lastActiveAction;
  28536. }
  28537. // Memory management for PropertyMixer objects
  28538. _addInactiveBinding( binding, rootUuid, trackName ) {
  28539. const bindingsByRoot = this._bindingsByRootAndName,
  28540. bindings = this._bindings;
  28541. let bindingByName = bindingsByRoot[ rootUuid ];
  28542. if ( bindingByName === undefined ) {
  28543. bindingByName = {};
  28544. bindingsByRoot[ rootUuid ] = bindingByName;
  28545. }
  28546. bindingByName[ trackName ] = binding;
  28547. binding._cacheIndex = bindings.length;
  28548. bindings.push( binding );
  28549. }
  28550. _removeInactiveBinding( binding ) {
  28551. const bindings = this._bindings,
  28552. propBinding = binding.binding,
  28553. rootUuid = propBinding.rootNode.uuid,
  28554. trackName = propBinding.path,
  28555. bindingsByRoot = this._bindingsByRootAndName,
  28556. bindingByName = bindingsByRoot[ rootUuid ],
  28557. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28558. cacheIndex = binding._cacheIndex;
  28559. lastInactiveBinding._cacheIndex = cacheIndex;
  28560. bindings[ cacheIndex ] = lastInactiveBinding;
  28561. bindings.pop();
  28562. delete bindingByName[ trackName ];
  28563. if ( Object.keys( bindingByName ).length === 0 ) {
  28564. delete bindingsByRoot[ rootUuid ];
  28565. }
  28566. }
  28567. _lendBinding( binding ) {
  28568. const bindings = this._bindings,
  28569. prevIndex = binding._cacheIndex,
  28570. lastActiveIndex = this._nActiveBindings ++,
  28571. firstInactiveBinding = bindings[ lastActiveIndex ];
  28572. binding._cacheIndex = lastActiveIndex;
  28573. bindings[ lastActiveIndex ] = binding;
  28574. firstInactiveBinding._cacheIndex = prevIndex;
  28575. bindings[ prevIndex ] = firstInactiveBinding;
  28576. }
  28577. _takeBackBinding( binding ) {
  28578. const bindings = this._bindings,
  28579. prevIndex = binding._cacheIndex,
  28580. firstInactiveIndex = -- this._nActiveBindings,
  28581. lastActiveBinding = bindings[ firstInactiveIndex ];
  28582. binding._cacheIndex = firstInactiveIndex;
  28583. bindings[ firstInactiveIndex ] = binding;
  28584. lastActiveBinding._cacheIndex = prevIndex;
  28585. bindings[ prevIndex ] = lastActiveBinding;
  28586. }
  28587. // Memory management of Interpolants for weight and time scale
  28588. _lendControlInterpolant() {
  28589. const interpolants = this._controlInterpolants,
  28590. lastActiveIndex = this._nActiveControlInterpolants ++;
  28591. let interpolant = interpolants[ lastActiveIndex ];
  28592. if ( interpolant === undefined ) {
  28593. interpolant = new LinearInterpolant(
  28594. new Float32Array( 2 ), new Float32Array( 2 ),
  28595. 1, this._controlInterpolantsResultBuffer );
  28596. interpolant.__cacheIndex = lastActiveIndex;
  28597. interpolants[ lastActiveIndex ] = interpolant;
  28598. }
  28599. return interpolant;
  28600. }
  28601. _takeBackControlInterpolant( interpolant ) {
  28602. const interpolants = this._controlInterpolants,
  28603. prevIndex = interpolant.__cacheIndex,
  28604. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28605. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28606. interpolant.__cacheIndex = firstInactiveIndex;
  28607. interpolants[ firstInactiveIndex ] = interpolant;
  28608. lastActiveInterpolant.__cacheIndex = prevIndex;
  28609. interpolants[ prevIndex ] = lastActiveInterpolant;
  28610. }
  28611. // return an action for a clip optionally using a custom root target
  28612. // object (this method allocates a lot of dynamic memory in case a
  28613. // previously unknown clip/root combination is specified)
  28614. clipAction( clip, optionalRoot, blendMode ) {
  28615. const root = optionalRoot || this._root,
  28616. rootUuid = root.uuid;
  28617. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28618. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28619. const actionsForClip = this._actionsByClip[ clipUuid ];
  28620. let prototypeAction = null;
  28621. if ( blendMode === undefined ) {
  28622. if ( clipObject !== null ) {
  28623. blendMode = clipObject.blendMode;
  28624. } else {
  28625. blendMode = NormalAnimationBlendMode;
  28626. }
  28627. }
  28628. if ( actionsForClip !== undefined ) {
  28629. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28630. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28631. return existingAction;
  28632. }
  28633. // we know the clip, so we don't have to parse all
  28634. // the bindings again but can just copy
  28635. prototypeAction = actionsForClip.knownActions[ 0 ];
  28636. // also, take the clip from the prototype action
  28637. if ( clipObject === null )
  28638. clipObject = prototypeAction._clip;
  28639. }
  28640. // clip must be known when specified via string
  28641. if ( clipObject === null ) return null;
  28642. // allocate all resources required to run it
  28643. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28644. this._bindAction( newAction, prototypeAction );
  28645. // and make the action known to the memory manager
  28646. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28647. return newAction;
  28648. }
  28649. // get an existing action
  28650. existingAction( clip, optionalRoot ) {
  28651. const root = optionalRoot || this._root,
  28652. rootUuid = root.uuid,
  28653. clipObject = typeof clip === 'string' ?
  28654. AnimationClip.findByName( root, clip ) : clip,
  28655. clipUuid = clipObject ? clipObject.uuid : clip,
  28656. actionsForClip = this._actionsByClip[ clipUuid ];
  28657. if ( actionsForClip !== undefined ) {
  28658. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28659. }
  28660. return null;
  28661. }
  28662. // deactivates all previously scheduled actions
  28663. stopAllAction() {
  28664. const actions = this._actions,
  28665. nActions = this._nActiveActions;
  28666. for ( let i = nActions - 1; i >= 0; -- i ) {
  28667. actions[ i ].stop();
  28668. }
  28669. return this;
  28670. }
  28671. // advance the time and update apply the animation
  28672. update( deltaTime ) {
  28673. deltaTime *= this.timeScale;
  28674. const actions = this._actions,
  28675. nActions = this._nActiveActions,
  28676. time = this.time += deltaTime,
  28677. timeDirection = Math.sign( deltaTime ),
  28678. accuIndex = this._accuIndex ^= 1;
  28679. // run active actions
  28680. for ( let i = 0; i !== nActions; ++ i ) {
  28681. const action = actions[ i ];
  28682. action._update( time, deltaTime, timeDirection, accuIndex );
  28683. }
  28684. // update scene graph
  28685. const bindings = this._bindings,
  28686. nBindings = this._nActiveBindings;
  28687. for ( let i = 0; i !== nBindings; ++ i ) {
  28688. bindings[ i ].apply( accuIndex );
  28689. }
  28690. return this;
  28691. }
  28692. // Allows you to seek to a specific time in an animation.
  28693. setTime( timeInSeconds ) {
  28694. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28695. for ( let i = 0; i < this._actions.length; i ++ ) {
  28696. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28697. }
  28698. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28699. }
  28700. // return this mixer's root target object
  28701. getRoot() {
  28702. return this._root;
  28703. }
  28704. // free all resources specific to a particular clip
  28705. uncacheClip( clip ) {
  28706. const actions = this._actions,
  28707. clipUuid = clip.uuid,
  28708. actionsByClip = this._actionsByClip,
  28709. actionsForClip = actionsByClip[ clipUuid ];
  28710. if ( actionsForClip !== undefined ) {
  28711. // note: just calling _removeInactiveAction would mess up the
  28712. // iteration state and also require updating the state we can
  28713. // just throw away
  28714. const actionsToRemove = actionsForClip.knownActions;
  28715. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28716. const action = actionsToRemove[ i ];
  28717. this._deactivateAction( action );
  28718. const cacheIndex = action._cacheIndex,
  28719. lastInactiveAction = actions[ actions.length - 1 ];
  28720. action._cacheIndex = null;
  28721. action._byClipCacheIndex = null;
  28722. lastInactiveAction._cacheIndex = cacheIndex;
  28723. actions[ cacheIndex ] = lastInactiveAction;
  28724. actions.pop();
  28725. this._removeInactiveBindingsForAction( action );
  28726. }
  28727. delete actionsByClip[ clipUuid ];
  28728. }
  28729. }
  28730. // free all resources specific to a particular root target object
  28731. uncacheRoot( root ) {
  28732. const rootUuid = root.uuid,
  28733. actionsByClip = this._actionsByClip;
  28734. for ( const clipUuid in actionsByClip ) {
  28735. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28736. action = actionByRoot[ rootUuid ];
  28737. if ( action !== undefined ) {
  28738. this._deactivateAction( action );
  28739. this._removeInactiveAction( action );
  28740. }
  28741. }
  28742. const bindingsByRoot = this._bindingsByRootAndName,
  28743. bindingByName = bindingsByRoot[ rootUuid ];
  28744. if ( bindingByName !== undefined ) {
  28745. for ( const trackName in bindingByName ) {
  28746. const binding = bindingByName[ trackName ];
  28747. binding.restoreOriginalState();
  28748. this._removeInactiveBinding( binding );
  28749. }
  28750. }
  28751. }
  28752. // remove a targeted clip from the cache
  28753. uncacheAction( clip, optionalRoot ) {
  28754. const action = this.existingAction( clip, optionalRoot );
  28755. if ( action !== null ) {
  28756. this._deactivateAction( action );
  28757. this._removeInactiveAction( action );
  28758. }
  28759. }
  28760. }
  28761. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  28762. class Uniform {
  28763. constructor( value ) {
  28764. if ( typeof value === 'string' ) {
  28765. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  28766. value = arguments[ 1 ];
  28767. }
  28768. this.value = value;
  28769. }
  28770. clone() {
  28771. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28772. }
  28773. }
  28774. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28775. constructor( array, stride, meshPerAttribute = 1 ) {
  28776. super( array, stride );
  28777. this.meshPerAttribute = meshPerAttribute;
  28778. }
  28779. copy( source ) {
  28780. super.copy( source );
  28781. this.meshPerAttribute = source.meshPerAttribute;
  28782. return this;
  28783. }
  28784. clone( data ) {
  28785. const ib = super.clone( data );
  28786. ib.meshPerAttribute = this.meshPerAttribute;
  28787. return ib;
  28788. }
  28789. toJSON( data ) {
  28790. const json = super.toJSON( data );
  28791. json.isInstancedInterleavedBuffer = true;
  28792. json.meshPerAttribute = this.meshPerAttribute;
  28793. return json;
  28794. }
  28795. }
  28796. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  28797. class GLBufferAttribute {
  28798. constructor( buffer, type, itemSize, elementSize, count ) {
  28799. this.buffer = buffer;
  28800. this.type = type;
  28801. this.itemSize = itemSize;
  28802. this.elementSize = elementSize;
  28803. this.count = count;
  28804. this.version = 0;
  28805. }
  28806. set needsUpdate( value ) {
  28807. if ( value === true ) this.version ++;
  28808. }
  28809. setBuffer( buffer ) {
  28810. this.buffer = buffer;
  28811. return this;
  28812. }
  28813. setType( type, elementSize ) {
  28814. this.type = type;
  28815. this.elementSize = elementSize;
  28816. return this;
  28817. }
  28818. setItemSize( itemSize ) {
  28819. this.itemSize = itemSize;
  28820. return this;
  28821. }
  28822. setCount( count ) {
  28823. this.count = count;
  28824. return this;
  28825. }
  28826. }
  28827. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  28828. class Raycaster {
  28829. constructor( origin, direction, near = 0, far = Infinity ) {
  28830. this.ray = new Ray( origin, direction );
  28831. // direction is assumed to be normalized (for accurate distance calculations)
  28832. this.near = near;
  28833. this.far = far;
  28834. this.camera = null;
  28835. this.layers = new Layers();
  28836. this.params = {
  28837. Mesh: {},
  28838. Line: { threshold: 1 },
  28839. LOD: {},
  28840. Points: { threshold: 1 },
  28841. Sprite: {}
  28842. };
  28843. }
  28844. set( origin, direction ) {
  28845. // direction is assumed to be normalized (for accurate distance calculations)
  28846. this.ray.set( origin, direction );
  28847. }
  28848. setFromCamera( coords, camera ) {
  28849. if ( camera && camera.isPerspectiveCamera ) {
  28850. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28851. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28852. this.camera = camera;
  28853. } else if ( camera && camera.isOrthographicCamera ) {
  28854. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28855. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28856. this.camera = camera;
  28857. } else {
  28858. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28859. }
  28860. }
  28861. intersectObject( object, recursive = false, intersects = [] ) {
  28862. intersectObject( object, this, intersects, recursive );
  28863. intersects.sort( ascSort );
  28864. return intersects;
  28865. }
  28866. intersectObjects( objects, recursive = false, intersects = [] ) {
  28867. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28868. intersectObject( objects[ i ], this, intersects, recursive );
  28869. }
  28870. intersects.sort( ascSort );
  28871. return intersects;
  28872. }
  28873. }
  28874. function ascSort( a, b ) {
  28875. return a.distance - b.distance;
  28876. }
  28877. function intersectObject( object, raycaster, intersects, recursive ) {
  28878. if ( object.layers.test( raycaster.layers ) ) {
  28879. object.raycast( raycaster, intersects );
  28880. }
  28881. if ( recursive === true ) {
  28882. const children = object.children;
  28883. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28884. intersectObject( children[ i ], raycaster, intersects, true );
  28885. }
  28886. }
  28887. }
  28888. /**
  28889. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28890. *
  28891. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28892. * The azimuthal angle (theta) is measured from the positive z-axis.
  28893. */
  28894. class Spherical {
  28895. constructor( radius = 1, phi = 0, theta = 0 ) {
  28896. this.radius = radius;
  28897. this.phi = phi; // polar angle
  28898. this.theta = theta; // azimuthal angle
  28899. return this;
  28900. }
  28901. set( radius, phi, theta ) {
  28902. this.radius = radius;
  28903. this.phi = phi;
  28904. this.theta = theta;
  28905. return this;
  28906. }
  28907. copy( other ) {
  28908. this.radius = other.radius;
  28909. this.phi = other.phi;
  28910. this.theta = other.theta;
  28911. return this;
  28912. }
  28913. // restrict phi to be betwee EPS and PI-EPS
  28914. makeSafe() {
  28915. const EPS = 0.000001;
  28916. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28917. return this;
  28918. }
  28919. setFromVector3( v ) {
  28920. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28921. }
  28922. setFromCartesianCoords( x, y, z ) {
  28923. this.radius = Math.sqrt( x * x + y * y + z * z );
  28924. if ( this.radius === 0 ) {
  28925. this.theta = 0;
  28926. this.phi = 0;
  28927. } else {
  28928. this.theta = Math.atan2( x, z );
  28929. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28930. }
  28931. return this;
  28932. }
  28933. clone() {
  28934. return new this.constructor().copy( this );
  28935. }
  28936. }
  28937. /**
  28938. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28939. */
  28940. class Cylindrical {
  28941. constructor( radius = 1, theta = 0, y = 0 ) {
  28942. this.radius = radius; // distance from the origin to a point in the x-z plane
  28943. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28944. this.y = y; // height above the x-z plane
  28945. return this;
  28946. }
  28947. set( radius, theta, y ) {
  28948. this.radius = radius;
  28949. this.theta = theta;
  28950. this.y = y;
  28951. return this;
  28952. }
  28953. copy( other ) {
  28954. this.radius = other.radius;
  28955. this.theta = other.theta;
  28956. this.y = other.y;
  28957. return this;
  28958. }
  28959. setFromVector3( v ) {
  28960. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28961. }
  28962. setFromCartesianCoords( x, y, z ) {
  28963. this.radius = Math.sqrt( x * x + z * z );
  28964. this.theta = Math.atan2( x, z );
  28965. this.y = y;
  28966. return this;
  28967. }
  28968. clone() {
  28969. return new this.constructor().copy( this );
  28970. }
  28971. }
  28972. const _vector$4 = /*@__PURE__*/ new Vector2();
  28973. class Box2 {
  28974. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28975. this.min = min;
  28976. this.max = max;
  28977. }
  28978. set( min, max ) {
  28979. this.min.copy( min );
  28980. this.max.copy( max );
  28981. return this;
  28982. }
  28983. setFromPoints( points ) {
  28984. this.makeEmpty();
  28985. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28986. this.expandByPoint( points[ i ] );
  28987. }
  28988. return this;
  28989. }
  28990. setFromCenterAndSize( center, size ) {
  28991. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28992. this.min.copy( center ).sub( halfSize );
  28993. this.max.copy( center ).add( halfSize );
  28994. return this;
  28995. }
  28996. clone() {
  28997. return new this.constructor().copy( this );
  28998. }
  28999. copy( box ) {
  29000. this.min.copy( box.min );
  29001. this.max.copy( box.max );
  29002. return this;
  29003. }
  29004. makeEmpty() {
  29005. this.min.x = this.min.y = + Infinity;
  29006. this.max.x = this.max.y = - Infinity;
  29007. return this;
  29008. }
  29009. isEmpty() {
  29010. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  29011. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  29012. }
  29013. getCenter( target ) {
  29014. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  29015. }
  29016. getSize( target ) {
  29017. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  29018. }
  29019. expandByPoint( point ) {
  29020. this.min.min( point );
  29021. this.max.max( point );
  29022. return this;
  29023. }
  29024. expandByVector( vector ) {
  29025. this.min.sub( vector );
  29026. this.max.add( vector );
  29027. return this;
  29028. }
  29029. expandByScalar( scalar ) {
  29030. this.min.addScalar( - scalar );
  29031. this.max.addScalar( scalar );
  29032. return this;
  29033. }
  29034. containsPoint( point ) {
  29035. return point.x < this.min.x || point.x > this.max.x ||
  29036. point.y < this.min.y || point.y > this.max.y ? false : true;
  29037. }
  29038. containsBox( box ) {
  29039. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  29040. this.min.y <= box.min.y && box.max.y <= this.max.y;
  29041. }
  29042. getParameter( point, target ) {
  29043. // This can potentially have a divide by zero if the box
  29044. // has a size dimension of 0.
  29045. return target.set(
  29046. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  29047. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  29048. );
  29049. }
  29050. intersectsBox( box ) {
  29051. // using 4 splitting planes to rule out intersections
  29052. return box.max.x < this.min.x || box.min.x > this.max.x ||
  29053. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  29054. }
  29055. clampPoint( point, target ) {
  29056. return target.copy( point ).clamp( this.min, this.max );
  29057. }
  29058. distanceToPoint( point ) {
  29059. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  29060. return clampedPoint.sub( point ).length();
  29061. }
  29062. intersect( box ) {
  29063. this.min.max( box.min );
  29064. this.max.min( box.max );
  29065. return this;
  29066. }
  29067. union( box ) {
  29068. this.min.min( box.min );
  29069. this.max.max( box.max );
  29070. return this;
  29071. }
  29072. translate( offset ) {
  29073. this.min.add( offset );
  29074. this.max.add( offset );
  29075. return this;
  29076. }
  29077. equals( box ) {
  29078. return box.min.equals( this.min ) && box.max.equals( this.max );
  29079. }
  29080. }
  29081. Box2.prototype.isBox2 = true;
  29082. const _startP = /*@__PURE__*/ new Vector3();
  29083. const _startEnd = /*@__PURE__*/ new Vector3();
  29084. class Line3 {
  29085. constructor( start = new Vector3(), end = new Vector3() ) {
  29086. this.start = start;
  29087. this.end = end;
  29088. }
  29089. set( start, end ) {
  29090. this.start.copy( start );
  29091. this.end.copy( end );
  29092. return this;
  29093. }
  29094. copy( line ) {
  29095. this.start.copy( line.start );
  29096. this.end.copy( line.end );
  29097. return this;
  29098. }
  29099. getCenter( target ) {
  29100. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  29101. }
  29102. delta( target ) {
  29103. return target.subVectors( this.end, this.start );
  29104. }
  29105. distanceSq() {
  29106. return this.start.distanceToSquared( this.end );
  29107. }
  29108. distance() {
  29109. return this.start.distanceTo( this.end );
  29110. }
  29111. at( t, target ) {
  29112. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29113. }
  29114. closestPointToPointParameter( point, clampToLine ) {
  29115. _startP.subVectors( point, this.start );
  29116. _startEnd.subVectors( this.end, this.start );
  29117. const startEnd2 = _startEnd.dot( _startEnd );
  29118. const startEnd_startP = _startEnd.dot( _startP );
  29119. let t = startEnd_startP / startEnd2;
  29120. if ( clampToLine ) {
  29121. t = clamp( t, 0, 1 );
  29122. }
  29123. return t;
  29124. }
  29125. closestPointToPoint( point, clampToLine, target ) {
  29126. const t = this.closestPointToPointParameter( point, clampToLine );
  29127. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29128. }
  29129. applyMatrix4( matrix ) {
  29130. this.start.applyMatrix4( matrix );
  29131. this.end.applyMatrix4( matrix );
  29132. return this;
  29133. }
  29134. equals( line ) {
  29135. return line.start.equals( this.start ) && line.end.equals( this.end );
  29136. }
  29137. clone() {
  29138. return new this.constructor().copy( this );
  29139. }
  29140. }
  29141. class ImmediateRenderObject extends Object3D {
  29142. constructor( material ) {
  29143. super();
  29144. this.material = material;
  29145. this.render = function ( /* renderCallback */ ) {};
  29146. this.hasPositions = false;
  29147. this.hasNormals = false;
  29148. this.hasColors = false;
  29149. this.hasUvs = false;
  29150. this.positionArray = null;
  29151. this.normalArray = null;
  29152. this.colorArray = null;
  29153. this.uvArray = null;
  29154. this.count = 0;
  29155. }
  29156. }
  29157. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  29158. const _vector$3 = /*@__PURE__*/ new Vector3();
  29159. class SpotLightHelper extends Object3D {
  29160. constructor( light, color ) {
  29161. super();
  29162. this.light = light;
  29163. this.light.updateMatrixWorld();
  29164. this.matrix = light.matrixWorld;
  29165. this.matrixAutoUpdate = false;
  29166. this.color = color;
  29167. const geometry = new BufferGeometry();
  29168. const positions = [
  29169. 0, 0, 0, 0, 0, 1,
  29170. 0, 0, 0, 1, 0, 1,
  29171. 0, 0, 0, - 1, 0, 1,
  29172. 0, 0, 0, 0, 1, 1,
  29173. 0, 0, 0, 0, - 1, 1
  29174. ];
  29175. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  29176. const p1 = ( i / l ) * Math.PI * 2;
  29177. const p2 = ( j / l ) * Math.PI * 2;
  29178. positions.push(
  29179. Math.cos( p1 ), Math.sin( p1 ), 1,
  29180. Math.cos( p2 ), Math.sin( p2 ), 1
  29181. );
  29182. }
  29183. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29184. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29185. this.cone = new LineSegments( geometry, material );
  29186. this.add( this.cone );
  29187. this.update();
  29188. }
  29189. dispose() {
  29190. this.cone.geometry.dispose();
  29191. this.cone.material.dispose();
  29192. }
  29193. update() {
  29194. this.light.updateMatrixWorld();
  29195. const coneLength = this.light.distance ? this.light.distance : 1000;
  29196. const coneWidth = coneLength * Math.tan( this.light.angle );
  29197. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  29198. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29199. this.cone.lookAt( _vector$3 );
  29200. if ( this.color !== undefined ) {
  29201. this.cone.material.color.set( this.color );
  29202. } else {
  29203. this.cone.material.color.copy( this.light.color );
  29204. }
  29205. }
  29206. }
  29207. const _vector$2 = /*@__PURE__*/ new Vector3();
  29208. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  29209. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  29210. class SkeletonHelper extends LineSegments {
  29211. constructor( object ) {
  29212. const bones = getBoneList( object );
  29213. const geometry = new BufferGeometry();
  29214. const vertices = [];
  29215. const colors = [];
  29216. const color1 = new Color( 0, 0, 1 );
  29217. const color2 = new Color( 0, 1, 0 );
  29218. for ( let i = 0; i < bones.length; i ++ ) {
  29219. const bone = bones[ i ];
  29220. if ( bone.parent && bone.parent.isBone ) {
  29221. vertices.push( 0, 0, 0 );
  29222. vertices.push( 0, 0, 0 );
  29223. colors.push( color1.r, color1.g, color1.b );
  29224. colors.push( color2.r, color2.g, color2.b );
  29225. }
  29226. }
  29227. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29228. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29229. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  29230. super( geometry, material );
  29231. this.type = 'SkeletonHelper';
  29232. this.isSkeletonHelper = true;
  29233. this.root = object;
  29234. this.bones = bones;
  29235. this.matrix = object.matrixWorld;
  29236. this.matrixAutoUpdate = false;
  29237. }
  29238. updateMatrixWorld( force ) {
  29239. const bones = this.bones;
  29240. const geometry = this.geometry;
  29241. const position = geometry.getAttribute( 'position' );
  29242. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29243. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29244. const bone = bones[ i ];
  29245. if ( bone.parent && bone.parent.isBone ) {
  29246. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29247. _vector$2.setFromMatrixPosition( _boneMatrix );
  29248. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29249. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29250. _vector$2.setFromMatrixPosition( _boneMatrix );
  29251. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29252. j += 2;
  29253. }
  29254. }
  29255. geometry.getAttribute( 'position' ).needsUpdate = true;
  29256. super.updateMatrixWorld( force );
  29257. }
  29258. }
  29259. function getBoneList( object ) {
  29260. const boneList = [];
  29261. if ( object && object.isBone ) {
  29262. boneList.push( object );
  29263. }
  29264. for ( let i = 0; i < object.children.length; i ++ ) {
  29265. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29266. }
  29267. return boneList;
  29268. }
  29269. class PointLightHelper extends Mesh {
  29270. constructor( light, sphereSize, color ) {
  29271. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29272. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29273. super( geometry, material );
  29274. this.light = light;
  29275. this.light.updateMatrixWorld();
  29276. this.color = color;
  29277. this.type = 'PointLightHelper';
  29278. this.matrix = this.light.matrixWorld;
  29279. this.matrixAutoUpdate = false;
  29280. this.update();
  29281. /*
  29282. // TODO: delete this comment?
  29283. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  29284. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29285. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29286. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29287. const d = light.distance;
  29288. if ( d === 0.0 ) {
  29289. this.lightDistance.visible = false;
  29290. } else {
  29291. this.lightDistance.scale.set( d, d, d );
  29292. }
  29293. this.add( this.lightDistance );
  29294. */
  29295. }
  29296. dispose() {
  29297. this.geometry.dispose();
  29298. this.material.dispose();
  29299. }
  29300. update() {
  29301. if ( this.color !== undefined ) {
  29302. this.material.color.set( this.color );
  29303. } else {
  29304. this.material.color.copy( this.light.color );
  29305. }
  29306. /*
  29307. const d = this.light.distance;
  29308. if ( d === 0.0 ) {
  29309. this.lightDistance.visible = false;
  29310. } else {
  29311. this.lightDistance.visible = true;
  29312. this.lightDistance.scale.set( d, d, d );
  29313. }
  29314. */
  29315. }
  29316. }
  29317. const _vector$1 = /*@__PURE__*/ new Vector3();
  29318. const _color1 = /*@__PURE__*/ new Color();
  29319. const _color2 = /*@__PURE__*/ new Color();
  29320. class HemisphereLightHelper extends Object3D {
  29321. constructor( light, size, color ) {
  29322. super();
  29323. this.light = light;
  29324. this.light.updateMatrixWorld();
  29325. this.matrix = light.matrixWorld;
  29326. this.matrixAutoUpdate = false;
  29327. this.color = color;
  29328. const geometry = new OctahedronGeometry( size );
  29329. geometry.rotateY( Math.PI * 0.5 );
  29330. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29331. if ( this.color === undefined ) this.material.vertexColors = true;
  29332. const position = geometry.getAttribute( 'position' );
  29333. const colors = new Float32Array( position.count * 3 );
  29334. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29335. this.add( new Mesh( geometry, this.material ) );
  29336. this.update();
  29337. }
  29338. dispose() {
  29339. this.children[ 0 ].geometry.dispose();
  29340. this.children[ 0 ].material.dispose();
  29341. }
  29342. update() {
  29343. const mesh = this.children[ 0 ];
  29344. if ( this.color !== undefined ) {
  29345. this.material.color.set( this.color );
  29346. } else {
  29347. const colors = mesh.geometry.getAttribute( 'color' );
  29348. _color1.copy( this.light.color );
  29349. _color2.copy( this.light.groundColor );
  29350. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29351. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29352. colors.setXYZ( i, color.r, color.g, color.b );
  29353. }
  29354. colors.needsUpdate = true;
  29355. }
  29356. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29357. }
  29358. }
  29359. class GridHelper extends LineSegments {
  29360. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29361. color1 = new Color( color1 );
  29362. color2 = new Color( color2 );
  29363. const center = divisions / 2;
  29364. const step = size / divisions;
  29365. const halfSize = size / 2;
  29366. const vertices = [], colors = [];
  29367. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29368. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29369. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29370. const color = i === center ? color1 : color2;
  29371. color.toArray( colors, j ); j += 3;
  29372. color.toArray( colors, j ); j += 3;
  29373. color.toArray( colors, j ); j += 3;
  29374. color.toArray( colors, j ); j += 3;
  29375. }
  29376. const geometry = new BufferGeometry();
  29377. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29378. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29379. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29380. super( geometry, material );
  29381. this.type = 'GridHelper';
  29382. }
  29383. }
  29384. class PolarGridHelper extends LineSegments {
  29385. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29386. color1 = new Color( color1 );
  29387. color2 = new Color( color2 );
  29388. const vertices = [];
  29389. const colors = [];
  29390. // create the radials
  29391. for ( let i = 0; i <= radials; i ++ ) {
  29392. const v = ( i / radials ) * ( Math.PI * 2 );
  29393. const x = Math.sin( v ) * radius;
  29394. const z = Math.cos( v ) * radius;
  29395. vertices.push( 0, 0, 0 );
  29396. vertices.push( x, 0, z );
  29397. const color = ( i & 1 ) ? color1 : color2;
  29398. colors.push( color.r, color.g, color.b );
  29399. colors.push( color.r, color.g, color.b );
  29400. }
  29401. // create the circles
  29402. for ( let i = 0; i <= circles; i ++ ) {
  29403. const color = ( i & 1 ) ? color1 : color2;
  29404. const r = radius - ( radius / circles * i );
  29405. for ( let j = 0; j < divisions; j ++ ) {
  29406. // first vertex
  29407. let v = ( j / divisions ) * ( Math.PI * 2 );
  29408. let x = Math.sin( v ) * r;
  29409. let z = Math.cos( v ) * r;
  29410. vertices.push( x, 0, z );
  29411. colors.push( color.r, color.g, color.b );
  29412. // second vertex
  29413. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29414. x = Math.sin( v ) * r;
  29415. z = Math.cos( v ) * r;
  29416. vertices.push( x, 0, z );
  29417. colors.push( color.r, color.g, color.b );
  29418. }
  29419. }
  29420. const geometry = new BufferGeometry();
  29421. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29422. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29423. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29424. super( geometry, material );
  29425. this.type = 'PolarGridHelper';
  29426. }
  29427. }
  29428. const _v1 = /*@__PURE__*/ new Vector3();
  29429. const _v2 = /*@__PURE__*/ new Vector3();
  29430. const _v3 = /*@__PURE__*/ new Vector3();
  29431. class DirectionalLightHelper extends Object3D {
  29432. constructor( light, size, color ) {
  29433. super();
  29434. this.light = light;
  29435. this.light.updateMatrixWorld();
  29436. this.matrix = light.matrixWorld;
  29437. this.matrixAutoUpdate = false;
  29438. this.color = color;
  29439. if ( size === undefined ) size = 1;
  29440. let geometry = new BufferGeometry();
  29441. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29442. - size, size, 0,
  29443. size, size, 0,
  29444. size, - size, 0,
  29445. - size, - size, 0,
  29446. - size, size, 0
  29447. ], 3 ) );
  29448. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29449. this.lightPlane = new Line( geometry, material );
  29450. this.add( this.lightPlane );
  29451. geometry = new BufferGeometry();
  29452. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29453. this.targetLine = new Line( geometry, material );
  29454. this.add( this.targetLine );
  29455. this.update();
  29456. }
  29457. dispose() {
  29458. this.lightPlane.geometry.dispose();
  29459. this.lightPlane.material.dispose();
  29460. this.targetLine.geometry.dispose();
  29461. this.targetLine.material.dispose();
  29462. }
  29463. update() {
  29464. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29465. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29466. _v3.subVectors( _v2, _v1 );
  29467. this.lightPlane.lookAt( _v2 );
  29468. if ( this.color !== undefined ) {
  29469. this.lightPlane.material.color.set( this.color );
  29470. this.targetLine.material.color.set( this.color );
  29471. } else {
  29472. this.lightPlane.material.color.copy( this.light.color );
  29473. this.targetLine.material.color.copy( this.light.color );
  29474. }
  29475. this.targetLine.lookAt( _v2 );
  29476. this.targetLine.scale.z = _v3.length();
  29477. }
  29478. }
  29479. const _vector = /*@__PURE__*/ new Vector3();
  29480. const _camera = /*@__PURE__*/ new Camera();
  29481. /**
  29482. * - shows frustum, line of sight and up of the camera
  29483. * - suitable for fast updates
  29484. * - based on frustum visualization in lightgl.js shadowmap example
  29485. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  29486. */
  29487. class CameraHelper extends LineSegments {
  29488. constructor( camera ) {
  29489. const geometry = new BufferGeometry();
  29490. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29491. const vertices = [];
  29492. const colors = [];
  29493. const pointMap = {};
  29494. // colors
  29495. const colorFrustum = new Color( 0xffaa00 );
  29496. const colorCone = new Color( 0xff0000 );
  29497. const colorUp = new Color( 0x00aaff );
  29498. const colorTarget = new Color( 0xffffff );
  29499. const colorCross = new Color( 0x333333 );
  29500. // near
  29501. addLine( 'n1', 'n2', colorFrustum );
  29502. addLine( 'n2', 'n4', colorFrustum );
  29503. addLine( 'n4', 'n3', colorFrustum );
  29504. addLine( 'n3', 'n1', colorFrustum );
  29505. // far
  29506. addLine( 'f1', 'f2', colorFrustum );
  29507. addLine( 'f2', 'f4', colorFrustum );
  29508. addLine( 'f4', 'f3', colorFrustum );
  29509. addLine( 'f3', 'f1', colorFrustum );
  29510. // sides
  29511. addLine( 'n1', 'f1', colorFrustum );
  29512. addLine( 'n2', 'f2', colorFrustum );
  29513. addLine( 'n3', 'f3', colorFrustum );
  29514. addLine( 'n4', 'f4', colorFrustum );
  29515. // cone
  29516. addLine( 'p', 'n1', colorCone );
  29517. addLine( 'p', 'n2', colorCone );
  29518. addLine( 'p', 'n3', colorCone );
  29519. addLine( 'p', 'n4', colorCone );
  29520. // up
  29521. addLine( 'u1', 'u2', colorUp );
  29522. addLine( 'u2', 'u3', colorUp );
  29523. addLine( 'u3', 'u1', colorUp );
  29524. // target
  29525. addLine( 'c', 't', colorTarget );
  29526. addLine( 'p', 'c', colorCross );
  29527. // cross
  29528. addLine( 'cn1', 'cn2', colorCross );
  29529. addLine( 'cn3', 'cn4', colorCross );
  29530. addLine( 'cf1', 'cf2', colorCross );
  29531. addLine( 'cf3', 'cf4', colorCross );
  29532. function addLine( a, b, color ) {
  29533. addPoint( a, color );
  29534. addPoint( b, color );
  29535. }
  29536. function addPoint( id, color ) {
  29537. vertices.push( 0, 0, 0 );
  29538. colors.push( color.r, color.g, color.b );
  29539. if ( pointMap[ id ] === undefined ) {
  29540. pointMap[ id ] = [];
  29541. }
  29542. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29543. }
  29544. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29545. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29546. super( geometry, material );
  29547. this.type = 'CameraHelper';
  29548. this.camera = camera;
  29549. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29550. this.matrix = camera.matrixWorld;
  29551. this.matrixAutoUpdate = false;
  29552. this.pointMap = pointMap;
  29553. this.update();
  29554. }
  29555. update() {
  29556. const geometry = this.geometry;
  29557. const pointMap = this.pointMap;
  29558. const w = 1, h = 1;
  29559. // we need just camera projection matrix inverse
  29560. // world matrix must be identity
  29561. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29562. // center / target
  29563. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29564. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29565. // near
  29566. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29567. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29568. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29569. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29570. // far
  29571. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29572. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29573. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29574. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29575. // up
  29576. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29577. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29578. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29579. // cross
  29580. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29581. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29582. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29583. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29584. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29585. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29586. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29587. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29588. geometry.getAttribute( 'position' ).needsUpdate = true;
  29589. }
  29590. dispose() {
  29591. this.geometry.dispose();
  29592. this.material.dispose();
  29593. }
  29594. }
  29595. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29596. _vector.set( x, y, z ).unproject( camera );
  29597. const points = pointMap[ point ];
  29598. if ( points !== undefined ) {
  29599. const position = geometry.getAttribute( 'position' );
  29600. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29601. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29602. }
  29603. }
  29604. }
  29605. const _box = /*@__PURE__*/ new Box3();
  29606. class BoxHelper extends LineSegments {
  29607. constructor( object, color = 0xffff00 ) {
  29608. 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 ] );
  29609. const positions = new Float32Array( 8 * 3 );
  29610. const geometry = new BufferGeometry();
  29611. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29612. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29613. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29614. this.object = object;
  29615. this.type = 'BoxHelper';
  29616. this.matrixAutoUpdate = false;
  29617. this.update();
  29618. }
  29619. update( object ) {
  29620. if ( object !== undefined ) {
  29621. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29622. }
  29623. if ( this.object !== undefined ) {
  29624. _box.setFromObject( this.object );
  29625. }
  29626. if ( _box.isEmpty() ) return;
  29627. const min = _box.min;
  29628. const max = _box.max;
  29629. /*
  29630. 5____4
  29631. 1/___0/|
  29632. | 6__|_7
  29633. 2/___3/
  29634. 0: max.x, max.y, max.z
  29635. 1: min.x, max.y, max.z
  29636. 2: min.x, min.y, max.z
  29637. 3: max.x, min.y, max.z
  29638. 4: max.x, max.y, min.z
  29639. 5: min.x, max.y, min.z
  29640. 6: min.x, min.y, min.z
  29641. 7: max.x, min.y, min.z
  29642. */
  29643. const position = this.geometry.attributes.position;
  29644. const array = position.array;
  29645. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29646. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29647. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29648. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29649. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29650. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29651. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29652. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29653. position.needsUpdate = true;
  29654. this.geometry.computeBoundingSphere();
  29655. }
  29656. setFromObject( object ) {
  29657. this.object = object;
  29658. this.update();
  29659. return this;
  29660. }
  29661. copy( source ) {
  29662. LineSegments.prototype.copy.call( this, source );
  29663. this.object = source.object;
  29664. return this;
  29665. }
  29666. }
  29667. class Box3Helper extends LineSegments {
  29668. constructor( box, color = 0xffff00 ) {
  29669. 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 ] );
  29670. 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 ];
  29671. const geometry = new BufferGeometry();
  29672. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29673. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29674. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29675. this.box = box;
  29676. this.type = 'Box3Helper';
  29677. this.geometry.computeBoundingSphere();
  29678. }
  29679. updateMatrixWorld( force ) {
  29680. const box = this.box;
  29681. if ( box.isEmpty() ) return;
  29682. box.getCenter( this.position );
  29683. box.getSize( this.scale );
  29684. this.scale.multiplyScalar( 0.5 );
  29685. super.updateMatrixWorld( force );
  29686. }
  29687. }
  29688. class PlaneHelper extends Line {
  29689. constructor( plane, size = 1, hex = 0xffff00 ) {
  29690. const color = hex;
  29691. 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 ];
  29692. const geometry = new BufferGeometry();
  29693. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29694. geometry.computeBoundingSphere();
  29695. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29696. this.type = 'PlaneHelper';
  29697. this.plane = plane;
  29698. this.size = size;
  29699. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  29700. const geometry2 = new BufferGeometry();
  29701. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29702. geometry2.computeBoundingSphere();
  29703. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29704. }
  29705. updateMatrixWorld( force ) {
  29706. let scale = - this.plane.constant;
  29707. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  29708. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  29709. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29710. this.lookAt( this.plane.normal );
  29711. super.updateMatrixWorld( force );
  29712. }
  29713. }
  29714. const _axis = /*@__PURE__*/ new Vector3();
  29715. let _lineGeometry, _coneGeometry;
  29716. class ArrowHelper extends Object3D {
  29717. // dir is assumed to be normalized
  29718. 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 ) {
  29719. super();
  29720. this.type = 'ArrowHelper';
  29721. if ( _lineGeometry === undefined ) {
  29722. _lineGeometry = new BufferGeometry();
  29723. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29724. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29725. _coneGeometry.translate( 0, - 0.5, 0 );
  29726. }
  29727. this.position.copy( origin );
  29728. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29729. this.line.matrixAutoUpdate = false;
  29730. this.add( this.line );
  29731. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29732. this.cone.matrixAutoUpdate = false;
  29733. this.add( this.cone );
  29734. this.setDirection( dir );
  29735. this.setLength( length, headLength, headWidth );
  29736. }
  29737. setDirection( dir ) {
  29738. // dir is assumed to be normalized
  29739. if ( dir.y > 0.99999 ) {
  29740. this.quaternion.set( 0, 0, 0, 1 );
  29741. } else if ( dir.y < - 0.99999 ) {
  29742. this.quaternion.set( 1, 0, 0, 0 );
  29743. } else {
  29744. _axis.set( dir.z, 0, - dir.x ).normalize();
  29745. const radians = Math.acos( dir.y );
  29746. this.quaternion.setFromAxisAngle( _axis, radians );
  29747. }
  29748. }
  29749. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29750. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29751. this.line.updateMatrix();
  29752. this.cone.scale.set( headWidth, headLength, headWidth );
  29753. this.cone.position.y = length;
  29754. this.cone.updateMatrix();
  29755. }
  29756. setColor( color ) {
  29757. this.line.material.color.set( color );
  29758. this.cone.material.color.set( color );
  29759. }
  29760. copy( source ) {
  29761. super.copy( source, false );
  29762. this.line.copy( source.line );
  29763. this.cone.copy( source.cone );
  29764. return this;
  29765. }
  29766. }
  29767. class AxesHelper extends LineSegments {
  29768. constructor( size = 1 ) {
  29769. const vertices = [
  29770. 0, 0, 0, size, 0, 0,
  29771. 0, 0, 0, 0, size, 0,
  29772. 0, 0, 0, 0, 0, size
  29773. ];
  29774. const colors = [
  29775. 1, 0, 0, 1, 0.6, 0,
  29776. 0, 1, 0, 0.6, 1, 0,
  29777. 0, 0, 1, 0, 0.6, 1
  29778. ];
  29779. const geometry = new BufferGeometry();
  29780. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29781. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29782. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29783. super( geometry, material );
  29784. this.type = 'AxesHelper';
  29785. }
  29786. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29787. const color = new Color();
  29788. const array = this.geometry.attributes.color.array;
  29789. color.set( xAxisColor );
  29790. color.toArray( array, 0 );
  29791. color.toArray( array, 3 );
  29792. color.set( yAxisColor );
  29793. color.toArray( array, 6 );
  29794. color.toArray( array, 9 );
  29795. color.set( zAxisColor );
  29796. color.toArray( array, 12 );
  29797. color.toArray( array, 15 );
  29798. this.geometry.attributes.color.needsUpdate = true;
  29799. return this;
  29800. }
  29801. dispose() {
  29802. this.geometry.dispose();
  29803. this.material.dispose();
  29804. }
  29805. }
  29806. const _floatView = new Float32Array( 1 );
  29807. const _int32View = new Int32Array( _floatView.buffer );
  29808. class DataUtils {
  29809. // Converts float32 to float16 (stored as uint16 value).
  29810. static toHalfFloat( val ) {
  29811. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  29812. /* This method is faster than the OpenEXR implementation (very often
  29813. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  29814. * by James Tursa?s half-precision code. */
  29815. _floatView[ 0 ] = val;
  29816. const x = _int32View[ 0 ];
  29817. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  29818. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  29819. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  29820. /* If zero, or denormal, or exponent underflows too much for a denormal
  29821. * half, return signed zero. */
  29822. if ( e < 103 ) return bits;
  29823. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  29824. if ( e > 142 ) {
  29825. bits |= 0x7c00;
  29826. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  29827. * not Inf, so make sure we set one mantissa bit too. */
  29828. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  29829. return bits;
  29830. }
  29831. /* If exponent underflows but not too much, return a denormal */
  29832. if ( e < 113 ) {
  29833. m |= 0x0800;
  29834. /* Extra rounding may overflow and set mantissa to 0 and exponent
  29835. * to 1, which is OK. */
  29836. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  29837. return bits;
  29838. }
  29839. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  29840. /* Extra rounding. An overflow will set mantissa to 0 and increment
  29841. * the exponent, which is OK. */
  29842. bits += m & 1;
  29843. return bits;
  29844. }
  29845. }
  29846. const LineStrip = 0;
  29847. const LinePieces = 1;
  29848. const NoColors = 0;
  29849. const FaceColors = 1;
  29850. const VertexColors = 2;
  29851. function MeshFaceMaterial( materials ) {
  29852. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  29853. return materials;
  29854. }
  29855. function MultiMaterial( materials = [] ) {
  29856. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  29857. materials.isMultiMaterial = true;
  29858. materials.materials = materials;
  29859. materials.clone = function () {
  29860. return materials.slice();
  29861. };
  29862. return materials;
  29863. }
  29864. function PointCloud( geometry, material ) {
  29865. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  29866. return new Points( geometry, material );
  29867. }
  29868. function Particle( material ) {
  29869. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  29870. return new Sprite( material );
  29871. }
  29872. function ParticleSystem( geometry, material ) {
  29873. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  29874. return new Points( geometry, material );
  29875. }
  29876. function PointCloudMaterial( parameters ) {
  29877. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  29878. return new PointsMaterial( parameters );
  29879. }
  29880. function ParticleBasicMaterial( parameters ) {
  29881. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  29882. return new PointsMaterial( parameters );
  29883. }
  29884. function ParticleSystemMaterial( parameters ) {
  29885. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  29886. return new PointsMaterial( parameters );
  29887. }
  29888. function Vertex( x, y, z ) {
  29889. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  29890. return new Vector3( x, y, z );
  29891. }
  29892. //
  29893. function DynamicBufferAttribute( array, itemSize ) {
  29894. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  29895. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  29896. }
  29897. function Int8Attribute( array, itemSize ) {
  29898. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  29899. return new Int8BufferAttribute( array, itemSize );
  29900. }
  29901. function Uint8Attribute( array, itemSize ) {
  29902. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  29903. return new Uint8BufferAttribute( array, itemSize );
  29904. }
  29905. function Uint8ClampedAttribute( array, itemSize ) {
  29906. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  29907. return new Uint8ClampedBufferAttribute( array, itemSize );
  29908. }
  29909. function Int16Attribute( array, itemSize ) {
  29910. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  29911. return new Int16BufferAttribute( array, itemSize );
  29912. }
  29913. function Uint16Attribute( array, itemSize ) {
  29914. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  29915. return new Uint16BufferAttribute( array, itemSize );
  29916. }
  29917. function Int32Attribute( array, itemSize ) {
  29918. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  29919. return new Int32BufferAttribute( array, itemSize );
  29920. }
  29921. function Uint32Attribute( array, itemSize ) {
  29922. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  29923. return new Uint32BufferAttribute( array, itemSize );
  29924. }
  29925. function Float32Attribute( array, itemSize ) {
  29926. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  29927. return new Float32BufferAttribute( array, itemSize );
  29928. }
  29929. function Float64Attribute( array, itemSize ) {
  29930. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29931. return new Float64BufferAttribute( array, itemSize );
  29932. }
  29933. //
  29934. Curve.create = function ( construct, getPoint ) {
  29935. console.log( 'THREE.Curve.create() has been deprecated' );
  29936. construct.prototype = Object.create( Curve.prototype );
  29937. construct.prototype.constructor = construct;
  29938. construct.prototype.getPoint = getPoint;
  29939. return construct;
  29940. };
  29941. //
  29942. Path.prototype.fromPoints = function ( points ) {
  29943. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  29944. return this.setFromPoints( points );
  29945. };
  29946. //
  29947. function AxisHelper( size ) {
  29948. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  29949. return new AxesHelper( size );
  29950. }
  29951. function BoundingBoxHelper( object, color ) {
  29952. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29953. return new BoxHelper( object, color );
  29954. }
  29955. function EdgesHelper( object, hex ) {
  29956. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29957. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29958. }
  29959. GridHelper.prototype.setColors = function () {
  29960. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29961. };
  29962. SkeletonHelper.prototype.update = function () {
  29963. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  29964. };
  29965. function WireframeHelper( object, hex ) {
  29966. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29967. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29968. }
  29969. //
  29970. Loader.prototype.extractUrlBase = function ( url ) {
  29971. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  29972. return LoaderUtils.extractUrlBase( url );
  29973. };
  29974. Loader.Handlers = {
  29975. add: function ( /* regex, loader */ ) {
  29976. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  29977. },
  29978. get: function ( /* file */ ) {
  29979. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  29980. }
  29981. };
  29982. function XHRLoader( manager ) {
  29983. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29984. return new FileLoader( manager );
  29985. }
  29986. function BinaryTextureLoader( manager ) {
  29987. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  29988. return new DataTextureLoader( manager );
  29989. }
  29990. //
  29991. Box2.prototype.center = function ( optionalTarget ) {
  29992. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29993. return this.getCenter( optionalTarget );
  29994. };
  29995. Box2.prototype.empty = function () {
  29996. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29997. return this.isEmpty();
  29998. };
  29999. Box2.prototype.isIntersectionBox = function ( box ) {
  30000. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30001. return this.intersectsBox( box );
  30002. };
  30003. Box2.prototype.size = function ( optionalTarget ) {
  30004. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  30005. return this.getSize( optionalTarget );
  30006. };
  30007. //
  30008. Box3.prototype.center = function ( optionalTarget ) {
  30009. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  30010. return this.getCenter( optionalTarget );
  30011. };
  30012. Box3.prototype.empty = function () {
  30013. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  30014. return this.isEmpty();
  30015. };
  30016. Box3.prototype.isIntersectionBox = function ( box ) {
  30017. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30018. return this.intersectsBox( box );
  30019. };
  30020. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  30021. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30022. return this.intersectsSphere( sphere );
  30023. };
  30024. Box3.prototype.size = function ( optionalTarget ) {
  30025. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  30026. return this.getSize( optionalTarget );
  30027. };
  30028. //
  30029. Sphere.prototype.empty = function () {
  30030. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  30031. return this.isEmpty();
  30032. };
  30033. //
  30034. Frustum.prototype.setFromMatrix = function ( m ) {
  30035. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  30036. return this.setFromProjectionMatrix( m );
  30037. };
  30038. //
  30039. Line3.prototype.center = function ( optionalTarget ) {
  30040. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  30041. return this.getCenter( optionalTarget );
  30042. };
  30043. //
  30044. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  30045. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30046. return this.toArray( array, offset );
  30047. };
  30048. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  30049. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  30050. return vector.applyMatrix3( this );
  30051. };
  30052. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  30053. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  30054. };
  30055. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  30056. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  30057. return attribute.applyMatrix3( this );
  30058. };
  30059. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  30060. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  30061. };
  30062. Matrix3.prototype.getInverse = function ( matrix ) {
  30063. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30064. return this.copy( matrix ).invert();
  30065. };
  30066. //
  30067. Matrix4.prototype.extractPosition = function ( m ) {
  30068. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  30069. return this.copyPosition( m );
  30070. };
  30071. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  30072. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30073. return this.toArray( array, offset );
  30074. };
  30075. Matrix4.prototype.getPosition = function () {
  30076. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  30077. return new Vector3().setFromMatrixColumn( this, 3 );
  30078. };
  30079. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  30080. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  30081. return this.makeRotationFromQuaternion( q );
  30082. };
  30083. Matrix4.prototype.multiplyToArray = function () {
  30084. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  30085. };
  30086. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  30087. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30088. return vector.applyMatrix4( this );
  30089. };
  30090. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  30091. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30092. return vector.applyMatrix4( this );
  30093. };
  30094. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  30095. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  30096. };
  30097. Matrix4.prototype.rotateAxis = function ( v ) {
  30098. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  30099. v.transformDirection( this );
  30100. };
  30101. Matrix4.prototype.crossVector = function ( vector ) {
  30102. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30103. return vector.applyMatrix4( this );
  30104. };
  30105. Matrix4.prototype.translate = function () {
  30106. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  30107. };
  30108. Matrix4.prototype.rotateX = function () {
  30109. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  30110. };
  30111. Matrix4.prototype.rotateY = function () {
  30112. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  30113. };
  30114. Matrix4.prototype.rotateZ = function () {
  30115. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  30116. };
  30117. Matrix4.prototype.rotateByAxis = function () {
  30118. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  30119. };
  30120. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  30121. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  30122. return attribute.applyMatrix4( this );
  30123. };
  30124. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  30125. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  30126. };
  30127. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  30128. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  30129. return this.makePerspective( left, right, top, bottom, near, far );
  30130. };
  30131. Matrix4.prototype.getInverse = function ( matrix ) {
  30132. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30133. return this.copy( matrix ).invert();
  30134. };
  30135. //
  30136. Plane.prototype.isIntersectionLine = function ( line ) {
  30137. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  30138. return this.intersectsLine( line );
  30139. };
  30140. //
  30141. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  30142. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  30143. return vector.applyQuaternion( this );
  30144. };
  30145. Quaternion.prototype.inverse = function ( ) {
  30146. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  30147. return this.invert();
  30148. };
  30149. //
  30150. Ray.prototype.isIntersectionBox = function ( box ) {
  30151. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30152. return this.intersectsBox( box );
  30153. };
  30154. Ray.prototype.isIntersectionPlane = function ( plane ) {
  30155. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  30156. return this.intersectsPlane( plane );
  30157. };
  30158. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  30159. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30160. return this.intersectsSphere( sphere );
  30161. };
  30162. //
  30163. Triangle.prototype.area = function () {
  30164. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  30165. return this.getArea();
  30166. };
  30167. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  30168. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30169. return this.getBarycoord( point, target );
  30170. };
  30171. Triangle.prototype.midpoint = function ( target ) {
  30172. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  30173. return this.getMidpoint( target );
  30174. };
  30175. Triangle.prototypenormal = function ( target ) {
  30176. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30177. return this.getNormal( target );
  30178. };
  30179. Triangle.prototype.plane = function ( target ) {
  30180. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  30181. return this.getPlane( target );
  30182. };
  30183. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  30184. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30185. return Triangle.getBarycoord( point, a, b, c, target );
  30186. };
  30187. Triangle.normal = function ( a, b, c, target ) {
  30188. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30189. return Triangle.getNormal( a, b, c, target );
  30190. };
  30191. //
  30192. Shape.prototype.extractAllPoints = function ( divisions ) {
  30193. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  30194. return this.extractPoints( divisions );
  30195. };
  30196. Shape.prototype.extrude = function ( options ) {
  30197. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  30198. return new ExtrudeGeometry( this, options );
  30199. };
  30200. Shape.prototype.makeGeometry = function ( options ) {
  30201. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  30202. return new ShapeGeometry( this, options );
  30203. };
  30204. //
  30205. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  30206. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30207. return this.fromBufferAttribute( attribute, index, offset );
  30208. };
  30209. Vector2.prototype.distanceToManhattan = function ( v ) {
  30210. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30211. return this.manhattanDistanceTo( v );
  30212. };
  30213. Vector2.prototype.lengthManhattan = function () {
  30214. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  30215. return this.manhattanLength();
  30216. };
  30217. //
  30218. Vector3.prototype.setEulerFromRotationMatrix = function () {
  30219. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  30220. };
  30221. Vector3.prototype.setEulerFromQuaternion = function () {
  30222. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  30223. };
  30224. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  30225. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  30226. return this.setFromMatrixPosition( m );
  30227. };
  30228. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  30229. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  30230. return this.setFromMatrixScale( m );
  30231. };
  30232. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  30233. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  30234. return this.setFromMatrixColumn( matrix, index );
  30235. };
  30236. Vector3.prototype.applyProjection = function ( m ) {
  30237. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  30238. return this.applyMatrix4( m );
  30239. };
  30240. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  30241. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30242. return this.fromBufferAttribute( attribute, index, offset );
  30243. };
  30244. Vector3.prototype.distanceToManhattan = function ( v ) {
  30245. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30246. return this.manhattanDistanceTo( v );
  30247. };
  30248. Vector3.prototype.lengthManhattan = function () {
  30249. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  30250. return this.manhattanLength();
  30251. };
  30252. //
  30253. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  30254. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30255. return this.fromBufferAttribute( attribute, index, offset );
  30256. };
  30257. Vector4.prototype.lengthManhattan = function () {
  30258. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  30259. return this.manhattanLength();
  30260. };
  30261. //
  30262. Object3D.prototype.getChildByName = function ( name ) {
  30263. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  30264. return this.getObjectByName( name );
  30265. };
  30266. Object3D.prototype.renderDepth = function () {
  30267. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  30268. };
  30269. Object3D.prototype.translate = function ( distance, axis ) {
  30270. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  30271. return this.translateOnAxis( axis, distance );
  30272. };
  30273. Object3D.prototype.getWorldRotation = function () {
  30274. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  30275. };
  30276. Object3D.prototype.applyMatrix = function ( matrix ) {
  30277. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  30278. return this.applyMatrix4( matrix );
  30279. };
  30280. Object.defineProperties( Object3D.prototype, {
  30281. eulerOrder: {
  30282. get: function () {
  30283. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30284. return this.rotation.order;
  30285. },
  30286. set: function ( value ) {
  30287. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30288. this.rotation.order = value;
  30289. }
  30290. },
  30291. useQuaternion: {
  30292. get: function () {
  30293. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30294. },
  30295. set: function () {
  30296. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30297. }
  30298. }
  30299. } );
  30300. Mesh.prototype.setDrawMode = function () {
  30301. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30302. };
  30303. Object.defineProperties( Mesh.prototype, {
  30304. drawMode: {
  30305. get: function () {
  30306. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  30307. return TrianglesDrawMode;
  30308. },
  30309. set: function () {
  30310. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30311. }
  30312. }
  30313. } );
  30314. SkinnedMesh.prototype.initBones = function () {
  30315. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  30316. };
  30317. //
  30318. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  30319. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  30320. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  30321. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  30322. this.setFocalLength( focalLength );
  30323. };
  30324. //
  30325. Object.defineProperties( Light.prototype, {
  30326. onlyShadow: {
  30327. set: function () {
  30328. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  30329. }
  30330. },
  30331. shadowCameraFov: {
  30332. set: function ( value ) {
  30333. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  30334. this.shadow.camera.fov = value;
  30335. }
  30336. },
  30337. shadowCameraLeft: {
  30338. set: function ( value ) {
  30339. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  30340. this.shadow.camera.left = value;
  30341. }
  30342. },
  30343. shadowCameraRight: {
  30344. set: function ( value ) {
  30345. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  30346. this.shadow.camera.right = value;
  30347. }
  30348. },
  30349. shadowCameraTop: {
  30350. set: function ( value ) {
  30351. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  30352. this.shadow.camera.top = value;
  30353. }
  30354. },
  30355. shadowCameraBottom: {
  30356. set: function ( value ) {
  30357. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  30358. this.shadow.camera.bottom = value;
  30359. }
  30360. },
  30361. shadowCameraNear: {
  30362. set: function ( value ) {
  30363. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  30364. this.shadow.camera.near = value;
  30365. }
  30366. },
  30367. shadowCameraFar: {
  30368. set: function ( value ) {
  30369. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  30370. this.shadow.camera.far = value;
  30371. }
  30372. },
  30373. shadowCameraVisible: {
  30374. set: function () {
  30375. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  30376. }
  30377. },
  30378. shadowBias: {
  30379. set: function ( value ) {
  30380. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  30381. this.shadow.bias = value;
  30382. }
  30383. },
  30384. shadowDarkness: {
  30385. set: function () {
  30386. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  30387. }
  30388. },
  30389. shadowMapWidth: {
  30390. set: function ( value ) {
  30391. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  30392. this.shadow.mapSize.width = value;
  30393. }
  30394. },
  30395. shadowMapHeight: {
  30396. set: function ( value ) {
  30397. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  30398. this.shadow.mapSize.height = value;
  30399. }
  30400. }
  30401. } );
  30402. //
  30403. Object.defineProperties( BufferAttribute.prototype, {
  30404. length: {
  30405. get: function () {
  30406. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  30407. return this.array.length;
  30408. }
  30409. },
  30410. dynamic: {
  30411. get: function () {
  30412. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30413. return this.usage === DynamicDrawUsage;
  30414. },
  30415. set: function ( /* value */ ) {
  30416. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30417. this.setUsage( DynamicDrawUsage );
  30418. }
  30419. }
  30420. } );
  30421. BufferAttribute.prototype.setDynamic = function ( value ) {
  30422. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30423. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30424. return this;
  30425. };
  30426. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  30427. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  30428. },
  30429. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  30430. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30431. };
  30432. //
  30433. BufferGeometry.prototype.addIndex = function ( index ) {
  30434. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  30435. this.setIndex( index );
  30436. };
  30437. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  30438. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  30439. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  30440. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  30441. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  30442. }
  30443. if ( name === 'index' ) {
  30444. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  30445. this.setIndex( attribute );
  30446. return this;
  30447. }
  30448. return this.setAttribute( name, attribute );
  30449. };
  30450. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  30451. if ( indexOffset !== undefined ) {
  30452. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  30453. }
  30454. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  30455. this.addGroup( start, count );
  30456. };
  30457. BufferGeometry.prototype.clearDrawCalls = function () {
  30458. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  30459. this.clearGroups();
  30460. };
  30461. BufferGeometry.prototype.computeOffsets = function () {
  30462. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  30463. };
  30464. BufferGeometry.prototype.removeAttribute = function ( name ) {
  30465. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  30466. return this.deleteAttribute( name );
  30467. };
  30468. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  30469. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30470. return this.applyMatrix4( matrix );
  30471. };
  30472. Object.defineProperties( BufferGeometry.prototype, {
  30473. drawcalls: {
  30474. get: function () {
  30475. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  30476. return this.groups;
  30477. }
  30478. },
  30479. offsets: {
  30480. get: function () {
  30481. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  30482. return this.groups;
  30483. }
  30484. }
  30485. } );
  30486. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  30487. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30488. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30489. return this;
  30490. };
  30491. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  30492. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30493. };
  30494. //
  30495. ExtrudeGeometry.prototype.getArrays = function () {
  30496. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  30497. };
  30498. ExtrudeGeometry.prototype.addShapeList = function () {
  30499. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  30500. };
  30501. ExtrudeGeometry.prototype.addShape = function () {
  30502. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  30503. };
  30504. //
  30505. Scene.prototype.dispose = function () {
  30506. console.error( 'THREE.Scene: .dispose() has been removed.' );
  30507. };
  30508. //
  30509. Uniform.prototype.onUpdate = function () {
  30510. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30511. return this;
  30512. };
  30513. //
  30514. Object.defineProperties( Material.prototype, {
  30515. wrapAround: {
  30516. get: function () {
  30517. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30518. },
  30519. set: function () {
  30520. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30521. }
  30522. },
  30523. overdraw: {
  30524. get: function () {
  30525. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30526. },
  30527. set: function () {
  30528. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30529. }
  30530. },
  30531. wrapRGB: {
  30532. get: function () {
  30533. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  30534. return new Color();
  30535. }
  30536. },
  30537. shading: {
  30538. get: function () {
  30539. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30540. },
  30541. set: function ( value ) {
  30542. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30543. this.flatShading = ( value === FlatShading );
  30544. }
  30545. },
  30546. stencilMask: {
  30547. get: function () {
  30548. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30549. return this.stencilFuncMask;
  30550. },
  30551. set: function ( value ) {
  30552. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30553. this.stencilFuncMask = value;
  30554. }
  30555. },
  30556. vertexTangents: {
  30557. get: function () {
  30558. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  30559. },
  30560. set: function () {
  30561. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  30562. }
  30563. },
  30564. } );
  30565. Object.defineProperties( ShaderMaterial.prototype, {
  30566. derivatives: {
  30567. get: function () {
  30568. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30569. return this.extensions.derivatives;
  30570. },
  30571. set: function ( value ) {
  30572. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30573. this.extensions.derivatives = value;
  30574. }
  30575. }
  30576. } );
  30577. //
  30578. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  30579. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  30580. this.setRenderTarget( renderTarget );
  30581. this.clear( color, depth, stencil );
  30582. };
  30583. WebGLRenderer.prototype.animate = function ( callback ) {
  30584. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  30585. this.setAnimationLoop( callback );
  30586. };
  30587. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  30588. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  30589. return this.getRenderTarget();
  30590. };
  30591. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  30592. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  30593. return this.capabilities.getMaxAnisotropy();
  30594. };
  30595. WebGLRenderer.prototype.getPrecision = function () {
  30596. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  30597. return this.capabilities.precision;
  30598. };
  30599. WebGLRenderer.prototype.resetGLState = function () {
  30600. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  30601. return this.state.reset();
  30602. };
  30603. WebGLRenderer.prototype.supportsFloatTextures = function () {
  30604. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30605. return this.extensions.get( 'OES_texture_float' );
  30606. };
  30607. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  30608. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30609. return this.extensions.get( 'OES_texture_half_float' );
  30610. };
  30611. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  30612. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30613. return this.extensions.get( 'OES_standard_derivatives' );
  30614. };
  30615. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  30616. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30617. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30618. };
  30619. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  30620. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30621. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30622. };
  30623. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  30624. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30625. return this.extensions.get( 'EXT_blend_minmax' );
  30626. };
  30627. WebGLRenderer.prototype.supportsVertexTextures = function () {
  30628. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30629. return this.capabilities.vertexTextures;
  30630. };
  30631. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  30632. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30633. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30634. };
  30635. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  30636. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  30637. this.setScissorTest( boolean );
  30638. };
  30639. WebGLRenderer.prototype.initMaterial = function () {
  30640. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  30641. };
  30642. WebGLRenderer.prototype.addPrePlugin = function () {
  30643. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  30644. };
  30645. WebGLRenderer.prototype.addPostPlugin = function () {
  30646. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  30647. };
  30648. WebGLRenderer.prototype.updateShadowMap = function () {
  30649. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  30650. };
  30651. WebGLRenderer.prototype.setFaceCulling = function () {
  30652. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  30653. };
  30654. WebGLRenderer.prototype.allocTextureUnit = function () {
  30655. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  30656. };
  30657. WebGLRenderer.prototype.setTexture = function () {
  30658. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  30659. };
  30660. WebGLRenderer.prototype.setTexture2D = function () {
  30661. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  30662. };
  30663. WebGLRenderer.prototype.setTextureCube = function () {
  30664. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  30665. };
  30666. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  30667. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  30668. return this.getActiveMipmapLevel();
  30669. };
  30670. Object.defineProperties( WebGLRenderer.prototype, {
  30671. shadowMapEnabled: {
  30672. get: function () {
  30673. return this.shadowMap.enabled;
  30674. },
  30675. set: function ( value ) {
  30676. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  30677. this.shadowMap.enabled = value;
  30678. }
  30679. },
  30680. shadowMapType: {
  30681. get: function () {
  30682. return this.shadowMap.type;
  30683. },
  30684. set: function ( value ) {
  30685. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  30686. this.shadowMap.type = value;
  30687. }
  30688. },
  30689. shadowMapCullFace: {
  30690. get: function () {
  30691. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30692. return undefined;
  30693. },
  30694. set: function ( /* value */ ) {
  30695. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30696. }
  30697. },
  30698. context: {
  30699. get: function () {
  30700. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  30701. return this.getContext();
  30702. }
  30703. },
  30704. vr: {
  30705. get: function () {
  30706. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  30707. return this.xr;
  30708. }
  30709. },
  30710. gammaInput: {
  30711. get: function () {
  30712. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30713. return false;
  30714. },
  30715. set: function () {
  30716. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30717. }
  30718. },
  30719. gammaOutput: {
  30720. get: function () {
  30721. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30722. return false;
  30723. },
  30724. set: function ( value ) {
  30725. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30726. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  30727. }
  30728. },
  30729. toneMappingWhitePoint: {
  30730. get: function () {
  30731. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30732. return 1.0;
  30733. },
  30734. set: function () {
  30735. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30736. }
  30737. },
  30738. } );
  30739. Object.defineProperties( WebGLShadowMap.prototype, {
  30740. cullFace: {
  30741. get: function () {
  30742. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30743. return undefined;
  30744. },
  30745. set: function ( /* cullFace */ ) {
  30746. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30747. }
  30748. },
  30749. renderReverseSided: {
  30750. get: function () {
  30751. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30752. return undefined;
  30753. },
  30754. set: function () {
  30755. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30756. }
  30757. },
  30758. renderSingleSided: {
  30759. get: function () {
  30760. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30761. return undefined;
  30762. },
  30763. set: function () {
  30764. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30765. }
  30766. }
  30767. } );
  30768. function WebGLRenderTargetCube( width, height, options ) {
  30769. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  30770. return new WebGLCubeRenderTarget( width, options );
  30771. }
  30772. //
  30773. Object.defineProperties( WebGLRenderTarget.prototype, {
  30774. wrapS: {
  30775. get: function () {
  30776. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30777. return this.texture.wrapS;
  30778. },
  30779. set: function ( value ) {
  30780. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30781. this.texture.wrapS = value;
  30782. }
  30783. },
  30784. wrapT: {
  30785. get: function () {
  30786. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30787. return this.texture.wrapT;
  30788. },
  30789. set: function ( value ) {
  30790. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30791. this.texture.wrapT = value;
  30792. }
  30793. },
  30794. magFilter: {
  30795. get: function () {
  30796. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30797. return this.texture.magFilter;
  30798. },
  30799. set: function ( value ) {
  30800. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30801. this.texture.magFilter = value;
  30802. }
  30803. },
  30804. minFilter: {
  30805. get: function () {
  30806. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30807. return this.texture.minFilter;
  30808. },
  30809. set: function ( value ) {
  30810. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30811. this.texture.minFilter = value;
  30812. }
  30813. },
  30814. anisotropy: {
  30815. get: function () {
  30816. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30817. return this.texture.anisotropy;
  30818. },
  30819. set: function ( value ) {
  30820. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30821. this.texture.anisotropy = value;
  30822. }
  30823. },
  30824. offset: {
  30825. get: function () {
  30826. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30827. return this.texture.offset;
  30828. },
  30829. set: function ( value ) {
  30830. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30831. this.texture.offset = value;
  30832. }
  30833. },
  30834. repeat: {
  30835. get: function () {
  30836. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30837. return this.texture.repeat;
  30838. },
  30839. set: function ( value ) {
  30840. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30841. this.texture.repeat = value;
  30842. }
  30843. },
  30844. format: {
  30845. get: function () {
  30846. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30847. return this.texture.format;
  30848. },
  30849. set: function ( value ) {
  30850. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30851. this.texture.format = value;
  30852. }
  30853. },
  30854. type: {
  30855. get: function () {
  30856. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30857. return this.texture.type;
  30858. },
  30859. set: function ( value ) {
  30860. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30861. this.texture.type = value;
  30862. }
  30863. },
  30864. generateMipmaps: {
  30865. get: function () {
  30866. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30867. return this.texture.generateMipmaps;
  30868. },
  30869. set: function ( value ) {
  30870. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30871. this.texture.generateMipmaps = value;
  30872. }
  30873. }
  30874. } );
  30875. //
  30876. Audio.prototype.load = function ( file ) {
  30877. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  30878. const scope = this;
  30879. const audioLoader = new AudioLoader();
  30880. audioLoader.load( file, function ( buffer ) {
  30881. scope.setBuffer( buffer );
  30882. } );
  30883. return this;
  30884. };
  30885. AudioAnalyser.prototype.getData = function () {
  30886. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  30887. return this.getFrequencyData();
  30888. };
  30889. //
  30890. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  30891. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  30892. return this.update( renderer, scene );
  30893. };
  30894. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  30895. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  30896. return this.renderTarget.clear( renderer, color, depth, stencil );
  30897. };
  30898. ImageUtils.crossOrigin = undefined;
  30899. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  30900. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  30901. const loader = new TextureLoader();
  30902. loader.setCrossOrigin( this.crossOrigin );
  30903. const texture = loader.load( url, onLoad, undefined, onError );
  30904. if ( mapping ) texture.mapping = mapping;
  30905. return texture;
  30906. };
  30907. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  30908. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  30909. const loader = new CubeTextureLoader();
  30910. loader.setCrossOrigin( this.crossOrigin );
  30911. const texture = loader.load( urls, onLoad, undefined, onError );
  30912. if ( mapping ) texture.mapping = mapping;
  30913. return texture;
  30914. };
  30915. ImageUtils.loadCompressedTexture = function () {
  30916. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  30917. };
  30918. ImageUtils.loadCompressedTextureCube = function () {
  30919. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  30920. };
  30921. //
  30922. function CanvasRenderer() {
  30923. console.error( 'THREE.CanvasRenderer has been removed' );
  30924. }
  30925. //
  30926. function JSONLoader() {
  30927. console.error( 'THREE.JSONLoader has been removed.' );
  30928. }
  30929. //
  30930. const SceneUtils = {
  30931. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  30932. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30933. },
  30934. detach: function ( /* child, parent, scene */ ) {
  30935. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30936. },
  30937. attach: function ( /* child, scene, parent */ ) {
  30938. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30939. }
  30940. };
  30941. //
  30942. function LensFlare() {
  30943. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  30944. }
  30945. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30946. /* eslint-disable no-undef */
  30947. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30948. revision: REVISION,
  30949. } } ) );
  30950. /* eslint-enable no-undef */
  30951. }
  30952. if ( typeof window !== 'undefined' ) {
  30953. if ( window.__THREE__ ) {
  30954. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30955. } else {
  30956. window.__THREE__ = REVISION;
  30957. }
  30958. }
  30959. /***/ })
  30960. /******/ });
  30961. /************************************************************************/
  30962. /******/ // The module cache
  30963. /******/ var __webpack_module_cache__ = {};
  30964. /******/
  30965. /******/ // The require function
  30966. /******/ function __webpack_require__(moduleId) {
  30967. /******/ // Check if module is in cache
  30968. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  30969. /******/ if (cachedModule !== undefined) {
  30970. /******/ return cachedModule.exports;
  30971. /******/ }
  30972. /******/ // Create a new module (and put it into the cache)
  30973. /******/ var module = __webpack_module_cache__[moduleId] = {
  30974. /******/ // no module.id needed
  30975. /******/ // no module.loaded needed
  30976. /******/ exports: {}
  30977. /******/ };
  30978. /******/
  30979. /******/ // Execute the module function
  30980. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  30981. /******/
  30982. /******/ // Return the exports of the module
  30983. /******/ return module.exports;
  30984. /******/ }
  30985. /******/
  30986. /************************************************************************/
  30987. /******/ /* webpack/runtime/define property getters */
  30988. /******/ (() => {
  30989. /******/ // define getter functions for harmony exports
  30990. /******/ __webpack_require__.d = (exports, definition) => {
  30991. /******/ for(var key in definition) {
  30992. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  30993. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  30994. /******/ }
  30995. /******/ }
  30996. /******/ };
  30997. /******/ })();
  30998. /******/
  30999. /******/ /* webpack/runtime/global */
  31000. /******/ (() => {
  31001. /******/ __webpack_require__.g = (function() {
  31002. /******/ if (typeof globalThis === 'object') return globalThis;
  31003. /******/ try {
  31004. /******/ return this || new Function('return this')();
  31005. /******/ } catch (e) {
  31006. /******/ if (typeof window === 'object') return window;
  31007. /******/ }
  31008. /******/ })();
  31009. /******/ })();
  31010. /******/
  31011. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  31012. /******/ (() => {
  31013. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  31014. /******/ })();
  31015. /******/
  31016. /******/ /* webpack/runtime/make namespace object */
  31017. /******/ (() => {
  31018. /******/ // define __esModule on exports
  31019. /******/ __webpack_require__.r = (exports) => {
  31020. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  31021. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  31022. /******/ }
  31023. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  31024. /******/ };
  31025. /******/ })();
  31026. /******/
  31027. /******/ /* webpack/runtime/publicPath */
  31028. /******/ (() => {
  31029. /******/ var scriptUrl;
  31030. /******/ if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
  31031. /******/ var document = __webpack_require__.g.document;
  31032. /******/ if (!scriptUrl && document) {
  31033. /******/ if (document.currentScript)
  31034. /******/ scriptUrl = document.currentScript.src
  31035. /******/ if (!scriptUrl) {
  31036. /******/ var scripts = document.getElementsByTagName("script");
  31037. /******/ if(scripts.length) scriptUrl = scripts[scripts.length - 1].src
  31038. /******/ }
  31039. /******/ }
  31040. /******/ // When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
  31041. /******/ // or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
  31042. /******/ if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
  31043. /******/ scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
  31044. /******/ __webpack_require__.p = scriptUrl;
  31045. /******/ })();
  31046. /******/
  31047. /************************************************************************/
  31048. var __webpack_exports__ = {};
  31049. // This entry need to be wrapped in an IIFE because it need to be in strict mode.
  31050. (() => {
  31051. "use strict";
  31052. /*!**********************!*\
  31053. !*** ./src/Dubel.js ***!
  31054. \**********************/
  31055. __webpack_require__.r(__webpack_exports__);
  31056. /* harmony import */ var three__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! three */ "./node_modules/three/build/three.module.js");
  31057. /* harmony import */ var _Users_chop_Desktop_chamran_Three_texture_text_png__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Users/chop/Desktop/chamran/Three/texture/text.png */ "../../Users/chop/Desktop/chamran/Three/texture/text.png");
  31058. /* harmony import */ var three_dragcontrols__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! three-dragcontrols */ "./node_modules/three-dragcontrols/lib/index.module.js");
  31059. var OrbitControls = __webpack_require__(/*! three-orbitcontrols */ "./node_modules/three-orbitcontrols/OrbitControls.js");
  31060. var main = document.querySelector("#main");
  31061. var scene = new three__WEBPACK_IMPORTED_MODULE_2__.Scene();
  31062. var camera = new three__WEBPACK_IMPORTED_MODULE_2__.PerspectiveCamera(75, innerHeight / innerHeight, 0.1, 1000); // controls.enableDamping = true
  31063. // controls.dampingFactor = 0.25
  31064. // controls.enableZoom = false
  31065. var light = new three__WEBPACK_IMPORTED_MODULE_2__.PointLight(0xffffff, 1, 1000);
  31066. light.position.set(200, 200, 200);
  31067. scene.add(light);
  31068. scene.background = new three__WEBPACK_IMPORTED_MODULE_2__.Color("#17191c");
  31069. camera.position.set(0, 0, 100);
  31070. var renderer = new three__WEBPACK_IMPORTED_MODULE_2__.WebGLRenderer();
  31071. var texture = new three__WEBPACK_IMPORTED_MODULE_2__.TextureLoader().load(_Users_chop_Desktop_chamran_Three_texture_text_png__WEBPACK_IMPORTED_MODULE_0__["default"]);
  31072. texture.wrapS = three__WEBPACK_IMPORTED_MODULE_2__.RepeatWrapping;
  31073. texture.wrapT = three__WEBPACK_IMPORTED_MODULE_2__.RepeatWrapping;
  31074. texture.repeat.set(10, 6);
  31075. var ballMaterial1 = {
  31076. clearcoat: 1.0,
  31077. cleacoatRoughness: 0.1,
  31078. metalness: 0.9,
  31079. roughness: 0.5,
  31080. color: "#8afff1",
  31081. normalMap: texture,
  31082. normalScale: new three__WEBPACK_IMPORTED_MODULE_2__.Vector2(0.15, 0.15)
  31083. };
  31084. var ballMaterial2 = {
  31085. clearcoat: 1.0,
  31086. cleacoatRoughness: 0.1,
  31087. metalness: 0.9,
  31088. roughness: 0.5,
  31089. color: "red",
  31090. normalMap: texture,
  31091. normalScale: new three__WEBPACK_IMPORTED_MODULE_2__.Vector2(0.15, 0.15)
  31092. };
  31093. var dayere = new three__WEBPACK_IMPORTED_MODULE_2__.SphereGeometry(20, 64, 64);
  31094. var dayereTex1 = new three__WEBPACK_IMPORTED_MODULE_2__.MeshPhysicalMaterial(ballMaterial1);
  31095. var dayereTex2 = new three__WEBPACK_IMPORTED_MODULE_2__.MeshPhysicalMaterial(ballMaterial2);
  31096. var meterial = new three__WEBPACK_IMPORTED_MODULE_2__.MeshBasicMaterial();
  31097. meterial.color.set('#e61cc7');
  31098. var mesh1 = new three__WEBPACK_IMPORTED_MODULE_2__.Mesh(dayere, dayereTex1);
  31099. var mesh2 = new three__WEBPACK_IMPORTED_MODULE_2__.Mesh(dayere, dayereTex2);
  31100. mesh1.position.x = 30;
  31101. mesh2.position.x = -30; // var fgeometry = new THREE.PlaneGeometry( 500, 500, 1, 1 );
  31102. // var fmaterial = new THREE.MeshBasicMaterial( { color: "#1c3ae6" } )
  31103. // var floor = new THREE.Mesh( fgeometry, fmaterial );
  31104. // floor.material.side = THREE.DoubleSide;
  31105. // floor.rotation.x = 90;
  31106. // scene.add( floor );
  31107. renderer.setSize(innerWidth, innerHeight);
  31108. main.appendChild(renderer.domElement);
  31109. scene.add(mesh1);
  31110. scene.add(mesh2); // const controls = new DragControls(geometry, camera, renderer.domElement)
  31111. // console.log(controls);
  31112. // controls.addEventListener('dragstart', function (event) {
  31113. // console.log("adadwdsd");
  31114. // event.geometry.material.opacity = 0.33
  31115. // console.log(event);
  31116. // })
  31117. // controls.addEventListener('dragend', function (event) {
  31118. // event.geometry.material.opacity = 1
  31119. // })
  31120. var controlsCamra = new OrbitControls(camera, renderer.domElement);
  31121. function animate() {
  31122. controlsCamra.update();
  31123. requestAnimationFrame(animate);
  31124. renderer.render(scene, camera); // mesh.rotation.y += 0.01;
  31125. }
  31126. animate();
  31127. })();
  31128. /******/ })()
  31129. ;