DeviceOrientationControls.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @author chrisl / Geodan
  3. *
  4. * adapted from Potree.FirstPersonControls by
  5. *
  6. * @author mschuetz / http://mschuetz.at
  7. *
  8. * and THREE.DeviceOrientationControls by
  9. *
  10. * @author richt / http://richt.me
  11. * @author WestLangley / http://github.com/WestLangley
  12. *
  13. *
  14. *
  15. */
  16. import * as THREE from "../../libs/three.js/build/three.module.js";
  17. import {EventDispatcher} from "../EventDispatcher.js";
  18. export class DeviceOrientationControls extends EventDispatcher{
  19. constructor(viewer){
  20. super();
  21. this.viewer = viewer;
  22. this.renderer = viewer.renderer;
  23. this.scene = null;
  24. this.sceneControls = new THREE.Scene();
  25. this.screenOrientation = window.orientation || 0;
  26. let deviceOrientationChange = e => {
  27. this.deviceOrientation = e;
  28. };
  29. let screenOrientationChange = e => {
  30. this.screenOrientation = window.orientation || 0;
  31. };
  32. if ('ondeviceorientationabsolute' in window) {
  33. window.addEventListener('deviceorientationabsolute', deviceOrientationChange);
  34. } else if ('ondeviceorientation' in window) {
  35. window.addEventListener('deviceorientation', deviceOrientationChange);
  36. } else {
  37. console.warn("No device orientation found.");
  38. }
  39. // window.addEventListener('deviceorientation', deviceOrientationChange);
  40. window.addEventListener('orientationchange', screenOrientationChange);
  41. }
  42. setScene (scene) {
  43. this.scene = scene;
  44. }
  45. update (delta) {
  46. let computeQuaternion = function (alpha, beta, gamma, orient) {
  47. let quaternion = new THREE.Quaternion();
  48. let zee = new THREE.Vector3(0, 0, 1);
  49. let euler = new THREE.Euler();
  50. let q0 = new THREE.Quaternion();
  51. euler.set(beta, gamma, alpha, 'ZXY');
  52. quaternion.setFromEuler(euler);
  53. quaternion.multiply(q0.setFromAxisAngle(zee, -orient));
  54. return quaternion;
  55. };
  56. if (typeof this.deviceOrientation !== 'undefined') {
  57. let alpha = this.deviceOrientation.alpha ? THREE.Math.degToRad(this.deviceOrientation.alpha) : 0;
  58. let beta = this.deviceOrientation.beta ? THREE.Math.degToRad(this.deviceOrientation.beta) : 0;
  59. let gamma = this.deviceOrientation.gamma ? THREE.Math.degToRad(this.deviceOrientation.gamma) : 0;
  60. let orient = this.screenOrientation ? THREE.Math.degToRad(this.screenOrientation) : 0;
  61. let quaternion = computeQuaternion(alpha, beta, gamma, orient);
  62. viewer.scene.cameraP.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  63. }
  64. }
  65. };