UNPKG

itowns

Version:

A JS/WebGL framework for 3D geospatial data visualization

381 lines (318 loc) 13.4 kB
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var THREE = _interopRequireWildcard(require("three")); var _MainLoop = require("../Core/MainLoop"); // Note: we could use existing three.js controls (like https://github.com/mrdoob/three.js/blob/dev/examples/js/controls/FirstPersonControls.js) // but including these controls in itowns allows use to integrate them tightly with itowns. // Especially the existing controls are expecting a continuous update loop while we have a pausable one (so our controls use .notifyChange when needed) function limitRotation(camera3D, rot, verticalFOV) { // Limit vertical rotation (look up/down) to make sure the user cannot see // outside of the cone defined by verticalFOV var limit = THREE.Math.degToRad(verticalFOV - camera3D.fov) * 0.5; return THREE.Math.clamp(rot, -limit, limit); } var axisY = new THREE.Vector3(0, 1, 0); function applyRotation(view, camera3D, state) { camera3D.quaternion.setFromUnitVectors(axisY, camera3D.up); camera3D.rotateY(state.rotateY); camera3D.rotateX(state.rotateX); view.notifyChange(view.camera.camera3D); } var MOVEMENTS = { 38: { method: 'translateZ', sign: -1 }, // FORWARD: up key 40: { method: 'translateZ', sign: 1 }, // BACKWARD: down key 37: { method: 'translateX', sign: -1 }, // STRAFE_LEFT: left key 39: { method: 'translateX', sign: 1 }, // STRAFE_RIGHT: right key 33: { method: 'translateY', sign: 1 }, // UP: PageUp key 34: { method: 'translateY', sign: -1 } // DOWN: PageDown key }; function moveCameraVerticalPlanar(value) { this.camera.position.z += value; } var normal = new THREE.Vector3(); var q = new THREE.Quaternion(); var e = new THREE.Euler(0, 0, 0, 'YXZ'); function moveCameraVerticalGlobe(value) { // compute geodesic normale normal.copy(this.camera.position); normal.normalize(); this.camera.position.add(normal.multiplyScalar(value)); } var FirstPersonControls = /*#__PURE__*/ function (_THREE$EventDispatche) { (0, _inherits2["default"])(FirstPersonControls, _THREE$EventDispatche); /** * @Constructor * @param {View} view * @param {object} options * @param {boolean} options.focusOnClick - whether or not to focus the renderer domElement on click * @param {boolean} options.focusOnMouseOver - whether or not to focus when the mouse is over the domElement * @param {boolean} options.moveSpeed - if > 0, pressing the arrow keys will move the camera * @param {number} options.verticalFOV - define the max visible vertical angle of the scene in degrees (default 180) * @param {number} options.panoramaRatio - alternative way to specify the max vertical angle when using a panorama. * You can specify the panorama width/height ratio and the verticalFOV will be computed automatically * @param {boolean} options.disableEventListeners - if true, the controls will not self listen to mouse/key events. * You'll have to manually forward the events to the appropriate functions: onMouseDown, onMouseMove, onMouseUp, * onKeyUp, onKeyDown and onMouseWheel. */ function FirstPersonControls(view) { var _this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; (0, _classCallCheck2["default"])(this, FirstPersonControls); _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(FirstPersonControls).call(this)); _this.isFirstPersonControls = true; _this.camera = view.camera.camera3D; _this.view = view; _this.moves = new Set(); if (options.panoramaRatio) { var radius = options.panoramaRatio * 200 / (2 * Math.PI); options.verticalFOV = options.panoramaRatio == 2 ? 180 : THREE.Math.radToDeg(2 * Math.atan(200 / (2 * radius))); } options.verticalFOV = options.verticalFOV || 180; options.moveSpeed = options.moveSpeed === undefined ? 10 : options.moveSpeed; // backward or forward move speed in m/s _this.options = options; _this._isMouseDown = false; _this._onMouseDownMouseX = 0; _this._onMouseDownMouseY = 0; _this._state = { rotateX: 0, rotateY: 0, snapshot: function snapshot() { return { rotateX: this.rotateX, rotateY: this.rotateY }; } }; _this.reset(); var domElement = view.mainLoop.gfxEngine.renderer.domElement; if (!options.disableEventListeners) { domElement.addEventListener('mousedown', _this.onMouseDown.bind((0, _assertThisInitialized2["default"])(_this)), false); domElement.addEventListener('touchstart', _this.onMouseDown.bind((0, _assertThisInitialized2["default"])(_this)), false); domElement.addEventListener('mousemove', _this.onMouseMove.bind((0, _assertThisInitialized2["default"])(_this)), false); domElement.addEventListener('touchmove', _this.onMouseMove.bind((0, _assertThisInitialized2["default"])(_this)), false); domElement.addEventListener('mouseup', _this.onMouseUp.bind((0, _assertThisInitialized2["default"])(_this)), false); domElement.addEventListener('touchend', _this.onMouseUp.bind((0, _assertThisInitialized2["default"])(_this)), false); domElement.addEventListener('keyup', _this.onKeyUp.bind((0, _assertThisInitialized2["default"])(_this)), true); domElement.addEventListener('keydown', _this.onKeyDown.bind((0, _assertThisInitialized2["default"])(_this)), true); domElement.addEventListener('mousewheel', _this.onMouseWheel.bind((0, _assertThisInitialized2["default"])(_this)), false); domElement.addEventListener('DOMMouseScroll', _this.onMouseWheel.bind((0, _assertThisInitialized2["default"])(_this)), false); // firefox } _this.view.addFrameRequester(_MainLoop.MAIN_LOOP_EVENTS.AFTER_CAMERA_UPDATE, _this.update.bind((0, _assertThisInitialized2["default"])(_this))); // focus policy if (options.focusOnMouseOver) { domElement.addEventListener('mouseover', function () { return domElement.focus(); }); } if (options.focusOnClick) { domElement.addEventListener('click', function () { return domElement.focus(); }); } if (view.referenceCrs == 'EPSG:4978') { _this.moveCameraVertical = moveCameraVerticalGlobe; } else { _this.moveCameraVertical = moveCameraVerticalPlanar; } return _this; } (0, _createClass2["default"])(FirstPersonControls, [{ key: "isUserInteracting", value: function isUserInteracting() { return this.moves.size !== 0 && !this._isMouseDown; } /** * Resets the controls internal state to match the camera' state. * This must be called when manually modifying the camera's position or rotation. * @param {boolean} preserveRotationOnX - if true, the look up/down rotation will * not be copied from the camera */ }, { key: "reset", value: function reset() { var preserveRotationOnX = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; // Compute the correct init state, given the calculus in applyRotation: // cam.quaternion = q * r // => r = inverse(q) * cam.quaterion // q is the quaternion derived from the up vector q.setFromUnitVectors(axisY, this.camera.up); q.inverse(); q.multiply(this.camera.quaternion); // tranform it to euler e.setFromQuaternion(q); if (!preserveRotationOnX) { this._state.rotateX = e.x; } this._state.rotateY = e.y; } /** * Updates the camera position / rotation based on occured input events. * This is done automatically when needed but can also be done if needed. * @param {number} dt - ellpased time since last update in seconds * @param {boolean} updateLoopRestarted - true if itowns' update loop just restarted * @param {boolean} force - set to true if you want to force the update, even if it * appears unneeded. */ }, { key: "update", value: function update(dt, updateLoopRestarted, force) { if (this.enabled == false) { return; } // dt will not be relevant when we just started rendering, we consider a 1-frame move in this case if (updateLoopRestarted) { dt = 16; } var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this.moves[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var move = _step.value; if (move.method === 'translateY') { this.moveCameraVertical(move.sign * this.options.moveSpeed * dt / 1000); } else { this.camera[move.method](move.sign * this.options.moveSpeed * dt / 1000); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (this._isMouseDown === true || force === true) { applyRotation(this.view, this.camera, this._state); } if (this.moves.size) { this.view.notifyChange(this.view.camera.camera3D); } } // Event callback functions // Mouse movement handling }, { key: "onMouseDown", value: function onMouseDown(event) { if (this.enabled == false) { return; } // next line is commented because, when I uncomment it, key binding doesn't work any more. // event.preventDefault(); this._isMouseDown = true; var coords = this.view.eventToViewCoords(event); this._onMouseDownMouseX = coords.x; this._onMouseDownMouseY = coords.y; this._stateOnMouseDown = this._state.snapshot(); } }, { key: "onMouseUp", value: function onMouseUp() { if (this.enabled == false) { return; } this._isMouseDown = false; } }, { key: "onMouseMove", value: function onMouseMove(event) { if (this.enabled == false) { return; } if (this._isMouseDown === true) { // in rigor we have tan(theta) = tan(cameraFOV) * deltaH / H // (where deltaH is the vertical amount we moved, and H the renderer height) // we loosely approximate tan(x) by x var pxToAngleRatio = THREE.Math.degToRad(this.camera.fov) / this.view.mainLoop.gfxEngine.height; var coords = this.view.eventToViewCoords(event); // update state based on pointer movement this._state.rotateY = (coords.x - this._onMouseDownMouseX) * pxToAngleRatio + this._stateOnMouseDown.rotateY; this._state.rotateX = limitRotation(this.camera, (coords.y - this._onMouseDownMouseY) * pxToAngleRatio + this._stateOnMouseDown.rotateX, this.options.verticalFOV); applyRotation(this.view, this.camera, this._state); } } // Mouse wheel }, { key: "onMouseWheel", value: function onMouseWheel(event) { if (this.enabled == false) { return; } var delta = 0; if (event.wheelDelta !== undefined) { delta = -event.wheelDelta; // Firefox } else if (event.detail !== undefined) { delta = event.detail; } this.camera.fov = THREE.Math.clamp(this.camera.fov + Math.sign(delta), 10, Math.min(100, this.options.verticalFOV)); this.camera.updateProjectionMatrix(); this._state.rotateX = limitRotation(this.camera, this._state.rotateX, this.options.verticalFOV); applyRotation(this.view, this.camera, this._state); } // Keyboard handling }, { key: "onKeyUp", value: function onKeyUp(e) { if (this.enabled == false) { return; } var move = MOVEMENTS[e.keyCode]; if (move) { this.moves["delete"](move); this.view.notifyChange(undefined, false); e.preventDefault(); } } }, { key: "onKeyDown", value: function onKeyDown(e) { if (this.enabled == false) { return; } var move = MOVEMENTS[e.keyCode]; if (move) { this.moves.add(move); this.view.notifyChange(undefined, false); e.preventDefault(); } } }]); return FirstPersonControls; }(THREE.EventDispatcher); var _default = FirstPersonControls; exports["default"] = _default;