ovr_sdk

view LibOVR/Src/OVR_CAPI.h @ 0:1b39a1b46319

initial 0.4.4
author John Tsiombikas <nuclear@member.fsf.org>
date Wed, 14 Jan 2015 06:51:16 +0200
parents
children
line source
1 /************************************************************************************
3 Filename : OVR_CAPI.h
4 Content : C Interface to Oculus tracking and rendering.
5 Created : November 23, 2013
6 Authors : Michael Antonov
8 Copyright : Copyright 2014 Oculus VR, LLC All Rights reserved.
10 Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
11 you may not use the Oculus VR Rift SDK except in compliance with the License,
12 which is provided at the time of installation or download, or which
13 otherwise accompanies this software in either electronic or hard copy form.
15 You may obtain a copy of the License at
17 http://www.oculusvr.com/licenses/LICENSE-3.2
19 Unless required by applicable law or agreed to in writing, the Oculus VR SDK
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
25 ************************************************************************************/
27 /// @file OVR_CAPI.h
28 /// Exposes all general Rift functionality.
30 #ifndef OVR_CAPI_h
31 #define OVR_CAPI_h
33 #include <stdint.h>
35 #include "OVR_CAPI_Keys.h"
37 typedef char ovrBool;
39 //-----------------------------------------------------------------------------------
40 // ***** OVR_EXPORT definition
42 #if !defined(OVR_EXPORT)
43 #ifdef OVR_OS_WIN32
44 #define OVR_EXPORT __declspec(dllexport)
45 #else
46 #define OVR_EXPORT
47 #endif
48 #endif
52 //-----------------------------------------------------------------------------------
53 // ***** OVR_ALIGNAS definition
54 //
55 #if !defined(OVR_ALIGNAS)
56 // C++11 alignas
57 #if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) && (defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L))
58 #define OVR_ALIGNAS(n) alignas(n)
59 #elif defined(__clang__) && !defined(__APPLE__) && (((__clang_major__ * 100) + __clang_minor__) >= 300) && (__cplusplus >= 201103L)
60 #define OVR_ALIGNAS(n) alignas(n)
61 #elif defined(__clang__) && defined(__APPLE__) && (((__clang_major__ * 100) + __clang_minor__) >= 401) && (__cplusplus >= 201103L)
62 #define OVR_ALIGNAS(n) alignas(n)
63 #elif defined(_MSC_VER) && (_MSC_VER >= 1900)
64 #define OVR_ALIGNAS(n) alignas(n)
65 #elif defined(__EDG_VERSION__) && (__EDG_VERSION__ >= 408)
66 #define OVR_ALIGNAS(n) alignas(n)
68 // Pre-C++11 alignas fallbacks
69 #elif defined(__GNUC__) || defined(__clang__)
70 #define OVR_ALIGNAS(n) __attribute__((aligned(n)))
71 #elif defined(_MSC_VER) || defined(__INTEL_COMPILER)
72 #define OVR_ALIGNAS(n) __declspec(align(n)) // For Microsoft the alignment must be a literal integer.
73 #elif defined(__CC_ARM)
74 #define OVR_ALIGNAS(n) __align(n)
75 #else
76 #error Need to define OVR_ALIGNAS
77 #endif
78 #endif
80 #if defined(_MSC_VER)
81 #pragma warning(push)
82 #pragma warning(disable: 4324) // structure was padded due to __declspec(align())
83 #endif
86 //#define ENABLE_LATENCY_TESTER
88 //-----------------------------------------------------------------------------------
89 // ***** Simple Math Structures
91 /// A 2D vector with integer components.
92 typedef struct ovrVector2i_
93 {
94 int x, y;
95 } ovrVector2i;
97 /// A 2D size with integer components.
98 typedef struct ovrSizei_
99 {
100 int w, h;
101 } ovrSizei;
102 /// A 2D rectangle with a position and size.
103 /// All components are integers.
104 typedef struct ovrRecti_
105 {
106 ovrVector2i Pos;
107 ovrSizei Size;
108 } ovrRecti;
110 /// A quaternion rotation.
111 typedef struct ovrQuatf_
112 {
113 float x, y, z, w;
114 } ovrQuatf;
116 /// A 2D vector with float components.
117 typedef struct ovrVector2f_
118 {
119 float x, y;
120 } ovrVector2f;
122 /// A 3D vector with float components.
123 typedef struct ovrVector3f_
124 {
125 float x, y, z;
126 } ovrVector3f;
128 /// A 4x4 matrix with float elements.
129 typedef struct ovrMatrix4f_
130 {
131 float M[4][4];
132 } ovrMatrix4f;
134 /// Position and orientation together.
135 typedef struct ovrPosef_
136 {
137 ovrQuatf Orientation;
138 ovrVector3f Position;
139 } ovrPosef;
141 /// A full pose (rigid body) configuration with first and second derivatives.
142 typedef struct ovrPoseStatef_
143 {
144 ovrPosef ThePose; ///< The body's position and orientation.
145 ovrVector3f AngularVelocity; ///< The body's angular velocity in radians per second.
146 ovrVector3f LinearVelocity; ///< The body's velocity in meters per second.
147 ovrVector3f AngularAcceleration; ///< The body's angular acceleration in radians per second per second.
148 ovrVector3f LinearAcceleration; ///< The body's acceleration in meters per second per second.
149 double TimeInSeconds; ///< Absolute time of this state sample.
150 } ovrPoseStatef;
152 /// Field Of View (FOV) in tangent of the angle units.
153 /// As an example, for a standard 90 degree vertical FOV, we would
154 /// have: { UpTan = tan(90 degrees / 2), DownTan = tan(90 degrees / 2) }.
155 typedef struct ovrFovPort_
156 {
157 /// The tangent of the angle between the viewing vector and the top edge of the field of view.
158 float UpTan;
159 /// The tangent of the angle between the viewing vector and the bottom edge of the field of view.
160 float DownTan;
161 /// The tangent of the angle between the viewing vector and the left edge of the field of view.
162 float LeftTan;
163 /// The tangent of the angle between the viewing vector and the right edge of the field of view.
164 float RightTan;
165 } ovrFovPort;
167 //-----------------------------------------------------------------------------------
168 // ***** HMD Types
170 /// Enumerates all HMD types that we support.
171 typedef enum
172 {
173 ovrHmd_None = 0,
174 ovrHmd_DK1 = 3,
175 ovrHmd_DKHD = 4,
176 ovrHmd_DK2 = 6,
177 ovrHmd_Other // Some HMD other then the one in the enumeration.
178 } ovrHmdType;
180 /// HMD capability bits reported by device.
181 typedef enum
182 {
183 // Read-only flags.
184 ovrHmdCap_Present = 0x0001, /// The HMD is plugged in and detected by the system.
185 ovrHmdCap_Available = 0x0002, /// The HMD and its sensor are available for ownership use.
186 /// i.e. it is not already owned by another application.
187 ovrHmdCap_Captured = 0x0004, /// Set to 'true' if we captured ownership of this HMD.
189 // These flags are intended for use with the new driver display mode.
190 ovrHmdCap_ExtendDesktop = 0x0008, /// (read only) Means the display driver is in compatibility mode.
192 // Modifiable flags (through ovrHmd_SetEnabledCaps).
193 ovrHmdCap_NoMirrorToWindow = 0x2000, /// Disables mirroring of HMD output to the window. This may improve
194 /// rendering performance slightly (only if 'ExtendDesktop' is off).
195 ovrHmdCap_DisplayOff = 0x0040, /// Turns off HMD screen and output (only if 'ExtendDesktop' is off).
197 ovrHmdCap_LowPersistence = 0x0080, /// HMD supports low persistence mode.
198 ovrHmdCap_DynamicPrediction = 0x0200, /// Adjust prediction dynamically based on internally measured latency.
199 ovrHmdCap_DirectPentile = 0x0400, /// Write directly in pentile color mapping format
200 ovrHmdCap_NoVSync = 0x1000, /// Support rendering without VSync for debugging.
202 // These bits can be modified by ovrHmd_SetEnabledCaps.
203 ovrHmdCap_Writable_Mask = 0x32F0,
205 /// These flags are currently passed into the service. May change without notice.
206 ovrHmdCap_Service_Mask = 0x22F0
207 } ovrHmdCaps;
210 /// Tracking capability bits reported by the device.
211 /// Used with ovrHmd_ConfigureTracking.
212 typedef enum
213 {
214 ovrTrackingCap_Orientation = 0x0010, /// Supports orientation tracking (IMU).
215 ovrTrackingCap_MagYawCorrection = 0x0020, /// Supports yaw drift correction via a magnetometer or other means.
216 ovrTrackingCap_Position = 0x0040, /// Supports positional tracking.
217 /// Overrides the other flags. Indicates that the application
218 /// doesn't care about tracking settings. This is the internal
219 /// default before ovrHmd_ConfigureTracking is called.
220 ovrTrackingCap_Idle = 0x0100,
221 } ovrTrackingCaps;
223 /// Distortion capability bits reported by device.
224 /// Used with ovrHmd_ConfigureRendering and ovrHmd_CreateDistortionMesh.
225 typedef enum
226 {
227 ovrDistortionCap_Chromatic = 0x01, /// Supports chromatic aberration correction.
228 ovrDistortionCap_TimeWarp = 0x02, /// Supports timewarp.
229 // 0x04 unused
230 ovrDistortionCap_Vignette = 0x08, /// Supports vignetting around the edges of the view.
231 ovrDistortionCap_NoRestore = 0x10, /// Do not save and restore the graphics and compute state when rendering distortion.
232 ovrDistortionCap_FlipInput = 0x20, /// Flip the vertical texture coordinate of input images.
233 ovrDistortionCap_SRGB = 0x40, /// Assume input images are in sRGB gamma-corrected color space.
234 ovrDistortionCap_Overdrive = 0x80, /// Overdrive brightness transitions to reduce artifacts on DK2+ displays
235 ovrDistortionCap_HqDistortion = 0x100, /// High-quality sampling of distortion buffer for anti-aliasing
236 ovrDistortionCap_LinuxDevFullscreen = 0x200, /// Indicates window is fullscreen on a device when set. The SDK will automatically apply distortion mesh rotation if needed.
237 ovrDistortionCap_ComputeShader = 0x400, /// Using compute shader (DX11+ only)
239 ovrDistortionCap_ProfileNoTimewarpSpinWaits = 0x10000, /// Use when profiling with timewarp to remove false positives
240 } ovrDistortionCaps;
242 /// Specifies which eye is being used for rendering.
243 /// This type explicitly does not include a third "NoStereo" option, as such is
244 /// not required for an HMD-centered API.
245 typedef enum
246 {
247 ovrEye_Left = 0,
248 ovrEye_Right = 1,
249 ovrEye_Count = 2
250 } ovrEyeType;
252 /// This is a complete descriptor of the HMD.
253 typedef struct ovrHmdDesc_
254 {
255 /// Internal handle of this HMD.
256 struct ovrHmdStruct* Handle;
258 /// This HMD's type.
259 ovrHmdType Type;
261 /// Name string describing the product: "Oculus Rift DK1", etc.
262 const char* ProductName;
263 const char* Manufacturer;
265 /// HID Vendor and ProductId of the device.
266 short VendorId;
267 short ProductId;
268 /// Sensor (and display) serial number.
269 char SerialNumber[24];
270 /// Sensor firmware version.
271 short FirmwareMajor;
272 short FirmwareMinor;
273 /// External tracking camera frustum dimensions (if present).
274 float CameraFrustumHFovInRadians;
275 float CameraFrustumVFovInRadians;
276 float CameraFrustumNearZInMeters;
277 float CameraFrustumFarZInMeters;
279 /// Capability bits described by ovrHmdCaps.
280 unsigned int HmdCaps;
281 /// Capability bits described by ovrTrackingCaps.
282 unsigned int TrackingCaps;
283 /// Capability bits described by ovrDistortionCaps.
284 unsigned int DistortionCaps;
286 /// These define the recommended and maximum optical FOVs for the HMD.
287 ovrFovPort DefaultEyeFov[ovrEye_Count];
288 ovrFovPort MaxEyeFov[ovrEye_Count];
290 /// Preferred eye rendering order for best performance.
291 /// Can help reduce latency on sideways-scanned screens.
292 ovrEyeType EyeRenderOrder[ovrEye_Count];
294 /// Resolution of the full HMD screen (both eyes) in pixels.
295 ovrSizei Resolution;
296 /// Location of the application window on the desktop (or 0,0).
297 ovrVector2i WindowsPos;
299 /// Display that the HMD should present on.
300 /// TBD: It may be good to remove this information relying on WindowPos instead.
301 /// Ultimately, we may need to come up with a more convenient alternative,
302 /// such as API-specific functions that return adapter, or something that will
303 /// work with our monitor driver.
304 /// Windows: (e.g. "\\\\.\\DISPLAY3", can be used in EnumDisplaySettings/CreateDC).
305 const char* DisplayDeviceName;
306 /// MacOS:
307 int DisplayId;
309 } ovrHmdDesc;
311 /// Simple type ovrHmd is used in ovrHmd_* calls.
312 typedef const ovrHmdDesc * ovrHmd;
314 /// Bit flags describing the current status of sensor tracking.
315 typedef enum
316 {
317 ovrStatus_OrientationTracked = 0x0001, /// Orientation is currently tracked (connected and in use).
318 ovrStatus_PositionTracked = 0x0002, /// Position is currently tracked (false if out of range).
319 ovrStatus_CameraPoseTracked = 0x0004, /// Camera pose is currently tracked.
320 ovrStatus_PositionConnected = 0x0020, /// Position tracking hardware is connected.
321 ovrStatus_HmdConnected = 0x0080 /// HMD Display is available and connected.
322 } ovrStatusBits;
324 /// Specifies a reading we can query from the sensor.
325 typedef struct ovrSensorData_
326 {
327 ovrVector3f Accelerometer; /// Acceleration reading in m/s^2.
328 ovrVector3f Gyro; /// Rotation rate in rad/s.
329 ovrVector3f Magnetometer; /// Magnetic field in Gauss.
330 float Temperature; /// Temperature of the sensor in degrees Celsius.
331 float TimeInSeconds; /// Time when the reported IMU reading took place, in seconds.
332 } ovrSensorData;
334 /// Tracking state at a given absolute time (describes predicted HMD pose etc).
335 /// Returned by ovrHmd_GetTrackingState.
336 typedef struct ovrTrackingState_
337 {
338 /// Predicted head pose (and derivatives) at the requested absolute time.
339 /// The look-ahead interval is equal to (HeadPose.TimeInSeconds - RawSensorData.TimeInSeconds).
340 ovrPoseStatef HeadPose;
342 /// Current pose of the external camera (if present).
343 /// This pose includes camera tilt (roll and pitch). For a leveled coordinate
344 /// system use LeveledCameraPose.
345 ovrPosef CameraPose;
347 /// Camera frame aligned with gravity.
348 /// This value includes position and yaw of the camera, but not roll and pitch.
349 /// It can be used as a reference point to render real-world objects in the correct location.
350 ovrPosef LeveledCameraPose;
352 /// The most recent sensor data received from the HMD.
353 ovrSensorData RawSensorData;
355 /// Tracking status described by ovrStatusBits.
356 unsigned int StatusFlags;
358 //// 0.4.1
360 // Measures the time from receiving the camera frame until vision CPU processing completes.
361 double LastVisionProcessingTime;
363 //// 0.4.3
365 // Measures the time from exposure until the pose is available for the frame, including processing time.
366 double LastVisionFrameLatency;
368 /// Tag the vision processing results to a certain frame counter number.
369 uint32_t LastCameraFrameCounter;
370 } ovrTrackingState;
372 /// Frame timing data reported by ovrHmd_BeginFrameTiming() or ovrHmd_BeginFrame().
373 typedef struct ovrFrameTiming_
374 {
375 /// The amount of time that has passed since the previous frame's
376 /// ThisFrameSeconds value (usable for movement scaling).
377 /// This will be clamped to no more than 0.1 seconds to prevent
378 /// excessive movement after pauses due to loading or initialization.
379 float DeltaSeconds;
381 /// It is generally expected that the following holds:
382 /// ThisFrameSeconds < TimewarpPointSeconds < NextFrameSeconds <
383 /// EyeScanoutSeconds[EyeOrder[0]] <= ScanoutMidpointSeconds <= EyeScanoutSeconds[EyeOrder[1]].
385 /// Absolute time value when rendering of this frame began or is expected to
386 /// begin. Generally equal to NextFrameSeconds of the previous frame. Can be used
387 /// for animation timing.
388 double ThisFrameSeconds;
389 /// Absolute point when IMU expects to be sampled for this frame.
390 double TimewarpPointSeconds;
391 /// Absolute time when frame Present followed by GPU Flush will finish and the next frame begins.
392 double NextFrameSeconds;
394 /// Time when half of the screen will be scanned out. Can be passed as an absolute time
395 /// to ovrHmd_GetTrackingState() to get the predicted general orientation.
396 double ScanoutMidpointSeconds;
397 /// Timing points when each eye will be scanned out to display. Used when rendering each eye.
398 double EyeScanoutSeconds[2];
399 } ovrFrameTiming;
401 /// Rendering information for each eye. Computed by either ovrHmd_ConfigureRendering()
402 /// or ovrHmd_GetRenderDesc() based on the specified FOV. Note that the rendering viewport
403 /// is not included here as it can be specified separately and modified per frame through:
404 /// (a) ovrHmd_GetRenderScaleAndOffset in the case of client rendered distortion,
405 /// or (b) passing different values via ovrTexture in the case of SDK rendered distortion.
406 typedef struct ovrEyeRenderDesc_
407 {
408 ovrEyeType Eye; ///< The eye index this instance corresponds to.
409 ovrFovPort Fov; ///< The field of view.
410 ovrRecti DistortedViewport; ///< Distortion viewport.
411 ovrVector2f PixelsPerTanAngleAtCenter; ///< How many display pixels will fit in tan(angle) = 1.
412 ovrVector3f HmdToEyeViewOffset; ///< Translation to be applied to view matrix for each eye offset.
413 } ovrEyeRenderDesc;
415 //-----------------------------------------------------------------------------------
416 // ***** Platform-independent Rendering Configuration
418 /// These types are used to hide platform-specific details when passing
419 /// render device, OS, and texture data to the API.
420 ///
421 /// The benefit of having these wrappers versus platform-specific API functions is
422 /// that they allow game glue code to be portable. A typical example is an
423 /// engine that has multiple back ends, say GL and D3D. Portable code that calls
424 /// these back ends may also use LibOVR. To do this, back ends can be modified
425 /// to return portable types such as ovrTexture and ovrRenderAPIConfig.
426 typedef enum
427 {
428 ovrRenderAPI_None,
429 ovrRenderAPI_OpenGL,
430 ovrRenderAPI_Android_GLES, // May include extra native window pointers, etc.
431 ovrRenderAPI_D3D9,
432 ovrRenderAPI_D3D10,
433 ovrRenderAPI_D3D11,
434 ovrRenderAPI_Count
435 } ovrRenderAPIType;
437 /// Platform-independent part of rendering API-configuration data.
438 /// It is a part of ovrRenderAPIConfig, passed to ovrHmd_Configure.
439 typedef struct OVR_ALIGNAS(8) ovrRenderAPIConfigHeader_
440 {
441 ovrRenderAPIType API;
442 ovrSizei BackBufferSize; // Previously named RTSize.
443 int Multisample;
444 } ovrRenderAPIConfigHeader;
446 /// Contains platform-specific information for rendering.
447 typedef struct OVR_ALIGNAS(8) ovrRenderAPIConfig_
448 {
449 ovrRenderAPIConfigHeader Header;
450 uintptr_t PlatformData[8];
451 } ovrRenderAPIConfig;
453 /// Platform-independent part of the eye texture descriptor.
454 /// It is a part of ovrTexture, passed to ovrHmd_EndFrame.
455 /// If RenderViewport is all zeros then the full texture will be used.
456 typedef struct OVR_ALIGNAS(8) ovrTextureHeader_
457 {
458 ovrRenderAPIType API;
459 ovrSizei TextureSize;
460 ovrRecti RenderViewport; // Pixel viewport in texture that holds eye image.
461 uint32_t _PAD0_;
462 } ovrTextureHeader;
464 /// Contains platform-specific information about a texture.
465 typedef struct OVR_ALIGNAS(8) ovrTexture_
466 {
467 ovrTextureHeader Header;
468 uintptr_t PlatformData[8];
469 } ovrTexture;
472 // -----------------------------------------------------------------------------------
473 // ***** API Interfaces
475 // Basic steps to use the API:
476 //
477 // Setup:
478 // * ovrInitialize()
479 // * ovrHMD hmd = ovrHmd_Create(0)
480 // * Use hmd members and ovrHmd_GetFovTextureSize() to determine graphics configuration.
481 // * Call ovrHmd_ConfigureTracking() to configure and initialize tracking.
482 // * Call ovrHmd_ConfigureRendering() to setup graphics for SDK rendering,
483 // which is the preferred approach.
484 // Please refer to "Client Distorton Rendering" below if you prefer to do that instead.
485 // * If the ovrHmdCap_ExtendDesktop flag is not set, then use ovrHmd_AttachToWindow to
486 // associate the relevant application window with the hmd.
487 // * Allocate render target textures as needed.
488 //
489 // Game Loop:
490 // * Call ovrHmd_BeginFrame() to get the current frame timing information.
491 // * Render each eye using ovrHmd_GetEyePoses or ovrHmd_GetHmdPosePerEye to get
492 // the predicted hmd pose and each eye pose.
493 // * Call ovrHmd_EndFrame() to render the distorted textures to the back buffer
494 // and present them on the hmd.
495 //
496 // Shutdown:
497 // * ovrHmd_Destroy(hmd)
498 // * ovr_Shutdown()
499 //
501 #ifdef __cplusplus
502 extern "C" {
503 #endif
505 // ovr_InitializeRenderingShim initializes the rendering shim appart from everything
506 // else in LibOVR. This may be helpful if the application prefers to avoid
507 // creating any OVR resources (allocations, service connections, etc) at this point.
508 // ovr_InitializeRenderingShim does not bring up anything within LibOVR except the
509 // necessary hooks to enable the Direct-to-Rift functionality.
510 //
511 // Either ovr_InitializeRenderingShim() or ovr_Initialize() must be called before any
512 // Direct3D or OpenGL initilization is done by applictaion (creation of devices, etc).
513 // ovr_Initialize() must still be called after to use the rest of LibOVR APIs.
514 OVR_EXPORT ovrBool ovr_InitializeRenderingShim();
516 // Library init/shutdown, must be called around all other OVR code.
517 // No other functions calls besides ovr_InitializeRenderingShim are allowed
518 // before ovr_Initialize succeeds or after ovr_Shutdown.
519 /// Initializes all Oculus functionality.
520 OVR_EXPORT ovrBool ovr_Initialize();
521 /// Shuts down all Oculus functionality.
522 OVR_EXPORT void ovr_Shutdown();
524 /// Returns version string representing libOVR version. Static, so
525 /// string remains valid for app lifespan
526 OVR_EXPORT const char* ovr_GetVersionString();
528 /// Detects or re-detects HMDs and reports the total number detected.
529 /// Users can get information about each HMD by calling ovrHmd_Create with an index.
530 OVR_EXPORT int ovrHmd_Detect();
532 /// Creates a handle to an HMD which doubles as a description structure.
533 /// Index can [0 .. ovrHmd_Detect()-1]. Index mappings can cange after each ovrHmd_Detect call.
534 /// If not null, then the returned handle must be freed with ovrHmd_Destroy.
535 OVR_EXPORT ovrHmd ovrHmd_Create(int index);
536 OVR_EXPORT void ovrHmd_Destroy(ovrHmd hmd);
538 /// Creates a 'fake' HMD used for debugging only. This is not tied to specific hardware,
539 /// but may be used to debug some of the related rendering.
540 OVR_EXPORT ovrHmd ovrHmd_CreateDebug(ovrHmdType type);
542 /// Returns last error for HMD state. Returns null for no error.
543 /// String is valid until next call or GetLastError or HMD is destroyed.
544 /// Pass null hmd to get global errors (during create etc).
545 OVR_EXPORT const char* ovrHmd_GetLastError(ovrHmd hmd);
547 /// Platform specific function to specify the application window whose output will be
548 /// displayed on the HMD. Only used if the ovrHmdCap_ExtendDesktop flag is false.
549 /// Windows: SwapChain associated with this window will be displayed on the HMD.
550 /// Specify 'destMirrorRect' in window coordinates to indicate an area
551 /// of the render target output that will be mirrored from 'sourceRenderTargetRect'.
552 /// Null pointers mean "full size".
553 /// @note Source and dest mirror rects are not yet implemented.
554 OVR_EXPORT ovrBool ovrHmd_AttachToWindow(ovrHmd hmd, void* window,
555 const ovrRecti* destMirrorRect,
556 const ovrRecti* sourceRenderTargetRect);
558 /// Returns capability bits that are enabled at this time as described by ovrHmdCaps.
559 /// Note that this value is different font ovrHmdDesc::HmdCaps, which describes what
560 /// capabilities are available for that HMD.
561 OVR_EXPORT unsigned int ovrHmd_GetEnabledCaps(ovrHmd hmd);
563 /// Modifies capability bits described by ovrHmdCaps that can be modified,
564 /// such as ovrHmdCap_LowPersistance.
565 OVR_EXPORT void ovrHmd_SetEnabledCaps(ovrHmd hmd, unsigned int hmdCaps);
567 //-------------------------------------------------------------------------------------
568 // ***** Tracking Interface
570 /// All tracking interface functions are thread-safe, allowing tracking state to be sampled
571 /// from different threads.
572 /// ConfigureTracking starts sensor sampling, enabling specified capabilities,
573 /// described by ovrTrackingCaps.
574 /// - supportedTrackingCaps specifies support that is requested. The function will succeed
575 /// even if these caps are not available (i.e. sensor or camera is unplugged). Support
576 /// will automatically be enabled if such device is plugged in later. Software should
577 /// check ovrTrackingState.StatusFlags for real-time status.
578 /// - requiredTrackingCaps specify sensor capabilities required at the time of the call.
579 /// If they are not available, the function will fail. Pass 0 if only specifying
580 /// supportedTrackingCaps.
581 /// - Pass 0 for both supportedTrackingCaps and requiredTrackingCaps to disable tracking.
582 OVR_EXPORT ovrBool ovrHmd_ConfigureTracking(ovrHmd hmd, unsigned int supportedTrackingCaps,
583 unsigned int requiredTrackingCaps);
585 /// Re-centers the sensor orientation.
586 /// Normally this will recenter the (x,y,z) translational components and the yaw
587 /// component of orientation.
588 OVR_EXPORT void ovrHmd_RecenterPose(ovrHmd hmd);
590 /// Returns tracking state reading based on the specified absolute system time.
591 /// Pass an absTime value of 0.0 to request the most recent sensor reading. In this case
592 /// both PredictedPose and SamplePose will have the same value.
593 /// ovrHmd_GetEyePoses relies on this function internally.
594 /// This may also be used for more refined timing of FrontBuffer rendering logic, etc.
595 OVR_EXPORT ovrTrackingState ovrHmd_GetTrackingState(ovrHmd hmd, double absTime);
597 //-------------------------------------------------------------------------------------
598 // ***** Graphics Setup
600 /// Calculates the recommended texture size for rendering a given eye within the HMD
601 /// with a given FOV cone. Higher FOV will generally require larger textures to
602 /// maintain quality.
603 /// - pixelsPerDisplayPixel specifies the ratio of the number of render target pixels
604 /// to display pixels at the center of distortion. 1.0 is the default value. Lower
605 /// values can improve performance.
606 OVR_EXPORT ovrSizei ovrHmd_GetFovTextureSize(ovrHmd hmd, ovrEyeType eye, ovrFovPort fov,
607 float pixelsPerDisplayPixel);
609 //-------------------------------------------------------------------------------------
610 // ***** Rendering API Thread Safety
612 // All of rendering functions including the configure and frame functions
613 // are *NOT thread safe*. It is ok to use ConfigureRendering on one thread and handle
614 // frames on another thread, but explicit synchronization must be done since
615 // functions that depend on configured state are not reentrant.
616 //
617 // As an extra requirement, any of the following calls must be done on
618 // the render thread, which is the same thread that calls ovrHmd_BeginFrame
619 // or ovrHmd_BeginFrameTiming.
620 // - ovrHmd_EndFrame
621 // - ovrHmd_GetEyeTimewarpMatrices
623 //-------------------------------------------------------------------------------------
624 // ***** SDK Distortion Rendering Functions
626 // These functions support rendering of distortion by the SDK through direct
627 // access to the underlying rendering API, such as D3D or GL.
628 // This is the recommended approach since it allows better support for future
629 // Oculus hardware, and enables a range of low-level optimizations.
631 /// Configures rendering and fills in computed render parameters.
632 /// This function can be called multiple times to change rendering settings.
633 /// eyeRenderDescOut is a pointer to an array of two ovrEyeRenderDesc structs
634 /// that are used to return complete rendering information for each eye.
635 /// - apiConfig provides D3D/OpenGL specific parameters. Pass null
636 /// to shutdown rendering and release all resources.
637 /// - distortionCaps describe desired distortion settings.
638 OVR_EXPORT ovrBool ovrHmd_ConfigureRendering( ovrHmd hmd,
639 const ovrRenderAPIConfig* apiConfig,
640 unsigned int distortionCaps,
641 const ovrFovPort eyeFovIn[2],
642 ovrEyeRenderDesc eyeRenderDescOut[2] );
645 /// Begins a frame, returning timing information.
646 /// This should be called at the beginning of the game rendering loop (on the render thread).
647 /// Pass 0 for the frame index if not using ovrHmd_GetFrameTiming.
648 OVR_EXPORT ovrFrameTiming ovrHmd_BeginFrame(ovrHmd hmd, unsigned int frameIndex);
650 /// Ends a frame, submitting the rendered textures to the frame buffer.
651 /// - RenderViewport within each eyeTexture can change per frame if necessary.
652 /// - 'renderPose' will typically be the value returned from ovrHmd_GetEyePoses,
653 /// ovrHmd_GetHmdPosePerEye but can be different if a different head pose was
654 /// used for rendering.
655 /// - This may perform distortion and scaling internally, assuming is it not
656 /// delegated to another thread.
657 /// - Must be called on the same thread as BeginFrame.
658 /// - *** This Function will call Present/SwapBuffers and potentially wait for GPU Sync ***.
659 OVR_EXPORT void ovrHmd_EndFrame(ovrHmd hmd,
660 const ovrPosef renderPose[2],
661 const ovrTexture eyeTexture[2]);
663 /// Returns predicted head pose in outHmdTrackingState and offset eye poses in outEyePoses
664 /// as an atomic operation. Caller need not worry about applying HmdToEyeViewOffset to the
665 /// returned outEyePoses variables.
666 /// - Thread-safe function where caller should increment frameIndex with every frame
667 /// and pass the index where applicable to functions called on the rendering thread.
668 /// - hmdToEyeViewOffset[2] can be ovrEyeRenderDesc.HmdToEyeViewOffset returned from
669 /// ovrHmd_ConfigureRendering or ovrHmd_GetRenderDesc. For monoscopic rendering,
670 /// use a vector that is the average of the two vectors for both eyes.
671 /// - If frameIndex is not being used, pass in 0.
672 /// - Assuming outEyePoses are used for rendering, it should be passed into ovrHmd_EndFrame.
673 /// - If called doesn't need outHmdTrackingState, it can be NULL
674 OVR_EXPORT void ovrHmd_GetEyePoses(ovrHmd hmd, unsigned int frameIndex, ovrVector3f hmdToEyeViewOffset[2],
675 ovrPosef outEyePoses[2], ovrTrackingState* outHmdTrackingState);
677 /// Function was previously called ovrHmd_GetEyePose
678 /// Returns the predicted head pose to use when rendering the specified eye.
679 /// - Important: Caller must apply HmdToEyeViewOffset before using ovrPosef for rendering
680 /// - Must be called between ovrHmd_BeginFrameTiming and ovrHmd_EndFrameTiming.
681 /// - If the pose is used for rendering the eye, it should be passed to ovrHmd_EndFrame.
682 /// - Parameter 'eye' is used for prediction timing only
683 OVR_EXPORT ovrPosef ovrHmd_GetHmdPosePerEye(ovrHmd hmd, ovrEyeType eye);
686 //-------------------------------------------------------------------------------------
687 // ***** Client Distortion Rendering Functions
689 // These functions provide the distortion data and render timing support necessary to allow
690 // client rendering of distortion. Client-side rendering involves the following steps:
691 //
692 // 1. Setup ovrEyeDesc based on the desired texture size and FOV.
693 // Call ovrHmd_GetRenderDesc to get the necessary rendering parameters for each eye.
694 //
695 // 2. Use ovrHmd_CreateDistortionMesh to generate the distortion mesh.
696 //
697 // 3. Use ovrHmd_BeginFrameTiming, ovrHmd_GetEyePoses, and ovrHmd_BeginFrameTiming in
698 // the rendering loop to obtain timing and predicted head orientation when rendering each eye.
699 // - When using timewarp, use ovr_WaitTillTime after the rendering and gpu flush, followed
700 // by ovrHmd_GetEyeTimewarpMatrices to obtain the timewarp matrices used
701 // by the distortion pixel shader. This will minimize latency.
702 //
704 /// Computes the distortion viewport, view adjust, and other rendering parameters for
705 /// the specified eye. This can be used instead of ovrHmd_ConfigureRendering to do
706 /// setup for client rendered distortion.
707 OVR_EXPORT ovrEyeRenderDesc ovrHmd_GetRenderDesc(ovrHmd hmd,
708 ovrEyeType eyeType, ovrFovPort fov);
711 /// Describes a vertex used by the distortion mesh. This is intended to be converted into
712 /// the engine-specific format. Some fields may be unused based on the ovrDistortionCaps
713 /// flags selected. TexG and TexB, for example, are not used if chromatic correction is
714 /// not requested.
715 typedef struct ovrDistortionVertex_
716 {
717 ovrVector2f ScreenPosNDC; ///< [-1,+1],[-1,+1] over the entire framebuffer.
718 float TimeWarpFactor; ///< Lerp factor between time-warp matrices. Can be encoded in Pos.z.
719 float VignetteFactor; ///< Vignette fade factor. Can be encoded in Pos.w.
720 ovrVector2f TanEyeAnglesR; ///< The tangents of the horizontal and vertical eye angles for the red channel.
721 ovrVector2f TanEyeAnglesG; ///< The tangents of the horizontal and vertical eye angles for the green channel.
722 ovrVector2f TanEyeAnglesB; ///< The tangents of the horizontal and vertical eye angles for the blue channel.
723 } ovrDistortionVertex;
725 /// Describes a full set of distortion mesh data, filled in by ovrHmd_CreateDistortionMesh.
726 /// Contents of this data structure, if not null, should be freed by ovrHmd_DestroyDistortionMesh.
727 typedef struct ovrDistortionMesh_
728 {
729 ovrDistortionVertex* pVertexData; ///< The distortion vertices representing each point in the mesh.
730 unsigned short* pIndexData; ///< Indices for connecting the mesh vertices into polygons.
731 unsigned int VertexCount; ///< The number of vertices in the mesh.
732 unsigned int IndexCount; ///< The number of indices in the mesh.
733 } ovrDistortionMesh;
735 /// Generate distortion mesh per eye.
736 /// Distortion capabilities will depend on 'distortionCaps' flags. Users should
737 /// render using the appropriate shaders based on their settings.
738 /// Distortion mesh data will be allocated and written into the ovrDistortionMesh data structure,
739 /// which should be explicitly freed with ovrHmd_DestroyDistortionMesh.
740 /// Users should call ovrHmd_GetRenderScaleAndOffset to get uvScale and Offset values for rendering.
741 /// The function shouldn't fail unless theres is a configuration or memory error, in which case
742 /// ovrDistortionMesh values will be set to null.
743 /// This is the only function in the SDK reliant on eye relief, currently imported from profiles,
744 /// or overridden here.
745 OVR_EXPORT ovrBool ovrHmd_CreateDistortionMesh( ovrHmd hmd,
746 ovrEyeType eyeType, ovrFovPort fov,
747 unsigned int distortionCaps,
748 ovrDistortionMesh *meshData);
749 OVR_EXPORT ovrBool ovrHmd_CreateDistortionMeshDebug( ovrHmd hmddesc,
750 ovrEyeType eyeType, ovrFovPort fov,
751 unsigned int distortionCaps,
752 ovrDistortionMesh *meshData,
753 float debugEyeReliefOverrideInMetres);
756 /// Used to free the distortion mesh allocated by ovrHmd_GenerateDistortionMesh. meshData elements
757 /// are set to null and zeroes after the call.
758 OVR_EXPORT void ovrHmd_DestroyDistortionMesh( ovrDistortionMesh* meshData );
760 /// Computes updated 'uvScaleOffsetOut' to be used with a distortion if render target size or
761 /// viewport changes after the fact. This can be used to adjust render size every frame if desired.
762 OVR_EXPORT void ovrHmd_GetRenderScaleAndOffset( ovrFovPort fov,
763 ovrSizei textureSize, ovrRecti renderViewport,
764 ovrVector2f uvScaleOffsetOut[2] );
766 /// Thread-safe timing function for the main thread. Caller should increment frameIndex
767 /// with every frame and pass the index where applicable to functions called on the
768 /// rendering thread.
769 OVR_EXPORT ovrFrameTiming ovrHmd_GetFrameTiming(ovrHmd hmd, unsigned int frameIndex);
771 /// Called at the beginning of the frame on the rendering thread.
772 /// Pass frameIndex == 0 if ovrHmd_GetFrameTiming isn't being used. Otherwise,
773 /// pass the same frame index as was used for GetFrameTiming on the main thread.
774 OVR_EXPORT ovrFrameTiming ovrHmd_BeginFrameTiming(ovrHmd hmd, unsigned int frameIndex);
776 /// Marks the end of client distortion rendered frame, tracking the necessary timing information.
777 /// This function must be called immediately after Present/SwapBuffers + GPU sync. GPU sync is
778 /// important before this call to reduce latency and ensure proper timing.
779 OVR_EXPORT void ovrHmd_EndFrameTiming(ovrHmd hmd);
781 /// Initializes and resets frame time tracking. This is typically not necessary, but
782 /// is helpful if game changes vsync state or video mode. vsync is assumed to be on if this
783 /// isn't called. Resets internal frame index to the specified number.
784 OVR_EXPORT void ovrHmd_ResetFrameTiming(ovrHmd hmd, unsigned int frameIndex);
786 /// Computes timewarp matrices used by distortion mesh shader, these are used to adjust
787 /// for head orientation change since the last call to ovrHmd_GetEyePoses
788 /// when rendering this eye. The ovrDistortionVertex::TimeWarpFactor is used to blend between the
789 /// matrices, usually representing two different sides of the screen.
790 /// Must be called on the same thread as ovrHmd_BeginFrameTiming.
791 OVR_EXPORT void ovrHmd_GetEyeTimewarpMatrices (ovrHmd hmd, ovrEyeType eye,
792 ovrPosef renderPose, ovrMatrix4f twmOut[2]);
793 OVR_EXPORT void ovrHmd_GetEyeTimewarpMatricesDebug(ovrHmd hmd, ovrEyeType eye,
794 ovrPosef renderPose, ovrMatrix4f twmOut[2],
795 double debugTimingOffsetInSeconds);
800 //-------------------------------------------------------------------------------------
801 // ***** Stateless math setup functions
803 /// Used to generate projection from ovrEyeDesc::Fov.
804 OVR_EXPORT ovrMatrix4f ovrMatrix4f_Projection( ovrFovPort fov,
805 float znear, float zfar, ovrBool rightHanded );
807 /// Used for 2D rendering, Y is down
808 /// orthoScale = 1.0f / pixelsPerTanAngleAtCenter
809 /// orthoDistance = distance from camera, such as 0.8m
810 OVR_EXPORT ovrMatrix4f ovrMatrix4f_OrthoSubProjection(ovrMatrix4f projection, ovrVector2f orthoScale,
811 float orthoDistance, float hmdToEyeViewOffsetX);
813 /// Returns global, absolute high-resolution time in seconds. This is the same
814 /// value as used in sensor messages.
815 OVR_EXPORT double ovr_GetTimeInSeconds();
817 /// Waits until the specified absolute time.
818 OVR_EXPORT double ovr_WaitTillTime(double absTime);
820 // -----------------------------------------------------------------------------------
821 // ***** Latency Test interface
823 /// Does latency test processing and returns 'TRUE' if specified rgb color should
824 /// be used to clear the screen.
825 OVR_EXPORT ovrBool ovrHmd_ProcessLatencyTest(ovrHmd hmd, unsigned char rgbColorOut[3]);
827 /// Returns non-null string once with latency test result, when it is available.
828 /// Buffer is valid until next call.
829 OVR_EXPORT const char* ovrHmd_GetLatencyTestResult(ovrHmd hmd);
831 /// Returns the latency testing color in rgbColorOut to render when using a DK2
832 /// Returns false if this feature is disabled or not-applicable (e.g. using a DK1)
833 OVR_EXPORT ovrBool ovrHmd_GetLatencyTest2DrawColor(ovrHmd hmddesc, unsigned char rgbColorOut[3]);
835 //-------------------------------------------------------------------------------------
836 // ***** Health and Safety Warning Display interface
837 //
839 /// Used by ovrhmd_GetHSWDisplayState to report the current display state.
840 typedef struct ovrHSWDisplayState_
841 {
842 /// If true then the warning should be currently visible
843 /// and the following variables have meaning. Else there is no
844 /// warning being displayed for this application on the given HMD.
845 ovrBool Displayed; ///< True if the Health&Safety Warning is currently displayed.
846 double StartTime; ///< Absolute time when the warning was first displayed. See ovr_GetTimeInSeconds().
847 double DismissibleTime; ///< Earliest absolute time when the warning can be dismissed. May be a time in the past.
848 } ovrHSWDisplayState;
850 /// Returns the current state of the HSW display. If the application is doing the rendering of
851 /// the HSW display then this function serves to indicate that the warning should be
852 /// currently displayed. If the application is using SDK-based eye rendering then the SDK by
853 /// default automatically handles the drawing of the HSW display. An application that uses
854 /// application-based eye rendering should use this function to know when to start drawing the
855 /// HSW display itself and can optionally use it in conjunction with ovrhmd_DismissHSWDisplay
856 /// as described below.
857 ///
858 /// Example usage for application-based rendering:
859 /// bool HSWDisplayCurrentlyDisplayed = false; // global or class member variable
860 /// ovrHSWDisplayState hswDisplayState;
861 /// ovrhmd_GetHSWDisplayState(Hmd, &hswDisplayState);
862 ///
863 /// if (hswDisplayState.Displayed && !HSWDisplayCurrentlyDisplayed) {
864 /// <insert model into the scene that stays in front of the user>
865 /// HSWDisplayCurrentlyDisplayed = true;
866 /// }
867 OVR_EXPORT void ovrHmd_GetHSWDisplayState(ovrHmd hmd, ovrHSWDisplayState *hasWarningState);
869 /// Dismisses the HSW display if the warning is dismissible and the earliest dismissal time
870 /// has occurred. Returns true if the display is valid and could be dismissed. The application
871 /// should recognize that the HSW display is being displayed (via ovrhmd_GetHSWDisplayState)
872 /// and if so then call this function when the appropriate user input to dismiss the warning
873 /// occurs.
874 ///
875 /// Example usage :
876 /// void ProcessEvent(int key) {
877 /// if (key == escape) {
878 /// ovrHSWDisplayState hswDisplayState;
879 /// ovrhmd_GetHSWDisplayState(hmd, &hswDisplayState);
880 ///
881 /// if (hswDisplayState.Displayed && ovrhmd_DismissHSWDisplay(hmd)) {
882 /// <remove model from the scene>
883 /// HSWDisplayCurrentlyDisplayed = false;
884 /// }
885 /// }
886 /// }
887 OVR_EXPORT ovrBool ovrHmd_DismissHSWDisplay(ovrHmd hmd);
889 /// Get boolean property. Returns first element if property is a boolean array.
890 /// Returns defaultValue if property doesn't exist.
891 OVR_EXPORT ovrBool ovrHmd_GetBool(ovrHmd hmd, const char* propertyName, ovrBool defaultVal);
893 /// Modify bool property; false if property doesn't exist or is readonly.
894 OVR_EXPORT ovrBool ovrHmd_SetBool(ovrHmd hmd, const char* propertyName, ovrBool value);
896 /// Get integer property. Returns first element if property is an integer array.
897 /// Returns defaultValue if property doesn't exist.
898 OVR_EXPORT int ovrHmd_GetInt(ovrHmd hmd, const char* propertyName, int defaultVal);
900 /// Modify integer property; false if property doesn't exist or is readonly.
901 OVR_EXPORT ovrBool ovrHmd_SetInt(ovrHmd hmd, const char* propertyName, int value);
903 /// Get float property. Returns first element if property is a float array.
904 /// Returns defaultValue if property doesn't exist.
905 OVR_EXPORT float ovrHmd_GetFloat(ovrHmd hmd, const char* propertyName, float defaultVal);
907 /// Modify float property; false if property doesn't exist or is readonly.
908 OVR_EXPORT ovrBool ovrHmd_SetFloat(ovrHmd hmd, const char* propertyName, float value);
910 /// Get float[] property. Returns the number of elements filled in, 0 if property doesn't exist.
911 /// Maximum of arraySize elements will be written.
912 OVR_EXPORT unsigned int ovrHmd_GetFloatArray(ovrHmd hmd, const char* propertyName,
913 float values[], unsigned int arraySize);
915 /// Modify float[] property; false if property doesn't exist or is readonly.
916 OVR_EXPORT ovrBool ovrHmd_SetFloatArray(ovrHmd hmd, const char* propertyName,
917 float values[], unsigned int arraySize);
919 /// Get string property. Returns first element if property is a string array.
920 /// Returns defaultValue if property doesn't exist.
921 /// String memory is guaranteed to exist until next call to GetString or GetStringArray, or HMD is destroyed.
922 OVR_EXPORT const char* ovrHmd_GetString(ovrHmd hmd, const char* propertyName,
923 const char* defaultVal);
925 /// Set string property
926 OVR_EXPORT ovrBool ovrHmd_SetString(ovrHmd hmddesc, const char* propertyName,
927 const char* value);
929 // -----------------------------------------------------------------------------------
930 // ***** Logging
932 /// Start performance logging. guid is optional and if included is written with each file entry.
933 /// If called while logging is already active with the same filename, only the guid will be updated
934 /// If called while logging is already active with a different filename, ovrHmd_StopPerfLog() will be called, followed by ovrHmd_StartPerfLog()
935 OVR_EXPORT ovrBool ovrHmd_StartPerfLog(ovrHmd hmd, const char* fileName, const char* userData1);
936 /// Stop performance logging.
937 OVR_EXPORT ovrBool ovrHmd_StopPerfLog(ovrHmd hmd);
940 #ifdef __cplusplus
941 } // extern "C"
942 #endif
945 #if defined(_MSC_VER)
946 #pragma warning(pop)
947 #endif
950 #endif // OVR_CAPI_h