babylon.arcRotateCamera.ts 20 KB

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