babylon.arcRotateCamera.ts 24 KB

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