poseEnabledController.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import { Observable } from "../../Misc/observable";
  2. import { Nullable } from "../../types";
  3. import { Quaternion, Matrix, Vector3, Tmp } from "../../Maths/math";
  4. import { Node } from "../../node";
  5. import { TransformNode } from "../../Meshes/transformNode";
  6. import { AbstractMesh } from "../../Meshes/abstractMesh";
  7. import { Ray } from "../../Culling/ray";
  8. import { _TimeToken } from "../../Instrumentation/timeToken";
  9. import { _DepthCullingState, _StencilState, _AlphaState } from "../../States/index";
  10. import { EngineStore } from "../../Engines/engineStore";
  11. import { Gamepad } from "../../Gamepads/gamepad";
  12. import { WebVRFreeCamera, PoseControlled, DevicePose } from "../../Cameras/VR/webVRCamera";
  13. import { TargetCamera } from "../../Cameras/targetCamera";
  14. /**
  15. * Defines the types of pose enabled controllers that are supported
  16. */
  17. export enum PoseEnabledControllerType {
  18. /**
  19. * HTC Vive
  20. */
  21. VIVE,
  22. /**
  23. * Oculus Rift
  24. */
  25. OCULUS,
  26. /**
  27. * Windows mixed reality
  28. */
  29. WINDOWS,
  30. /**
  31. * Samsung gear VR
  32. */
  33. GEAR_VR,
  34. /**
  35. * Google Daydream
  36. */
  37. DAYDREAM,
  38. /**
  39. * Generic
  40. */
  41. GENERIC
  42. }
  43. /**
  44. * Defines the MutableGamepadButton interface for the state of a gamepad button
  45. */
  46. export interface MutableGamepadButton {
  47. /**
  48. * Value of the button/trigger
  49. */
  50. value: number;
  51. /**
  52. * If the button/trigger is currently touched
  53. */
  54. touched: boolean;
  55. /**
  56. * If the button/trigger is currently pressed
  57. */
  58. pressed: boolean;
  59. }
  60. /**
  61. * Defines the ExtendedGamepadButton interface for a gamepad button which includes state provided by a pose controller
  62. * @hidden
  63. */
  64. export interface ExtendedGamepadButton extends GamepadButton {
  65. /**
  66. * If the button/trigger is currently pressed
  67. */
  68. readonly pressed: boolean;
  69. /**
  70. * If the button/trigger is currently touched
  71. */
  72. readonly touched: boolean;
  73. /**
  74. * Value of the button/trigger
  75. */
  76. readonly value: number;
  77. }
  78. /** @hidden */
  79. export interface _GamePadFactory {
  80. /**
  81. * Returns wether or not the current gamepad can be created for this type of controller.
  82. * @param gamepadInfo Defines the gamepad info as receveid from the controller APIs.
  83. * @returns true if it can be created, otherwise false
  84. */
  85. canCreate(gamepadInfo: any): boolean;
  86. /**
  87. * Creates a new instance of the Gamepad.
  88. * @param gamepadInfo Defines the gamepad info as receveid from the controller APIs.
  89. * @returns the new gamepad instance
  90. */
  91. create(gamepadInfo: any): Gamepad;
  92. }
  93. /**
  94. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  95. */
  96. export class PoseEnabledControllerHelper {
  97. /** @hidden */
  98. public static _ControllerFactories: _GamePadFactory[] = [];
  99. /** @hidden */
  100. public static _DefaultControllerFactory: Nullable<(gamepadInfo: any) => Gamepad> = null;
  101. /**
  102. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  103. * @param vrGamepad the gamepad to initialized
  104. * @returns a vr controller of the type the gamepad identified as
  105. */
  106. public static InitiateController(vrGamepad: any) {
  107. for (let factory of this._ControllerFactories) {
  108. if (factory.canCreate(vrGamepad)) {
  109. return factory.create(vrGamepad);
  110. }
  111. }
  112. if (this._DefaultControllerFactory) {
  113. return this._DefaultControllerFactory(vrGamepad);
  114. }
  115. throw "The type of gamepad you are trying to load needs to be imported first or is not supported.";
  116. }
  117. }
  118. /**
  119. * Defines the PoseEnabledController object that contains state of a vr capable controller
  120. */
  121. export class PoseEnabledController extends Gamepad implements PoseControlled {
  122. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  123. private _deviceRoomPosition = Vector3.Zero();
  124. private _deviceRoomRotationQuaternion = new Quaternion();
  125. /**
  126. * The device position in babylon space
  127. */
  128. public devicePosition = Vector3.Zero();
  129. /**
  130. * The device rotation in babylon space
  131. */
  132. public deviceRotationQuaternion = new Quaternion();
  133. /**
  134. * The scale factor of the device in babylon space
  135. */
  136. public deviceScaleFactor: number = 1;
  137. /**
  138. * (Likely devicePosition should be used instead) The device position in its room space
  139. */
  140. public position: Vector3;
  141. /**
  142. * (Likely deviceRotationQuaternion should be used instead) The device rotation in its room space
  143. */
  144. public rotationQuaternion: Quaternion;
  145. /**
  146. * The type of controller (Eg. Windows mixed reality)
  147. */
  148. public controllerType: PoseEnabledControllerType;
  149. protected _calculatedPosition: Vector3;
  150. private _calculatedRotation: Quaternion;
  151. /**
  152. * The raw pose from the device
  153. */
  154. public rawPose: DevicePose; //GamepadPose;
  155. // Used to convert 6dof controllers to 3dof
  156. private _trackPosition = true;
  157. private _maxRotationDistFromHeadset = Math.PI / 5;
  158. private _draggedRoomRotation = 0;
  159. /**
  160. * @hidden
  161. */
  162. public _disableTrackPosition(fixedPosition: Vector3) {
  163. if (this._trackPosition) {
  164. this._calculatedPosition.copyFrom(fixedPosition);
  165. this._trackPosition = false;
  166. }
  167. }
  168. /**
  169. * Internal, the mesh attached to the controller
  170. * @hidden
  171. */
  172. public _mesh: Nullable<AbstractMesh>; // a node that will be attached to this Gamepad
  173. private _poseControlledCamera: TargetCamera;
  174. private _leftHandSystemQuaternion: Quaternion = new Quaternion();
  175. /**
  176. * Internal, matrix used to convert room space to babylon space
  177. * @hidden
  178. */
  179. public _deviceToWorld = Matrix.Identity();
  180. /**
  181. * Node to be used when casting a ray from the controller
  182. * @hidden
  183. */
  184. public _pointingPoseNode: Nullable<TransformNode> = null;
  185. /**
  186. * Name of the child mesh that can be used to cast a ray from the controller
  187. */
  188. public static readonly POINTING_POSE = "POINTING_POSE";
  189. /**
  190. * Creates a new PoseEnabledController from a gamepad
  191. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  192. */
  193. constructor(browserGamepad: any) {
  194. super(browserGamepad.id, browserGamepad.index, browserGamepad);
  195. this.type = Gamepad.POSE_ENABLED;
  196. this.controllerType = PoseEnabledControllerType.GENERIC;
  197. this.position = Vector3.Zero();
  198. this.rotationQuaternion = new Quaternion();
  199. this._calculatedPosition = Vector3.Zero();
  200. this._calculatedRotation = new Quaternion();
  201. Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, this._leftHandSystemQuaternion);
  202. }
  203. private _workingMatrix = Matrix.Identity();
  204. /**
  205. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  206. */
  207. public update() {
  208. super.update();
  209. this._updatePoseAndMesh();
  210. }
  211. /**
  212. * Updates only the pose device and mesh without doing any button event checking
  213. */
  214. protected _updatePoseAndMesh() {
  215. var pose: GamepadPose = this.browserGamepad.pose;
  216. this.updateFromDevice(pose);
  217. if (!this._trackPosition && EngineStore.LastCreatedScene && EngineStore.LastCreatedScene.activeCamera && (<WebVRFreeCamera>EngineStore.LastCreatedScene.activeCamera).devicePosition) {
  218. var camera = <WebVRFreeCamera>EngineStore.LastCreatedScene.activeCamera;
  219. camera._computeDevicePosition();
  220. this._deviceToWorld.setTranslation(camera.devicePosition);
  221. if (camera.deviceRotationQuaternion) {
  222. var camera = camera;
  223. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(Tmp.Vector3[0]);
  224. // Find the radian distance away that the headset is from the controllers rotation
  225. var distanceAway = Math.atan2(Math.sin(Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(Tmp.Vector3[0].y - this._draggedRoomRotation));
  226. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  227. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  228. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  229. this._draggedRoomRotation += rotationAmount;
  230. // Rotate controller around headset
  231. var sin = Math.sin(-rotationAmount);
  232. var cos = Math.cos(-rotationAmount);
  233. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  234. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  235. }
  236. }
  237. }
  238. Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  239. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  240. Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  241. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  242. if (this._mesh) {
  243. this._mesh.position.copyFrom(this.devicePosition);
  244. if (this._mesh.rotationQuaternion) {
  245. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  246. }
  247. }
  248. }
  249. /**
  250. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  251. * @param poseData raw pose fromthe device
  252. */
  253. updateFromDevice(poseData: DevicePose) {
  254. if (poseData) {
  255. this.rawPose = poseData;
  256. if (poseData.position) {
  257. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  258. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  259. this._deviceRoomPosition.z *= -1;
  260. }
  261. if (this._trackPosition) {
  262. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  263. }
  264. this._calculatedPosition.addInPlace(this.position);
  265. }
  266. let pose = this.rawPose;
  267. if (poseData.orientation && pose.orientation) {
  268. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  269. if (this._mesh) {
  270. if (this._mesh.getScene().useRightHandedSystem) {
  271. this._deviceRoomRotationQuaternion.z *= -1;
  272. this._deviceRoomRotationQuaternion.w *= -1;
  273. } else {
  274. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  275. }
  276. }
  277. // if the camera is set, rotate to the camera's rotation
  278. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  279. }
  280. }
  281. }
  282. /**
  283. * @hidden
  284. */
  285. public _meshAttachedObservable = new Observable<AbstractMesh>();
  286. /**
  287. * Attaches a mesh to the controller
  288. * @param mesh the mesh to be attached
  289. */
  290. public attachToMesh(mesh: AbstractMesh) {
  291. if (this._mesh) {
  292. this._mesh.parent = null;
  293. }
  294. this._mesh = mesh;
  295. if (this._poseControlledCamera) {
  296. this._mesh.parent = this._poseControlledCamera;
  297. }
  298. if (!this._mesh.rotationQuaternion) {
  299. this._mesh.rotationQuaternion = new Quaternion();
  300. }
  301. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  302. this._updatePoseAndMesh();
  303. if (this._pointingPoseNode) {
  304. var parents = [];
  305. var obj: Node = this._pointingPoseNode;
  306. while (obj.parent) {
  307. parents.push(obj.parent);
  308. obj = obj.parent;
  309. }
  310. parents.reverse().forEach((p) => { p.computeWorldMatrix(true); });
  311. }
  312. this._meshAttachedObservable.notifyObservers(mesh);
  313. }
  314. /**
  315. * Attaches the controllers mesh to a camera
  316. * @param camera the camera the mesh should be attached to
  317. */
  318. public attachToPoseControlledCamera(camera: TargetCamera) {
  319. this._poseControlledCamera = camera;
  320. if (this._mesh) {
  321. this._mesh.parent = this._poseControlledCamera;
  322. }
  323. }
  324. /**
  325. * Disposes of the controller
  326. */
  327. public dispose() {
  328. if (this._mesh) {
  329. this._mesh.dispose();
  330. }
  331. this._mesh = null;
  332. super.dispose();
  333. }
  334. /**
  335. * The mesh that is attached to the controller
  336. */
  337. public get mesh(): Nullable<AbstractMesh> {
  338. return this._mesh;
  339. }
  340. /**
  341. * Gets the ray of the controller in the direction the controller is pointing
  342. * @param length the length the resulting ray should be
  343. * @returns a ray in the direction the controller is pointing
  344. */
  345. public getForwardRay(length = 100): Ray {
  346. if (!this.mesh) {
  347. return new Ray(Vector3.Zero(), new Vector3(0, 0, 1), length);
  348. }
  349. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  350. var origin = m.getTranslation();
  351. var forward = new Vector3(0, 0, -1);
  352. var forwardWorld = Vector3.TransformNormal(forward, m);
  353. var direction = Vector3.Normalize(forwardWorld);
  354. return new Ray(origin, direction, length);
  355. }
  356. }