OrbitControls.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  1. import {
  2. EventDispatcher,
  3. MOUSE,
  4. Quaternion,
  5. Spherical,
  6. TOUCH,
  7. Vector2,
  8. Vector3,
  9. Plane,
  10. Ray,
  11. MathUtils
  12. } from 'three';
  13. // OrbitControls performs orbiting, dollying (zooming), and panning.
  14. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  15. //
  16. // Orbit - left mouse / touch: one-finger move
  17. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  18. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  19. const _changeEvent = { type: 'change' };
  20. const _startEvent = { type: 'start' };
  21. const _endEvent = { type: 'end' };
  22. const _ray = new Ray();
  23. const _plane = new Plane();
  24. const TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
  25. class OrbitControls extends EventDispatcher {
  26. constructor( object, domElement ) {
  27. super();
  28. this.object = object;
  29. this.domElement = domElement;
  30. this.domElement.style.touchAction = 'none'; // disable touch scroll
  31. // Set to false to disable this control
  32. this.enabled = true;
  33. // "target" sets the location of focus, where the object orbits around
  34. this.target = new Vector3();
  35. // Sets the 3D cursor (similar to Blender), from which the maxTargetRadius takes effect
  36. this.cursor = new Vector3();
  37. // How far you can dolly in and out ( PerspectiveCamera only )
  38. this.minDistance = 0;
  39. this.maxDistance = Infinity;
  40. // How far you can zoom in and out ( OrthographicCamera only )
  41. this.minZoom = 0;
  42. this.maxZoom = Infinity;
  43. // Limit camera target within a spherical area around the cursor
  44. this.minTargetRadius = 0;
  45. this.maxTargetRadius = Infinity;
  46. // How far you can orbit vertically, upper and lower limits.
  47. // Range is 0 to Math.PI radians.
  48. this.minPolarAngle = 0; // radians
  49. this.maxPolarAngle = Math.PI; // radians
  50. // How far you can orbit horizontally, upper and lower limits.
  51. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
  52. this.minAzimuthAngle = - Infinity; // radians
  53. this.maxAzimuthAngle = Infinity; // radians
  54. // Set to true to enable damping (inertia)
  55. // If damping is enabled, you must call controls.update() in your animation loop
  56. this.enableDamping = false;
  57. this.dampingFactor = 0.05;
  58. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  59. // Set to false to disable zooming
  60. this.enableZoom = true;
  61. this.zoomSpeed = 1.0;
  62. // Set to false to disable rotating
  63. this.enableRotate = true;
  64. this.rotateSpeed = 1.0;
  65. // Set to false to disable panning
  66. this.enablePan = true;
  67. this.panSpeed = 1.0;
  68. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  69. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  70. this.zoomToCursor = false;
  71. // Set to true to automatically rotate around the target
  72. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  73. this.autoRotate = false;
  74. this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
  75. // The four arrow keys
  76. this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
  77. // Mouse buttons
  78. this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
  79. // Touch fingers
  80. this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
  81. // for reset
  82. this.target0 = this.target.clone();
  83. this.position0 = this.object.position.clone();
  84. this.zoom0 = this.object.zoom;
  85. // the target DOM element for key events
  86. this._domElementKeyEvents = null;
  87. //
  88. // public methods
  89. //
  90. this.getPolarAngle = function () {
  91. return spherical.phi;
  92. };
  93. this.getAzimuthalAngle = function () {
  94. return spherical.theta;
  95. };
  96. this.getDistance = function () {
  97. return this.object.position.distanceTo( this.target );
  98. };
  99. this.listenToKeyEvents = function ( domElement ) {
  100. domElement.addEventListener( 'keydown', onKeyDown );
  101. this._domElementKeyEvents = domElement;
  102. };
  103. this.stopListenToKeyEvents = function () {
  104. this._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  105. this._domElementKeyEvents = null;
  106. };
  107. this.saveState = function () {
  108. scope.target0.copy( scope.target );
  109. scope.position0.copy( scope.object.position );
  110. scope.zoom0 = scope.object.zoom;
  111. };
  112. this.reset = function () {
  113. scope.target.copy( scope.target0 );
  114. scope.object.position.copy( scope.position0 );
  115. scope.object.zoom = scope.zoom0;
  116. scope.object.updateProjectionMatrix();
  117. scope.dispatchEvent( _changeEvent );
  118. scope.update();
  119. state = STATE.NONE;
  120. };
  121. // this method is exposed, but perhaps it would be better if we can make it private...
  122. this.update = function () {
  123. const offset = new Vector3();
  124. // so camera.up is the orbit axis
  125. const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
  126. const quatInverse = quat.clone().invert();
  127. const lastPosition = new Vector3();
  128. const lastQuaternion = new Quaternion();
  129. const lastTargetPosition = new Vector3();
  130. const twoPI = 2 * Math.PI;
  131. return function update( deltaTime = null ) {
  132. const position = scope.object.position;
  133. offset.copy( position ).sub( scope.target );
  134. // rotate offset to "y-axis-is-up" space
  135. offset.applyQuaternion( quat );
  136. // angle from z-axis around y-axis
  137. spherical.setFromVector3( offset );
  138. if ( scope.autoRotate && state === STATE.NONE ) {
  139. rotateLeft( getAutoRotationAngle( deltaTime ) );
  140. }
  141. if ( scope.enableDamping ) {
  142. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  143. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  144. } else {
  145. spherical.theta += sphericalDelta.theta;
  146. spherical.phi += sphericalDelta.phi;
  147. }
  148. // restrict theta to be between desired limits
  149. let min = scope.minAzimuthAngle;
  150. let max = scope.maxAzimuthAngle;
  151. if ( isFinite( min ) && isFinite( max ) ) {
  152. if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
  153. if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
  154. if ( min <= max ) {
  155. spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
  156. } else {
  157. spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ?
  158. Math.max( min, spherical.theta ) :
  159. Math.min( max, spherical.theta );
  160. }
  161. }
  162. // restrict phi to be between desired limits
  163. spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
  164. spherical.makeSafe();
  165. // move target to panned location
  166. if ( scope.enableDamping === true ) {
  167. scope.target.addScaledVector( panOffset, scope.dampingFactor );
  168. } else {
  169. scope.target.add( panOffset );
  170. }
  171. // Limit the target distance from the cursor to create a sphere around the center of interest
  172. scope.target.sub( scope.cursor );
  173. scope.target.clampLength( scope.minTargetRadius, scope.maxTargetRadius );
  174. scope.target.add( scope.cursor );
  175. // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
  176. // we adjust zoom later in these cases
  177. if ( scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera ) {
  178. spherical.radius = clampDistance( spherical.radius );
  179. } else {
  180. spherical.radius = clampDistance( spherical.radius * scale );
  181. }
  182. offset.setFromSpherical( spherical );
  183. // rotate offset back to "camera-up-vector-is-up" space
  184. offset.applyQuaternion( quatInverse );
  185. position.copy( scope.target ).add( offset );
  186. scope.object.lookAt( scope.target );
  187. if ( scope.enableDamping === true ) {
  188. sphericalDelta.theta *= ( 1 - scope.dampingFactor );
  189. sphericalDelta.phi *= ( 1 - scope.dampingFactor );
  190. panOffset.multiplyScalar( 1 - scope.dampingFactor );
  191. } else {
  192. sphericalDelta.set( 0, 0, 0 );
  193. panOffset.set( 0, 0, 0 );
  194. }
  195. // adjust camera position
  196. let zoomChanged = false;
  197. if ( scope.zoomToCursor && performCursorZoom ) {
  198. let newRadius = null;
  199. if ( scope.object.isPerspectiveCamera ) {
  200. // move the camera down the pointer ray
  201. // this method avoids floating point error
  202. const prevRadius = offset.length();
  203. newRadius = clampDistance( prevRadius * scale );
  204. const radiusDelta = prevRadius - newRadius;
  205. scope.object.position.addScaledVector( dollyDirection, radiusDelta );
  206. scope.object.updateMatrixWorld();
  207. } else if ( scope.object.isOrthographicCamera ) {
  208. // adjust the ortho camera position based on zoom changes
  209. const mouseBefore = new Vector3( mouse.x, mouse.y, 0 );
  210. mouseBefore.unproject( scope.object );
  211. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) );
  212. scope.object.updateProjectionMatrix();
  213. zoomChanged = true;
  214. const mouseAfter = new Vector3( mouse.x, mouse.y, 0 );
  215. mouseAfter.unproject( scope.object );
  216. scope.object.position.sub( mouseAfter ).add( mouseBefore );
  217. scope.object.updateMatrixWorld();
  218. newRadius = offset.length();
  219. } else {
  220. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' );
  221. scope.zoomToCursor = false;
  222. }
  223. // handle the placement of the target
  224. if ( newRadius !== null ) {
  225. if ( this.screenSpacePanning ) {
  226. // position the orbit target in front of the new camera position
  227. scope.target.set( 0, 0, - 1 )
  228. .transformDirection( scope.object.matrix )
  229. .multiplyScalar( newRadius )
  230. .add( scope.object.position );
  231. } else {
  232. // get the ray and translation plane to compute target
  233. _ray.origin.copy( scope.object.position );
  234. _ray.direction.set( 0, 0, - 1 ).transformDirection( scope.object.matrix );
  235. // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
  236. // extremely large values
  237. if ( Math.abs( scope.object.up.dot( _ray.direction ) ) < TILT_LIMIT ) {
  238. object.lookAt( scope.target );
  239. } else {
  240. _plane.setFromNormalAndCoplanarPoint( scope.object.up, scope.target );
  241. _ray.intersectPlane( _plane, scope.target );
  242. }
  243. }
  244. }
  245. } else if ( scope.object.isOrthographicCamera ) {
  246. zoomChanged = scale !== 1;
  247. if ( zoomChanged ) {
  248. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) );
  249. scope.object.updateProjectionMatrix();
  250. }
  251. }
  252. scale = 1;
  253. performCursorZoom = false;
  254. // update condition is:
  255. // min(camera displacement, camera rotation in radians)^2 > EPS
  256. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  257. if ( zoomChanged ||
  258. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  259. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ||
  260. lastTargetPosition.distanceToSquared( scope.target ) > EPS ) {
  261. scope.dispatchEvent( _changeEvent );
  262. lastPosition.copy( scope.object.position );
  263. lastQuaternion.copy( scope.object.quaternion );
  264. lastTargetPosition.copy( scope.target );
  265. return true;
  266. }
  267. return false;
  268. };
  269. }();
  270. this.dispose = function () {
  271. scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
  272. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  273. scope.domElement.removeEventListener( 'pointercancel', onPointerUp );
  274. scope.domElement.removeEventListener( 'wheel', onMouseWheel );
  275. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  276. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  277. if ( scope._domElementKeyEvents !== null ) {
  278. scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  279. scope._domElementKeyEvents = null;
  280. }
  281. //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  282. };
  283. //
  284. // internals
  285. //
  286. const scope = this;
  287. const STATE = {
  288. NONE: - 1,
  289. ROTATE: 0,
  290. DOLLY: 1,
  291. PAN: 2,
  292. TOUCH_ROTATE: 3,
  293. TOUCH_PAN: 4,
  294. TOUCH_DOLLY_PAN: 5,
  295. TOUCH_DOLLY_ROTATE: 6
  296. };
  297. let state = STATE.NONE;
  298. const EPS = 0.000001;
  299. // current position in spherical coordinates
  300. const spherical = new Spherical();
  301. const sphericalDelta = new Spherical();
  302. let scale = 1;
  303. const panOffset = new Vector3();
  304. const rotateStart = new Vector2();
  305. const rotateEnd = new Vector2();
  306. const rotateDelta = new Vector2();
  307. const panStart = new Vector2();
  308. const panEnd = new Vector2();
  309. const panDelta = new Vector2();
  310. const dollyStart = new Vector2();
  311. const dollyEnd = new Vector2();
  312. const dollyDelta = new Vector2();
  313. const dollyDirection = new Vector3();
  314. const mouse = new Vector2();
  315. let performCursorZoom = false;
  316. const pointers = [];
  317. const pointerPositions = {};
  318. let controlActive = false;
  319. function getAutoRotationAngle( deltaTime ) {
  320. if ( deltaTime !== null ) {
  321. return ( 2 * Math.PI / 60 * scope.autoRotateSpeed ) * deltaTime;
  322. } else {
  323. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  324. }
  325. }
  326. function getZoomScale( delta ) {
  327. const normalizedDelta = Math.abs( delta * 0.01 );
  328. return Math.pow( 0.95, scope.zoomSpeed * normalizedDelta );
  329. }
  330. function rotateLeft( angle ) {
  331. sphericalDelta.theta -= angle;
  332. }
  333. function rotateUp( angle ) {
  334. sphericalDelta.phi -= angle;
  335. }
  336. const panLeft = function () {
  337. const v = new Vector3();
  338. return function panLeft( distance, objectMatrix ) {
  339. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  340. v.multiplyScalar( - distance );
  341. panOffset.add( v );
  342. };
  343. }();
  344. const panUp = function () {
  345. const v = new Vector3();
  346. return function panUp( distance, objectMatrix ) {
  347. if ( scope.screenSpacePanning === true ) {
  348. v.setFromMatrixColumn( objectMatrix, 1 );
  349. } else {
  350. v.setFromMatrixColumn( objectMatrix, 0 );
  351. v.crossVectors( scope.object.up, v );
  352. }
  353. v.multiplyScalar( distance );
  354. panOffset.add( v );
  355. };
  356. }();
  357. // deltaX and deltaY are in pixels; right and down are positive
  358. const pan = function () {
  359. const offset = new Vector3();
  360. return function pan( deltaX, deltaY ) {
  361. const element = scope.domElement;
  362. if ( scope.object.isPerspectiveCamera ) {
  363. // perspective
  364. const position = scope.object.position;
  365. offset.copy( position ).sub( scope.target );
  366. let targetDistance = offset.length();
  367. // half of the fov is center to top of screen
  368. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  369. // we use only clientHeight here so aspect ratio does not distort speed
  370. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  371. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  372. } else if ( scope.object.isOrthographicCamera ) {
  373. // orthographic
  374. panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
  375. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
  376. } else {
  377. // camera neither orthographic nor perspective
  378. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  379. scope.enablePan = false;
  380. }
  381. };
  382. }();
  383. function dollyOut( dollyScale ) {
  384. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  385. scale /= dollyScale;
  386. } else {
  387. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  388. scope.enableZoom = false;
  389. }
  390. }
  391. function dollyIn( dollyScale ) {
  392. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  393. scale *= dollyScale;
  394. } else {
  395. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  396. scope.enableZoom = false;
  397. }
  398. }
  399. function updateZoomParameters( x, y ) {
  400. if ( ! scope.zoomToCursor ) {
  401. return;
  402. }
  403. performCursorZoom = true;
  404. const rect = scope.domElement.getBoundingClientRect();
  405. const dx = x - rect.left;
  406. const dy = y - rect.top;
  407. const w = rect.width;
  408. const h = rect.height;
  409. mouse.x = ( dx / w ) * 2 - 1;
  410. mouse.y = - ( dy / h ) * 2 + 1;
  411. dollyDirection.set( mouse.x, mouse.y, 1 ).unproject( scope.object ).sub( scope.object.position ).normalize();
  412. }
  413. function clampDistance( dist ) {
  414. return Math.max( scope.minDistance, Math.min( scope.maxDistance, dist ) );
  415. }
  416. //
  417. // event callbacks - update the object state
  418. //
  419. function handleMouseDownRotate( event ) {
  420. rotateStart.set( event.clientX, event.clientY );
  421. }
  422. function handleMouseDownDolly( event ) {
  423. updateZoomParameters( event.clientX, event.clientX );
  424. dollyStart.set( event.clientX, event.clientY );
  425. }
  426. function handleMouseDownPan( event ) {
  427. panStart.set( event.clientX, event.clientY );
  428. }
  429. function handleMouseMoveRotate( event ) {
  430. rotateEnd.set( event.clientX, event.clientY );
  431. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  432. const element = scope.domElement;
  433. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  434. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  435. rotateStart.copy( rotateEnd );
  436. scope.update();
  437. }
  438. function handleMouseMoveDolly( event ) {
  439. dollyEnd.set( event.clientX, event.clientY );
  440. dollyDelta.subVectors( dollyEnd, dollyStart );
  441. if ( dollyDelta.y > 0 ) {
  442. dollyOut( getZoomScale( dollyDelta.y ) );
  443. } else if ( dollyDelta.y < 0 ) {
  444. dollyIn( getZoomScale( dollyDelta.y ) );
  445. }
  446. dollyStart.copy( dollyEnd );
  447. scope.update();
  448. }
  449. function handleMouseMovePan( event ) {
  450. panEnd.set( event.clientX, event.clientY );
  451. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  452. pan( panDelta.x, panDelta.y );
  453. panStart.copy( panEnd );
  454. scope.update();
  455. }
  456. function handleMouseWheel( event ) {
  457. updateZoomParameters( event.clientX, event.clientY );
  458. if ( event.deltaY < 0 ) {
  459. dollyIn( getZoomScale( event.deltaY ) );
  460. } else if ( event.deltaY > 0 ) {
  461. dollyOut( getZoomScale( event.deltaY ) );
  462. }
  463. scope.update();
  464. }
  465. function handleKeyDown( event ) {
  466. let needsUpdate = false;
  467. switch ( event.code ) {
  468. case scope.keys.UP:
  469. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  470. rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  471. } else {
  472. pan( 0, scope.keyPanSpeed );
  473. }
  474. needsUpdate = true;
  475. break;
  476. case scope.keys.BOTTOM:
  477. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  478. rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  479. } else {
  480. pan( 0, - scope.keyPanSpeed );
  481. }
  482. needsUpdate = true;
  483. break;
  484. case scope.keys.LEFT:
  485. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  486. rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  487. } else {
  488. pan( scope.keyPanSpeed, 0 );
  489. }
  490. needsUpdate = true;
  491. break;
  492. case scope.keys.RIGHT:
  493. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  494. rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  495. } else {
  496. pan( - scope.keyPanSpeed, 0 );
  497. }
  498. needsUpdate = true;
  499. break;
  500. }
  501. if ( needsUpdate ) {
  502. // prevent the browser from scrolling on cursor keys
  503. event.preventDefault();
  504. scope.update();
  505. }
  506. }
  507. function handleTouchStartRotate( event ) {
  508. if ( pointers.length === 1 ) {
  509. rotateStart.set( event.pageX, event.pageY );
  510. } else {
  511. const position = getSecondPointerPosition( event );
  512. const x = 0.5 * ( event.pageX + position.x );
  513. const y = 0.5 * ( event.pageY + position.y );
  514. rotateStart.set( x, y );
  515. }
  516. }
  517. function handleTouchStartPan( event ) {
  518. if ( pointers.length === 1 ) {
  519. panStart.set( event.pageX, event.pageY );
  520. } else {
  521. const position = getSecondPointerPosition( event );
  522. const x = 0.5 * ( event.pageX + position.x );
  523. const y = 0.5 * ( event.pageY + position.y );
  524. panStart.set( x, y );
  525. }
  526. }
  527. function handleTouchStartDolly( event ) {
  528. const position = getSecondPointerPosition( event );
  529. const dx = event.pageX - position.x;
  530. const dy = event.pageY - position.y;
  531. const distance = Math.sqrt( dx * dx + dy * dy );
  532. dollyStart.set( 0, distance );
  533. }
  534. function handleTouchStartDollyPan( event ) {
  535. if ( scope.enableZoom ) handleTouchStartDolly( event );
  536. if ( scope.enablePan ) handleTouchStartPan( event );
  537. }
  538. function handleTouchStartDollyRotate( event ) {
  539. if ( scope.enableZoom ) handleTouchStartDolly( event );
  540. if ( scope.enableRotate ) handleTouchStartRotate( event );
  541. }
  542. function handleTouchMoveRotate( event ) {
  543. if ( pointers.length == 1 ) {
  544. rotateEnd.set( event.pageX, event.pageY );
  545. } else {
  546. const position = getSecondPointerPosition( event );
  547. const x = 0.5 * ( event.pageX + position.x );
  548. const y = 0.5 * ( event.pageY + position.y );
  549. rotateEnd.set( x, y );
  550. }
  551. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  552. const element = scope.domElement;
  553. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  554. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  555. rotateStart.copy( rotateEnd );
  556. }
  557. function handleTouchMovePan( event ) {
  558. if ( pointers.length === 1 ) {
  559. panEnd.set( event.pageX, event.pageY );
  560. } else {
  561. const position = getSecondPointerPosition( event );
  562. const x = 0.5 * ( event.pageX + position.x );
  563. const y = 0.5 * ( event.pageY + position.y );
  564. panEnd.set( x, y );
  565. }
  566. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  567. pan( panDelta.x, panDelta.y );
  568. panStart.copy( panEnd );
  569. }
  570. function handleTouchMoveDolly( event ) {
  571. const position = getSecondPointerPosition( event );
  572. const dx = event.pageX - position.x;
  573. const dy = event.pageY - position.y;
  574. const distance = Math.sqrt( dx * dx + dy * dy );
  575. dollyEnd.set( 0, distance );
  576. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  577. dollyOut( dollyDelta.y );
  578. dollyStart.copy( dollyEnd );
  579. const centerX = ( event.pageX + position.x ) * 0.5;
  580. const centerY = ( event.pageY + position.y ) * 0.5;
  581. updateZoomParameters( centerX, centerY );
  582. }
  583. function handleTouchMoveDollyPan( event ) {
  584. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  585. if ( scope.enablePan ) handleTouchMovePan( event );
  586. }
  587. function handleTouchMoveDollyRotate( event ) {
  588. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  589. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  590. }
  591. //
  592. // event handlers - FSM: listen for events and reset state
  593. //
  594. function onPointerDown( event ) {
  595. if ( scope.enabled === false ) return;
  596. if ( pointers.length === 0 ) {
  597. scope.domElement.setPointerCapture( event.pointerId );
  598. scope.domElement.addEventListener( 'pointermove', onPointerMove );
  599. scope.domElement.addEventListener( 'pointerup', onPointerUp );
  600. }
  601. //
  602. if ( isTrackingPointer( event ) ) return;
  603. //
  604. addPointer( event );
  605. if ( event.pointerType === 'touch' ) {
  606. onTouchStart( event );
  607. } else {
  608. onMouseDown( event );
  609. }
  610. }
  611. function onPointerMove( event ) {
  612. if ( scope.enabled === false ) return;
  613. if ( event.pointerType === 'touch' ) {
  614. onTouchMove( event );
  615. } else {
  616. onMouseMove( event );
  617. }
  618. }
  619. function onPointerUp( event ) {
  620. removePointer( event );
  621. switch ( pointers.length ) {
  622. case 0:
  623. scope.domElement.releasePointerCapture( event.pointerId );
  624. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  625. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  626. scope.dispatchEvent( _endEvent );
  627. state = STATE.NONE;
  628. break;
  629. case 1:
  630. const pointerId = pointers[ 0 ];
  631. const position = pointerPositions[ pointerId ];
  632. // minimal placeholder event - allows state correction on pointer-up
  633. onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } );
  634. break;
  635. }
  636. }
  637. function onMouseDown( event ) {
  638. let mouseAction;
  639. switch ( event.button ) {
  640. case 0:
  641. mouseAction = scope.mouseButtons.LEFT;
  642. break;
  643. case 1:
  644. mouseAction = scope.mouseButtons.MIDDLE;
  645. break;
  646. case 2:
  647. mouseAction = scope.mouseButtons.RIGHT;
  648. break;
  649. default:
  650. mouseAction = - 1;
  651. }
  652. switch ( mouseAction ) {
  653. case MOUSE.DOLLY:
  654. if ( scope.enableZoom === false ) return;
  655. handleMouseDownDolly( event );
  656. state = STATE.DOLLY;
  657. break;
  658. case MOUSE.ROTATE:
  659. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  660. if ( scope.enablePan === false ) return;
  661. handleMouseDownPan( event );
  662. state = STATE.PAN;
  663. } else {
  664. if ( scope.enableRotate === false ) return;
  665. handleMouseDownRotate( event );
  666. state = STATE.ROTATE;
  667. }
  668. break;
  669. case MOUSE.PAN:
  670. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  671. if ( scope.enableRotate === false ) return;
  672. handleMouseDownRotate( event );
  673. state = STATE.ROTATE;
  674. } else {
  675. if ( scope.enablePan === false ) return;
  676. handleMouseDownPan( event );
  677. state = STATE.PAN;
  678. }
  679. break;
  680. default:
  681. state = STATE.NONE;
  682. }
  683. if ( state !== STATE.NONE ) {
  684. scope.dispatchEvent( _startEvent );
  685. }
  686. }
  687. function onMouseMove( event ) {
  688. switch ( state ) {
  689. case STATE.ROTATE:
  690. if ( scope.enableRotate === false ) return;
  691. handleMouseMoveRotate( event );
  692. break;
  693. case STATE.DOLLY:
  694. if ( scope.enableZoom === false ) return;
  695. handleMouseMoveDolly( event );
  696. break;
  697. case STATE.PAN:
  698. if ( scope.enablePan === false ) return;
  699. handleMouseMovePan( event );
  700. break;
  701. }
  702. }
  703. function onMouseWheel( event ) {
  704. if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;
  705. event.preventDefault();
  706. scope.dispatchEvent( _startEvent );
  707. handleMouseWheel( customWheelEvent( event ) );
  708. scope.dispatchEvent( _endEvent );
  709. }
  710. function customWheelEvent( event ) {
  711. const mode = event.deltaMode;
  712. // minimal wheel event altered to meet delta-zoom demand
  713. const newEvent = {
  714. clientX: event.clientX,
  715. clientY: event.clientY,
  716. deltaY: event.deltaY,
  717. };
  718. switch ( mode ) {
  719. case 1: // LINE_MODE
  720. newEvent.deltaY *= 16;
  721. break;
  722. case 2: // PAGE_MODE
  723. newEvent.deltaY *= 100;
  724. break;
  725. }
  726. // detect if event was triggered by pinching
  727. if ( event.ctrlKey && ! controlActive ) {
  728. newEvent.deltaY *= 10;
  729. }
  730. return newEvent;
  731. }
  732. function interceptControlDown( event ) {
  733. if ( event.key === 'Control' ) {
  734. controlActive = true;
  735. const document = scope.domElement.getRootNode(); // offscreen canvas compatibility
  736. document.addEventListener( 'keyup', interceptControlUp, { passive: true, capture: true } );
  737. }
  738. }
  739. function interceptControlUp( event ) {
  740. if ( event.key === 'Control' ) {
  741. controlActive = false;
  742. const document = scope.domElement.getRootNode(); // offscreen canvas compatibility
  743. document.removeEventListener( 'keyup', interceptControlUp, { passive: true, capture: true } );
  744. }
  745. }
  746. function onKeyDown( event ) {
  747. if ( scope.enabled === false || scope.enablePan === false ) return;
  748. handleKeyDown( event );
  749. }
  750. function onTouchStart( event ) {
  751. trackPointer( event );
  752. switch ( pointers.length ) {
  753. case 1:
  754. switch ( scope.touches.ONE ) {
  755. case TOUCH.ROTATE:
  756. if ( scope.enableRotate === false ) return;
  757. handleTouchStartRotate( event );
  758. state = STATE.TOUCH_ROTATE;
  759. break;
  760. case TOUCH.PAN:
  761. if ( scope.enablePan === false ) return;
  762. handleTouchStartPan( event );
  763. state = STATE.TOUCH_PAN;
  764. break;
  765. default:
  766. state = STATE.NONE;
  767. }
  768. break;
  769. case 2:
  770. switch ( scope.touches.TWO ) {
  771. case TOUCH.DOLLY_PAN:
  772. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  773. handleTouchStartDollyPan( event );
  774. state = STATE.TOUCH_DOLLY_PAN;
  775. break;
  776. case TOUCH.DOLLY_ROTATE:
  777. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  778. handleTouchStartDollyRotate( event );
  779. state = STATE.TOUCH_DOLLY_ROTATE;
  780. break;
  781. default:
  782. state = STATE.NONE;
  783. }
  784. break;
  785. default:
  786. state = STATE.NONE;
  787. }
  788. if ( state !== STATE.NONE ) {
  789. scope.dispatchEvent( _startEvent );
  790. }
  791. }
  792. function onTouchMove( event ) {
  793. trackPointer( event );
  794. switch ( state ) {
  795. case STATE.TOUCH_ROTATE:
  796. if ( scope.enableRotate === false ) return;
  797. handleTouchMoveRotate( event );
  798. scope.update();
  799. break;
  800. case STATE.TOUCH_PAN:
  801. if ( scope.enablePan === false ) return;
  802. handleTouchMovePan( event );
  803. scope.update();
  804. break;
  805. case STATE.TOUCH_DOLLY_PAN:
  806. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  807. handleTouchMoveDollyPan( event );
  808. scope.update();
  809. break;
  810. case STATE.TOUCH_DOLLY_ROTATE:
  811. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  812. handleTouchMoveDollyRotate( event );
  813. scope.update();
  814. break;
  815. default:
  816. state = STATE.NONE;
  817. }
  818. }
  819. function onContextMenu( event ) {
  820. if ( scope.enabled === false ) return;
  821. event.preventDefault();
  822. }
  823. function addPointer( event ) {
  824. pointers.push( event.pointerId );
  825. }
  826. function removePointer( event ) {
  827. delete pointerPositions[ event.pointerId ];
  828. for ( let i = 0; i < pointers.length; i ++ ) {
  829. if ( pointers[ i ] == event.pointerId ) {
  830. pointers.splice( i, 1 );
  831. return;
  832. }
  833. }
  834. }
  835. function isTrackingPointer( event ) {
  836. for ( let i = 0; i < pointers.length; i ++ ) {
  837. if ( pointers[ i ] == event.pointerId ) return true;
  838. }
  839. return false;
  840. }
  841. function trackPointer( event ) {
  842. let position = pointerPositions[ event.pointerId ];
  843. if ( position === undefined ) {
  844. position = new Vector2();
  845. pointerPositions[ event.pointerId ] = position;
  846. }
  847. position.set( event.pageX, event.pageY );
  848. }
  849. function getSecondPointerPosition( event ) {
  850. const pointerId = ( event.pointerId === pointers[ 0 ] ) ? pointers[ 1 ] : pointers[ 0 ];
  851. return pointerPositions[ pointerId ];
  852. }
  853. //
  854. scope.domElement.addEventListener( 'contextmenu', onContextMenu );
  855. scope.domElement.addEventListener( 'pointerdown', onPointerDown );
  856. scope.domElement.addEventListener( 'pointercancel', onPointerUp );
  857. scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
  858. const document = scope.domElement.getRootNode(); // offscreen canvas compatibility
  859. document.addEventListener( 'keydown', interceptControlDown, { passive: true, capture: true } );
  860. // force an update at start
  861. this.update();
  862. }
  863. }
  864. export { OrbitControls };