babylon.webVRCamera.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. declare var HMDVRDevice: any;
  2. declare var VRDisplay: any;
  3. declare var VRFrameData: any;
  4. module BABYLON {
  5. /**
  6. * This is a copy of VRPose.
  7. * IMPORTANT!! The data is right-hand data.
  8. * @export
  9. * @interface DevicePose
  10. */
  11. export interface DevicePose {
  12. readonly position?: Float32Array;
  13. readonly linearVelocity?: Float32Array;
  14. readonly linearAcceleration?: Float32Array;
  15. readonly orientation?: Float32Array;
  16. readonly angularVelocity?: Float32Array;
  17. readonly angularAcceleration?: Float32Array;
  18. }
  19. export interface PoseControlled {
  20. position: Vector3;
  21. rotationQuaternion: Quaternion;
  22. devicePosition?: Vector3;
  23. deviceRotationQuaternion: Quaternion;
  24. rawPose: Nullable<DevicePose>;
  25. deviceScaleFactor: number;
  26. updateFromDevice(poseData: DevicePose): void;
  27. }
  28. export interface WebVROptions {
  29. trackPosition?: boolean; //for the sake of your users - set it to true.
  30. positionScale?: number;
  31. displayName?: string; //if there are more than one VRDisplays.
  32. controllerMeshes?: boolean; // should the native controller meshes be initialized
  33. defaultLightingOnControllers?: boolean; // creating a default HemiLight only on controllers
  34. useCustomVRButton?: boolean; // if you don't want to use the default VR button of the helper
  35. customVRButton?: HTMLButtonElement; //if you'd like to provide your own button to the VRHelper
  36. rayLength?: number; // to change the length of the ray for gaze/controllers.
  37. defaultHeight?: number; // to change the default offset from the ground to account for user's height
  38. }
  39. export class WebVRFreeCamera extends FreeCamera implements PoseControlled {
  40. public _vrDevice: any = null;
  41. public rawPose: Nullable<DevicePose> = null;
  42. private _onVREnabled: (success: boolean) => void;
  43. private _specsVersion: string = "1.1";
  44. private _attached: boolean = false;
  45. private _frameData: any;
  46. protected _descendants: Array<Node> = [];
  47. public devicePosition = Vector3.Zero();
  48. public deviceRotationQuaternion: Quaternion;
  49. public deviceScaleFactor: number = 1;
  50. public controllers: Array<WebVRController> = [];
  51. public onControllersAttachedObservable = new Observable<Array<WebVRController>>();
  52. public onControllerMeshLoadedObservable = new Observable<WebVRController>();
  53. public rigParenting: boolean = true; // should the rig cameras be used as parent instead of this camera.
  54. private _lightOnControllers: BABYLON.HemisphericLight;
  55. constructor(name: string, position: Vector3, scene: Scene, private webVROptions: WebVROptions = {}) {
  56. super(name, position, scene);
  57. if(webVROptions.defaultHeight){
  58. this.position.y = webVROptions.defaultHeight;
  59. }
  60. this.minZ = 0.1;
  61. //legacy support - the compensation boolean was removed.
  62. if (arguments.length === 5) {
  63. this.webVROptions = arguments[4];
  64. }
  65. // default webVR options
  66. if (this.webVROptions.trackPosition == undefined) {
  67. this.webVROptions.trackPosition = true;
  68. }
  69. if (this.webVROptions.controllerMeshes == undefined) {
  70. this.webVROptions.controllerMeshes = true;
  71. }
  72. if (this.webVROptions.defaultLightingOnControllers == undefined) {
  73. this.webVROptions.defaultLightingOnControllers = true;
  74. }
  75. this.rotationQuaternion = new Quaternion();
  76. this.deviceRotationQuaternion = new Quaternion();
  77. if (this.webVROptions && this.webVROptions.positionScale) {
  78. this.deviceScaleFactor = this.webVROptions.positionScale;
  79. }
  80. //enable VR
  81. var engine = this.getEngine();
  82. this._onVREnabled = (success: boolean) => { if (success) { this.initControllers(); } };
  83. engine.onVRRequestPresentComplete.add(this._onVREnabled);
  84. engine.initWebVR().add((event: IDisplayChangedEventArgs) => {
  85. if (!event.vrDisplay || this._vrDevice === event.vrDisplay) {
  86. return;
  87. }
  88. this._vrDevice = event.vrDisplay;
  89. //reset the rig parameters.
  90. this.setCameraRigMode(Camera.RIG_MODE_WEBVR, { parentCamera: this, vrDisplay: this._vrDevice, frameData: this._frameData, specs: this._specsVersion });
  91. if (this._attached) {
  92. this.getEngine().enableVR();
  93. }
  94. });
  95. if (typeof(VRFrameData) !== "undefined")
  96. this._frameData = new VRFrameData();
  97. /**
  98. * The idea behind the following lines:
  99. * objects that have the camera as parent should actually have the rig cameras as a parent.
  100. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  101. * the second will not show it correctly.
  102. *
  103. * To solve this - each object that has the camera as parent will be added to a protected array.
  104. * When the rig camera renders, it will take this array and set all of those to be its children.
  105. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  106. * Amazing!
  107. */
  108. scene.onBeforeCameraRenderObservable.add((camera) => {
  109. if (camera.parent === this && this.rigParenting) {
  110. this._descendants = this.getDescendants(true, (n) => {
  111. // don't take the cameras or the controllers!
  112. let isController = this.controllers.some(controller => { return controller._mesh === n });
  113. let isRigCamera = this._rigCameras.indexOf(<Camera>n) !== -1
  114. return !isController && !isRigCamera;
  115. });
  116. this._descendants.forEach(node => {
  117. node.parent = camera;
  118. });
  119. }
  120. });
  121. scene.onAfterCameraRenderObservable.add((camera) => {
  122. if (camera.parent === this && this.rigParenting) {
  123. this._descendants.forEach(node => {
  124. node.parent = this;
  125. });
  126. }
  127. });
  128. }
  129. public dispose(): void {
  130. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  131. super.dispose();
  132. }
  133. public getControllerByName(name: string): Nullable<WebVRController> {
  134. for (var gp of this.controllers) {
  135. if (gp.hand === name) {
  136. return gp;
  137. }
  138. }
  139. return null;
  140. }
  141. private _leftController: Nullable<WebVRController>;
  142. public get leftController(): Nullable<WebVRController> {
  143. if (!this._leftController) {
  144. this._leftController = this.getControllerByName("left");
  145. }
  146. return this._leftController;
  147. };
  148. private _rightController: Nullable<WebVRController>;
  149. public get rightController(): Nullable<WebVRController> {
  150. if (!this._rightController) {
  151. this._rightController = this.getControllerByName("right");
  152. }
  153. return this._rightController;
  154. };
  155. public getForwardRay(length = 100): Ray {
  156. if (this.leftCamera) {
  157. // Use left eye to avoid computation to compute center on every call
  158. return super.getForwardRay(length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  159. }
  160. else {
  161. return super.getForwardRay(length);
  162. }
  163. }
  164. public _checkInputs(): void {
  165. if (this._vrDevice && this._vrDevice.isPresenting) {
  166. this._vrDevice.getFrameData(this._frameData);
  167. this.updateFromDevice(this._frameData.pose);
  168. }
  169. super._checkInputs();
  170. }
  171. updateFromDevice(poseData: DevicePose) {
  172. if (poseData && poseData.orientation) {
  173. this.rawPose = poseData;
  174. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  175. if (this.getScene().useRightHandedSystem) {
  176. this.deviceRotationQuaternion.z *= -1;
  177. this.deviceRotationQuaternion.w *= -1;
  178. }
  179. if (this.webVROptions.trackPosition && this.rawPose.position) {
  180. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  181. if (this.getScene().useRightHandedSystem) {
  182. this.devicePosition.z *= -1;
  183. }
  184. }
  185. }
  186. }
  187. /**
  188. * WebVR's attach control will start broadcasting frames to the device.
  189. * Note that in certain browsers (chrome for example) this function must be called
  190. * within a user-interaction callback. Example:
  191. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  192. *
  193. * @param {HTMLElement} element
  194. * @param {boolean} [noPreventDefault]
  195. *
  196. * @memberOf WebVRFreeCamera
  197. */
  198. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  199. super.attachControl(element, noPreventDefault);
  200. this._attached = true;
  201. noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  202. if (this._vrDevice) {
  203. this.getEngine().enableVR();
  204. }
  205. }
  206. public detachControl(element: HTMLElement): void {
  207. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  208. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  209. super.detachControl(element);
  210. this._attached = false;
  211. this.getEngine().disableVR();
  212. }
  213. public getClassName(): string {
  214. return "WebVRFreeCamera";
  215. }
  216. public resetToCurrentRotation() {
  217. //uses the vrDisplay's "resetPose()".
  218. //pitch and roll won't be affected.
  219. this._vrDevice.resetPose();
  220. }
  221. public _updateRigCameras() {
  222. var camLeft = <TargetCamera>this._rigCameras[0];
  223. var camRight = <TargetCamera>this._rigCameras[1];
  224. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  225. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  226. camLeft.position.copyFrom(this.devicePosition);
  227. camRight.position.copyFrom(this.devicePosition);
  228. }
  229. /**
  230. * This function is called by the two RIG cameras.
  231. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  232. */
  233. protected _getWebVRViewMatrix(): Matrix {
  234. //WebVR 1.1
  235. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  236. Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  237. if (!this.getScene().useRightHandedSystem) {
  238. [2, 6, 8, 9, 14].forEach((num) => {
  239. this._webvrViewMatrix.m[num] *= -1;
  240. });
  241. }
  242. // update the camera rotation matrix
  243. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  244. Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  245. // Computing target and final matrix
  246. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  247. let parentCamera: WebVRFreeCamera = this._cameraRigParams["parentCamera"];
  248. // should the view matrix be updated with scale and position offset?
  249. if (parentCamera.deviceScaleFactor !== 1) {
  250. this._webvrViewMatrix.invert();
  251. // scale the position, if set
  252. if (parentCamera.deviceScaleFactor) {
  253. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  254. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  255. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  256. }
  257. this._webvrViewMatrix.invert();
  258. }
  259. return this._webvrViewMatrix;
  260. }
  261. protected _getWebVRProjectionMatrix(): Matrix {
  262. let parentCamera = <WebVRFreeCamera>this.parent;
  263. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  264. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  265. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  266. Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  267. //babylon compatible matrix
  268. if (!this.getScene().useRightHandedSystem) {
  269. [8, 9, 10, 11].forEach((num) => {
  270. this._projectionMatrix.m[num] *= -1;
  271. });
  272. }
  273. return this._projectionMatrix;
  274. }
  275. private _onGamepadConnectedObserver: Nullable<Observer<Gamepad>>;
  276. private _onGamepadDisconnectedObserver: Nullable<Observer<Gamepad>>;
  277. public initControllers() {
  278. this.controllers = [];
  279. let manager = this.getScene().gamepadManager;
  280. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {
  281. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  282. let webVrController: WebVRController = <WebVRController>gamepad;
  283. if (webVrController.defaultModel) {
  284. webVrController.defaultModel.setEnabled(false);
  285. }
  286. if(webVrController.hand === "right"){
  287. this._rightController = null;
  288. }
  289. if(webVrController.hand === "left"){
  290. this._rightController = null;
  291. }
  292. const controllerIndex = this.controllers.indexOf(webVrController);
  293. if (controllerIndex !== -1) {
  294. this.controllers.splice(controllerIndex, 1);
  295. }
  296. }
  297. });
  298. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {
  299. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  300. let webVrController: WebVRController = <WebVRController>gamepad;
  301. if (this.webVROptions.controllerMeshes) {
  302. if (webVrController.defaultModel) {
  303. webVrController.defaultModel.setEnabled(true);
  304. } else {
  305. // Load the meshes
  306. webVrController.initControllerMesh(this.getScene(), (loadedMesh) => {
  307. this.onControllerMeshLoadedObservable.notifyObservers(webVrController);
  308. if (this.webVROptions.defaultLightingOnControllers) {
  309. if (!this._lightOnControllers) {
  310. this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), this.getScene());
  311. }
  312. let activateLightOnSubMeshes = function (mesh: AbstractMesh, light: HemisphericLight) {
  313. let children = mesh.getChildren();
  314. if (children.length !== 0) {
  315. children.forEach((mesh) => {
  316. light.includedOnlyMeshes.push(<AbstractMesh>mesh);
  317. activateLightOnSubMeshes(<AbstractMesh>mesh, light);
  318. });
  319. }
  320. }
  321. this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  322. activateLightOnSubMeshes(loadedMesh, this._lightOnControllers);
  323. }
  324. });
  325. }
  326. }
  327. webVrController.attachToPoseControlledCamera(this);
  328. // since this is async - sanity check. Is the controller already stored?
  329. if (this.controllers.indexOf(webVrController) === -1) {
  330. //add to the controllers array
  331. this.controllers.push(webVrController);
  332. //did we find enough controllers? Great! let the developer know.
  333. if (this.controllers.length >= 2) {
  334. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  335. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  336. // So we're overriding setting left & right manually to be sure
  337. let firstViveWandDetected = false;
  338. for (let i = 0; i < this.controllers.length; i++) {
  339. if (this.controllers[i].controllerType === PoseEnabledControllerType.VIVE) {
  340. if (!firstViveWandDetected) {
  341. firstViveWandDetected = true;
  342. this.controllers[i].hand = "left";
  343. }
  344. else {
  345. this.controllers[i].hand = "right";
  346. }
  347. }
  348. }
  349. this.onControllersAttachedObservable.notifyObservers(this.controllers);
  350. }
  351. }
  352. }
  353. });
  354. }
  355. }
  356. }