babylon.arcRotateCamera.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 BABYLON.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. constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene: Scene) {
  49. super(name, BABYLON.Vector3.Zero(), scene);
  50. if(!this.target) {
  51. this.target = Vector3.Zero();
  52. }
  53. this.getViewMatrix();
  54. }
  55. public _getTargetPosition(): Vector3 {
  56. return this.target.position || this.target;
  57. }
  58. // Cache
  59. public _initCache(): void {
  60. super._initCache();
  61. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  62. this._cache.alpha = undefined;
  63. this._cache.beta = undefined;
  64. this._cache.radius = undefined;
  65. this._cache.targetScreenOffset = undefined;
  66. }
  67. public _updateCache(ignoreParentClass?: boolean): void {
  68. if (!ignoreParentClass) {
  69. super._updateCache();
  70. }
  71. this._cache.target.copyFrom(this._getTargetPosition());
  72. this._cache.alpha = this.alpha;
  73. this._cache.beta = this.beta;
  74. this._cache.radius = this.radius;
  75. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  76. }
  77. // Synchronized
  78. public _isSynchronizedViewMatrix(): boolean {
  79. if (!super._isSynchronizedViewMatrix())
  80. return false;
  81. return this._cache.target.equals(this._getTargetPosition())
  82. && this._cache.alpha === this.alpha
  83. && this._cache.beta === this.beta
  84. && this._cache.radius === this.radius
  85. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  86. }
  87. // Methods
  88. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  89. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  90. var previousPinchDistance = 0;
  91. var pointers = new BABYLON.SmartCollection();
  92. if (this._attachedElement) {
  93. return;
  94. }
  95. this._attachedElement = element;
  96. var engine = this.getEngine();
  97. if (this._onPointerDown === undefined) {
  98. this._onPointerDown = evt => {
  99. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  100. cacheSoloPointer = pointers.item(evt.pointerId);
  101. if (!noPreventDefault) {
  102. evt.preventDefault();
  103. }
  104. };
  105. this._onPointerUp = evt => {
  106. cacheSoloPointer = null;
  107. previousPinchDistance = 0;
  108. pointers.remove(evt.pointerId);
  109. if (!noPreventDefault) {
  110. evt.preventDefault();
  111. }
  112. };
  113. this._onPointerMove = evt => {
  114. if (!noPreventDefault) {
  115. evt.preventDefault();
  116. }
  117. switch (pointers.count) {
  118. case 1: //normal camera rotation
  119. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  120. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  121. var offsetX = evt.clientX - cacheSoloPointer.x;
  122. var offsetY = evt.clientY - cacheSoloPointer.y;
  123. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  124. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  125. //pointers.item(evt.pointerId).x = evt.clientX;
  126. //pointers.item(evt.pointerId).y = evt.clientY;
  127. cacheSoloPointer.x = evt.clientX;
  128. cacheSoloPointer.y = evt.clientY;
  129. break;
  130. case 2: //pinch
  131. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  132. pointers.item(evt.pointerId).x = evt.clientX;
  133. pointers.item(evt.pointerId).y = evt.clientY;
  134. var direction = 1;
  135. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  136. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  137. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  138. if (previousPinchDistance === 0) {
  139. previousPinchDistance = pinchSquaredDistance;
  140. return;
  141. }
  142. if (pinchSquaredDistance != previousPinchDistance) {
  143. if (pinchSquaredDistance > previousPinchDistance) {
  144. direction = -1;
  145. }
  146. this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (this.pinchPrecision * this.wheelPrecision * this.angularSensibility);
  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. // Keyboard
  292. for (var index = 0; index < this._keys.length; index++) {
  293. var keyCode = this._keys[index];
  294. if (this.keysLeft.indexOf(keyCode) !== -1) {
  295. this.inertialAlphaOffset -= 0.01;
  296. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  297. this.inertialBetaOffset -= 0.01;
  298. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  299. this.inertialAlphaOffset += 0.01;
  300. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  301. this.inertialBetaOffset += 0.01;
  302. }
  303. }
  304. // Inertia
  305. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  306. this.alpha += this.inertialAlphaOffset;
  307. this.beta += this.inertialBetaOffset;
  308. this.radius -= this.inertialRadiusOffset;
  309. this.inertialAlphaOffset *= this.inertia;
  310. this.inertialBetaOffset *= this.inertia;
  311. this.inertialRadiusOffset *= this.inertia;
  312. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  313. this.inertialAlphaOffset = 0;
  314. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  315. this.inertialBetaOffset = 0;
  316. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  317. this.inertialRadiusOffset = 0;
  318. }
  319. // Limits
  320. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  321. this.alpha = this.lowerAlphaLimit;
  322. }
  323. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  324. this.alpha = this.upperAlphaLimit;
  325. }
  326. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  327. this.beta = this.lowerBetaLimit;
  328. }
  329. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  330. this.beta = this.upperBetaLimit;
  331. }
  332. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  333. this.radius = this.lowerRadiusLimit;
  334. }
  335. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  336. this.radius = this.upperRadiusLimit;
  337. }
  338. }
  339. public setPosition(position: Vector3): void {
  340. var radiusv3 = position.subtract(this._getTargetPosition());
  341. this.radius = radiusv3.length();
  342. // Alpha
  343. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  344. if (radiusv3.z < 0) {
  345. this.alpha = 2 * Math.PI - this.alpha;
  346. }
  347. // Beta
  348. this.beta = Math.acos(radiusv3.y / this.radius);
  349. }
  350. public _getViewMatrix(): Matrix {
  351. // Compute
  352. var cosa = Math.cos(this.alpha);
  353. var sina = Math.sin(this.alpha);
  354. var cosb = Math.cos(this.beta);
  355. var sinb = Math.sin(this.beta);
  356. var target = this._getTargetPosition();
  357. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  358. if (this.checkCollisions) {
  359. this._collider.radius = this.collisionRadius;
  360. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  361. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  362. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  363. this.position.copyFrom(this._previousPosition);
  364. this.alpha = this._previousAlpha;
  365. this.beta = this._previousBeta;
  366. this.radius = this._previousRadius;
  367. if (this.onCollide) {
  368. this.onCollide(this._collider.collidedMesh);
  369. }
  370. }
  371. }
  372. Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  373. this._previousAlpha = this.alpha;
  374. this._previousBeta = this.beta;
  375. this._previousRadius = this.radius;
  376. this._previousPosition.copyFrom(this.position);
  377. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  378. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  379. return this._viewMatrix;
  380. }
  381. public zoomOn(meshes?: AbstractMesh[]): void {
  382. meshes = meshes || this.getScene().meshes;
  383. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  384. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  385. this.radius = distance * this.zoomOnFactor;
  386. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  387. }
  388. public focusOn(meshesOrMinMaxVectorAndDistance): void {
  389. var meshesOrMinMaxVector;
  390. var distance;
  391. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  392. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  393. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  394. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  395. }
  396. else { //minMaxVector and distance
  397. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  398. distance = meshesOrMinMaxVectorAndDistance.distance;
  399. }
  400. this.target = Mesh.Center(meshesOrMinMaxVector);
  401. this.maxZ = distance * 2;
  402. }
  403. }
  404. }