/home/lindsay/xeolabs/xeogl-next/xeogl/src/controls/cameraControl.js
API Docs for:

File: /home/lindsay/xeolabs/xeogl-next/xeogl/src/controls/cameraControl.js

  1. /**
  2. Rotates, pans and zooms the {{#crossLink "Scene"}}{{/crossLink}}'s {{#crossLink "Camera"}}{{/crossLink}} with keyboard, mouse and touch input.
  3.  
  4. CameraControl fires these events:
  5.  
  6. * "hover" - Hover enters a new object
  7. * "hoverSurface" - Hover continues over an object surface - fired continuously as mouse moves over an object
  8. * "hoverLeave" - Hover has left the last object we were hovering over
  9. * "hoverOff" - Hover continues over empty space - fired continuously as mouse moves over nothing
  10. * "picked" - Clicked or tapped object
  11. * "pickedSurface" - Clicked or tapped object, with event containing surface intersection details
  12. * "doublePicked" - Double-clicked or double-tapped object
  13. * "doublePickedSurface" - Double-clicked or double-tapped object, with event containing surface intersection details
  14. * "pickedNothing" - Clicked or tapped, but not on any objects
  15. * "doublePickedNothing" - Double-clicked or double-tapped, but not on any objects
  16.  
  17. CameraControl only fires "hover" events when the mouse is up.
  18.  
  19. For efficiency, CameraControl only does surface intersection picking when you subscribe to "doublePicked" and
  20. "doublePickedSurface" events. Therefore, only subscribe to those when you're OK with the overhead incurred by the
  21. surface intersection tests.
  22.  
  23. ## Panning
  24.  
  25. ## Rotating
  26.  
  27. ## Pivoting
  28.  
  29. ## Zooming
  30.  
  31. ## Events
  32.  
  33. ## Activating and deactivating
  34.  
  35. ## Inertia
  36.  
  37. ## First person
  38.  
  39. ## Zoom to pointer
  40.  
  41. TODO: describe only works for first-person
  42. TODO: make configurable?
  43.  
  44. ## Keyboard layout
  45.  
  46. # Fly-to
  47.  
  48.  
  49. @class CameraControl
  50. @module xeogl
  51. @submodule controls
  52. @constructor
  53. @param [owner] {Component} Owner component. When destroyed, the owner will destroy this component as well. Creates this component within the default {{#crossLink "Scene"}}{{/crossLink}} when omitted.
  54. @param [cfg] {*} Configs
  55. @param [cfg.id] {String} Optional ID, unique among all components in the parent scene, generated automatically when omitted.
  56. @param [cfg.meta] {String:Object} Optional map of user-defined metadata to attach to this CameraControl.
  57. @param [cfg.firstPerson=false] {Boolean} Whether or not this CameraControl is in "first person" mode.
  58. @param [cfg.walking=false] {Boolean} Whether or not this CameraControl is in "walking" mode.
  59. @param [cfg.keyboardLayout="qwerty"] {String} Keyboard layout.
  60. @param [cfg.doublePickFlyTo=true] {Boolean} Whether to fly the camera to each {{#crossLink "Mesh"}}{{/crossLink}} that's double-clicked.
  61. @param [cfg.active=true] {Boolean} Indicates whether or not this CameraControl is active.
  62. @param [cfg.pivoting=false] {Boolean} When true, clicking on a {{#crossLink "Mesh"}}{{/crossLink}} and dragging will pivot
  63. the {{#crossLink "Camera"}}{{/crossLink}} about the picked point on the Mesh's surface.
  64. @param [cfg.panToPointer=false] {Boolean} When true, mouse wheel when mouse is over a {{#crossLink "Mesh"}}{{/crossLink}} will zoom
  65. the {{#crossLink "Camera"}}{{/crossLink}} towards the hoveredd point on the Mesh's surface.
  66. @param [cfg.panToPivot=false] {Boolean} TODO.
  67. @param [cfg.inertia=0.5] {Number} A factor in range [0..1] indicating how much the camera keeps moving after you finish panning or rotating it.
  68. @author xeolabs / http://xeolabs.com
  69. @author DerSchmale / http://www.derschmale.com
  70. @extends Component
  71. */
  72.  
  73. import {core} from "./../core.js";
  74. import {math} from '../math/math.js';
  75. import {Component} from '../component.js';
  76. import {Mesh} from '../objects/mesh.js';
  77. import {AABBGeometry} from '../geometry/aabbGeometry.js';
  78. import {PhongMaterial} from '../materials/phongMaterial.js';
  79. import {CameraFlightAnimation} from '../animation/cameraFlightAnimation.js';
  80. import {componentClasses} from "./../componentClasses.js";
  81.  
  82. const type = "xeogl.CameraControl";
  83.  
  84. class CameraControl extends Component {
  85.  
  86. /**
  87. JavaScript class name for this Component.
  88.  
  89. For example: "xeogl.AmbientLight", "xeogl.MetallicMaterial" etc.
  90.  
  91. @property type
  92. @type String
  93. @final
  94. */
  95. get type() {
  96. return type;
  97. }
  98.  
  99. init(cfg) {
  100.  
  101. super.init(cfg);
  102.  
  103. const self = this;
  104.  
  105. this._boundaryHelper = new Mesh(this, {
  106. geometry: new AABBGeometry(this),
  107. material: new PhongMaterial(this, {
  108. diffuse: [0, 0, 0],
  109. ambient: [0, 0, 0],
  110. specular: [0, 0, 0],
  111. emissive: [1.0, 1.0, 0.6],
  112. lineWidth: 4
  113. }),
  114. visible: false,
  115. collidable: false
  116. });
  117.  
  118. this._pivoter = new (function () { // Pivots the Camera around an arbitrary World-space position
  119.  
  120. // Pivot math by: http://www.derschmale.com/
  121.  
  122. const scene = self.scene;
  123. const camera = scene.camera;
  124. const canvas = scene.canvas;
  125. const pivotPoint = new Float32Array(3);
  126. let cameraOffset;
  127. let azimuth = 0;
  128. let polar = 0;
  129. let radius = 0;
  130. let pivoting = false; // True while pivoting
  131.  
  132. const spot = document.createElement("div");
  133. spot.innerText = " ";
  134. spot.style.color = "#ffffff";
  135. spot.style.position = "absolute";
  136. spot.style.width = "25px";
  137. spot.style.height = "25px";
  138. spot.style.left = "0px";
  139. spot.style.top = "0px";
  140. spot.style["border-radius"] = "15px";
  141. spot.style["border"] = "2px solid #ffffff";
  142. spot.style["background"] = "black";
  143. spot.style.visibility = "hidden";
  144. spot.style["box-shadow"] = "5px 5px 15px 1px #000000";
  145. spot.style["z-index"] = 0;
  146. spot.style["pointer-events"] = "none";
  147. document.body.appendChild(spot);
  148.  
  149. (function () {
  150. const viewPos = math.vec4();
  151. const projPos = math.vec4();
  152. const canvasPos = math.vec2();
  153. let distDirty = true;
  154. camera.on("viewMatrix", function () {
  155. distDirty = true;
  156. });
  157. camera.on("projMatrix", function () {
  158. distDirty = true;
  159. });
  160. scene.on("tick", function () {
  161. if (pivoting && distDirty) {
  162. math.transformPoint3(camera.viewMatrix, pivotPoint, viewPos);
  163. viewPos[3] = 1;
  164. math.transformPoint4(camera.projMatrix, viewPos, projPos);
  165. const aabb = canvas.boundary;
  166. canvasPos[0] = Math.floor((1 + projPos[0] / projPos[3]) * aabb[2] / 2);
  167. canvasPos[1] = Math.floor((1 - projPos[1] / projPos[3]) * aabb[3] / 2);
  168. const canvasElem = canvas.canvas;
  169. const rect = canvasElem.getBoundingClientRect();
  170. spot.style.left = (Math.floor(rect.left + canvasPos[0]) - 12) + "px";
  171. spot.style.top = (Math.floor(rect.top + canvasPos[1]) - 12) + "px";
  172. spot.style.visibility = "visible";
  173. distDirty = false;
  174. }
  175. });
  176. })();
  177.  
  178. this.startPivot = function (worldPos) {
  179. if (worldPos) { // Use last pivotPoint by default
  180. pivotPoint.set(worldPos);
  181. }
  182. let lookat = math.lookAtMat4v(camera.eye, camera.look, camera.worldUp);
  183. cameraOffset = math.transformPoint3(lookat, pivotPoint);
  184. cameraOffset[2] += math.distVec3(camera.eye, pivotPoint);
  185. lookat = math.inverseMat4(lookat);
  186. const offset = math.transformVec3(lookat, cameraOffset);
  187. const diff = math.vec3();
  188. math.subVec3(camera.eye, pivotPoint, diff);
  189. math.addVec3(diff, offset);
  190. if (camera.worldUp[2] === 1) {
  191. const t = diff[1];
  192. diff[1] = diff[2];
  193. diff[2] = t;
  194. }
  195. radius = math.lenVec3(diff);
  196. polar = Math.acos(diff[1] / radius);
  197. azimuth = Math.atan2(diff[0], diff[2]);
  198. pivoting = true;
  199. };
  200.  
  201. this.getPivoting = function () {
  202. return pivoting;
  203. };
  204.  
  205. this.getPivotPos = function () {
  206. return pivotPoint;
  207. };
  208.  
  209. this.continuePivot = function (yawInc, pitchInc) {
  210. if (!pivoting) {
  211. return;
  212. }
  213. if (yawInc === 0 && pitchInc === 0) {
  214. return;
  215. }
  216. if (camera.worldUp[2] === 1) {
  217. dx = -dx;
  218. }
  219. var dx = -yawInc;
  220. const dy = -pitchInc;
  221. azimuth += -dx * .01;
  222. polar += dy * .01;
  223. polar = math.clamp(polar, .001, Math.PI - .001);
  224. const pos = [
  225. radius * Math.sin(polar) * Math.sin(azimuth),
  226. radius * Math.cos(polar),
  227. radius * Math.sin(polar) * Math.cos(azimuth)
  228. ];
  229. if (camera.worldUp[2] === 1) {
  230. const t = pos[1];
  231. pos[1] = pos[2];
  232. pos[2] = t;
  233. }
  234. // Preserve the eye->look distance, since in xeogl "look" is the point-of-interest, not the direction vector.
  235. const eyeLookLen = math.lenVec3(math.subVec3(camera.look, camera.eye, math.vec3()));
  236. math.addVec3(pos, pivotPoint);
  237. let lookat = math.lookAtMat4v(pos, pivotPoint, camera.worldUp);
  238. lookat = math.inverseMat4(lookat);
  239. const offset = math.transformVec3(lookat, cameraOffset);
  240. lookat[12] -= offset[0];
  241. lookat[13] -= offset[1];
  242. lookat[14] -= offset[2];
  243. const zAxis = [lookat[8], lookat[9], lookat[10]];
  244. camera.eye = [lookat[12], lookat[13], lookat[14]];
  245. math.subVec3(camera.eye, math.mulVec3Scalar(zAxis, eyeLookLen), camera.look);
  246. camera.up = [lookat[4], lookat[5], lookat[6]];
  247. spot.style.visibility = "visible";
  248. };
  249.  
  250. this.endPivot = function () {
  251. spot.style.visibility = "hidden";
  252. pivoting = false;
  253. };
  254.  
  255. })();
  256.  
  257. this._cameraFlight = new CameraFlightAnimation(this, {
  258. duration: 0.5
  259. });
  260.  
  261. this.firstPerson = cfg.firstPerson;
  262. this.walking = cfg.walking;
  263. this.keyboardLayout = cfg.keyboardLayout;
  264. this.doublePickFlyTo = cfg.doublePickFlyTo;
  265. this.active = cfg.active;
  266. this.pivoting = cfg.pivoting;
  267. this.panToPointer = cfg.panToPointer;
  268. this.panToPivot = cfg.panToPivot;
  269. this.inertia = cfg.inertia;
  270.  
  271. this._initEvents(); // Set up all the mouse/touch/kb handlers
  272. }
  273.  
  274. /**
  275. Indicates whether this CameraControl is active or not.
  276.  
  277. @property active
  278. @default true
  279. @type Boolean
  280. */
  281. set active(value) {
  282. this._active = value !== false;
  283. }
  284.  
  285. get active() {
  286. return this._active;
  287. }
  288.  
  289. /**
  290. When true, clicking on a {{#crossLink "Mesh"}}{{/crossLink}} and dragging will pivot
  291. the {{#crossLink "Camera"}}{{/crossLink}} about the picked point on the Mesh's surface.
  292.  
  293. @property pivoting
  294. @default false
  295. @type Boolean
  296. */
  297. set pivoting(value) {
  298. this._pivoting = !!value;
  299. }
  300.  
  301. get pivoting() {
  302. return this._pivoting;
  303. }
  304.  
  305. /**
  306. When true, mouse wheel when mouse is over a {{#crossLink "Mesh"}}{{/crossLink}} will zoom
  307. the {{#crossLink "Camera"}}{{/crossLink}} towards the hovered point on the Mesh's surface.
  308.  
  309. @property panToPointer
  310. @default false
  311. @type Boolean
  312. */
  313. set panToPointer(value) {
  314. this._panToPointer = !!value;
  315. if (this._panToPointer) {
  316. this._panToPivot = false;
  317. }
  318. }
  319.  
  320. get panToPointer() {
  321. return this._panToPointer;
  322. }
  323.  
  324. /**
  325. When true, mouse wheel when mouse is over a {{#crossLink "Mesh"}}{{/crossLink}} will zoom
  326. the {{#crossLink "Camera"}}{{/crossLink}} towards the pivot point.
  327.  
  328. @property panToPivot
  329. @default false
  330. @type Boolean
  331. */
  332. set panToPivot(value) {
  333. this._panToPivot = !!value;
  334. if (this._panToPivot) {
  335. this._panToPointer = false;
  336. }
  337. }
  338.  
  339. get panToPivot() {
  340. return this._panToPivot;
  341. }
  342.  
  343. /**
  344. Indicates whether this CameraControl is in "first person" mode.
  345.  
  346. In "first person" mode (disabled by default) the look position rotates about the eye position. Otherwise,
  347. the eye rotates about the look.
  348.  
  349. @property firstPerson
  350. @default false
  351. @type Boolean
  352. */
  353. set firstPerson(value) {
  354. this._firstPerson = !!value;
  355. }
  356.  
  357. get firstPerson() {
  358. return this._firstPerson;
  359. }
  360.  
  361. /**
  362. Indicates whether this CameraControl is in "walking" mode.
  363.  
  364. When set true, this constrains eye movement to the horizontal X-Z plane. When doing a walkthrough,
  365. this is useful to allow us to look upwards or downwards as we move, while keeping us moving in the
  366. horizontal plane.
  367.  
  368. This only has an effect when also in "first person" mode.
  369.  
  370. @property walking
  371. @default false
  372. @type Boolean
  373. */
  374. set walking(value) {
  375. this._walking = !!value;
  376. }
  377.  
  378. get walking() {
  379. return this._walking;
  380. }
  381.  
  382. /**
  383. * TODO
  384. *
  385. *
  386. * @property doublePickFlyTo
  387. * @default true
  388. * @type Boolean
  389. */
  390. set doublePickFlyTo(value) {
  391. this._doublePickFlyTo = value !== false;
  392. }
  393.  
  394. get doublePickFlyTo() {
  395. return this._doublePickFlyTo;
  396. }
  397.  
  398. /**
  399. Factor in range [0..1] indicating how much the camera keeps moving after you finish
  400. panning or rotating it.
  401.  
  402. A value of 0.0 causes it to immediately stop, 0.5 causes its movement to decay 50% on each tick,
  403. while 1.0 causes no decay, allowing it continue moving, by the current rate of pan or rotation.
  404.  
  405. You may choose an inertia of zero when you want be able to precisely position or rotate the camera,
  406. without interference from inertia. ero inertia can also mean that less frames are rendered while
  407. you are positioning the camera.
  408.  
  409. @property inertia
  410. @default 0.5
  411. @type Number
  412. */
  413. set inertia(value) {
  414. this._inertia = value === undefined ? 0.5 : value;
  415. }
  416.  
  417. get inertia() {
  418. return this._inertia;
  419. }
  420.  
  421. /**
  422. * TODO
  423. *
  424. * @property keyboardLayout
  425. * @default "qwerty"
  426. * @type String
  427. */
  428. set keyboardLayout(value) {
  429. this._keyboardLayout = value || "qwerty";
  430. }
  431.  
  432. get keyboardLayout() {
  433. return this._keyboardLayout;
  434. }
  435.  
  436. _initEvents() {
  437.  
  438. const self = this;
  439. const scene = this.scene;
  440. const input = scene.input;
  441. const camera = scene.camera;
  442. const canvas = this.scene.canvas.canvas;
  443. let over = false;
  444. const mouseHoverDelay = 500;
  445. const mouseOrbitRate = 0.4;
  446. const mousePanRate = 0.4;
  447. const mouseZoomRate = 0.8;
  448. const mouseWheelPanRate = 0.4;
  449. const keyboardOrbitRate = .02;
  450. const keyboardPanRate = .02;
  451. const keyboardZoomRate = .02;
  452. const touchRotateRate = 0.3;
  453. const touchPanRate = 0.2;
  454. const touchZoomRate = 0.05;
  455.  
  456. canvas.oncontextmenu = function (e) {
  457. e.preventDefault();
  458. };
  459.  
  460. const getCanvasPosFromEvent = function (event, canvasPos) {
  461. if (!event) {
  462. event = window.event;
  463. canvasPos[0] = event.x;
  464. canvasPos[1] = event.y;
  465. } else {
  466. let element = event.target;
  467. let totalOffsetLeft = 0;
  468. let totalOffsetTop = 0;
  469. while (element.offsetParent) {
  470. totalOffsetLeft += element.offsetLeft;
  471. totalOffsetTop += element.offsetTop;
  472. element = element.offsetParent;
  473. }
  474. canvasPos[0] = event.pageX - totalOffsetLeft;
  475. canvasPos[1] = event.pageY - totalOffsetTop;
  476. }
  477. return canvasPos;
  478. };
  479.  
  480. const pickCursorPos = [0, 0];
  481. let needPickMesh = false;
  482. let needPickSurface = false;
  483. let lastPickedMeshId;
  484. let hit;
  485. let picked = false;
  486. let pickedSurface = false;
  487.  
  488. function updatePick() {
  489. if (!needPickMesh && !needPickSurface) {
  490. return;
  491. }
  492. picked = false;
  493. pickedSurface = false;
  494. if (needPickSurface || self.hasSubs("hoverSurface")) {
  495. hit = scene.pick({
  496. pickSurface: true,
  497. canvasPos: pickCursorPos
  498. });
  499. } else { // needPickMesh == true
  500. hit = scene.pick({
  501. canvasPos: pickCursorPos
  502. });
  503. }
  504. if (hit) {
  505. picked = true;
  506. const pickedMeshId = hit.mesh.id;
  507. if (lastPickedMeshId !== pickedMeshId) {
  508. if (lastPickedMeshId !== undefined) {
  509.  
  510. /**
  511. * Fired whenever the pointer no longer hovers over an {{#crossLink "Mesh"}}{{/crossLink}}.
  512. * @event hoverOut
  513. * @param mesh The Mesh
  514. */
  515. self.fire("hoverOut", {
  516. mesh: scene.meshes[lastPickedMeshId]
  517. });
  518. }
  519.  
  520. /**
  521. * Fired when the pointer is over a new {{#crossLink "Mesh"}}{{/crossLink}}.
  522. * @event hoverEnter
  523. * @param hit A pick hit result containing the ID of the Mesh - see {{#crossLink "Scene/pick:method"}}Scene#pick(){{/crossLink}}.
  524. */
  525. self.fire("hoverEnter", hit);
  526. lastPickedMeshId = pickedMeshId;
  527. }
  528. /**
  529. * Fired continuously while the pointer is moving while hovering over an {{#crossLink "Mesh"}}{{/crossLink}}.
  530. * @event hover
  531. * @param hit A pick hit result containing the ID of the Mesh - see {{#crossLink "Scene/pick:method"}}Scene#pick(){{/crossLink}}.
  532. */
  533. self.fire("hover", hit);
  534. if (hit.worldPos) {
  535. pickedSurface = true;
  536.  
  537. /**
  538. * Fired while the pointer hovers over the surface of an {{#crossLink "Mesh"}}{{/crossLink}}.
  539. *
  540. * This event provides 3D information about the point on the surface that the pointer is
  541. * hovering over.
  542. *
  543. * @event hoverSurface
  544. * @param hit A surface pick hit result, containing the ID of the Mesh and 3D info on the
  545. * surface position - see {{#crossLink "Scene/pick:method"}}Scene#pick(){{/crossLink}}.
  546. */
  547. self.fire("hoverSurface", hit);
  548. }
  549. } else {
  550. if (lastPickedMeshId !== undefined) {
  551. /**
  552. * Fired whenever the pointer no longer hovers over an {{#crossLink "Mesh"}}{{/crossLink}}.
  553. * @event hoverOut
  554. * @param mesh The Mesh
  555. */
  556. self.fire("hoverOut", {
  557. mesh: scene.meshes[lastPickedMeshId]
  558. });
  559. lastPickedMeshId = undefined;
  560. }
  561. /**
  562. * Fired continuously while the pointer is moving but not hovering over anything.
  563. *
  564. * @event hoverOff
  565. */
  566. self.fire("hoverOff", {
  567. canvasPos: pickCursorPos
  568. });
  569. }
  570. needPickMesh = false;
  571. needPickSurface = false;
  572. }
  573.  
  574. scene.on("tick", updatePick);
  575.  
  576. //------------------------------------------------------------------------------------
  577. // Mouse, touch and keyboard camera control
  578. //------------------------------------------------------------------------------------
  579.  
  580. (function () {
  581.  
  582. let rotateVx = 0;
  583. let rotateVy = 0;
  584. let panVx = 0;
  585. let panVy = 0;
  586. let panVz = 0;
  587. let vZoom = 0;
  588. const mousePos = math.vec2();
  589. let panToMouse = false;
  590.  
  591. let ctrlDown = false;
  592. let altDown = false;
  593. let shiftDown = false;
  594. const keyDown = {};
  595.  
  596. const EPSILON = 0.001;
  597.  
  598. const getEyeLookDist = (function () {
  599. const vec = new Float32Array(3);
  600. return function () {
  601. return math.lenVec3(math.subVec3(camera.look, camera.eye, vec));
  602. };
  603. })();
  604.  
  605. const getInverseProjectMat = (function () {
  606. let projMatDirty = true;
  607. camera.on("projMatrix", function () {
  608. projMatDirty = true;
  609. });
  610. const inverseProjectMat = math.mat4();
  611. return function () {
  612. if (projMatDirty) {
  613. math.inverseMat4(camera.projMatrix, inverseProjectMat);
  614. }
  615. return inverseProjectMat;
  616. }
  617. })();
  618.  
  619. const getTransposedProjectMat = (function () {
  620. let projMatDirty = true;
  621. camera.on("projMatrix", function () {
  622. projMatDirty = true;
  623. });
  624. const transposedProjectMat = math.mat4();
  625. return function () {
  626. if (projMatDirty) {
  627. math.transposeMat4(camera.projMatrix, transposedProjectMat);
  628. }
  629. return transposedProjectMat;
  630. }
  631. })();
  632.  
  633. const getInverseViewMat = (function () {
  634. let viewMatDirty = true;
  635. camera.on("viewMatrix", function () {
  636. viewMatDirty = true;
  637. });
  638. const inverseViewMat = math.mat4();
  639. return function () {
  640. if (viewMatDirty) {
  641. math.inverseMat4(camera.viewMatrix, inverseViewMat);
  642. }
  643. return inverseViewMat;
  644. }
  645. })();
  646.  
  647. const getSceneDiagSize = (function () {
  648. let sceneSizeDirty = true;
  649. let diag = 1; // Just in case
  650. scene.on("boundary", function () {
  651. sceneSizeDirty = true;
  652. });
  653. return function () {
  654. if (sceneSizeDirty) {
  655. diag = math.getAABB3Diag(scene.aabb);
  656. }
  657. return diag;
  658. };
  659. })();
  660.  
  661. const panToMousePos = (function () {
  662.  
  663. const cp = math.vec4();
  664. const viewPos = math.vec4();
  665. const worldPos = math.vec4();
  666. const eyeCursorVec = math.vec3();
  667.  
  668. const unproject = function (inverseProjMat, inverseViewMat, mousePos, z, viewPos, worldPos) {
  669. const canvas = scene.canvas.canvas;
  670. const halfCanvasWidth = canvas.offsetWidth / 2.0;
  671. const halfCanvasHeight = canvas.offsetHeight / 2.0;
  672. cp[0] = (mousePos[0] - halfCanvasWidth) / halfCanvasWidth;
  673. cp[1] = (mousePos[1] - halfCanvasHeight) / halfCanvasHeight;
  674. cp[2] = z;
  675. cp[3] = 1.0;
  676. math.mulMat4v4(inverseProjMat, cp, viewPos);
  677. math.mulVec3Scalar(viewPos, 1.0 / viewPos[3]); // Normalize homogeneous coord
  678. viewPos[3] = 1.0;
  679. viewPos[1] *= -1; // TODO: Why is this reversed?
  680. math.mulMat4v4(inverseViewMat, viewPos, worldPos);
  681. };
  682.  
  683. return function (mousePos, factor) {
  684.  
  685. const lastHoverDistance = 0;
  686. const inverseProjMat = getInverseProjectMat();
  687. const inverseViewMat = getInverseViewMat();
  688.  
  689. // Get last two columns of projection matrix
  690. const transposedProjectMat = getTransposedProjectMat();
  691. const Pt3 = transposedProjectMat.subarray(8, 12);
  692. const Pt4 = transposedProjectMat.subarray(12);
  693. const D = [0, 0, -(lastHoverDistance || getSceneDiagSize()), 1];
  694. const Z = math.dotVec4(D, Pt3) / math.dotVec4(D, Pt4);
  695.  
  696. unproject(inverseProjMat, inverseViewMat, mousePos, Z, viewPos, worldPos);
  697.  
  698. math.subVec3(worldPos, camera.eye, eyeCursorVec);
  699. math.normalizeVec3(eyeCursorVec);
  700.  
  701. const px = eyeCursorVec[0] * factor;
  702. const py = eyeCursorVec[1] * factor;
  703. const pz = eyeCursorVec[2] * factor;
  704.  
  705. const eye = camera.eye;
  706. const look = camera.look;
  707.  
  708. camera.eye = [eye[0] + px, eye[1] + py, eye[2] + pz];
  709. camera.look = [look[0] + px, look[1] + py, look[2] + pz];
  710. };
  711. })();
  712.  
  713. const panToWorldPos = (function () {
  714. const eyeCursorVec = math.vec3();
  715. return function (worldPos, factor) {
  716. math.subVec3(worldPos, camera.eye, eyeCursorVec);
  717. math.normalizeVec3(eyeCursorVec);
  718. const px = eyeCursorVec[0] * factor;
  719. const py = eyeCursorVec[1] * factor;
  720. const pz = eyeCursorVec[2] * factor;
  721. const eye = camera.eye;
  722. const look = camera.look;
  723. camera.eye = [eye[0] + px, eye[1] + py, eye[2] + pz];
  724. camera.look = [look[0] + px, look[1] + py, look[2] + pz];
  725. };
  726. })();
  727.  
  728. scene.on("tick", function () {
  729.  
  730. const cameraInertia = self._inertia;
  731.  
  732. if (Math.abs(rotateVx) < EPSILON) {
  733. rotateVx = 0;
  734. }
  735.  
  736. if (Math.abs(rotateVy) < EPSILON) {
  737. rotateVy = 0;
  738. }
  739.  
  740. if (rotateVy !== 0 || rotateVx !== 0) {
  741.  
  742. if (self._pivoter.getPivoting()) {
  743. self._pivoter.continuePivot(rotateVy, rotateVx);
  744.  
  745. } else {
  746.  
  747. if (rotateVx !== 0) {
  748.  
  749. if (self._firstPerson) {
  750. camera.pitch(-rotateVx);
  751.  
  752. } else {
  753. camera.orbitPitch(rotateVx);
  754. }
  755. }
  756.  
  757. if (rotateVy !== 0) {
  758.  
  759. if (self._firstPerson) {
  760. camera.yaw(rotateVy);
  761.  
  762. } else {
  763. camera.orbitYaw(rotateVy);
  764. }
  765. }
  766. }
  767.  
  768. rotateVx *= cameraInertia;
  769. rotateVy *= cameraInertia;
  770. }
  771.  
  772. if (Math.abs(panVx) < EPSILON) {
  773. panVx = 0;
  774. }
  775.  
  776. if (Math.abs(panVy) < EPSILON) {
  777. panVy = 0;
  778. }
  779.  
  780. if (Math.abs(panVz) < EPSILON) {
  781. panVz = 0;
  782. }
  783.  
  784. if (panVx !== 0 || panVy !== 0 || panVz !== 0) {
  785. const f = getEyeLookDist() / 80;
  786. if (self._walking) {
  787. var y = camera.eye[1];
  788. camera.pan([panVx * f, panVy * f, panVz * f]);
  789. var eye = camera.eye;
  790. eye[1] = y;
  791. camera.eye = eye;
  792. } else {
  793. camera.pan([panVx * f, panVy * f, panVz * f]);
  794. }
  795. }
  796.  
  797. panVx *= cameraInertia;
  798. panVy *= cameraInertia;
  799. panVz *= cameraInertia;
  800.  
  801. if (Math.abs(vZoom) < EPSILON) {
  802. vZoom = 0;
  803. }
  804.  
  805. if (vZoom !== 0) {
  806. if (self._firstPerson) {
  807. var y;
  808. if (self._walking) {
  809. y = camera.eye[1];
  810. }
  811. if (panToMouse) { // Using mouse input
  812. panToMousePos(mousePos, -vZoom * 2);
  813. } else {
  814. camera.pan([0, 0, vZoom]); // Touchscreen input with no cursor
  815. }
  816. if (self._walking) {
  817. var eye = camera.eye;
  818. eye[1] = y;
  819. camera.eye = eye;
  820. }
  821. } else {
  822. // Do both zoom and ortho scale so that we can switch projections without weird scale jumps
  823. if (self._panToPointer) {
  824. updatePick();
  825. if (pickedSurface) {
  826. panToWorldPos(hit.worldPos, -vZoom);
  827. } else {
  828. camera.zoom(vZoom);
  829. }
  830. } else if (self._panToPivot) {
  831. panToWorldPos(self._pivoter.getPivotPos(), -vZoom); // FIXME: What about when pivotPos undefined?
  832. } else {
  833. camera.zoom(vZoom);
  834. }
  835. camera.ortho.scale = camera.ortho.scale + vZoom;
  836. }
  837. vZoom *= cameraInertia;
  838. }
  839. });
  840.  
  841. function getZoomRate() {
  842. const aabb = scene.aabb;
  843. const xsize = aabb[3] - aabb[0];
  844. const ysize = aabb[4] - aabb[1];
  845. const zsize = aabb[5] - aabb[2];
  846. let max = (xsize > ysize ? xsize : ysize);
  847. max = (zsize > max ? zsize : max);
  848. return max / 30;
  849. }
  850.  
  851. document.addEventListener("keyDown", function (e) {
  852. if (!self._active) {
  853. return;
  854. }
  855. if (e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") {
  856. ctrlDown = e.ctrlKey || e.keyCode === 17 || e.metaKey; // !important, treat Windows or Mac Command Key as ctrl
  857. altDown = e.altKey || e.keyCode === 18;
  858. shiftDown = e.keyCode === 16;
  859. keyDown[e.keyCode] = true;
  860. }
  861. }, true);
  862.  
  863. document.addEventListener("keyup", function (e) {
  864. if (!self._active) {
  865. return;
  866. }
  867. if (e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") {
  868. if (e.ctrlKey || e.keyCode === 17) {
  869. ctrlDown = false;
  870. }
  871. if (e.altKey || e.keyCode === 18) {
  872. altDown = false;
  873. }
  874. if (e.keyCode === 16) {
  875. shiftDown = false;
  876. }
  877. keyDown[e.keyCode] = false;
  878. }
  879. });
  880.  
  881. // Mouse camera rotate, pan and zoom
  882.  
  883. (function () {
  884.  
  885. let lastX;
  886. let lastY;
  887. let xDelta = 0;
  888. let yDelta = 0;
  889. let down = false;
  890.  
  891. let mouseDownLeft;
  892. let mouseDownMiddle;
  893. let mouseDownRight;
  894.  
  895. canvas.addEventListener("mousedown", function (e) {
  896. if (!self._active) {
  897. return;
  898. }
  899. over = true;
  900. switch (e.which) {
  901. case 1: // Left button
  902. mouseDownLeft = true;
  903. down = true;
  904. xDelta = 0;
  905. yDelta = 0;
  906. getCanvasPosFromEvent(e, mousePos);
  907. lastX = mousePos[0];
  908. lastY = mousePos[1];
  909. break;
  910. case 2: // Middle/both buttons
  911. mouseDownMiddle = true;
  912. break;
  913. case 3: // Right button
  914. mouseDownRight = true;
  915. down = true;
  916. xDelta = 0;
  917. yDelta = 0;
  918. getCanvasPosFromEvent(e, mousePos);
  919. lastX = mousePos[0];
  920. lastY = mousePos[1];
  921. break;
  922. break;
  923. default:
  924. break;
  925. }
  926. });
  927.  
  928. canvas.addEventListener("mouseup", function (e) {
  929. if (!self._active) {
  930. return;
  931. }
  932. switch (e.which) {
  933. case 1: // Left button
  934. mouseDownLeft = false;
  935. break;
  936. case 2: // Middle/both buttons
  937. mouseDownMiddle = false;
  938. break;
  939. case 3: // Right button
  940. mouseDownRight = false;
  941. break;
  942. default:
  943. break;
  944. }
  945. down = false;
  946. xDelta = 0;
  947. yDelta = 0;
  948. });
  949.  
  950. document.addEventListener("mouseup", function (e) {
  951. if (!self._active) {
  952. return;
  953. }
  954. switch (e.which) {
  955. case 1: // Left button
  956. mouseDownLeft = false;
  957. break;
  958. case 2: // Middle/both buttons
  959. mouseDownMiddle = false;
  960. break;
  961. case 3: // Right button
  962. mouseDownRight = false;
  963. break;
  964. default:
  965. break;
  966. }
  967. down = false;
  968. xDelta = 0;
  969. yDelta = 0;
  970. });
  971.  
  972. canvas.addEventListener("mouseenter", function () {
  973. if (!self._active) {
  974. return;
  975. }
  976. over = true;
  977. xDelta = 0;
  978. yDelta = 0;
  979. });
  980.  
  981. canvas.addEventListener("mouseleave", function () {
  982. if (!self._active) {
  983. return;
  984. }
  985. over = false;
  986. xDelta = 0;
  987. yDelta = 0;
  988. });
  989.  
  990. canvas.addEventListener("mousemove", function (e) {
  991. if (!self._active) {
  992. return;
  993. }
  994. if (!over) {
  995. return;
  996. }
  997. getCanvasPosFromEvent(e, mousePos);
  998. panToMouse = true;
  999. if (!down) {
  1000. return;
  1001. }
  1002. const x = mousePos[0];
  1003. const y = mousePos[1];
  1004. xDelta += (x - lastX) * mouseOrbitRate;
  1005. yDelta += (y - lastY) * mouseOrbitRate;
  1006. lastX = x;
  1007. lastY = y;
  1008. });
  1009.  
  1010. scene.on("tick", function () {
  1011. if (!self._active) {
  1012. return;
  1013. }
  1014. if (Math.abs(xDelta) === 0 && Math.abs(yDelta) === 0) {
  1015. return;
  1016. }
  1017.  
  1018. const panning = shiftDown || mouseDownRight;
  1019.  
  1020. if (panning) {
  1021.  
  1022. // Panning
  1023.  
  1024. panVx = xDelta * mousePanRate;
  1025. panVy = yDelta * mousePanRate;
  1026.  
  1027. } else {
  1028.  
  1029. // Orbiting
  1030.  
  1031. rotateVy = -xDelta * mouseOrbitRate;
  1032. rotateVx = yDelta * mouseOrbitRate;
  1033. }
  1034.  
  1035. xDelta = 0;
  1036. yDelta = 0;
  1037. });
  1038.  
  1039. // Mouse wheel zoom
  1040.  
  1041. canvas.addEventListener("wheel", function (e) {
  1042. if (!self._active) {
  1043. return;
  1044. }
  1045. if (self._panToPointer) {
  1046. needPickSurface = true;
  1047. }
  1048. const delta = Math.max(-1, Math.min(1, -e.deltaY * 40));
  1049. if (delta === 0) {
  1050. return;
  1051. }
  1052. const d = delta / Math.abs(delta);
  1053. vZoom = -d * getZoomRate() * mouseZoomRate;
  1054. e.preventDefault();
  1055. });
  1056.  
  1057. // Keyboard zoom
  1058.  
  1059. scene.on("tick", function (e) {
  1060. if (!self._active) {
  1061. return;
  1062. }
  1063. if (!over) {
  1064. return;
  1065. }
  1066. const elapsed = e.deltaTime;
  1067. if (!self.ctrlDown && !self.altDown) {
  1068. const wkey = input.keyDown[input.KEY_ADD];
  1069. const skey = input.keyDown[input.KEY_SUBTRACT];
  1070. if (wkey || skey) {
  1071. if (skey) {
  1072. vZoom = elapsed * getZoomRate() * keyboardZoomRate;
  1073. } else if (wkey) {
  1074. vZoom = -elapsed * getZoomRate() * keyboardZoomRate;
  1075. }
  1076. }
  1077. }
  1078. });
  1079.  
  1080. // Keyboard panning
  1081.  
  1082. (function () {
  1083.  
  1084. scene.on("tick", function (e) {
  1085. if (!self._active) {
  1086. return;
  1087. }
  1088. if (!over) {
  1089. return;
  1090. }
  1091.  
  1092. const elapsed = e.deltaTime;
  1093.  
  1094. // if (!self.ctrlDown && !self.altDown) {
  1095. let front, back, left, right, up, down;
  1096. if (self._keyboardLayout == 'azerty') {
  1097. front = input.keyDown[input.KEY_Z];
  1098. back = input.keyDown[input.KEY_S];
  1099. left = input.keyDown[input.KEY_Q];
  1100. right = input.keyDown[input.KEY_D];
  1101. up = input.keyDown[input.KEY_W];
  1102. down = input.keyDown[input.KEY_X];
  1103. } else {
  1104. front = input.keyDown[input.KEY_W];
  1105. back = input.keyDown[input.KEY_S];
  1106. left = input.keyDown[input.KEY_A];
  1107. right = input.keyDown[input.KEY_D];
  1108. up = input.keyDown[input.KEY_Z];
  1109. down = input.keyDown[input.KEY_X];
  1110. }
  1111. if (front || back || left || right || up || down) {
  1112. if (down) {
  1113. panVy += elapsed * keyboardPanRate;
  1114. } else if (up) {
  1115. panVy -= -elapsed * keyboardPanRate;
  1116. }
  1117. if (right) {
  1118. panVx += -elapsed * keyboardPanRate;
  1119. } else if (left) {
  1120. panVx = elapsed * keyboardPanRate;
  1121. }
  1122. if (back) {
  1123. panVz = elapsed * keyboardPanRate;
  1124. } else if (front) {
  1125. panVz = -elapsed * keyboardPanRate;
  1126. }
  1127. }
  1128. // }
  1129. });
  1130. })();
  1131. })();
  1132.  
  1133. // Touch camera rotate, pan and zoom
  1134.  
  1135. (function () {
  1136.  
  1137. let touchStartTime;
  1138. const tapStartPos = new Float32Array(2);
  1139. let tapStartTime = -1;
  1140.  
  1141. const lastTouches = [];
  1142. let numTouches = 0;
  1143.  
  1144. const touch0Vec = new Float32Array(2);
  1145. const touch1Vec = new Float32Array(2);
  1146.  
  1147. const MODE_CHANGE_TIMEOUT = 50;
  1148. const MODE_NONE = 0;
  1149. const MODE_ROTATE = 1;
  1150. const MODE_PAN = 1 << 1;
  1151. const MODE_ZOOM = 1 << 2;
  1152. let currentMode = MODE_NONE;
  1153. let transitionTime = Date.now();
  1154.  
  1155. function checkMode(mode) {
  1156. const currentTime = Date.now();
  1157. if (currentMode === MODE_NONE) {
  1158. currentMode = mode;
  1159. return true;
  1160. }
  1161. if (currentMode === mode) {
  1162. return currentTime - transitionTime > MODE_CHANGE_TIMEOUT;
  1163. }
  1164. currentMode = mode;
  1165. transitionTime = currentTime;
  1166. return false;
  1167. }
  1168.  
  1169. canvas.addEventListener("touchstart", function (event) {
  1170. if (!self._active) {
  1171. return;
  1172. }
  1173. const touches = event.touches;
  1174. const changedTouches = event.changedTouches;
  1175.  
  1176. touchStartTime = Date.now();
  1177.  
  1178. if (touches.length === 1 && changedTouches.length === 1) {
  1179. tapStartTime = touchStartTime;
  1180. tapStartPos[0] = touches[0].pageX;
  1181. tapStartPos[1] = touches[0].pageY;
  1182. } else {
  1183. tapStartTime = -1;
  1184. }
  1185.  
  1186. while (lastTouches.length < touches.length) {
  1187. lastTouches.push(new Float32Array(2));
  1188. }
  1189.  
  1190. for (let i = 0, len = touches.length; i < len; ++i) {
  1191. lastTouches[i][0] = touches[i].pageX;
  1192. lastTouches[i][1] = touches[i].pageY;
  1193. }
  1194.  
  1195. currentMode = MODE_NONE;
  1196. numTouches = touches.length;
  1197.  
  1198. event.stopPropagation();
  1199. }, {passive: true});
  1200.  
  1201. canvas.addEventListener("touchmove", function (event) {
  1202. if (!self._active) {
  1203. return;
  1204. }
  1205. const touches = event.touches;
  1206.  
  1207. if (numTouches === 1) {
  1208.  
  1209. var touch0 = touches[0];
  1210.  
  1211. if (checkMode(MODE_ROTATE)) {
  1212. const deltaX = touch0.pageX - lastTouches[0][0];
  1213. const deltaY = touch0.pageY - lastTouches[0][1];
  1214. const rotateX = deltaX * touchRotateRate;
  1215. const rotateY = deltaY * touchRotateRate;
  1216. rotateVx = rotateY;
  1217. rotateVy = -rotateX;
  1218. }
  1219.  
  1220. } else if (numTouches === 2) {
  1221.  
  1222. var touch0 = touches[0];
  1223. const touch1 = touches[1];
  1224.  
  1225. math.subVec2([touch0.pageX, touch0.pageY], lastTouches[0], touch0Vec);
  1226. math.subVec2([touch1.pageX, touch1.pageY], lastTouches[1], touch1Vec);
  1227.  
  1228. const panning = math.dotVec2(touch0Vec, touch1Vec) > 0;
  1229.  
  1230. if (panning && checkMode(MODE_PAN)) {
  1231. math.subVec2([touch0.pageX, touch0.pageY], lastTouches[0], touch0Vec);
  1232. panVx = touch0Vec[0] * touchPanRate;
  1233. panVy = touch0Vec[1] * touchPanRate;
  1234. }
  1235.  
  1236. if (!panning && checkMode(MODE_ZOOM)) {
  1237. const d1 = math.distVec2([touch0.pageX, touch0.pageY], [touch1.pageX, touch1.pageY]);
  1238. const d2 = math.distVec2(lastTouches[0], lastTouches[1]);
  1239. vZoom = (d2 - d1) * getZoomRate() * touchZoomRate;
  1240. }
  1241. }
  1242.  
  1243. for (let i = 0; i < numTouches; ++i) {
  1244. lastTouches[i][0] = touches[i].pageX;
  1245. lastTouches[i][1] = touches[i].pageY;
  1246. }
  1247.  
  1248. event.stopPropagation();
  1249. }, {passive: true});
  1250.  
  1251. })();
  1252.  
  1253. // Keyboard rotation
  1254.  
  1255. (function () {
  1256.  
  1257. scene.on("tick", function (e) {
  1258. if (!self._active) {
  1259. return;
  1260. }
  1261. if (!over) {
  1262. return;
  1263. }
  1264. const elapsed = e.deltaTime;
  1265. const left = input.keyDown[input.KEY_LEFT_ARROW];
  1266. const right = input.keyDown[input.KEY_RIGHT_ARROW];
  1267. const up = input.keyDown[input.KEY_UP_ARROW];
  1268. const down = input.keyDown[input.KEY_DOWN_ARROW];
  1269. if (left || right || up || down) {
  1270. if (right) {
  1271. rotateVy += -elapsed * keyboardOrbitRate;
  1272.  
  1273. } else if (left) {
  1274. rotateVy += elapsed * keyboardOrbitRate;
  1275. }
  1276. if (down) {
  1277. rotateVx += elapsed * keyboardOrbitRate;
  1278.  
  1279. } else if (up) {
  1280. rotateVx += -elapsed * keyboardOrbitRate;
  1281. }
  1282. }
  1283. });
  1284. })();
  1285.  
  1286. // First-person rotation about vertical axis with A and E keys for AZERTY layout
  1287.  
  1288. (function () {
  1289.  
  1290. scene.on("tick", function (e) {
  1291. if (!self._active) {
  1292. return;
  1293. }
  1294. if (!over) {
  1295. return;
  1296. }
  1297. const elapsed = e.deltaTime;
  1298. let rotateLeft;
  1299. let rotateRight;
  1300. if (self._keyboardLayout == 'azerty') {
  1301. rotateLeft = input.keyDown[input.KEY_A];
  1302. rotateRight = input.keyDown[input.KEY_E];
  1303. } else {
  1304. rotateLeft = input.keyDown[input.KEY_Q];
  1305. rotateRight = input.keyDown[input.KEY_E];
  1306. }
  1307. if (rotateRight || rotateLeft) {
  1308. if (rotateLeft) {
  1309. rotateVy += elapsed * keyboardOrbitRate;
  1310. } else if (rotateRight) {
  1311. rotateVy += -elapsed * keyboardOrbitRate;
  1312. }
  1313. }
  1314. });
  1315.  
  1316. })();
  1317. })();
  1318.  
  1319. //------------------------------------------------------------------------------------
  1320. // Mouse and touch picking
  1321. //------------------------------------------------------------------------------------
  1322.  
  1323. (function () {
  1324.  
  1325. // Mouse picking
  1326.  
  1327. (function () {
  1328.  
  1329. canvas.addEventListener("mousemove", function (e) {
  1330.  
  1331. if (!self._active) {
  1332. return;
  1333. }
  1334.  
  1335. getCanvasPosFromEvent(e, pickCursorPos);
  1336.  
  1337. if (self.hasSubs("hover") || self.hasSubs("hoverOut") || self.hasSubs("hoverOff") || self.hasSubs("hoverSurface")) {
  1338. needPickMesh = true;
  1339. }
  1340. });
  1341.  
  1342. let downX;
  1343. let downY;
  1344. let downCursorX;
  1345. let downCursorY;
  1346.  
  1347. canvas.addEventListener('mousedown', function (e) {
  1348. if (!self._active) {
  1349. return;
  1350. }
  1351. downX = e.clientX;
  1352. downY = e.clientY;
  1353. downCursorX = pickCursorPos[0];
  1354. downCursorY = pickCursorPos[1];
  1355.  
  1356. needPickSurface = self._pivoting;
  1357. updatePick();
  1358. if (self._pivoting) {
  1359. if (hit) {
  1360. self._pivoter.startPivot(hit.worldPos);
  1361. } else {
  1362. self._pivoter.startPivot(); // Continue to use last pivot point
  1363. }
  1364. }
  1365. });
  1366.  
  1367. canvas.addEventListener('mouseup', (function (e) {
  1368.  
  1369. let clicks = 0;
  1370. let timeout;
  1371.  
  1372. return function (e) {
  1373.  
  1374. if (!self._active) {
  1375. return;
  1376. }
  1377.  
  1378. self._pivoter.endPivot();
  1379.  
  1380. if (Math.abs(e.clientX - downX) > 3 || Math.abs(e.clientY - downY) > 3) {
  1381. return;
  1382. }
  1383.  
  1384. if (!self._doublePickFlyTo && !self.hasSubs("doublePicked") && !self.hasSubs("doublePickedSurface") && !self.hasSubs("doublePickedNothing")) {
  1385.  
  1386. // Avoid the single/double click differentiation timeout
  1387.  
  1388. needPickSurface = !!self.hasSubs("pickedSurface");
  1389.  
  1390. updatePick();
  1391.  
  1392. if (hit) {
  1393.  
  1394. /**
  1395. * Fired whenever the pointer has picked (ie. clicked or tapped) an {{#crossLink "Mesh"}}{{/crossLink}}.
  1396. *
  1397. * @event picked
  1398. * @param hit A surface pick hit result containing the ID of the Mesh - see {{#crossLink "Scene/pick:method"}}Scene#pick(){{/crossLink}}.
  1399. */
  1400. self.fire("picked", hit);
  1401. if (pickedSurface) {
  1402.  
  1403. /**
  1404. * Fired when the pointer has picked (ie. clicked or tapped) the surface of an {{#crossLink "Mesh"}}{{/crossLink}}.
  1405. *
  1406. * This event provides 3D information about the point on the surface that the pointer has picked.
  1407. *
  1408. * @event pickedSurface
  1409. * @param hit A surface pick hit result, containing the ID of the Mesh and 3D info on the
  1410. * surface possition - see {{#crossLink "Scene/pick:method"}}Scene#pick(){{/crossLink}}.
  1411. */
  1412. self.fire("pickedSurface", hit);
  1413. }
  1414. } else {
  1415.  
  1416. /**
  1417. * Fired when the pointer attempted a pick (ie. clicked or tapped), but has hit nothing.
  1418. *
  1419. * @event pickedNothing
  1420. */
  1421. self.fire("pickedNothing");
  1422. }
  1423.  
  1424. return;
  1425. }
  1426.  
  1427. clicks++;
  1428.  
  1429. if (clicks == 1) {
  1430. timeout = setTimeout(function () {
  1431.  
  1432. needPickMesh = self._doublePickFlyTo;
  1433. needPickSurface = needPickMesh || !!self.hasSubs("pickedSurface");
  1434. pickCursorPos[0] = downCursorX;
  1435. pickCursorPos[1] = downCursorY;
  1436.  
  1437. updatePick();
  1438.  
  1439. if (hit) {
  1440. self.fire("picked", hit);
  1441. if (pickedSurface) {
  1442. self.fire("pickedSurface", hit);
  1443. }
  1444. } else {
  1445. self.fire("pickedNothing");
  1446. }
  1447.  
  1448. clicks = 0;
  1449. }, 250); // FIXME: Too short for track pads
  1450.  
  1451. } else {
  1452.  
  1453. clearTimeout(timeout);
  1454.  
  1455. needPickMesh = self._doublePickFlyTo;
  1456. needPickSurface = needPickMesh && !!self.hasSubs("doublePickedSurface");
  1457.  
  1458. updatePick();
  1459.  
  1460. if (hit) {
  1461. /**
  1462. * Fired whenever the pointer has double-picked (ie. double-clicked or double-tapped) an {{#crossLink "Mesh"}}{{/crossLink}}.
  1463. *
  1464. * @event picked
  1465. * @param hit A surface pick hit result containing the ID of the Mesh - see {{#crossLink "Scene/pick:method"}}Scene#pick(){{/crossLink}}.
  1466. */
  1467. self.fire("doublePicked", hit);
  1468. if (pickedSurface) {
  1469. /**
  1470. * Fired when the pointer has double-picked (ie. double-clicked or double-tapped) the surface of an {{#crossLink "Mesh"}}{{/crossLink}}.
  1471. *
  1472. * This event provides 3D information about the point on the surface that the pointer has picked.
  1473. *
  1474. * @event doublePickedSurface
  1475. * @param hit A surface pick hit result, containing the ID of the Mesh and 3D info on the
  1476. * surface possition - see {{#crossLink "Scene/pick:method"}}Scene#pick(){{/crossLink}}.
  1477. */
  1478. self.fire("doublePickedSurface", hit);
  1479. }
  1480. if (self._doublePickFlyTo) {
  1481. self._flyTo(hit);
  1482. }
  1483. } else {
  1484.  
  1485. /**
  1486. * Fired when the pointer attempted a double-pick (ie. double-clicked or double-tapped), but has hit nothing.
  1487. *
  1488. * @event doublePickedNothing
  1489. */
  1490. self.fire("doublePickedNothing");
  1491. if (self._doublePickFlyTo) {
  1492. self._flyTo();
  1493. }
  1494. }
  1495. clicks = 0;
  1496. }
  1497. };
  1498. })(), false);
  1499.  
  1500. })();
  1501.  
  1502. // Touch picking
  1503.  
  1504. (function () {
  1505.  
  1506. const TAP_INTERVAL = 150;
  1507. const DBL_TAP_INTERVAL = 325;
  1508. const TAP_DISTANCE_THRESHOLD = 4;
  1509.  
  1510. let touchStartTime;
  1511. const activeTouches = [];
  1512. const tapStartPos = new Float32Array(2);
  1513. let tapStartTime = -1;
  1514. let lastTapTime = -1;
  1515.  
  1516. canvas.addEventListener("touchstart", function (event) {
  1517.  
  1518. if (!self._active) {
  1519. return;
  1520. }
  1521.  
  1522. const touches = event.touches;
  1523. const changedTouches = event.changedTouches;
  1524.  
  1525. touchStartTime = Date.now();
  1526.  
  1527. if (touches.length === 1 && changedTouches.length === 1) {
  1528. tapStartTime = touchStartTime;
  1529. tapStartPos[0] = touches[0].pageX;
  1530. tapStartPos[1] = touches[0].pageY;
  1531. } else {
  1532. tapStartTime = -1;
  1533. }
  1534.  
  1535. while (activeTouches.length < touches.length) {
  1536. activeTouches.push(new Float32Array(2))
  1537. }
  1538.  
  1539. for (let i = 0, len = touches.length; i < len; ++i) {
  1540. activeTouches[i][0] = touches[i].pageX;
  1541. activeTouches[i][1] = touches[i].pageY;
  1542. }
  1543.  
  1544. activeTouches.length = touches.length;
  1545.  
  1546. event.stopPropagation();
  1547. }, {passive: true});
  1548.  
  1549. //canvas.addEventListener("touchmove", function (event) {
  1550. // event.preventDefault();
  1551. // event.stopPropagation();
  1552. //});
  1553.  
  1554. canvas.addEventListener("touchend", function (event) {
  1555.  
  1556. if (!self._active) {
  1557. return;
  1558. }
  1559.  
  1560. const currentTime = Date.now();
  1561. const touches = event.touches;
  1562. const changedTouches = event.changedTouches;
  1563.  
  1564. // process tap
  1565.  
  1566. if (touches.length === 0 && changedTouches.length === 1) {
  1567.  
  1568. if (tapStartTime > -1 && currentTime - tapStartTime < TAP_INTERVAL) {
  1569.  
  1570. if (lastTapTime > -1 && tapStartTime - lastTapTime < DBL_TAP_INTERVAL) {
  1571.  
  1572. // Double-tap
  1573.  
  1574. pickCursorPos[0] = Math.round(changedTouches[0].clientX);
  1575. pickCursorPos[1] = Math.round(changedTouches[0].clientY);
  1576. needPickMesh = true;
  1577. needPickSurface = !!self.hasSubs("pickedSurface");
  1578.  
  1579. updatePick();
  1580.  
  1581. if (hit) {
  1582. self.fire("doublePicked", hit);
  1583. if (pickedSurface) {
  1584. self.fire("doublePickedSurface", hit);
  1585. }
  1586. if (self._doublePickFlyTo) {
  1587. self._flyTo(hit);
  1588. }
  1589. } else {
  1590. self.fire("doublePickedNothing");
  1591. if (self._doublePickFlyTo) {
  1592. self._flyTo();
  1593. }
  1594. }
  1595.  
  1596. lastTapTime = -1;
  1597.  
  1598. } else if (math.distVec2(activeTouches[0], tapStartPos) < TAP_DISTANCE_THRESHOLD) {
  1599.  
  1600. // Single-tap
  1601.  
  1602. pickCursorPos[0] = Math.round(changedTouches[0].clientX);
  1603. pickCursorPos[1] = Math.round(changedTouches[0].clientY);
  1604. needPickMesh = true;
  1605. needPickSurface = !!self.hasSubs("pickedSurface");
  1606.  
  1607. updatePick();
  1608.  
  1609. if (hit) {
  1610. self.fire("picked", hit);
  1611. if (pickedSurface) {
  1612. self.fire("pickedSurface", hit);
  1613. }
  1614. } else {
  1615. self.fire("pickedNothing");
  1616. }
  1617.  
  1618. lastTapTime = currentTime;
  1619. }
  1620.  
  1621. tapStartTime = -1
  1622. }
  1623. }
  1624.  
  1625. activeTouches.length = touches.length;
  1626.  
  1627. for (let i = 0, len = touches.length; i < len; ++i) {
  1628. activeTouches[i][0] = touches[i].pageX;
  1629. activeTouches[i][1] = touches[i].pageY;
  1630. }
  1631.  
  1632. event.stopPropagation();
  1633. }, {passive: true});
  1634. })();
  1635. })();
  1636.  
  1637. //------------------------------------------------------------------------------------
  1638. // Keyboard camera axis views
  1639. //------------------------------------------------------------------------------------
  1640.  
  1641. (function () {
  1642.  
  1643. const KEY_NUM_1 = 49;
  1644. const KEY_NUM_2 = 50;
  1645. const KEY_NUM_3 = 51;
  1646. const KEY_NUM_4 = 52;
  1647. const KEY_NUM_5 = 53;
  1648. const KEY_NUM_6 = 54;
  1649.  
  1650. const center = math.vec3();
  1651. const tempVec3a = math.vec3();
  1652. const tempVec3b = math.vec3();
  1653. const tempVec3c = math.vec3();
  1654.  
  1655. const cameraTarget = {
  1656. eye: new Float32Array(3),
  1657. look: new Float32Array(3),
  1658. up: new Float32Array(3)
  1659. };
  1660.  
  1661. document.addEventListener("keydown", function (e) {
  1662.  
  1663. if (!self._active) {
  1664. return;
  1665. }
  1666.  
  1667. if (!over) {
  1668. return;
  1669. }
  1670.  
  1671. const keyCode = e.keyCode;
  1672.  
  1673. if (keyCode !== KEY_NUM_1 &&
  1674. keyCode !== KEY_NUM_2 &&
  1675. keyCode !== KEY_NUM_3 &&
  1676. keyCode !== KEY_NUM_4 &&
  1677. keyCode !== KEY_NUM_5 &&
  1678. keyCode !== KEY_NUM_6) {
  1679. return;
  1680. }
  1681.  
  1682. const aabb = scene.aabb;
  1683. const diag = math.getAABB3Diag(aabb);
  1684. center[0] = aabb[0] + aabb[3] / 2.0;
  1685. center[1] = aabb[1] + aabb[4] / 2.0;
  1686. center[2] = aabb[2] + aabb[5] / 2.0;
  1687. const dist = Math.abs((diag) / Math.tan(self._cameraFlight.fitFOV / 2));
  1688.  
  1689. switch (keyCode) {
  1690.  
  1691. case KEY_NUM_1: // Right
  1692.  
  1693. cameraTarget.eye.set(math.mulVec3Scalar(camera.worldRight, dist, tempVec3a));
  1694. cameraTarget.look.set(center);
  1695. cameraTarget.up.set(camera.worldUp);
  1696.  
  1697. break;
  1698.  
  1699. case KEY_NUM_2: // Back
  1700.  
  1701. cameraTarget.eye.set(math.mulVec3Scalar(camera.worldForward, dist, tempVec3a));
  1702. cameraTarget.look.set(center);
  1703. cameraTarget.up.set(camera.worldUp);
  1704.  
  1705. break;
  1706.  
  1707. case KEY_NUM_3: // Left
  1708.  
  1709. cameraTarget.eye.set(math.mulVec3Scalar(camera.worldRight, -dist, tempVec3a));
  1710. cameraTarget.look.set(center);
  1711. cameraTarget.up.set(camera.worldUp);
  1712.  
  1713. break;
  1714.  
  1715. case KEY_NUM_4: // Front
  1716.  
  1717. cameraTarget.eye.set(math.mulVec3Scalar(camera.worldForward, -dist, tempVec3a));
  1718. cameraTarget.look.set(center);
  1719. cameraTarget.up.set(camera.worldUp);
  1720.  
  1721. break;
  1722.  
  1723. case KEY_NUM_5: // Top
  1724.  
  1725. cameraTarget.eye.set(math.mulVec3Scalar(camera.worldUp, dist, tempVec3a));
  1726. cameraTarget.look.set(center);
  1727. cameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(camera.worldForward, 1, tempVec3b), tempVec3c));
  1728.  
  1729. break;
  1730.  
  1731. case KEY_NUM_6: // Bottom
  1732.  
  1733. cameraTarget.eye.set(math.mulVec3Scalar(camera.worldUp, -dist, tempVec3a));
  1734. cameraTarget.look.set(center);
  1735. cameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(camera.worldForward, -1, tempVec3b)));
  1736.  
  1737. break;
  1738.  
  1739. default:
  1740. return;
  1741. }
  1742.  
  1743. if (self._cameraFlight.duration > 0) {
  1744. self._cameraFlight.flyTo(cameraTarget);
  1745. } else {
  1746. self._cameraFlight.jumpTo(cameraTarget);
  1747. }
  1748. });
  1749.  
  1750. })();
  1751. }
  1752.  
  1753. _flyTo(hit) {
  1754.  
  1755. let pos;
  1756.  
  1757. if (hit && hit.worldPos) {
  1758. pos = hit.worldPos
  1759. }
  1760.  
  1761. const aabb = hit ? hit.mesh.aabb : this.scene.aabb;
  1762.  
  1763. this._boundaryHelper.geometry.targetAABB = aabb;
  1764. // this._boundaryHelper.visible = true;
  1765.  
  1766. if (pos) {
  1767.  
  1768. // Fly to look at point, don't change eye->look dist
  1769.  
  1770. const camera = this.scene.camera;
  1771. const diff = math.subVec3(camera.eye, camera.look, []);
  1772.  
  1773. this._cameraFlight.flyTo({
  1774. // look: pos,
  1775. // eye: xeogl.math.addVec3(pos, diff, []),
  1776. // up: camera.up,
  1777. aabb: aabb
  1778. },
  1779. this._hideBoundary, this);
  1780.  
  1781. // TODO: Option to back off to fit AABB in view
  1782.  
  1783. } else {
  1784.  
  1785. // Fly to fit target boundary in view
  1786.  
  1787. this._cameraFlight.flyTo({
  1788. aabb: aabb
  1789. },
  1790. this._hideBoundary, this);
  1791. }
  1792. }
  1793.  
  1794. _hideBoundary() {
  1795. // this._boundaryHelper.visible = false;
  1796. }
  1797.  
  1798. destroy() {
  1799. this.active = false;
  1800. super.destroy();
  1801. }
  1802. }
  1803.  
  1804. componentClasses[type] = CameraControl;
  1805.  
  1806. export {CameraControl};
  1807.