babylon.arcRotateCamera.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. module BABYLON {
  2. var eventPrefix = Tools.GetPointerPrefix();
  3. export class ArcRotateCamera extends Camera {
  4. public inertialAlphaOffset = 0;
  5. public inertialBetaOffset = 0;
  6. public inertialRadiusOffset = 0;
  7. public lowerAlphaLimit = null;
  8. public upperAlphaLimit = null;
  9. public lowerBetaLimit = 0.01;
  10. public upperBetaLimit = Math.PI;
  11. public lowerRadiusLimit = null;
  12. public upperRadiusLimit = null;
  13. public angularSensibility = 1000.0;
  14. public wheelPrecision = 3.0;
  15. public keysUp = [38];
  16. public keysDown = [40];
  17. public keysLeft = [37];
  18. public keysRight = [39];
  19. public zoomOnFactor = 1;
  20. private _keys = [];
  21. private _viewMatrix = new BABYLON.Matrix();
  22. private _attachedElement: HTMLElement;
  23. private _onPointerDown: (e: PointerEvent) => void;
  24. private _onPointerUp: (e: PointerEvent) => void;
  25. private _onPointerMove: (e: PointerEvent) => void;
  26. private _wheel: (e: MouseWheelEvent) => void;
  27. private _onMouseMove: (e: MouseEvent) => any;
  28. private _onKeyDown: (e: KeyboardEvent) => any;
  29. private _onKeyUp: (e: KeyboardEvent) => any;
  30. private _onLostFocus: (e: FocusEvent) => any;
  31. private _reset: () => void;
  32. private _onGestureStart: (e: PointerEvent) => void;
  33. private _onGesture: (e: MSGestureEvent) => void;
  34. private _MSGestureHandler: MSGesture;
  35. // Collisions
  36. public onCollide: (collidedMesh: AbstractMesh) => void;
  37. public checkCollisions = false;
  38. public collisionRadius = new Vector3(0.5, 0.5, 0.5);
  39. private _collider = new Collider();
  40. private _previousPosition = Vector3.Zero();
  41. private _collisionVelocity = Vector3.Zero();
  42. private _newPosition = Vector3.Zero();
  43. private _previousAlpha: number;
  44. private _previousBeta: number;
  45. private _previousRadius: number;
  46. // Pinch
  47. // value for pinch step scaling
  48. // set to 20 by default
  49. public pinchPrecision = 20;
  50. // Event for pinch
  51. private _touchStart: (e: any) => void;
  52. private _touchMove: (e: any) => void;
  53. private _touchEnd: (e: any) => void;
  54. // Method for pinch
  55. private _pinchStart: (e: any) => void;
  56. private _pinchMove: (e: any) => void;
  57. private _pinchEnd: (e: any) => void;
  58. constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene: Scene) {
  59. super(name, BABYLON.Vector3.Zero(), scene);
  60. this.getViewMatrix();
  61. }
  62. public _getTargetPosition(): Vector3 {
  63. return this.target.position || this.target;
  64. }
  65. // Cache
  66. public _initCache(): void {
  67. super._initCache();
  68. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69. this._cache.alpha = undefined;
  70. this._cache.beta = undefined;
  71. this._cache.radius = undefined;
  72. }
  73. public _updateCache(ignoreParentClass?: boolean): void {
  74. if (!ignoreParentClass) {
  75. super._updateCache();
  76. }
  77. this._cache.target.copyFrom(this._getTargetPosition());
  78. this._cache.alpha = this.alpha;
  79. this._cache.beta = this.beta;
  80. this._cache.radius = this.radius;
  81. }
  82. // Synchronized
  83. public _isSynchronizedViewMatrix(): boolean {
  84. if (!super._isSynchronizedViewMatrix())
  85. return false;
  86. return this._cache.target.equals(this._getTargetPosition())
  87. && this._cache.alpha === this.alpha
  88. && this._cache.beta === this.beta
  89. && this._cache.radius === this.radius;
  90. }
  91. // Methods
  92. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  93. var previousPosition;
  94. var pointerId;
  95. // to know if pinch started
  96. var pinchStarted = false;
  97. // two pinch point on X
  98. // that will use for find if user action is pinch open or pinch close
  99. var pinchPointX1, pinchPointX2;
  100. if (this._attachedElement) {
  101. return;
  102. }
  103. this._attachedElement = element;
  104. var engine = this.getEngine();
  105. if (this._onPointerDown === undefined) {
  106. this._onPointerDown = evt => {
  107. if (pointerId) {
  108. return;
  109. }
  110. pointerId = evt.pointerId;
  111. previousPosition = {
  112. x: evt.clientX,
  113. y: evt.clientY
  114. };
  115. if (!noPreventDefault) {
  116. evt.preventDefault();
  117. }
  118. };
  119. this._onPointerUp = evt => {
  120. previousPosition = null;
  121. pointerId = null;
  122. if (!noPreventDefault) {
  123. evt.preventDefault();
  124. }
  125. };
  126. this._onPointerMove = evt => {
  127. if (!previousPosition) {
  128. return;
  129. }
  130. if (pointerId !== evt.pointerId) {
  131. return;
  132. }
  133. // return pinch is started
  134. if (pinchStarted) {
  135. return;
  136. }
  137. var offsetX = evt.clientX - previousPosition.x;
  138. var offsetY = evt.clientY - previousPosition.y;
  139. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  140. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  141. previousPosition = {
  142. x: evt.clientX,
  143. y: evt.clientY
  144. };
  145. if (!noPreventDefault) {
  146. evt.preventDefault();
  147. }
  148. };
  149. this._onMouseMove = evt => {
  150. if (!engine.isPointerLock) {
  151. return;
  152. }
  153. // return pinch is started
  154. if (pinchStarted) {
  155. return;
  156. }
  157. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  158. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  159. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  160. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  161. if (!noPreventDefault) {
  162. evt.preventDefault();
  163. }
  164. };
  165. this._wheel = event => {
  166. var delta = 0;
  167. if (event.wheelDelta) {
  168. delta = event.wheelDelta / (this.wheelPrecision * 40);
  169. } else if (event.detail) {
  170. delta = -event.detail / this.wheelPrecision;
  171. }
  172. if (delta)
  173. this.inertialRadiusOffset += delta;
  174. if (event.preventDefault) {
  175. if (!noPreventDefault) {
  176. event.preventDefault();
  177. }
  178. }
  179. };
  180. this._onKeyDown = evt => {
  181. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  182. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  183. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  184. this.keysRight.indexOf(evt.keyCode) !== -1) {
  185. var index = this._keys.indexOf(evt.keyCode);
  186. if (index === -1) {
  187. this._keys.push(evt.keyCode);
  188. }
  189. if (evt.preventDefault) {
  190. if (!noPreventDefault) {
  191. evt.preventDefault();
  192. }
  193. }
  194. }
  195. };
  196. this._onKeyUp = evt => {
  197. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  198. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  199. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  200. this.keysRight.indexOf(evt.keyCode) !== -1) {
  201. var index = this._keys.indexOf(evt.keyCode);
  202. if (index >= 0) {
  203. this._keys.splice(index, 1);
  204. }
  205. if (evt.preventDefault) {
  206. if (!noPreventDefault) {
  207. evt.preventDefault();
  208. }
  209. }
  210. }
  211. };
  212. this._onLostFocus = () => {
  213. this._keys = [];
  214. pointerId = null;
  215. };
  216. this._onGestureStart = e => {
  217. if (window.MSGesture === undefined) {
  218. return;
  219. }
  220. if (!this._MSGestureHandler) {
  221. this._MSGestureHandler = new MSGesture();
  222. this._MSGestureHandler.target = element;
  223. }
  224. this._MSGestureHandler.addPointer(e.pointerId);
  225. };
  226. this._onGesture = e => {
  227. this.radius *= e.scale;
  228. if (e.preventDefault) {
  229. if (!noPreventDefault) {
  230. e.stopPropagation();
  231. e.preventDefault();
  232. }
  233. }
  234. };
  235. this._reset = () => {
  236. this._keys = [];
  237. this.inertialAlphaOffset = 0;
  238. this.inertialBetaOffset = 0;
  239. this.inertialRadiusOffset = 0;
  240. previousPosition = null;
  241. pointerId = null;
  242. };
  243. this._touchStart = event => {
  244. if (event.touches.length == 2) {
  245. //-- start pinch if two fingers on the screen
  246. pinchStarted = true;
  247. this._pinchStart(event);
  248. }
  249. };
  250. this._touchMove = event => {
  251. if (pinchStarted) {
  252. //-- make scaling
  253. this._pinchMove(event);
  254. }
  255. };
  256. this._touchEnd = event => {
  257. if (pinchStarted) {
  258. //-- end of pinch
  259. this._pinchEnd(event);
  260. }
  261. };
  262. this._pinchStart = event => {
  263. // save origin touch point
  264. pinchPointX1 = event.touches[0].clientX;
  265. pinchPointX2 = event.touches[1].clientX;
  266. // block the camera
  267. // if not it rotate around target during pinch
  268. pinchStarted = true;
  269. };
  270. this._pinchMove = event => {
  271. // variable for new camera's radius
  272. var delta = 0;
  273. // variables to know if pinch open or pinch close
  274. var direction = 1;
  275. var distanceXOrigine, distanceXNow;
  276. if (event.touches.length != 2)
  277. return;
  278. // calculate absolute distances of the two fingers
  279. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  280. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  281. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  282. if (distanceXNow < distanceXOrigine) {
  283. direction = -1;
  284. }
  285. // calculate new radius
  286. delta = (this.pinchPrecision / (this.wheelPrecision * 40)) * direction;
  287. // set new radius
  288. this.inertialRadiusOffset += delta;
  289. // save origin touch point
  290. pinchPointX1 = event.touches[0].clientX;
  291. pinchPointX2 = event.touches[1].clientX;
  292. };
  293. this._pinchEnd = event => {
  294. // cancel pinch and deblock camera rotation
  295. pinchStarted = false;
  296. };
  297. }
  298. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  299. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  300. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  301. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  302. element.addEventListener("mousemove", this._onMouseMove, false);
  303. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  304. element.addEventListener("MSGestureChange", this._onGesture, false);
  305. element.addEventListener('mousewheel', this._wheel, false);
  306. element.addEventListener('DOMMouseScroll', this._wheel, false);
  307. // pinch
  308. element.addEventListener('touchstart', this._touchStart, false);
  309. element.addEventListener('touchmove', this._touchMove, false);
  310. element.addEventListener('touchend', this._touchEnd, false);
  311. Tools.RegisterTopRootEvents([
  312. { name: "keydown", handler: this._onKeyDown },
  313. { name: "keyup", handler: this._onKeyUp },
  314. { name: "blur", handler: this._onLostFocus }
  315. ]);
  316. }
  317. public detachControl(element: HTMLElement): void {
  318. if (this._attachedElement != element) {
  319. return;
  320. }
  321. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  322. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  323. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  324. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  325. element.removeEventListener("mousemove", this._onMouseMove);
  326. element.removeEventListener("MSPointerDown", this._onGestureStart);
  327. element.removeEventListener("MSGestureChange", this._onGesture);
  328. element.removeEventListener('mousewheel', this._wheel);
  329. element.removeEventListener('DOMMouseScroll', this._wheel);
  330. // pinch
  331. element.removeEventListener('touchstart', this._touchStart);
  332. element.removeEventListener('touchmove', this._touchMove);
  333. element.removeEventListener('touchend', this._touchEnd);
  334. Tools.UnregisterTopRootEvents([
  335. { name: "keydown", handler: this._onKeyDown },
  336. { name: "keyup", handler: this._onKeyUp },
  337. { name: "blur", handler: this._onLostFocus }
  338. ]);
  339. this._MSGestureHandler = null;
  340. this._attachedElement = null;
  341. if (this._reset) {
  342. this._reset();
  343. }
  344. }
  345. public _update(): void {
  346. // Keyboard
  347. for (var index = 0; index < this._keys.length; index++) {
  348. var keyCode = this._keys[index];
  349. if (this.keysLeft.indexOf(keyCode) !== -1) {
  350. this.inertialAlphaOffset -= 0.01;
  351. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  352. this.inertialBetaOffset -= 0.01;
  353. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  354. this.inertialAlphaOffset += 0.01;
  355. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  356. this.inertialBetaOffset += 0.01;
  357. }
  358. }
  359. // Inertia
  360. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  361. this.alpha += this.inertialAlphaOffset;
  362. this.beta += this.inertialBetaOffset;
  363. this.radius -= this.inertialRadiusOffset;
  364. this.inertialAlphaOffset *= this.inertia;
  365. this.inertialBetaOffset *= this.inertia;
  366. this.inertialRadiusOffset *= this.inertia;
  367. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  368. this.inertialAlphaOffset = 0;
  369. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  370. this.inertialBetaOffset = 0;
  371. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  372. this.inertialRadiusOffset = 0;
  373. }
  374. // Limits
  375. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  376. this.alpha = this.lowerAlphaLimit;
  377. }
  378. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  379. this.alpha = this.upperAlphaLimit;
  380. }
  381. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  382. this.beta = this.lowerBetaLimit;
  383. }
  384. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  385. this.beta = this.upperBetaLimit;
  386. }
  387. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  388. this.radius = this.lowerRadiusLimit;
  389. }
  390. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  391. this.radius = this.upperRadiusLimit;
  392. }
  393. }
  394. public setPosition(position: Vector3): void {
  395. var radiusv3 = position.subtract(this._getTargetPosition());
  396. this.radius = radiusv3.length();
  397. // Alpha
  398. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  399. if (radiusv3.z < 0) {
  400. this.alpha = 2 * Math.PI - this.alpha;
  401. }
  402. // Beta
  403. this.beta = Math.acos(radiusv3.y / this.radius);
  404. }
  405. public _getViewMatrix(): Matrix {
  406. // Compute
  407. var cosa = Math.cos(this.alpha);
  408. var sina = Math.sin(this.alpha);
  409. var cosb = Math.cos(this.beta);
  410. var sinb = Math.sin(this.beta);
  411. var target = this._getTargetPosition();
  412. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  413. if (this.checkCollisions) {
  414. this._collider.radius = this.collisionRadius;
  415. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  416. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  417. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  418. this.position.copyFrom(this._previousPosition);
  419. this.alpha = this._previousAlpha;
  420. this.beta = this._previousBeta;
  421. this.radius = this._previousRadius;
  422. if (this.onCollide) {
  423. this.onCollide(this._collider.collidedMesh);
  424. }
  425. }
  426. }
  427. Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  428. this._previousAlpha = this.alpha;
  429. this._previousBeta = this.beta;
  430. this._previousRadius = this.radius;
  431. this._previousPosition.copyFrom(this.position);
  432. return this._viewMatrix;
  433. }
  434. public zoomOn(meshes?: AbstractMesh[]): void {
  435. meshes = meshes || this.getScene().meshes;
  436. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  437. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  438. this.radius = distance * this.zoomOnFactor;
  439. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  440. }
  441. public focusOn(meshesOrMinMaxVectorAndDistance): void {
  442. var meshesOrMinMaxVector;
  443. var distance;
  444. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  445. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  446. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  447. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  448. }
  449. else { //minMaxVector and distance
  450. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  451. distance = meshesOrMinMaxVectorAndDistance.distance;
  452. }
  453. this.target = Mesh.Center(meshesOrMinMaxVector);
  454. this.maxZ = distance * 2;
  455. }
  456. }
  457. }