OrbitControls.js 30 KB

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