babylon.arcRotateCamera.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 pinchPrecision = 2.0;
  16. public keysUp = [38];
  17. public keysDown = [40];
  18. public keysLeft = [37];
  19. public keysRight = [39];
  20. public zoomOnFactor = 1;
  21. public targetScreenOffset = Vector2.Zero();
  22. public pinchInwards: boolean = true;
  23. private _keys = [];
  24. private _viewMatrix = new Matrix();
  25. private _attachedElement: HTMLElement;
  26. private _onPointerDown: (e: PointerEvent) => void;
  27. private _onPointerUp: (e: PointerEvent) => void;
  28. private _onPointerMove: (e: PointerEvent) => void;
  29. private _wheel: (e: MouseWheelEvent) => void;
  30. private _onMouseMove: (e: MouseEvent) => any;
  31. private _onKeyDown: (e: KeyboardEvent) => any;
  32. private _onKeyUp: (e: KeyboardEvent) => any;
  33. private _onLostFocus: (e: FocusEvent) => any;
  34. private _reset: () => void;
  35. private _onGestureStart: (e: PointerEvent) => void;
  36. private _onGesture: (e: MSGestureEvent) => void;
  37. private _MSGestureHandler: MSGesture;
  38. // Collisions
  39. public onCollide: (collidedMesh: AbstractMesh) => void;
  40. public checkCollisions = false;
  41. public collisionRadius = new Vector3(0.5, 0.5, 0.5);
  42. private _collider = new Collider();
  43. private _previousPosition = Vector3.Zero();
  44. private _collisionVelocity = Vector3.Zero();
  45. private _newPosition = Vector3.Zero();
  46. private _previousAlpha: number;
  47. private _previousBeta: number;
  48. private _previousRadius: number;
  49. //due to async collision inspection
  50. private _collisionTriggered: boolean;
  51. constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene: Scene) {
  52. super(name, Vector3.Zero(), scene);
  53. if (!this.target) {
  54. this.target = Vector3.Zero();
  55. }
  56. this.getViewMatrix();
  57. }
  58. public _getTargetPosition(): Vector3 {
  59. return this.target.position || this.target;
  60. }
  61. // Cache
  62. public _initCache(): void {
  63. super._initCache();
  64. this._cache.target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65. this._cache.alpha = undefined;
  66. this._cache.beta = undefined;
  67. this._cache.radius = undefined;
  68. this._cache.targetScreenOffset = undefined;
  69. }
  70. public _updateCache(ignoreParentClass?: boolean): void {
  71. if (!ignoreParentClass) {
  72. super._updateCache();
  73. }
  74. this._cache.target.copyFrom(this._getTargetPosition());
  75. this._cache.alpha = this.alpha;
  76. this._cache.beta = this.beta;
  77. this._cache.radius = this.radius;
  78. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  79. }
  80. // Synchronized
  81. public _isSynchronizedViewMatrix(): boolean {
  82. if (!super._isSynchronizedViewMatrix())
  83. return false;
  84. return this._cache.target.equals(this._getTargetPosition())
  85. && this._cache.alpha === this.alpha
  86. && this._cache.beta === this.beta
  87. && this._cache.radius === this.radius
  88. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  89. }
  90. // Methods
  91. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  92. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  93. var previousPinchDistance = 0;
  94. var pointers = new SmartCollection();
  95. if (this._attachedElement) {
  96. return;
  97. }
  98. this._attachedElement = element;
  99. var engine = this.getEngine();
  100. if (this._onPointerDown === undefined) {
  101. this._onPointerDown = evt => {
  102. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  103. cacheSoloPointer = pointers.item(evt.pointerId);
  104. if (!noPreventDefault) {
  105. evt.preventDefault();
  106. }
  107. };
  108. this._onPointerUp = evt => {
  109. cacheSoloPointer = null;
  110. previousPinchDistance = 0;
  111. pointers.remove(evt.pointerId);
  112. if (!noPreventDefault) {
  113. evt.preventDefault();
  114. }
  115. };
  116. this._onPointerMove = evt => {
  117. if (!noPreventDefault) {
  118. evt.preventDefault();
  119. }
  120. switch (pointers.count) {
  121. case 1: //normal camera rotation
  122. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  123. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  124. var offsetX = evt.clientX - cacheSoloPointer.x;
  125. var offsetY = evt.clientY - cacheSoloPointer.y;
  126. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  127. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  128. //pointers.item(evt.pointerId).x = evt.clientX;
  129. //pointers.item(evt.pointerId).y = evt.clientY;
  130. cacheSoloPointer.x = evt.clientX;
  131. cacheSoloPointer.y = evt.clientY;
  132. break;
  133. case 2: //pinch
  134. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  135. pointers.item(evt.pointerId).x = evt.clientX;
  136. pointers.item(evt.pointerId).y = evt.clientY;
  137. var direction = this.pinchInwards ? 1 : -1;
  138. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  139. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  140. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  141. if (previousPinchDistance === 0) {
  142. previousPinchDistance = pinchSquaredDistance;
  143. return;
  144. }
  145. if (pinchSquaredDistance !== previousPinchDistance) {
  146. this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (this.pinchPrecision * this.wheelPrecision * this.angularSensibility * direction);
  147. previousPinchDistance = pinchSquaredDistance;
  148. }
  149. break;
  150. default:
  151. if (pointers.item(evt.pointerId)) {
  152. pointers.item(evt.pointerId).x = evt.clientX;
  153. pointers.item(evt.pointerId).y = evt.clientY;
  154. }
  155. }
  156. };
  157. this._onMouseMove = evt => {
  158. if (!engine.isPointerLock) {
  159. return;
  160. }
  161. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  162. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  163. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  164. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  165. if (!noPreventDefault) {
  166. evt.preventDefault();
  167. }
  168. };
  169. this._wheel = event => {
  170. var delta = 0;
  171. if (event.wheelDelta) {
  172. delta = event.wheelDelta / (this.wheelPrecision * 40);
  173. } else if (event.detail) {
  174. delta = -event.detail / this.wheelPrecision;
  175. }
  176. if (delta)
  177. this.inertialRadiusOffset += delta;
  178. if (event.preventDefault) {
  179. if (!noPreventDefault) {
  180. event.preventDefault();
  181. }
  182. }
  183. };
  184. this._onKeyDown = evt => {
  185. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  186. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  187. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  188. this.keysRight.indexOf(evt.keyCode) !== -1) {
  189. var index = this._keys.indexOf(evt.keyCode);
  190. if (index === -1) {
  191. this._keys.push(evt.keyCode);
  192. }
  193. if (evt.preventDefault) {
  194. if (!noPreventDefault) {
  195. evt.preventDefault();
  196. }
  197. }
  198. }
  199. };
  200. this._onKeyUp = evt => {
  201. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  202. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  203. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  204. this.keysRight.indexOf(evt.keyCode) !== -1) {
  205. var index = this._keys.indexOf(evt.keyCode);
  206. if (index >= 0) {
  207. this._keys.splice(index, 1);
  208. }
  209. if (evt.preventDefault) {
  210. if (!noPreventDefault) {
  211. evt.preventDefault();
  212. }
  213. }
  214. }
  215. };
  216. this._onLostFocus = () => {
  217. this._keys = [];
  218. pointers.empty();
  219. previousPinchDistance = 0;
  220. cacheSoloPointer = null;
  221. };
  222. this._onGestureStart = e => {
  223. if (window.MSGesture === undefined) {
  224. return;
  225. }
  226. if (!this._MSGestureHandler) {
  227. this._MSGestureHandler = new MSGesture();
  228. this._MSGestureHandler.target = element;
  229. }
  230. this._MSGestureHandler.addPointer(e.pointerId);
  231. };
  232. this._onGesture = e => {
  233. this.radius *= e.scale;
  234. if (e.preventDefault) {
  235. if (!noPreventDefault) {
  236. e.stopPropagation();
  237. e.preventDefault();
  238. }
  239. }
  240. };
  241. this._reset = () => {
  242. this._keys = [];
  243. this.inertialAlphaOffset = 0;
  244. this.inertialBetaOffset = 0;
  245. this.inertialRadiusOffset = 0;
  246. pointers.empty();
  247. previousPinchDistance = 0;
  248. cacheSoloPointer = null;
  249. };
  250. }
  251. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  252. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  253. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  254. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  255. element.addEventListener("mousemove", this._onMouseMove, false);
  256. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  257. element.addEventListener("MSGestureChange", this._onGesture, false);
  258. element.addEventListener('mousewheel', this._wheel, false);
  259. element.addEventListener('DOMMouseScroll', this._wheel, false);
  260. Tools.RegisterTopRootEvents([
  261. { name: "keydown", handler: this._onKeyDown },
  262. { name: "keyup", handler: this._onKeyUp },
  263. { name: "blur", handler: this._onLostFocus }
  264. ]);
  265. }
  266. public detachControl(element: HTMLElement): void {
  267. if (this._attachedElement !== element) {
  268. return;
  269. }
  270. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  271. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  272. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  273. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  274. element.removeEventListener("mousemove", this._onMouseMove);
  275. element.removeEventListener("MSPointerDown", this._onGestureStart);
  276. element.removeEventListener("MSGestureChange", this._onGesture);
  277. element.removeEventListener('mousewheel', this._wheel);
  278. element.removeEventListener('DOMMouseScroll', this._wheel);
  279. Tools.UnregisterTopRootEvents([
  280. { name: "keydown", handler: this._onKeyDown },
  281. { name: "keyup", handler: this._onKeyUp },
  282. { name: "blur", handler: this._onLostFocus }
  283. ]);
  284. this._MSGestureHandler = null;
  285. this._attachedElement = null;
  286. if (this._reset) {
  287. this._reset();
  288. }
  289. }
  290. public _update(): void {
  291. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  292. if (this._collisionTriggered) {
  293. return;
  294. }
  295. // Keyboard
  296. for (var index = 0; index < this._keys.length; index++) {
  297. var keyCode = this._keys[index];
  298. if (this.keysLeft.indexOf(keyCode) !== -1) {
  299. this.inertialAlphaOffset -= 0.01;
  300. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  301. this.inertialBetaOffset -= 0.01;
  302. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  303. this.inertialAlphaOffset += 0.01;
  304. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  305. this.inertialBetaOffset += 0.01;
  306. }
  307. }
  308. // Inertia
  309. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  310. this.alpha += this.inertialAlphaOffset;
  311. this.beta += this.inertialBetaOffset;
  312. this.radius -= this.inertialRadiusOffset;
  313. this.inertialAlphaOffset *= this.inertia;
  314. this.inertialBetaOffset *= this.inertia;
  315. this.inertialRadiusOffset *= this.inertia;
  316. if (Math.abs(this.inertialAlphaOffset) < Engine.Epsilon)
  317. this.inertialAlphaOffset = 0;
  318. if (Math.abs(this.inertialBetaOffset) < Engine.Epsilon)
  319. this.inertialBetaOffset = 0;
  320. if (Math.abs(this.inertialRadiusOffset) < Engine.Epsilon)
  321. this.inertialRadiusOffset = 0;
  322. }
  323. // Limits
  324. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  325. this.alpha = this.lowerAlphaLimit;
  326. }
  327. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  328. this.alpha = this.upperAlphaLimit;
  329. }
  330. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  331. this.beta = this.lowerBetaLimit;
  332. }
  333. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  334. this.beta = this.upperBetaLimit;
  335. }
  336. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  337. this.radius = this.lowerRadiusLimit;
  338. }
  339. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  340. this.radius = this.upperRadiusLimit;
  341. }
  342. }
  343. public setPosition(position: Vector3): void {
  344. var radiusv3 = position.subtract(this._getTargetPosition());
  345. this.radius = radiusv3.length();
  346. // Alpha
  347. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  348. if (radiusv3.z < 0) {
  349. this.alpha = 2 * Math.PI - this.alpha;
  350. }
  351. // Beta
  352. this.beta = Math.acos(radiusv3.y / this.radius);
  353. }
  354. public _getViewMatrix(): Matrix {
  355. // Compute
  356. var cosa = Math.cos(this.alpha);
  357. var sina = Math.sin(this.alpha);
  358. var cosb = Math.cos(this.beta);
  359. var sinb = Math.sin(this.beta);
  360. var target = this._getTargetPosition();
  361. target.addToRef(new Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  362. if (this.checkCollisions) {
  363. this._collider.radius = this.collisionRadius;
  364. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  365. this._collisionTriggered = true;
  366. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  367. }
  368. Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  369. this._previousAlpha = this.alpha;
  370. this._previousBeta = this.beta;
  371. this._previousRadius = this.radius;
  372. this._previousPosition.copyFrom(this.position);
  373. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  374. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  375. return this._viewMatrix;
  376. }
  377. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: AbstractMesh = null) => {
  378. if (collisionId != null || collisionId != undefined)
  379. newPosition.multiplyInPlace(this._collider.radius);
  380. if (!newPosition.equalsWithEpsilon(this.position)) {
  381. this.position.copyFrom(this._previousPosition);
  382. this.alpha = this._previousAlpha;
  383. this.beta = this._previousBeta;
  384. this.radius = this._previousRadius;
  385. if (this.onCollide && collidedMesh) {
  386. this.onCollide(collidedMesh);
  387. }
  388. }
  389. this._collisionTriggered = false;
  390. }
  391. public zoomOn(meshes?: AbstractMesh[]): void {
  392. meshes = meshes || this.getScene().meshes;
  393. var minMaxVector = Mesh.MinMax(meshes);
  394. var distance = Vector3.Distance(minMaxVector.min, minMaxVector.max);
  395. this.radius = distance * this.zoomOnFactor;
  396. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  397. }
  398. public focusOn(meshesOrMinMaxVectorAndDistance): void {
  399. var meshesOrMinMaxVector;
  400. var distance;
  401. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  402. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  403. meshesOrMinMaxVector = Mesh.MinMax(meshesOrMinMaxVector);
  404. distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  405. }
  406. else { //minMaxVector and distance
  407. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  408. distance = meshesOrMinMaxVectorAndDistance.distance;
  409. }
  410. this.target = Mesh.Center(meshesOrMinMaxVector);
  411. this.maxZ = distance * 2;
  412. }
  413. }
  414. }