OrbitControls.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  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. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) );
  247. scope.object.updateProjectionMatrix();
  248. zoomChanged = true;
  249. }
  250. scale = 1;
  251. performCursorZoom = false;
  252. // update condition is:
  253. // min(camera displacement, camera rotation in radians)^2 > EPS
  254. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  255. if ( zoomChanged ||
  256. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  257. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ||
  258. lastTargetPosition.distanceToSquared( scope.target ) > 0 ) {
  259. scope.dispatchEvent( _changeEvent );
  260. lastPosition.copy( scope.object.position );
  261. lastQuaternion.copy( scope.object.quaternion );
  262. lastTargetPosition.copy( scope.target );
  263. return true;
  264. }
  265. return false;
  266. };
  267. }();
  268. this.dispose = function () {
  269. scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
  270. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  271. scope.domElement.removeEventListener( 'pointercancel', onPointerUp );
  272. scope.domElement.removeEventListener( 'wheel', onMouseWheel );
  273. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  274. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  275. if ( scope._domElementKeyEvents !== null ) {
  276. scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  277. scope._domElementKeyEvents = null;
  278. }
  279. //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  280. };
  281. //
  282. // internals
  283. //
  284. const scope = this;
  285. const STATE = {
  286. NONE: - 1,
  287. ROTATE: 0,
  288. DOLLY: 1,
  289. PAN: 2,
  290. TOUCH_ROTATE: 3,
  291. TOUCH_PAN: 4,
  292. TOUCH_DOLLY_PAN: 5,
  293. TOUCH_DOLLY_ROTATE: 6
  294. };
  295. let state = STATE.NONE;
  296. const EPS = 0.000001;
  297. // current position in spherical coordinates
  298. const spherical = new Spherical();
  299. const sphericalDelta = new Spherical();
  300. let scale = 1;
  301. const panOffset = new Vector3();
  302. const rotateStart = new Vector2();
  303. const rotateEnd = new Vector2();
  304. const rotateDelta = new Vector2();
  305. const panStart = new Vector2();
  306. const panEnd = new Vector2();
  307. const panDelta = new Vector2();
  308. const dollyStart = new Vector2();
  309. const dollyEnd = new Vector2();
  310. const dollyDelta = new Vector2();
  311. const dollyDirection = new Vector3();
  312. const mouse = new Vector2();
  313. let performCursorZoom = false;
  314. const pointers = [];
  315. const pointerPositions = {};
  316. let controlActive = false;
  317. function getAutoRotationAngle( deltaTime ) {
  318. if ( deltaTime !== null ) {
  319. return ( 2 * Math.PI / 60 * scope.autoRotateSpeed ) * deltaTime;
  320. } else {
  321. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  322. }
  323. }
  324. function getZoomScale( delta ) {
  325. const normalizedDelta = Math.abs( delta * 0.01 );
  326. return Math.pow( 0.95, scope.zoomSpeed * normalizedDelta );
  327. }
  328. function rotateLeft( angle ) {
  329. sphericalDelta.theta -= angle;
  330. }
  331. function rotateUp( angle ) {
  332. sphericalDelta.phi -= angle;
  333. }
  334. const panLeft = function () {
  335. const v = new Vector3();
  336. return function panLeft( distance, objectMatrix ) {
  337. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  338. v.multiplyScalar( - distance );
  339. panOffset.add( v );
  340. };
  341. }();
  342. const panUp = function () {
  343. const v = new Vector3();
  344. return function panUp( distance, objectMatrix ) {
  345. if ( scope.screenSpacePanning === true ) {
  346. v.setFromMatrixColumn( objectMatrix, 1 );
  347. } else {
  348. v.setFromMatrixColumn( objectMatrix, 0 );
  349. v.crossVectors( scope.object.up, v );
  350. }
  351. v.multiplyScalar( distance );
  352. panOffset.add( v );
  353. };
  354. }();
  355. // deltaX and deltaY are in pixels; right and down are positive
  356. const pan = function () {
  357. const offset = new Vector3();
  358. return function pan( deltaX, deltaY ) {
  359. const element = scope.domElement;
  360. if ( scope.object.isPerspectiveCamera ) {
  361. // perspective
  362. const position = scope.object.position;
  363. offset.copy( position ).sub( scope.target );
  364. let targetDistance = offset.length();
  365. // half of the fov is center to top of screen
  366. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  367. // we use only clientHeight here so aspect ratio does not distort speed
  368. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  369. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  370. } else if ( scope.object.isOrthographicCamera ) {
  371. // orthographic
  372. panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
  373. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
  374. } else {
  375. // camera neither orthographic nor perspective
  376. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  377. scope.enablePan = false;
  378. }
  379. };
  380. }();
  381. function dollyOut( dollyScale ) {
  382. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  383. scale /= dollyScale;
  384. } else {
  385. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  386. scope.enableZoom = false;
  387. }
  388. }
  389. function dollyIn( dollyScale ) {
  390. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  391. scale *= dollyScale;
  392. } else {
  393. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  394. scope.enableZoom = false;
  395. }
  396. }
  397. function updateZoomParameters( x, y ) {
  398. if ( ! scope.zoomToCursor ) {
  399. return;
  400. }
  401. performCursorZoom = true;
  402. const rect = scope.domElement.getBoundingClientRect();
  403. const dx = x - rect.left;
  404. const dy = y - rect.top;
  405. const w = rect.width;
  406. const h = rect.height;
  407. mouse.x = ( dx / w ) * 2 - 1;
  408. mouse.y = - ( dy / h ) * 2 + 1;
  409. dollyDirection.set( mouse.x, mouse.y, 1 ).unproject( scope.object ).sub( scope.object.position ).normalize();
  410. }
  411. function clampDistance( dist ) {
  412. return Math.max( scope.minDistance, Math.min( scope.maxDistance, dist ) );
  413. }
  414. //
  415. // event callbacks - update the object state
  416. //
  417. function handleMouseDownRotate( event ) {
  418. rotateStart.set( event.clientX, event.clientY );
  419. }
  420. function handleMouseDownDolly( event ) {
  421. updateZoomParameters( event.clientX, event.clientX );
  422. dollyStart.set( event.clientX, event.clientY );
  423. }
  424. function handleMouseDownPan( event ) {
  425. panStart.set( event.clientX, event.clientY );
  426. }
  427. function handleMouseMoveRotate( event ) {
  428. rotateEnd.set( event.clientX, event.clientY );
  429. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  430. const element = scope.domElement;
  431. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  432. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  433. rotateStart.copy( rotateEnd );
  434. scope.update();
  435. }
  436. function handleMouseMoveDolly( event ) {
  437. dollyEnd.set( event.clientX, event.clientY );
  438. dollyDelta.subVectors( dollyEnd, dollyStart );
  439. if ( dollyDelta.y > 0 ) {
  440. dollyOut( getZoomScale( dollyDelta.y ) );
  441. } else if ( dollyDelta.y < 0 ) {
  442. dollyIn( getZoomScale( dollyDelta.y ) );
  443. }
  444. dollyStart.copy( dollyEnd );
  445. scope.update();
  446. }
  447. function handleMouseMovePan( event ) {
  448. panEnd.set( event.clientX, event.clientY );
  449. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  450. pan( panDelta.x, panDelta.y );
  451. panStart.copy( panEnd );
  452. scope.update();
  453. }
  454. function handleMouseWheel( event ) {
  455. updateZoomParameters( event.clientX, event.clientY );
  456. if ( event.deltaY < 0 ) {
  457. dollyIn( getZoomScale( event.deltaY ) );
  458. } else if ( event.deltaY > 0 ) {
  459. dollyOut( getZoomScale( event.deltaY ) );
  460. }
  461. scope.update();
  462. }
  463. function handleKeyDown( event ) {
  464. let needsUpdate = false;
  465. switch ( event.code ) {
  466. case scope.keys.UP:
  467. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  468. rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  469. } else {
  470. pan( 0, scope.keyPanSpeed );
  471. }
  472. needsUpdate = true;
  473. break;
  474. case scope.keys.BOTTOM:
  475. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  476. rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  477. } else {
  478. pan( 0, - scope.keyPanSpeed );
  479. }
  480. needsUpdate = true;
  481. break;
  482. case scope.keys.LEFT:
  483. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  484. rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  485. } else {
  486. pan( scope.keyPanSpeed, 0 );
  487. }
  488. needsUpdate = true;
  489. break;
  490. case scope.keys.RIGHT:
  491. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  492. rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  493. } else {
  494. pan( - scope.keyPanSpeed, 0 );
  495. }
  496. needsUpdate = true;
  497. break;
  498. }
  499. if ( needsUpdate ) {
  500. // prevent the browser from scrolling on cursor keys
  501. event.preventDefault();
  502. scope.update();
  503. }
  504. }
  505. function handleTouchStartRotate( event ) {
  506. if ( pointers.length === 1 ) {
  507. rotateStart.set( event.pageX, event.pageY );
  508. } else {
  509. const position = getSecondPointerPosition( event );
  510. const x = 0.5 * ( event.pageX + position.x );
  511. const y = 0.5 * ( event.pageY + position.y );
  512. rotateStart.set( x, y );
  513. }
  514. }
  515. function handleTouchStartPan( event ) {
  516. if ( pointers.length === 1 ) {
  517. panStart.set( event.pageX, event.pageY );
  518. } else {
  519. const position = getSecondPointerPosition( event );
  520. const x = 0.5 * ( event.pageX + position.x );
  521. const y = 0.5 * ( event.pageY + position.y );
  522. panStart.set( x, y );
  523. }
  524. }
  525. function handleTouchStartDolly( event ) {
  526. const position = getSecondPointerPosition( event );
  527. const dx = event.pageX - position.x;
  528. const dy = event.pageY - position.y;
  529. const distance = Math.sqrt( dx * dx + dy * dy );
  530. dollyStart.set( 0, distance );
  531. }
  532. function handleTouchStartDollyPan( event ) {
  533. if ( scope.enableZoom ) handleTouchStartDolly( event );
  534. if ( scope.enablePan ) handleTouchStartPan( event );
  535. }
  536. function handleTouchStartDollyRotate( event ) {
  537. if ( scope.enableZoom ) handleTouchStartDolly( event );
  538. if ( scope.enableRotate ) handleTouchStartRotate( event );
  539. }
  540. function handleTouchMoveRotate( event ) {
  541. if ( pointers.length == 1 ) {
  542. rotateEnd.set( event.pageX, event.pageY );
  543. } else {
  544. const position = getSecondPointerPosition( event );
  545. const x = 0.5 * ( event.pageX + position.x );
  546. const y = 0.5 * ( event.pageY + position.y );
  547. rotateEnd.set( x, y );
  548. }
  549. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  550. const element = scope.domElement;
  551. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  552. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  553. rotateStart.copy( rotateEnd );
  554. }
  555. function handleTouchMovePan( event ) {
  556. if ( pointers.length === 1 ) {
  557. panEnd.set( event.pageX, event.pageY );
  558. } else {
  559. const position = getSecondPointerPosition( event );
  560. const x = 0.5 * ( event.pageX + position.x );
  561. const y = 0.5 * ( event.pageY + position.y );
  562. panEnd.set( x, y );
  563. }
  564. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  565. pan( panDelta.x, panDelta.y );
  566. panStart.copy( panEnd );
  567. }
  568. function handleTouchMoveDolly( event ) {
  569. const position = getSecondPointerPosition( event );
  570. const dx = event.pageX - position.x;
  571. const dy = event.pageY - position.y;
  572. const distance = Math.sqrt( dx * dx + dy * dy );
  573. dollyEnd.set( 0, distance );
  574. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  575. dollyOut( dollyDelta.y );
  576. dollyStart.copy( dollyEnd );
  577. const centerX = ( event.pageX + position.x ) * 0.5;
  578. const centerY = ( event.pageY + position.y ) * 0.5;
  579. updateZoomParameters( centerX, centerY );
  580. }
  581. function handleTouchMoveDollyPan( event ) {
  582. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  583. if ( scope.enablePan ) handleTouchMovePan( event );
  584. }
  585. function handleTouchMoveDollyRotate( event ) {
  586. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  587. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  588. }
  589. //
  590. // event handlers - FSM: listen for events and reset state
  591. //
  592. function onPointerDown( event ) {
  593. if ( scope.enabled === false ) return;
  594. if ( pointers.length === 0 ) {
  595. scope.domElement.setPointerCapture( event.pointerId );
  596. scope.domElement.addEventListener( 'pointermove', onPointerMove );
  597. scope.domElement.addEventListener( 'pointerup', onPointerUp );
  598. }
  599. //
  600. addPointer( event );
  601. if ( event.pointerType === 'touch' ) {
  602. onTouchStart( event );
  603. } else {
  604. onMouseDown( event );
  605. }
  606. }
  607. function onPointerMove( event ) {
  608. if ( scope.enabled === false ) return;
  609. if ( event.pointerType === 'touch' ) {
  610. onTouchMove( event );
  611. } else {
  612. onMouseMove( event );
  613. }
  614. }
  615. function onPointerUp( event ) {
  616. removePointer( event );
  617. if ( pointers.length === 0 ) {
  618. scope.domElement.releasePointerCapture( event.pointerId );
  619. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  620. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  621. }
  622. scope.dispatchEvent( _endEvent );
  623. state = STATE.NONE;
  624. }
  625. function onMouseDown( event ) {
  626. let mouseAction;
  627. switch ( event.button ) {
  628. case 0:
  629. mouseAction = scope.mouseButtons.LEFT;
  630. break;
  631. case 1:
  632. mouseAction = scope.mouseButtons.MIDDLE;
  633. break;
  634. case 2:
  635. mouseAction = scope.mouseButtons.RIGHT;
  636. break;
  637. default:
  638. mouseAction = - 1;
  639. }
  640. switch ( mouseAction ) {
  641. case MOUSE.DOLLY:
  642. if ( scope.enableZoom === false ) return;
  643. handleMouseDownDolly( event );
  644. state = STATE.DOLLY;
  645. break;
  646. case MOUSE.ROTATE:
  647. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  648. if ( scope.enablePan === false ) return;
  649. handleMouseDownPan( event );
  650. state = STATE.PAN;
  651. } else {
  652. if ( scope.enableRotate === false ) return;
  653. handleMouseDownRotate( event );
  654. state = STATE.ROTATE;
  655. }
  656. break;
  657. case MOUSE.PAN:
  658. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  659. if ( scope.enableRotate === false ) return;
  660. handleMouseDownRotate( event );
  661. state = STATE.ROTATE;
  662. } else {
  663. if ( scope.enablePan === false ) return;
  664. handleMouseDownPan( event );
  665. state = STATE.PAN;
  666. }
  667. break;
  668. default:
  669. state = STATE.NONE;
  670. }
  671. if ( state !== STATE.NONE ) {
  672. scope.dispatchEvent( _startEvent );
  673. }
  674. }
  675. function onMouseMove( event ) {
  676. switch ( state ) {
  677. case STATE.ROTATE:
  678. if ( scope.enableRotate === false ) return;
  679. handleMouseMoveRotate( event );
  680. break;
  681. case STATE.DOLLY:
  682. if ( scope.enableZoom === false ) return;
  683. handleMouseMoveDolly( event );
  684. break;
  685. case STATE.PAN:
  686. if ( scope.enablePan === false ) return;
  687. handleMouseMovePan( event );
  688. break;
  689. }
  690. }
  691. function onMouseWheel( event ) {
  692. if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;
  693. event.preventDefault();
  694. scope.dispatchEvent( _startEvent );
  695. handleMouseWheel( customWheelEvent( event ) );
  696. scope.dispatchEvent( _endEvent );
  697. }
  698. function customWheelEvent( event ) {
  699. const mode = event.deltaMode;
  700. // minimal wheel event altered to meet delta-zoom demand
  701. const newEvent = {
  702. clientX: event.clientX,
  703. clientY: event.clientY,
  704. deltaY: event.deltaY,
  705. }
  706. switch ( mode ) {
  707. case 1: // LINE_MODE
  708. newEvent.deltaY *= 16;
  709. break;
  710. case 2: // PAGE_MODE
  711. newEvent.deltaY *= 100;
  712. break;
  713. }
  714. // detect if event was triggered by pinching
  715. if ( event.ctrlKey && !controlActive ) {
  716. newEvent.deltaY *= 10;
  717. }
  718. return newEvent;
  719. }
  720. function interceptControlDown( event ) {
  721. if ( event.key === "Control" ) {
  722. controlActive = true;
  723. document.addEventListener('keyup', interceptControlUp, { passive: true, capture: true });
  724. }
  725. }
  726. function interceptControlUp( event ) {
  727. if ( event.key === "Control" ) {
  728. controlActive = false;
  729. document.removeEventListener('keyup', interceptControlUp, { passive: true, capture: true });
  730. }
  731. }
  732. function onKeyDown( event ) {
  733. if ( scope.enabled === false || scope.enablePan === false ) return;
  734. handleKeyDown( event );
  735. }
  736. function onTouchStart( event ) {
  737. trackPointer( event );
  738. switch ( pointers.length ) {
  739. case 1:
  740. switch ( scope.touches.ONE ) {
  741. case TOUCH.ROTATE:
  742. if ( scope.enableRotate === false ) return;
  743. handleTouchStartRotate( event );
  744. state = STATE.TOUCH_ROTATE;
  745. break;
  746. case TOUCH.PAN:
  747. if ( scope.enablePan === false ) return;
  748. handleTouchStartPan( event );
  749. state = STATE.TOUCH_PAN;
  750. break;
  751. default:
  752. state = STATE.NONE;
  753. }
  754. break;
  755. case 2:
  756. switch ( scope.touches.TWO ) {
  757. case TOUCH.DOLLY_PAN:
  758. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  759. handleTouchStartDollyPan( event );
  760. state = STATE.TOUCH_DOLLY_PAN;
  761. break;
  762. case TOUCH.DOLLY_ROTATE:
  763. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  764. handleTouchStartDollyRotate( event );
  765. state = STATE.TOUCH_DOLLY_ROTATE;
  766. break;
  767. default:
  768. state = STATE.NONE;
  769. }
  770. break;
  771. default:
  772. state = STATE.NONE;
  773. }
  774. if ( state !== STATE.NONE ) {
  775. scope.dispatchEvent( _startEvent );
  776. }
  777. }
  778. function onTouchMove( event ) {
  779. trackPointer( event );
  780. switch ( state ) {
  781. case STATE.TOUCH_ROTATE:
  782. if ( scope.enableRotate === false ) return;
  783. handleTouchMoveRotate( event );
  784. scope.update();
  785. break;
  786. case STATE.TOUCH_PAN:
  787. if ( scope.enablePan === false ) return;
  788. handleTouchMovePan( event );
  789. scope.update();
  790. break;
  791. case STATE.TOUCH_DOLLY_PAN:
  792. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  793. handleTouchMoveDollyPan( event );
  794. scope.update();
  795. break;
  796. case STATE.TOUCH_DOLLY_ROTATE:
  797. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  798. handleTouchMoveDollyRotate( event );
  799. scope.update();
  800. break;
  801. default:
  802. state = STATE.NONE;
  803. }
  804. }
  805. function onContextMenu( event ) {
  806. if ( scope.enabled === false ) return;
  807. event.preventDefault();
  808. }
  809. function addPointer( event ) {
  810. pointers.push( event.pointerId );
  811. }
  812. function removePointer( event ) {
  813. delete pointerPositions[ event.pointerId ];
  814. for ( let i = 0; i < pointers.length; i ++ ) {
  815. if ( pointers[ i ] == event.pointerId ) {
  816. pointers.splice( i, 1 );
  817. return;
  818. }
  819. }
  820. }
  821. function trackPointer( event ) {
  822. let position = pointerPositions[ event.pointerId ];
  823. if ( position === undefined ) {
  824. position = new Vector2();
  825. pointerPositions[ event.pointerId ] = position;
  826. }
  827. position.set( event.pageX, event.pageY );
  828. }
  829. function getSecondPointerPosition( event ) {
  830. const pointerId = ( event.pointerId === pointers[ 0 ] ) ? pointers[ 1 ] : pointers[ 0 ];
  831. return pointerPositions[ pointerId ];
  832. }
  833. //
  834. scope.domElement.addEventListener( 'contextmenu', onContextMenu );
  835. scope.domElement.addEventListener( 'pointerdown', onPointerDown );
  836. scope.domElement.addEventListener( 'pointercancel', onPointerUp );
  837. scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
  838. document.addEventListener( 'keydown', interceptControlDown, { passive: true, capture: true } );
  839. // force an update at start
  840. this.update();
  841. }
  842. }
  843. export { OrbitControls };