VRControls.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @author dmarcos / https://github.com/dmarcos
  3. */
  4. THREE.VRControls = function ( camera, done ) {
  5. this._camera = camera;
  6. this._vrState = {
  7. hmd : {
  8. orientation: new THREE.Quaternion()
  9. }
  10. };
  11. this._init = function () {
  12. var self = this;
  13. if ( !navigator.mozGetVRDevices && !navigator.getVRDevices ) {
  14. if ( done ) {
  15. done("Your browser is not VR Ready");
  16. }
  17. return;
  18. }
  19. if ( navigator.getVRDevices ) {
  20. navigator.getVRDevices().then( gotVRDevices );
  21. } else {
  22. navigator.mozGetVRDevices( gotVRDevices );
  23. }
  24. function gotVRDevices( devices ) {
  25. var vrInput;
  26. var error;
  27. for ( var i = 0; i < devices.length; ++i ) {
  28. if ( devices[i] instanceof PositionSensorVRDevice ) {
  29. vrInput = devices[i]
  30. self._vrInput = vrInput;
  31. break; // We keep the first we encounter
  32. }
  33. }
  34. if ( done ) {
  35. if ( !vrInput ) {
  36. error = 'HMD not available';
  37. }
  38. done( error );
  39. }
  40. }
  41. };
  42. this._init();
  43. this.update = function() {
  44. var camera = this._camera;
  45. var quat;
  46. var vrState = this.getVRState();
  47. if ( !vrState ) {
  48. return;
  49. }
  50. // Applies head rotation from sensors data.
  51. if ( camera ) {
  52. camera.quaternion.copy( vrState.hmd.orientation );
  53. }
  54. };
  55. this.getVRState = function() {
  56. var vrInput = this._vrInput;
  57. var vrState = this._vrState;
  58. var orientation;
  59. if ( !vrInput ) {
  60. return null;
  61. }
  62. // If orientation is not available we return the identity quaternion (no rotation)
  63. orientation = vrInput.getState().orientation || { x: 0, y: 0, z:0, w:1 };
  64. vrState.hmd.orientation.set( orientation.x, orientation.y, orientation.z, orientation.w );
  65. return vrState;
  66. };
  67. };