浏览代码

Merge remote-tracking branch 'refs/remotes/raysan5/develop' into develop

pull/131/head
victorfisac 9 年前
父节点
当前提交
c9c1263e6f
共有 25 个文件被更改,包括 7870 次插入614 次删除
  1. +3
    -1
      .gitignore
  2. +26
    -14
      examples/core_oculus_rift.c
  3. +22
    -28
      examples/oculus_glfw_sample/oculus_glfw_sample.c
  4. +8
    -10
      examples/oculus_glfw_sample/raymath.h
  5. +413
    -8
      examples/oculus_glfw_sample/rlgl.c
  6. +11
    -1
      examples/oculus_glfw_sample/rlgl.h
  7. +27
    -19
      examples/oculus_glfw_sample/standard_shader.h
  8. +8
    -398
      src/core.c
  9. +196
    -0
      src/external/OculusSDK/LibOVR/Include/Extras/OVR_CAPI_Util.h
  10. +3785
    -0
      src/external/OculusSDK/LibOVR/Include/Extras/OVR_Math.h
  11. +70
    -0
      src/external/OculusSDK/LibOVR/Include/Extras/OVR_StereoProjection.h
  12. +2116
    -0
      src/external/OculusSDK/LibOVR/Include/OVR_CAPI.h
  13. +76
    -0
      src/external/OculusSDK/LibOVR/Include/OVR_CAPI_Audio.h
  14. +155
    -0
      src/external/OculusSDK/LibOVR/Include/OVR_CAPI_D3D.h
  15. +99
    -0
      src/external/OculusSDK/LibOVR/Include/OVR_CAPI_GL.h
  16. +53
    -0
      src/external/OculusSDK/LibOVR/Include/OVR_CAPI_Keys.h
  17. +209
    -0
      src/external/OculusSDK/LibOVR/Include/OVR_ErrorCode.h
  18. +60
    -0
      src/external/OculusSDK/LibOVR/Include/OVR_Version.h
  19. 二进制
      src/external/OculusSDK/LibOVR/LibOVRRT32_1.dll
  20. +17
    -17
      src/gestures.c
  21. +4
    -4
      src/gestures.h
  22. +107
    -101
      src/raygui.h
  23. +16
    -11
      src/raylib.h
  24. +378
    -1
      src/rlgl.c
  25. +11
    -1
      src/rlgl.h

+ 3
- 1
.gitignore 查看文件

@ -66,8 +66,10 @@ src/libraylib.a
src/libraylib.bc
# oculus example
!examples/oculus_glfw_sample/LibOVRRT32_1.dll
!examples/oculus_glfw_sample/
# external libraries DLLs
!src/external/glfw3/lib/win32/glfw3.dll
!src/external/openal_soft/lib/win32/OpenAL32.dll
!src/external/OculusSDK/LibOVR/LibOVRRT32_1.dll

+ 26
- 14
examples/core_oculus_rift.c 查看文件

@ -2,6 +2,9 @@
*
* raylib [core] example - Oculus Rift CV1
*
* Compile example using:
* gcc -o $(NAME_PART).exe $(FILE_NAME) -L. -L..\src\external\OculusSDK\LibOVR -lLibOVRRT32_1 -lraylib -lglfw3 -lopengl32 -lgdi32 -std=c99
*
* This example has been created using raylib 1.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
@ -21,8 +24,8 @@ int main()
InitWindow(screenWidth, screenHeight, "raylib [core] example - oculus rift");
InitOculusDevice();
// Define the camera to look into our 3d world
// Define the camera to look into our 3d world
Camera camera;
camera.position = (Vector3){ 5.0f, 5.0f, 5.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
@ -30,8 +33,8 @@ int main()
camera.fovy = 45.0f; // Camera field-of-view Y
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
SetTargetFPS(90); // Set our game to run at 90 frames-per-second
o">//SetTargetFPS(90); // Set our game to run at 90 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
@ -47,15 +50,24 @@ int main()
BeginDrawing();
ClearBackground(RAYWHITE);
Begin3dMode(camera);
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, MAROON);
DrawGrid(10, 1.0f);
End3dMode();
BeginOculusDrawing();
for (int eye = 0; eye < 2; eye++)
{
Begin3dMode(camera);
SetOculusMatrix(eye);
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, MAROON);
DrawGrid(10, 1.0f);
End3dMode();
}
EndOculusDrawing();
EndDrawing();
//----------------------------------------------------------------------------------
@ -63,7 +75,7 @@ int main()
// De-Initialization
//--------------------------------------------------------------------------------------
CloseOculusdevice(); // Close Oculus Rift device
CloseOculusDevice(); // Close Oculus Rift device
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------

+ 22
- 28
examples/oculus_glfw_sample/oculus_glfw_sample.c 查看文件

@ -23,8 +23,7 @@
#include <string.h>
#include <math.h>
#define GLAD_IMPLEMENTATION
#include "glad.h" // Extensions loading library
#include "glad.h"
#include <GLFW/glfw3.h> // Windows/Context and inputs management
#define RLGL_STANDALONE
@ -148,33 +147,34 @@ int main(void)
glfwSwapInterval(0);
// Load OpenGL 3.3 extensions
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
TraceLog(WARNING, "GLAD: Cannot load OpenGL extensions");
return 3;
}
else TraceLog(INFO, "GLAD: OpenGL extensions loaded successfully");
rlglLoadExtensions(glfwGetProcAddress);
// Initialize rlgl internal buffers and OpenGL state
rlglInit();
rlglInitGraphics(0, 0, screenWidth, screenHeight);
rlClearColor(245, 245, 245, 255); // Define clear color
rlEnableDepthTest(); // Enable DEPTH_TEST for 3D
//--------------------------------------------------------
#if defined(PLATFORM_OCULUS)
ovrResult result = ovr_Initialize(NULL);
if (OVR_FAILURE(result)) TraceLog(LOG_ERROR, "OVR: Could not initialize Oculus device");
if (OVR_FAILURE(result)) TraceLog(ERROR, "OVR: Could not initialize Oculus device");
result = ovr_Create(&session, &luid);
if (OVR_FAILURE(result))
{
TraceLog(LOG_WARNING, "OVR: Could not create Oculus session");
TraceLog(WARNING, "OVR: Could not create Oculus session");
ovr_Shutdown();
}
hmdDesc = ovr_GetHmdDesc(session);
TraceLog(LOG_INFO, "OVR: Product Name: %s", hmdDesc.ProductName);
TraceLog(LOG_INFO, "OVR: Manufacturer: %s", hmdDesc.Manufacturer);
TraceLog(LOG_INFO, "OVR: Product ID: %i", hmdDesc.ProductId);
TraceLog(LOG_INFO, "OVR: Product Type: %i", hmdDesc.Type);
TraceLog(LOG_INFO, "OVR: Serian Number: %s", hmdDesc.SerialNumber);
TraceLog(LOG_INFO, "OVR: Resolution: %ix%i", hmdDesc.Resolution.w, hmdDesc.Resolution.h);
TraceLog(INFO, "OVR: Product Name: %s", hmdDesc.ProductName);
TraceLog(INFO, "OVR: Manufacturer: %s", hmdDesc.Manufacturer);
TraceLog(INFO, "OVR: Product ID: %i", hmdDesc.ProductId);
TraceLog(INFO, "OVR: Product Type: %i", hmdDesc.Type);
TraceLog(INFO, "OVR: Serian Number: %s", hmdDesc.SerialNumber);
TraceLog(INFO, "OVR: Resolution: %ix%i", hmdDesc.Resolution.w, hmdDesc.Resolution.h);
//screenWidth = hmdDesc.Resolution.w/2;
//screenHeight = hmdDesc.Resolution.h/2;
@ -188,20 +188,14 @@ int main(void)
// Recenter OVR tracking origin
ovr_RecenterTrackingOrigin(session);
#endif
// Initialize rlgl internal buffers and OpenGL state
rlglInit();
rlglInitGraphics(0, 0, screenWidth, screenHeight);
rlClearColor(245, 245, 245, 255); // Define clear color
rlEnableDepthTest(); // Enable DEPTH_TEST for 3D
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
Camera camera;
camera.position = (Vector3){ 5.0f, 5.0f, 5.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
//--------------------------------------------------------------------------------------
// Main game loop
@ -293,7 +287,7 @@ int main(void)
// Get session status information
ovrSessionStatus sessionStatus;
ovr_GetSessionStatus(session, &sessionStatus);
if (sessionStatus.ShouldQuit) TraceLog(LOG_WARNING, "OVR: Session should quit...");
if (sessionStatus.ShouldQuit) TraceLog(WARNING, "OVR: Session should quit...");
if (sessionStatus.ShouldRecenter) ovr_RecenterTrackingOrigin(session);
#endif
@ -581,12 +575,12 @@ static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height)
ovrResult result = ovr_CreateTextureSwapChainGL(session, &desc, &buffer.textureChain);
if (!OVR_SUCCESS(result)) TraceLog(LOG_WARNING, "OVR: Failed to create swap textures buffer");
if (!OVR_SUCCESS(result)) TraceLog(WARNING, "OVR: Failed to create swap textures buffer");
int textureCount = 0;
ovr_GetTextureSwapChainLength(session, buffer.textureChain, &textureCount);
if (!OVR_SUCCESS(result) || !textureCount) TraceLog(LOG_WARNING, "OVR: Unable to count swap chain textures");
if (!OVR_SUCCESS(result) || !textureCount) TraceLog(WARNING, "OVR: Unable to count swap chain textures");
for (int i = 0; i < textureCount; ++i)
{
@ -682,7 +676,7 @@ static OculusMirror LoadOculusMirror(ovrSession session, int width, int height)
mirrorDesc.Width = mirror.width;
mirrorDesc.Height = mirror.height;
if (!OVR_SUCCESS(ovr_CreateMirrorTextureGL(session, &mirrorDesc, &mirror.texture))) TraceLog(LOG_WARNING, "Could not create mirror texture");
if (!OVR_SUCCESS(ovr_CreateMirrorTextureGL(session, &mirrorDesc, &mirror.texture))) TraceLog(WARNING, "Could not create mirror texture");
glGenFramebuffers(1, &mirror.fboId);

+ 8
- 10
examples/oculus_glfw_sample/raymath.h 查看文件

@ -47,10 +47,16 @@
#include "raylib.h" // Required for structs: Vector3, Matrix
#endif
#ifdef __cplusplus
#define RMEXTERN extern "C" // Functions visible from other files (no name mangling of functions in C++)
#else
#define RMEXTERN extern // Functions visible from other files
#endif
#if defined(RAYMATH_EXTERN_INLINE)
#define RMDEF extern inline
#define RMDEF RMEXTERN inline // Functions are embeded inline (compiler generated code)
#else
#define RMDEF extern
#define RMDEF RMEXTERN
#endif
//----------------------------------------------------------------------------------
@ -105,10 +111,6 @@ typedef struct Quaternion {
#ifndef RAYMATH_EXTERN_INLINE
#ifdef __cplusplus
extern "C" {
#endif
//------------------------------------------------------------------------------------
// Functions Declaration to work with Vector3
//------------------------------------------------------------------------------------
@ -166,10 +168,6 @@ RMDEF Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle); // Returns
RMDEF void QuaternionToAxisAngle(Quaternion q, Vector3 *outAxis, float *outAngle); // Returns the rotation angle and axis for a given quaternion
RMDEF void QuaternionTransform(Quaternion *q, Matrix mat); // Transform a quaternion given a transformation matrix
#ifdef __cplusplus
}
#endif
#endif // notdef RAYMATH_EXTERN_INLINE
#endif // RAYMATH_H

+ 413
- 8
examples/oculus_glfw_sample/rlgl.c 查看文件

@ -72,6 +72,10 @@
#include "standard_shader.h" // Standard shader to embed
#endif
#if defined(RLGL_OCULUS_SUPPORT)
#include "external/OculusSDK/LibOVR/Include/OVR_CAPI_GL.h" // Oculus SDK for OpenGL
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
@ -159,11 +163,45 @@ typedef struct {
// Draw call type
// NOTE: Used to track required draw-calls, organized by texture
typedef struct {
GLuint textureId;
int vertexCount;
// TODO: Store draw state -> blending mode, shader
GLuint vaoId;
GLuint textureId;
GLuint shaderId;
Matrix projection;
Matrix modelview;
// TODO: Store additional draw state data
//int blendMode;
//Guint fboId;
} DrawCall;
#if defined(RLGL_OCULUS_SUPPORT)
typedef struct OculusBuffer {
ovrTextureSwapChain textureChain;
GLuint depthId;
GLuint fboId;
int width;
int height;
} OculusBuffer;
typedef struct OculusMirror {
ovrMirrorTexture texture;
GLuint fboId;
int width;
int height;
} OculusMirror;
typedef struct OculusLayer {
ovrViewScaleDesc viewScaleDesc;
ovrLayerEyeFov eyeLayer; // layer 0
//ovrLayerQuad quadLayer; // TODO: layer 1: '2D' quad for GUI
Matrix eyeProjections[2];
int width;
int height;
} OculusLayer;
#endif
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
@ -213,6 +251,17 @@ static Light lights[MAX_LIGHTS]; // Lights pool
static int lightsCount; // Counts current enabled physic objects
#endif
#if defined(RLGL_OCULUS_SUPPORT)
// OVR device variables
static ovrSession session; // Oculus session (pointer to ovrHmdStruct)
static ovrHmdDesc hmdDesc; // Oculus device descriptor parameters
static ovrGraphicsLuid luid; // Oculus locally unique identifier for the program (64 bit)
static OculusLayer layer; // Oculus drawing layer (similar to photoshop)
static OculusBuffer buffer; // Oculus internal buffers (texture chain and fbo)
static OculusMirror mirror; // Oculus mirror texture and fbo
static unsigned int frameIndex = 0; // Oculus frames counter, used to discard frames from chain
#endif
// Compressed textures support flags
static bool texCompDXTSupported = false; // DDS texture compression support
static bool npotSupported = false; // NPOT textures full support
@ -228,15 +277,14 @@ static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays;
static int blendMode = 0;
// White texture useful for plain color polys (required by shader)
// NOTE: It's required in shapes and models modules!
unsigned int whiteTexture;
static unsigned int whiteTexture;
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
static void LoadCompressedTexture(unsigned char *data, int width, int height, int mipmapCount, int compressedFormat);
static unsigned int LoadShaderProgram(char *vShaderStr, char *fShaderStr); // Load custom shader strings and return program id
static unsigned int LoadShaderProgram(">const char *vShaderStr, const char *fShaderStr); // Load custom shader strings and return program id
static Shader LoadDefaultShader(void); // Load default shader (just vertex positioning and texture coloring)
static Shader LoadStandardShader(void); // Load standard shader (support materials and lighting)
@ -254,6 +302,16 @@ static void SetShaderLights(Shader shader); // Sets shader uniform values for li
static char *ReadTextFile(const char *fileName);
#endif
#if defined(RLGL_OCULUS_SUPPORT) // Oculus Rift functions
static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height); // Load Oculus required buffers
static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer); // Unload texture required buffers
static OculusMirror LoadOculusMirror(ovrSession session, int width, int height); // Load Oculus mirror buffers
static void UnloadOculusMirror(ovrSession session, OculusMirror mirror); // Unload Oculus mirror buffers
static void BlitOculusMirror(ovrSession session, OculusMirror mirror); // Copy Oculus screen buffer to mirror texture
static OculusLayer InitOculusLayer(ovrSession session); // Init Oculus layer (similar to photoshop)
static Matrix FromOvrMatrix(ovrMatrix4f ovrM); // Convert from Oculus ovrMatrix4f struct to raymath Matrix struct
#endif
#if defined(GRAPHICS_API_OPENGL_11)
static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight);
static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight);
@ -1146,6 +1204,23 @@ void rlglInitGraphics(int offsetX, int offsetY, int width, int height)
TraceLog(INFO, "OpenGL graphic device initialized successfully");
}
// Load OpenGL extensions
// NOTE: External loader function could be passed as a pointer
void rlglLoadExtensions(void *loader)
{
#if defined(GRAPHICS_API_OPENGL_33)
// NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions
if (!gladLoadGLLoader((GLADloadproc)loader)) TraceLog(WARNING, "GLAD: Cannot load OpenGL extensions");
else TraceLog(INFO, "GLAD: OpenGL extensions loaded successfully");
if (GLAD_GL_VERSION_3_3) TraceLog(INFO, "OpenGL 3.3 Core profile supported");
else TraceLog(ERROR, "OpenGL 3.3 Core profile not supported");
// With GLAD, we can check if an extension is supported using the GLAD_GL_xxx booleans
//if (GLAD_GL_ARB_vertex_array_object) // Use GL_ARB_vertex_array_object
#endif
}
// Get world coordinates from screen coordinates
Vector3 rlglUnproject(Vector3 source, Matrix proj, Matrix view)
{
@ -1177,11 +1252,13 @@ unsigned int rlglLoadTexture(void *data, int width, int height, int textureForma
GLuint id = 0;
// Check texture format support by OpenGL 1.1 (compressed textures not supported)
if ((rlGetVersion() == OPENGL_11) && (textureFormat >= 8))
#if defined(GRAPHICS_API_OPENGL_11)
if (textureFormat >= 8)
{
TraceLog(WARNING, "OpenGL 1.1 does not support GPU compressed texture formats");
return id;
}
#endif
if ((!texCompDXTSupported) && ((textureFormat == COMPRESSED_DXT1_RGB) || (textureFormat == COMPRESSED_DXT1_RGBA) ||
(textureFormat == COMPRESSED_DXT3_RGBA) || (textureFormat == COMPRESSED_DXT5_RGBA)))
@ -1795,8 +1872,13 @@ void rlglDrawMesh(Mesh mesh, Material material, Matrix transform)
// NOTE: standard shader specific locations are got at render time to keep Shader struct as simple as possible (with just default shader locations)
if (material.shader.id == standardShader.id)
{
// Transpose and inverse model transformations matrix for fragment normal calculations
Matrix transInvTransform = transform;
MatrixTranspose(&transInvTransform);
MatrixInvert(&transInvTransform);
// Send model transformations matrix to shader
glUniformMatrix4fv(glGetUniformLocation(material.shader.id, "modelMatrix"), 1, false, MatrixToFloat(transform));
glUniformMatrix4fv(glGetUniformLocation(material.shader.id, "modelMatrix"), 1, false, MatrixToFloat(transInvTransform));
// Send view transformation matrix to shader. View matrix 8, 9 and 10 are view direction vector axis values (target - position)
glUniform3f(glGetUniformLocation(material.shader.id, "viewDir"), matView.m8, matView.m9, matView.m10);
@ -2095,6 +2177,24 @@ void *rlglReadTexturePixels(Texture2D texture)
return pixels;
}
/*
// TODO: Record draw calls to be processed in batch
// NOTE: Global state must be kept
void rlglRecordDraw(void)
{
// TODO: Before adding a new draw, check if anything changed from last stored draw
#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
draws[drawsCounter].vaoId = currentState.vaoId; // lines.id, trangles.id, quads.id?
draws[drawsCounter].textureId = currentState.textureId; // whiteTexture?
draws[drawsCounter].shaderId = currentState.shaderId; // defaultShader.id
draws[drawsCounter].projection = projection;
draws[drawsCounter].modelview = modelview;
draws[drawsCounter].vertexCount = currentState.vertexCount;
drawsCounter++;
#endif
}
*/
//----------------------------------------------------------------------------------
// Module Functions Definition - Shaders Functions
@ -2361,6 +2461,130 @@ void DestroyLight(Light light)
#endif
}
#if defined(RLGL_OCULUS_SUPPORT)
// Init Oculus Rift device
// NOTE: Device initialization should be done before window creation?
void InitOculusDevice(void)
{
// Initialize Oculus device
ovrResult result = ovr_Initialize(NULL);
if (OVR_FAILURE(result)) TraceLog(WARNING, "OVR: Could not initialize Oculus device");
result = ovr_Create(&session, &luid);
if (OVR_FAILURE(result))
{
TraceLog(WARNING, "OVR: Could not create Oculus session");
ovr_Shutdown();
}
hmdDesc = ovr_GetHmdDesc(session);
TraceLog(INFO, "OVR: Product Name: %s", hmdDesc.ProductName);
TraceLog(INFO, "OVR: Manufacturer: %s", hmdDesc.Manufacturer);
TraceLog(INFO, "OVR: Product ID: %i", hmdDesc.ProductId);
TraceLog(INFO, "OVR: Product Type: %i", hmdDesc.Type);
//TraceLog(INFO, "OVR: Serial Number: %s", hmdDesc.SerialNumber);
TraceLog(INFO, "OVR: Resolution: %ix%i", hmdDesc.Resolution.w, hmdDesc.Resolution.h);
// NOTE: Oculus mirror is set to defined screenWidth and screenHeight...
// ...ideally, it should be (hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2)
// Initialize Oculus Buffers
layer = InitOculusLayer(session);
buffer = LoadOculusBuffer(session, layer.width, layer.height);
mirror = LoadOculusMirror(session, hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2); // NOTE: hardcoded...
layer.eyeLayer.ColorTexture[0] = buffer.textureChain; //SetOculusLayerTexture(eyeLayer, buffer.textureChain);
// Recenter OVR tracking origin
ovr_RecenterTrackingOrigin(session);
}
// Close Oculus Rift device
void CloseOculusDevice(void)
{
UnloadOculusMirror(session, mirror); // Unload Oculus mirror buffer
UnloadOculusBuffer(session, buffer); // Unload Oculus texture buffers
ovr_Destroy(session); // Free Oculus session data
ovr_Shutdown(); // Close Oculus device connection
}
// Update Oculus Rift tracking (position and orientation)
void UpdateOculusTracking(void)
{
frameIndex++;
ovrPosef eyePoses[2];
ovr_GetEyePoses(session, frameIndex, ovrTrue, layer.viewScaleDesc.HmdToEyeOffset, eyePoses, &layer.eyeLayer.SensorSampleTime);
layer.eyeLayer.RenderPose[0] = eyePoses[0];
layer.eyeLayer.RenderPose[1] = eyePoses[1];
}
void SetOculusMatrix(int eye)
{
rlViewport(layer.eyeLayer.Viewport[eye].Pos.x, layer.eyeLayer.Viewport[eye].Pos.y, layer.eyeLayer.Viewport[eye].Size.w, layer.eyeLayer.Viewport[eye].Size.h);
Quaternion eyeRPose = (Quaternion){ layer.eyeLayer.RenderPose[eye].Orientation.x,
layer.eyeLayer.RenderPose[eye].Orientation.y,
layer.eyeLayer.RenderPose[eye].Orientation.z,
layer.eyeLayer.RenderPose[eye].Orientation.w };
QuaternionInvert(&eyeRPose);
Matrix eyeOrientation = QuaternionToMatrix(eyeRPose);
Matrix eyeTranslation = MatrixTranslate(-layer.eyeLayer.RenderPose[eye].Position.x,
-layer.eyeLayer.RenderPose[eye].Position.y,
-layer.eyeLayer.RenderPose[eye].Position.z);
Matrix eyeView = MatrixMultiply(eyeTranslation, eyeOrientation);
Matrix modelEyeView = MatrixMultiply(modelview, eyeView); // Using internal camera modelview matrix
SetMatrixModelview(modelEyeView);
SetMatrixProjection(layer.eyeProjections[eye]);
}
void BeginOculusDrawing(void)
{
GLuint currentTexId;
int currentIndex;
ovr_GetTextureSwapChainCurrentIndex(session, buffer.textureChain, &currentIndex);
ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, currentIndex, &currentTexId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, currentTexId, 0);
//glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, buffer.depthId, 0); // Already binded
//glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye)
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Same as rlClearScreenBuffers()
// NOTE: If your application is configured to treat the texture as a linear format (e.g. GL_RGBA)
// and performs linear-to-gamma conversion in GLSL or does not care about gamma-correction, then:
// - Require OculusBuffer format to be OVR_FORMAT_R8G8B8A8_UNORM_SRGB
// - Do NOT enable GL_FRAMEBUFFER_SRGB
//glEnable(GL_FRAMEBUFFER_SRGB);
}
void EndOculusDrawing(void)
{
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
ovr_CommitTextureSwapChain(session, buffer.textureChain);
ovrLayerHeader *layers = &layer.eyeLayer.Header;
ovr_SubmitFrame(session, frameIndex, &layer.viewScaleDesc, &layers, 1);
// Blit mirror texture to back buffer
BlitOculusMirror(session, mirror);
// Get session status information
ovrSessionStatus sessionStatus;
ovr_GetSessionStatus(session, &sessionStatus);
if (sessionStatus.ShouldQuit) TraceLog(WARNING, "OVR: Session should quit...");
if (sessionStatus.ShouldRecenter) ovr_RecenterTrackingOrigin(session);
}
#endif
//----------------------------------------------------------------------------------
// Module specific Functions Definition
//----------------------------------------------------------------------------------
@ -2403,7 +2627,7 @@ static void LoadCompressedTexture(unsigned char *data, int width, int height, in
}
// Load custom shader strings and return program id
static unsigned int LoadShaderProgram(char *vShaderStr, char *fShaderStr)
static unsigned int LoadShaderProgram(">const char *vShaderStr, const char *fShaderStr)
{
unsigned int program = 0;
@ -3341,6 +3565,187 @@ static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight)
}
#endif
#if defined(RLGL_OCULUS_SUPPORT)
// Load Oculus required buffers: texture-swap-chain, fbo, texture-depth
static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height)
{
OculusBuffer buffer;
buffer.width = width;
buffer.height = height;
// Create OVR texture chain
ovrTextureSwapChainDesc desc = {};
desc.Type = ovrTexture_2D;
desc.ArraySize = 1;
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; // Requires glEnable(GL_FRAMEBUFFER_SRGB);
desc.SampleCount = 1;
desc.StaticImage = ovrFalse;
ovrResult result = ovr_CreateTextureSwapChainGL(session, &desc, &buffer.textureChain);
if (!OVR_SUCCESS(result)) TraceLog(WARNING, "OVR: Failed to create swap textures buffer");
int textureCount = 0;
ovr_GetTextureSwapChainLength(session, buffer.textureChain, &textureCount);
if (!OVR_SUCCESS(result) || !textureCount) TraceLog(WARNING, "OVR: Unable to count swap chain textures");
for (int i = 0; i < textureCount; ++i)
{
GLuint chainTexId;
ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, i, &chainTexId);
glBindTexture(GL_TEXTURE_2D, chainTexId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
glBindTexture(GL_TEXTURE_2D, 0);
/*
// Setup framebuffer object (using depth texture)
glGenFramebuffers(1, &buffer.fboId);
glGenTextures(1, &buffer.depthId);
glBindTexture(GL_TEXTURE_2D, buffer.depthId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, buffer.width, buffer.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
*/
// Setup framebuffer object (using depth renderbuffer)
glGenFramebuffers(1, &buffer.fboId);
glGenRenderbuffers(1, &buffer.depthId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId);
glBindRenderbuffer(GL_RENDERBUFFER, buffer.depthId);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, buffer.width, buffer.height);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, buffer.depthId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
return buffer;
}
// Unload texture required buffers
static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer)
{
if (buffer.textureChain)
{
ovr_DestroyTextureSwapChain(session, buffer.textureChain);
buffer.textureChain = NULL;
}
if (buffer.depthId != 0) glDeleteTextures(1, &buffer.depthId);
if (buffer.fboId != 0) glDeleteFramebuffers(1, &buffer.fboId);
}
// Load Oculus mirror buffers
static OculusMirror LoadOculusMirror(ovrSession session, int width, int height)
{
OculusMirror mirror;
mirror.width = width;
mirror.height = height;
ovrMirrorTextureDesc mirrorDesc;
memset(&mirrorDesc, 0, sizeof(mirrorDesc));
mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
mirrorDesc.Width = mirror.width;
mirrorDesc.Height = mirror.height;
if (!OVR_SUCCESS(ovr_CreateMirrorTextureGL(session, &mirrorDesc, &mirror.texture))) TraceLog(WARNING, "Could not create mirror texture");
glGenFramebuffers(1, &mirror.fboId);
return mirror;
}
// Unload Oculus mirror buffers
static void UnloadOculusMirror(ovrSession session, OculusMirror mirror)
{
if (mirror.fboId != 0) glDeleteFramebuffers(1, &mirror.fboId);
if (mirror.texture) ovr_DestroyMirrorTexture(session, mirror.texture);
}
// Copy Oculus screen buffer to mirror texture
static void BlitOculusMirror(ovrSession session, OculusMirror mirror)
{
GLuint mirrorTextureId;
ovr_GetMirrorTextureBufferGL(session, mirror.texture, &mirrorTextureId);
glBindFramebuffer(GL_READ_FRAMEBUFFER, mirror.fboId);
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mirrorTextureId, 0);
glBlitFramebuffer(0, 0, mirror.width, mirror.height, 0, mirror.height, mirror.width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
// Init Oculus layer (similar to photoshop)
static OculusLayer InitOculusLayer(ovrSession session)
{
OculusLayer layer = { 0 };
layer.viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.0f;
memset(&layer.eyeLayer, 0, sizeof(ovrLayerEyeFov));
layer.eyeLayer.Header.Type = ovrLayerType_EyeFov;
layer.eyeLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft;
ovrEyeRenderDesc eyeRenderDescs[2];
for (int eye = 0; eye < 2; eye++)
{
eyeRenderDescs[eye] = ovr_GetRenderDesc(session, eye, hmdDesc.DefaultEyeFov[eye]);
ovrMatrix4f ovrPerspectiveProjection = ovrMatrix4f_Projection(eyeRenderDescs[eye].Fov, 0.01f, 10000.0f, ovrProjection_None); //ovrProjection_ClipRangeOpenGL);
layer.eyeProjections[eye] = FromOvrMatrix(ovrPerspectiveProjection); // NOTE: struct ovrMatrix4f { float M[4][4] } --> struct Matrix
layer.viewScaleDesc.HmdToEyeOffset[eye] = eyeRenderDescs[eye].HmdToEyeOffset;
layer.eyeLayer.Fov[eye] = eyeRenderDescs[eye].Fov;
ovrSizei eyeSize = ovr_GetFovTextureSize(session, eye, layer.eyeLayer.Fov[eye], 1.0f);
layer.eyeLayer.Viewport[eye].Size = eyeSize;
layer.eyeLayer.Viewport[eye].Pos.x = layer.width;
layer.eyeLayer.Viewport[eye].Pos.y = 0;
layer.height = eyeSize.h; //std::max(renderTargetSize.y, (uint32_t)eyeSize.h);
layer.width += eyeSize.w;
}
return layer;
}
// Convert from Oculus ovrMatrix4f struct to raymath Matrix struct
static Matrix FromOvrMatrix(ovrMatrix4f ovrmat)
{
Matrix rmat;
rmat.m0 = ovrmat.M[0][0];
rmat.m1 = ovrmat.M[1][0];
rmat.m2 = ovrmat.M[2][0];
rmat.m3 = ovrmat.M[3][0];
rmat.m4 = ovrmat.M[0][1];
rmat.m5 = ovrmat.M[1][1];
rmat.m6 = ovrmat.M[2][1];
rmat.m7 = ovrmat.M[3][1];
rmat.m8 = ovrmat.M[0][2];
rmat.m9 = ovrmat.M[1][2];
rmat.m10 = ovrmat.M[2][2];
rmat.m11 = ovrmat.M[3][2];
rmat.m12 = ovrmat.M[0][3];
rmat.m13 = ovrmat.M[1][3];
rmat.m14 = ovrmat.M[2][3];
rmat.m15 = ovrmat.M[3][3];
MatrixTranspose(&rmat);
return rmat;
}
#endif
#if defined(RLGL_STANDALONE)
// Output a trace log message
// NOTE: Expected msgType: (0)Info, (1)Error, (2)Warning

+ 11
- 1
examples/oculus_glfw_sample/rlgl.h 查看文件

@ -48,7 +48,7 @@
// Choose opengl version here or just define it at compile time: -DGRAPHICS_API_OPENGL_33
//#define GRAPHICS_API_OPENGL_11 // Only available on PLATFORM_DESKTOP
//#define GRAPHICS_API_OPENGL_33 // Only available on PLATFORM_DESKTOP
//#define GRAPHICS_API_OPENGL_33 // Only available on PLATFORM_DESKTOP or Oculus Rift CV1
//#define GRAPHICS_API_OPENGL_ES2 // Only available on PLATFORM_ANDROID or PLATFORM_RPI or PLATFORM_WEB
// Security check in case no GRAPHICS_API_OPENGL_* defined
@ -296,6 +296,7 @@ void rlglInit(void); // Initialize rlgl (shaders, VAO
void rlglClose(void); // De-init rlgl
void rlglDraw(void); // Draw VAO/VBO
void rlglInitGraphics(int offsetX, int offsetY, int width, int height); // Initialize Graphics (OpenGL stuff)
void rlglLoadExtensions(void *loader); // Load OpenGL extensions
unsigned int rlglLoadTexture(void *data, int width, int height, int textureFormat, int mipmapCount); // Load texture in GPU
RenderTexture2D rlglLoadRenderTexture(int width, int height); // Load a texture to be used for rendering (fbo with color and depth attachments)
@ -346,6 +347,15 @@ void DestroyLight(Light light); // Destroy a
void TraceLog(int msgType, const char *text, ...);
#endif
#if defined(RLGL_OCULUS_SUPPORT)
void InitOculusDevice(void); // Init Oculus Rift device
void CloseOculusDevice(void); // Close Oculus Rift device
void UpdateOculusTracking(void); // Update Oculus Rift tracking (position and orientation)
void SetOculusMatrix(int eye); // Set internal projection and modelview matrix depending on eyes tracking data
void BeginOculusDrawing(void); // Begin Oculus drawing configuration
void EndOculusDrawing(void); // End Oculus drawing process (and desktop mirror)
#endif
#ifdef __cplusplus
}
#endif

+ 27
- 19
examples/oculus_glfw_sample/standard_shader.h 查看文件

@ -1,6 +1,6 @@
// Vertex shader definition to embed, no external file required
const static unsigned char vStandardShaderStr[] =
static const char vStandardShaderStr[] =
#if defined(GRAPHICS_API_OPENGL_21)
"#version 120 \n"
#elif defined(GRAPHICS_API_OPENGL_ES2)
@ -37,7 +37,7 @@ const static unsigned char vStandardShaderStr[] =
"} \n";
// Fragment shader definition to embed, no external file required
const static unsigned char fStandardShaderStr[] =
static const char fStandardShaderStr[] =
#if defined(GRAPHICS_API_OPENGL_21)
"#version 120 \n"
#elif defined(GRAPHICS_API_OPENGL_ES2)
@ -85,13 +85,13 @@ const static unsigned char fStandardShaderStr[] =
"{\n"
" vec3 surfacePos = vec3(modelMatrix*vec4(fragPosition, 1));\n"
" vec3 surfaceToLight = l.position - surfacePos;\n"
" float brightness = clamp(dot(n, surfaceToLight)/(length(surfaceToLight)*length(n)), 0, 1);\n"
" float brightness = clamp(float(dot(n, surfaceToLight)/(length(surfaceToLight)*length(n))), 0.0, 1.0);\n"
" float diff = 1.0/dot(surfaceToLight/l.radius, surfaceToLight/l.radius)*brightness*l.intensity;\n"
" float spec = 0.0;\n"
" if (diff > 0.0)\n"
" {\n"
" vec3 h = normalize(-l.direction + v);\n"
" spec = pow(dot(n, h), 3 + glossiness)*s;\n"
" spec = pow(dot(n, h), 3.0 + glossiness)*s;\n"
" }\n"
" return (diff*l.diffuse.rgb + spec*colSpecular.rgb);\n"
"}\n"
@ -99,23 +99,23 @@ const static unsigned char fStandardShaderStr[] =
"vec3 CalcDirectionalLight(Light l, vec3 n, vec3 v, float s)\n"
"{\n"
" vec3 lightDir = normalize(-l.direction);\n"
" float diff = clamp(dot(n, lightDir), 0.0, 1.0)*l.intensity;\n"
" float diff = clamp(float(dot(n, lightDir)), 0.0, 1.0)*l.intensity;\n"
" float spec = 0.0;\n"
" if (diff > 0.0)\n"
" {\n"
" vec3 h = normalize(lightDir + v);\n"
" spec = pow(dot(n, h), 3 + glossiness)*s;\n"
" spec = pow(dot(n, h), 3.0 + glossiness)*s;\n"
" }\n"
" return (diff*l.intensity*l.diffuse.rgb + spec*colSpecular.rgb);\n"
"}\n"
"\n"
"vec3 CalcSpotLight(Light l, vec3 n, vec3 v, float s)\n"
"{\n"
" vec3 surfacePos = vec3(modelMatrix*vec4(fragPosition, 1));\n"
" vec3 surfacePos = vec3(modelMatrix*vec4(fragPosition, 1.0));\n"
" vec3 lightToSurface = normalize(surfacePos - l.position);\n"
" vec3 lightDir = normalize(-l.direction);\n"
" float diff = clamp(dot(n, lightDir), 0.0, 1.0)*l.intensity;\n"
" float attenuation = clamp(dot(n, lightToSurface), 0.0, 1.0);\n"
" float diff = clamp(float(dot(n, lightDir)), 0.0, 1.0)*l.intensity;\n"
" float attenuation = clamp(float(dot(n, lightToSurface)), 0.0, 1.0);\n"
" attenuation = dot(lightToSurface, -lightDir);\n"
" float lightToSurfaceAngle = degrees(acos(attenuation));\n"
" if (lightToSurfaceAngle > l.coneAngle) attenuation = 0.0;\n"
@ -125,37 +125,45 @@ const static unsigned char fStandardShaderStr[] =
" if (diffAttenuation > 0.0)\n"
" {\n"
" vec3 h = normalize(lightDir + v);\n"
" spec = pow(dot(n, h), 3 + glossiness)*s;\n"
" spec = pow(dot(n, h), 3.0 + glossiness)*s;\n"
" }\n"
" return (falloff*(diffAttenuation*l.diffuse.rgb + spec*colSpecular.rgb));\n"
"}\n"
"\n"
"void main()\n"
"{\n"
" mat3 normalMatrix = transpose(inverse(mat3(modelMatrix)));\n"
" mat3 normalMatrix = mat3(modelMatrix);\n"
" vec3 normal = normalize(normalMatrix*fragNormal);\n"
" vec3 n = normalize(normal);\n"
" vec3 v = normalize(viewDir);\n"
#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21)
" vec4 texelColor = texture2D(texture0, fragTexCoord);\n"
#elif defined(GRAPHICS_API_OPENGL_33)
" vec4 texelColor = texture(texture0, fragTexCoord);\n"
#endif
" vec3 lighting = colAmbient.rgb;\n"
" if (useNormal == 1)\n"
" {\n"
#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21)
" n *= texture2D(texture1, fragTexCoord).rgb;\n"
#elif defined(GRAPHICS_API_OPENGL_33)
" n *= texture(texture1, fragTexCoord).rgb;\n"
#endif
" n = normalize(n);\n"
" }\n"
" float spec = 1.0;\n"
#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21)
" if (useSpecular == 1) spec *= normalize(texture2D(texture2, fragTexCoord).r);\n"
#elif defined(GRAPHICS_API_OPENGL_33)
" if (useSpecular == 1) spec *= normalize(texture(texture2, fragTexCoord).r);\n"
#endif
" for (int i = 0; i < lightsCount; i++)\n"
" {\n"
" if (lights[i].enabled == 1)\n"
" {\n"
" switch (lights[i].type)\n"
" {\n"
" case 0: lighting += CalcPointLight(lights[i], n, v, spec); break;\n"
" case 1: lighting += CalcDirectionalLight(lights[i], n, v, spec); break;\n"
" case 2: lighting += CalcSpotLight(lights[i], n, v, spec); break;\n"
" default: break;\n"
" }\n"
" if(lights[i].type == 0) lighting += CalcPointLight(lights[i], n, v, spec);\n"
" else if(lights[i].type == 1) lighting += CalcDirectionalLight(lights[i], n, v, spec);\n"
" else if(lights[i].type == 2) lighting += CalcSpotLight(lights[i], n, v, spec);\n"
" }\n"
" }\n"
#if defined(GRAPHICS_API_OPENGL_33)
@ -163,4 +171,4 @@ const static unsigned char fStandardShaderStr[] =
#elif defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21)
" gl_FragColor = vec4(texelColor.rgb*lighting*colDiffuse.rgb, texelColor.a*colDiffuse.a); \n"
#endif
"} \n";
"}\n";

+ 8
- 398
src/core.c 查看文件

@ -9,7 +9,7 @@
* PLATFORM_ANDROID - Only OpenGL ES 2.0 devices
* PLATFORM_RPI - Rapsberry Pi (tested on Raspbian)
* PLATFORM_WEB - Emscripten, HTML5
* PLATFORM_OCULUS - Oculus Rift CV1 (with desktop mirror)
* Oculus Rift CV1 (with desktop mirror) - View [rlgl] module to enable it
*
* On PLATFORM_DESKTOP, the external lib GLFW3 (www.glfw.com) is used to manage graphic
* device, OpenGL context and input on multiple operating systems (Windows, Linux, OSX).
@ -54,18 +54,6 @@
#include <string.h> // String function definitions, memset()
#include <errno.h> // Macros for reporting and retrieving error conditions through error codes
#if defined(PLATFORM_OCULUS)
#define PLATFORM_DESKTOP // Enable PLATFORM_DESKTOP code-base
#endif
#if defined(PLATFORM_DESKTOP)
#include "external/glad.h" // GLAD library: Manage OpenGL headers and extensions
#endif
#if defined(PLATFORM_OCULUS)
#include "../examples/oculus_glfw_sample/OculusSDK/LibOVR/Include/OVR_CAPI_GL.h" // Oculus SDK for OpenGL
#endif
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
//#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3
#include <GLFW/glfw3.h> // GLFW3 library: Windows, OpenGL context and Input management
@ -138,31 +126,7 @@
//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
#if defined(PLATFORM_OCULUS)
typedef struct OculusBuffer {
ovrTextureSwapChain textureChain;
GLuint depthId;
GLuint fboId;
int width;
int height;
} OculusBuffer;
typedef struct OculusMirror {
ovrMirrorTexture texture;
GLuint fboId;
int width;
int height;
} OculusMirror;
typedef struct OculusLayer {
ovrViewScaleDesc viewScaleDesc;
ovrLayerEyeFov eyeLayer; // layer 0
//ovrLayerQuad quadLayer; // TODO: layer 1: '2D' quad for GUI
Matrix eyeProjections[2];
int width;
int height;
} OculusLayer;
#endif
// ...
//----------------------------------------------------------------------------------
// Global Variables Definition
@ -217,17 +181,6 @@ static uint64_t baseTime; // Base time measure for hi-res timer
static bool windowShouldClose = false; // Flag to set window for closing
#endif
#if defined(PLATFORM_OCULUS)
// OVR device variables
static ovrSession session; // Oculus session (pointer to ovrHmdStruct)
static ovrHmdDesc hmdDesc; // Oculus device descriptor parameters
static ovrGraphicsLuid luid; // Oculus locally unique identifier for the program (64 bit)
static OculusLayer layer; // Oculus drawing layer (similar to photoshop)
static OculusBuffer buffer; // Oculus internal buffers (texture chain and fbo)
static OculusMirror mirror; // Oculus mirror texture and fbo
static unsigned int frameIndex = 0; // Oculus frames counter, used to discard frames from chain
#endif
static unsigned int displayWidth, displayHeight; // Display width and height (monitor, device-screen, LCD, ...)
static int screenWidth, screenHeight; // Screen width and height (used render area)
static int renderWidth, renderHeight; // Framebuffer width and height (render area)
@ -237,7 +190,6 @@ static int renderOffsetX = 0; // Offset X from render area (must b
static int renderOffsetY = 0; // Offset Y from render area (must be divided by 2)
static bool fullscreen = false; // Fullscreen mode (useful only for PLATFORM_DESKTOP)
static Matrix downscaleView; // Matrix to downscale view (in case screen size bigger than display size)
static Matrix cameraView; // Store camera view matrix (required for Oculus Rift)
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB)
static const char *windowTitle; // Window text title...
@ -336,19 +288,6 @@ static void InitGamepad(void); // Init raw gamepad inpu
static void *GamepadThread(void *arg); // Mouse reading thread
#endif
#if defined(PLATFORM_OCULUS)
// Oculus Rift functions
static Matrix FromOvrMatrix(ovrMatrix4f ovrM);
static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height);
static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer);
static void SetOculusBuffer(ovrSession session, OculusBuffer buffer);
static void UnsetOculusBuffer(OculusBuffer buffer);
static OculusMirror LoadOculusMirror(ovrSession session, int width, int height); // Load Oculus mirror buffers
static void UnloadOculusMirror(ovrSession session, OculusMirror mirror); // Unload Oculus mirror buffers
static void BlitOculusMirror(ovrSession session, OculusMirror mirror);
static OculusLayer InitOculusLayer(ovrSession session);
#endif
//----------------------------------------------------------------------------------
// Module Functions Definition - Window and OpenGL Context Functions
//----------------------------------------------------------------------------------
@ -397,11 +336,6 @@ void InitWindow(int width, int height, const char *title)
//emscripten_set_gamepaddisconnected_callback(NULL, 1, EmscriptenInputCallback);
#endif
#if defined(PLATFORM_OCULUS)
// Recenter OVR tracking origin
ovr_RecenterTrackingOrigin(session);
#endif
mousePosition.x = (float)screenWidth/2.0f;
mousePosition.y = (float)screenHeight/2.0f;
@ -516,64 +450,6 @@ void CloseWindow(void)
TraceLog(INFO, "Window closed successfully");
}
#if defined(PLATFORM_OCULUS)
// Init Oculus Rift device
// NOTE: Device initialization should be done before window creation?
void InitOculusDevice(void)
{
// Initialize Oculus device
ovrResult result = ovr_Initialize(NULL);
if (OVR_FAILURE(result)) TraceLog(WARNING, "OVR: Could not initialize Oculus device");
result = ovr_Create(&session, &luid);
if (OVR_FAILURE(result))
{
TraceLog(WARNING, "OVR: Could not create Oculus session");
ovr_Shutdown();
}
hmdDesc = ovr_GetHmdDesc(session);
TraceLog(INFO, "OVR: Product Name: %s", hmdDesc.ProductName);
TraceLog(INFO, "OVR: Manufacturer: %s", hmdDesc.Manufacturer);
TraceLog(INFO, "OVR: Product ID: %i", hmdDesc.ProductId);
TraceLog(INFO, "OVR: Product Type: %i", hmdDesc.Type);
//TraceLog(INFO, "OVR: Serial Number: %s", hmdDesc.SerialNumber);
TraceLog(INFO, "OVR: Resolution: %ix%i", hmdDesc.Resolution.w, hmdDesc.Resolution.h);
// NOTE: Oculus mirror is set to defined screenWidth and screenHeight...
// ...ideally, it should be (hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2)
// Initialize Oculus Buffers
layer = InitOculusLayer(session);
buffer = LoadOculusBuffer(session, layer.width, layer.height);
mirror = LoadOculusMirror(session, screenWidth, screenHeight);
layer.eyeLayer.ColorTexture[0] = buffer.textureChain; //SetOculusLayerTexture(eyeLayer, buffer.textureChain);
}
// Close Oculus Rift device
void CloseOculusDevice(void)
{
UnloadOculusMirror(session, mirror); // Unload Oculus mirror buffer
UnloadOculusBuffer(session, buffer); // Unload Oculus texture buffers
ovr_Destroy(session); // Free Oculus session data
ovr_Shutdown(); // Close Oculus device connection
}
// Update Oculus Rift tracking (position and orientation)
void UpdateOculusTracking(void)
{
frameIndex++;
ovrPosef eyePoses[2];
ovr_GetEyePoses(session, frameIndex, ovrTrue, layer.viewScaleDesc.HmdToEyeOffset, eyePoses, &layer.eyeLayer.SensorSampleTime);
layer.eyeLayer.RenderPose[0] = eyePoses[0];
layer.eyeLayer.RenderPose[1] = eyePoses[1];
}
#endif
// Detect if KEY_ESCAPE pressed or Close icon pressed
bool WindowShouldClose(void)
{
@ -642,10 +518,6 @@ void BeginDrawing(void)
currentTime = GetTime(); // Number of elapsed seconds since InitTimer() was called
updateTime = currentTime - previousTime;
previousTime = currentTime;
#if defined(PLATFORM_OCULUS)
SetOculusBuffer(session, buffer);
#endif
rlClearScreenBuffers(); // Clear current framebuffers
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
@ -658,49 +530,7 @@ void BeginDrawing(void)
// End canvas drawing and Swap Buffers (Double Buffering)
void EndDrawing(void)
{
#if defined(PLATFORM_OCULUS)
for (int eye = 0; eye < 2; eye++)
{
rlViewport(layer.eyeLayer.Viewport[eye].Pos.x, layer.eyeLayer.Viewport[eye].Pos.y, layer.eyeLayer.Viewport[eye].Size.w, layer.eyeLayer.Viewport[eye].Size.h);
Quaternion eyeRPose = (Quaternion){ layer.eyeLayer.RenderPose[eye].Orientation.x,
layer.eyeLayer.RenderPose[eye].Orientation.y,
layer.eyeLayer.RenderPose[eye].Orientation.z,
layer.eyeLayer.RenderPose[eye].Orientation.w };
QuaternionInvert(&eyeRPose);
Matrix eyeOrientation = QuaternionToMatrix(eyeRPose);
Matrix eyeTranslation = MatrixTranslate(-layer.eyeLayer.RenderPose[eye].Position.x,
-layer.eyeLayer.RenderPose[eye].Position.y,
-layer.eyeLayer.RenderPose[eye].Position.z);
Matrix eyeView = MatrixMultiply(eyeTranslation, eyeOrientation);
Matrix modelEyeView = MatrixMultiply(cameraView, eyeView); // Using internal camera modelview matrix
SetMatrixModelview(modelEyeView);
SetMatrixProjection(layer.eyeProjections[eye]);
#endif
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
#if defined(PLATFORM_OCULUS)
}
UnsetOculusBuffer(buffer);
ovr_CommitTextureSwapChain(session, buffer.textureChain);
ovrLayerHeader *layers = &layer.eyeLayer.Header;
ovr_SubmitFrame(session, frameIndex, &layer.viewScaleDesc, &layers, 1);
// Blit mirror texture to back buffer
BlitOculusMirror(session, mirror);
// Get session status information
ovrSessionStatus sessionStatus;
ovr_GetSessionStatus(session, &sessionStatus);
if (sessionStatus.ShouldQuit) TraceLog(WARNING, "OVR: Session should quit...");
if (sessionStatus.ShouldRecenter) ovr_RecenterTrackingOrigin(session);
#endif
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
SwapBuffers(); // Copy back buffer to front buffer
PollInputEvents(); // Poll user events
@ -772,7 +602,7 @@ void Begin3dMode(Camera camera)
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
// Setup Camera view
cameraView = MatrixLookAt(camera.position, camera.target, camera.up);
Matrix cameraView = MatrixLookAt(camera.position, camera.target, camera.up);
rlMultMatrixf(MatrixToFloat(cameraView)); // Multiply MODELVIEW matrix by view matrix (camera)
rlEnableDepthTest(); // Enable DEPTH_TEST for 3D
@ -1742,24 +1572,12 @@ static void InitDisplay(int width, int height)
#endif
glfwMakeContextCurrent(window);
#if defined(PLATFORM_OCULUS)
glfwSwapInterval(0);
#endif
glfwSwapInterval(0); // Disable VSync by default
#if defined(PLATFORM_DESKTOP)
// Load OpenGL 3.3 extensions using GLAD
if (rlGetVersion() == OPENGL_33)
{
// NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) TraceLog(WARNING, "GLAD: Cannot load OpenGL extensions");
else TraceLog(INFO, "GLAD: OpenGL extensions loaded successfully");
if (GLAD_GL_VERSION_3_3) TraceLog(INFO, "OpenGL 3.3 Core profile supported");
else TraceLog(ERROR, "OpenGL 3.3 Core profile not supported");
// With GLAD, we can check if an extension is supported using the GLAD_GL_xxx booleans
//if (GLAD_GL_ARB_vertex_array_object) // Use GL_ARB_vertex_array_object
}
// Load OpenGL 3.3 extensions
// NOTE: GLFW loader function is passed as parameter
rlglLoadExtensions(glfwGetProcAddress);
#endif
// Enables GPU v-sync, so frames are not limited to screen refresh rate (60Hz -> 60 FPS)
@ -2954,214 +2772,6 @@ static void *GamepadThread(void *arg)
}
#endif
#if defined(PLATFORM_OCULUS)
// Convert from Oculus ovrMatrix4f struct to raymath Matrix struct
static Matrix FromOvrMatrix(ovrMatrix4f ovrmat)
{
Matrix rmat;
rmat.m0 = ovrmat.M[0][0];
rmat.m1 = ovrmat.M[1][0];
rmat.m2 = ovrmat.M[2][0];
rmat.m3 = ovrmat.M[3][0];
rmat.m4 = ovrmat.M[0][1];
rmat.m5 = ovrmat.M[1][1];
rmat.m6 = ovrmat.M[2][1];
rmat.m7 = ovrmat.M[3][1];
rmat.m8 = ovrmat.M[0][2];
rmat.m9 = ovrmat.M[1][2];
rmat.m10 = ovrmat.M[2][2];
rmat.m11 = ovrmat.M[3][2];
rmat.m12 = ovrmat.M[0][3];
rmat.m13 = ovrmat.M[1][3];
rmat.m14 = ovrmat.M[2][3];
rmat.m15 = ovrmat.M[3][3];
MatrixTranspose(&rmat);
return rmat;
}
// Load Oculus required buffers: texture-swap-chain, fbo, texture-depth
static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height)
{
OculusBuffer buffer;
buffer.width = width;
buffer.height = height;
// Create OVR texture chain
ovrTextureSwapChainDesc desc = {};
desc.Type = ovrTexture_2D;
desc.ArraySize = 1;
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; // Requires glEnable(GL_FRAMEBUFFER_SRGB);
desc.SampleCount = 1;
desc.StaticImage = ovrFalse;
ovrResult result = ovr_CreateTextureSwapChainGL(session, &desc, &buffer.textureChain);
if (!OVR_SUCCESS(result)) TraceLog(WARNING, "OVR: Failed to create swap textures buffer");
int textureCount = 0;
ovr_GetTextureSwapChainLength(session, buffer.textureChain, &textureCount);
if (!OVR_SUCCESS(result) || !textureCount) TraceLog(WARNING, "OVR: Unable to count swap chain textures");
for (int i = 0; i < textureCount; ++i)
{
GLuint chainTexId;
ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, i, &chainTexId);
glBindTexture(GL_TEXTURE_2D, chainTexId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
glBindTexture(GL_TEXTURE_2D, 0);
/*
// Setup framebuffer object (using depth texture)
glGenFramebuffers(1, &buffer.fboId);
glGenTextures(1, &buffer.depthId);
glBindTexture(GL_TEXTURE_2D, buffer.depthId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, buffer.width, buffer.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
*/
// Setup framebuffer object (using depth renderbuffer)
glGenFramebuffers(1, &buffer.fboId);
glGenRenderbuffers(1, &buffer.depthId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId);
glBindRenderbuffer(GL_RENDERBUFFER, buffer.depthId);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, buffer.width, buffer.height);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, buffer.depthId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
return buffer;
}
// Unload texture required buffers
static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer)
{
if (buffer.textureChain)
{
ovr_DestroyTextureSwapChain(session, buffer.textureChain);
buffer.textureChain = NULL;
}
if (buffer.depthId != 0) glDeleteTextures(1, &buffer.depthId);
if (buffer.fboId != 0) glDeleteFramebuffers(1, &buffer.fboId);
}
// Set current Oculus buffer
static void SetOculusBuffer(ovrSession session, OculusBuffer buffer)
{
GLuint currentTexId;
int currentIndex;
ovr_GetTextureSwapChainCurrentIndex(session, buffer.textureChain, &currentIndex);
ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, currentIndex, &currentTexId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, currentTexId, 0);
//glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, buffer.depthId, 0); // Already binded
//glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye)
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Required if OculusBuffer format is OVR_FORMAT_R8G8B8A8_UNORM_SRGB
glEnable(GL_FRAMEBUFFER_SRGB);
}
// Unset Oculus buffer
static void UnsetOculusBuffer(OculusBuffer buffer)
{
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
// Load Oculus mirror buffers
static OculusMirror LoadOculusMirror(ovrSession session, int width, int height)
{
OculusMirror mirror;
mirror.width = width;
mirror.height = height;
ovrMirrorTextureDesc mirrorDesc;
memset(&mirrorDesc, 0, sizeof(mirrorDesc));
mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
mirrorDesc.Width = mirror.width;
mirrorDesc.Height = mirror.height;
if (!OVR_SUCCESS(ovr_CreateMirrorTextureGL(session, &mirrorDesc, &mirror.texture))) TraceLog(WARNING, "Could not create mirror texture");
glGenFramebuffers(1, &mirror.fboId);
return mirror;
}
// Unload Oculus mirror buffers
static void UnloadOculusMirror(ovrSession session, OculusMirror mirror)
{
if (mirror.fboId != 0) glDeleteFramebuffers(1, &mirror.fboId);
if (mirror.texture) ovr_DestroyMirrorTexture(session, mirror.texture);
}
static void BlitOculusMirror(ovrSession session, OculusMirror mirror)
{
GLuint mirrorTextureId;
ovr_GetMirrorTextureBufferGL(session, mirror.texture, &mirrorTextureId);
glBindFramebuffer(GL_READ_FRAMEBUFFER, mirror.fboId);
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mirrorTextureId, 0);
glBlitFramebuffer(0, 0, mirror.width, mirror.height, 0, mirror.height, mirror.width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
// Requires: session, hmdDesc
static OculusLayer InitOculusLayer(ovrSession session)
{
OculusLayer layer = { 0 };
layer.viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.0f;
memset(&layer.eyeLayer, 0, sizeof(ovrLayerEyeFov));
layer.eyeLayer.Header.Type = ovrLayerType_EyeFov;
layer.eyeLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft;
ovrEyeRenderDesc eyeRenderDescs[2];
for (int eye = 0; eye < 2; eye++)
{
eyeRenderDescs[eye] = ovr_GetRenderDesc(session, eye, hmdDesc.DefaultEyeFov[eye]);
ovrMatrix4f ovrPerspectiveProjection = ovrMatrix4f_Projection(eyeRenderDescs[eye].Fov, 0.01f, 10000.0f, ovrProjection_None); //ovrProjection_ClipRangeOpenGL);
layer.eyeProjections[eye] = FromOvrMatrix(ovrPerspectiveProjection); // NOTE: struct ovrMatrix4f { float M[4][4] } --> struct Matrix
layer.viewScaleDesc.HmdToEyeOffset[eye] = eyeRenderDescs[eye].HmdToEyeOffset;
layer.eyeLayer.Fov[eye] = eyeRenderDescs[eye].Fov;
ovrSizei eyeSize = ovr_GetFovTextureSize(session, eye, layer.eyeLayer.Fov[eye], 1.0f);
layer.eyeLayer.Viewport[eye].Size = eyeSize;
layer.eyeLayer.Viewport[eye].Pos.x = layer.width;
layer.eyeLayer.Viewport[eye].Pos.y = 0;
layer.height = eyeSize.h; //std::max(renderTargetSize.y, (uint32_t)eyeSize.h);
layer.width += eyeSize.w;
}
return layer;
}
#endif
// Plays raylib logo appearing animation
static void LogoAnimation(void)
{

+ 196
- 0
src/external/OculusSDK/LibOVR/Include/Extras/OVR_CAPI_Util.h 查看文件

@ -0,0 +1,196 @@
/********************************************************************************//**
\file OVR_CAPI_Util.h
\brief This header provides LibOVR utility function declarations
\copyright Copyright 2015-2016 Oculus VR, LLC All Rights reserved.
*************************************************************************************/
#ifndef OVR_CAPI_Util_h
#define OVR_CAPI_Util_h
#include "../OVR_CAPI.h"
#ifdef __cplusplus
extern "C" {
#endif
/// Enumerates modifications to the projection matrix based on the application's needs.
///
/// \see ovrMatrix4f_Projection
///
typedef enum ovrProjectionModifier_
{
/// Use for generating a default projection matrix that is:
/// * Right-handed.
/// * Near depth values stored in the depth buffer are smaller than far depth values.
/// * Both near and far are explicitly defined.
/// * With a clipping range that is (0 to w).
ovrProjection_None = 0x00,
/// Enable if using left-handed transformations in your application.
ovrProjection_LeftHanded = 0x01,
/// After the projection transform is applied, far values stored in the depth buffer will be less than closer depth values.
/// NOTE: Enable only if the application is using a floating-point depth buffer for proper precision.
ovrProjection_FarLessThanNear = 0x02,
/// When this flag is used, the zfar value pushed into ovrMatrix4f_Projection() will be ignored
/// NOTE: Enable only if ovrProjection_FarLessThanNear is also enabled where the far clipping plane will be pushed to infinity.
ovrProjection_FarClipAtInfinity = 0x04,
/// Enable if the application is rendering with OpenGL and expects a projection matrix with a clipping range of (-w to w).
/// Ignore this flag if your application already handles the conversion from D3D range (0 to w) to OpenGL.
ovrProjection_ClipRangeOpenGL = 0x08,
} ovrProjectionModifier;
/// Return values for ovr_Detect.
///
/// \see ovr_Detect
///
typedef struct OVR_ALIGNAS(8) ovrDetectResult_
{
/// Is ovrFalse when the Oculus Service is not running.
/// This means that the Oculus Service is either uninstalled or stopped.
/// IsOculusHMDConnected will be ovrFalse in this case.
/// Is ovrTrue when the Oculus Service is running.
/// This means that the Oculus Service is installed and running.
/// IsOculusHMDConnected will reflect the state of the HMD.
ovrBool IsOculusServiceRunning;
/// Is ovrFalse when an Oculus HMD is not detected.
/// If the Oculus Service is not running, this will be ovrFalse.
/// Is ovrTrue when an Oculus HMD is detected.
/// This implies that the Oculus Service is also installed and running.
ovrBool IsOculusHMDConnected;
OVR_UNUSED_STRUCT_PAD(pad0, 6) ///< \internal struct padding
} ovrDetectResult;
OVR_STATIC_ASSERT(sizeof(ovrDetectResult) == 8, "ovrDetectResult size mismatch");
/// Detects Oculus Runtime and Device Status
///
/// Checks for Oculus Runtime and Oculus HMD device status without loading the LibOVRRT
/// shared library. This may be called before ovr_Initialize() to help decide whether or
/// not to initialize LibOVR.
///
/// \param[in] timeoutMilliseconds Specifies a timeout to wait for HMD to be attached or 0 to poll.
///
/// \return Returns an ovrDetectResult object indicating the result of detection.
///
/// \see ovrDetectResult
///
OVR_PUBLIC_FUNCTION(ovrDetectResult) ovr_Detect(int timeoutMilliseconds);
// On the Windows platform,
#ifdef _WIN32
/// This is the Windows Named Event name that is used to check for HMD connected state.
#define OVR_HMD_CONNECTED_EVENT_NAME L"OculusHMDConnected"
#endif // _WIN32
/// Used to generate projection from ovrEyeDesc::Fov.
///
/// \param[in] fov Specifies the ovrFovPort to use.
/// \param[in] znear Distance to near Z limit.
/// \param[in] zfar Distance to far Z limit.
/// \param[in] projectionModFlags A combination of the ovrProjectionModifier flags.
///
/// \return Returns the calculated projection matrix.
///
/// \see ovrProjectionModifier
///
OVR_PUBLIC_FUNCTION(ovrMatrix4f) ovrMatrix4f_Projection(ovrFovPort fov, float znear, float zfar, unsigned int projectionModFlags);
/// Extracts the required data from the result of ovrMatrix4f_Projection.
///
/// \param[in] projection Specifies the project matrix from which to extract ovrTimewarpProjectionDesc.
/// \param[in] projectionModFlags A combination of the ovrProjectionModifier flags.
/// \return Returns the extracted ovrTimewarpProjectionDesc.
/// \see ovrTimewarpProjectionDesc
///
OVR_PUBLIC_FUNCTION(ovrTimewarpProjectionDesc) ovrTimewarpProjectionDesc_FromProjection(ovrMatrix4f projection, unsigned int projectionModFlags);
/// Generates an orthographic sub-projection.
///
/// Used for 2D rendering, Y is down.
///
/// \param[in] projection The perspective matrix that the orthographic matrix is derived from.
/// \param[in] orthoScale Equal to 1.0f / pixelsPerTanAngleAtCenter.
/// \param[in] orthoDistance Equal to the distance from the camera in meters, such as 0.8m.
/// \param[in] HmdToEyeOffsetX Specifies the offset of the eye from the center.
///
/// \return Returns the calculated projection matrix.
///
OVR_PUBLIC_FUNCTION(ovrMatrix4f) ovrMatrix4f_OrthoSubProjection(ovrMatrix4f projection, ovrVector2f orthoScale,
float orthoDistance, float HmdToEyeOffsetX);
/// Computes offset eye poses based on headPose returned by ovrTrackingState.
///
/// \param[in] headPose Indicates the HMD position and orientation to use for the calculation.
/// \param[in] hmdToEyeOffset Can be ovrEyeRenderDesc.HmdToEyeOffset returned from
/// ovr_GetRenderDesc. For monoscopic rendering, use a vector that is the average
/// of the two vectors for both eyes.
/// \param[out] outEyePoses If outEyePoses are used for rendering, they should be passed to
/// ovr_SubmitFrame in ovrLayerEyeFov::RenderPose or ovrLayerEyeFovDepth::RenderPose.
///
OVR_PUBLIC_FUNCTION(void) ovr_CalcEyePoses(ovrPosef headPose,
const ovrVector3f hmdToEyeOffset[2],
ovrPosef outEyePoses[2]);
/// Returns the predicted head pose in outHmdTrackingState and offset eye poses in outEyePoses.
///
/// This is a thread-safe function where caller should increment frameIndex with every frame
/// and pass that index where applicable to functions called on the rendering thread.
/// Assuming outEyePoses are used for rendering, it should be passed as a part of ovrLayerEyeFov.
/// The caller does not need to worry about applying HmdToEyeOffset to the returned outEyePoses variables.
///
/// \param[in] hmd Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] frameIndex Specifies the targeted frame index, or 0 to refer to one frame after
/// the last time ovr_SubmitFrame was called.
/// \param[in] latencyMarker Specifies that this call is the point in time where
/// the "App-to-Mid-Photon" latency timer starts from. If a given ovrLayer
/// provides "SensorSampleTimestamp", that will override the value stored here.
/// \param[in] hmdToEyeOffset Can be ovrEyeRenderDesc.HmdToEyeOffset returned from
/// ovr_GetRenderDesc. For monoscopic rendering, use a vector that is the average
/// of the two vectors for both eyes.
/// \param[out] outEyePoses The predicted eye poses.
/// \param[out] outSensorSampleTime The time when this function was called. May be NULL, in which case it is ignored.
///
OVR_PUBLIC_FUNCTION(void) ovr_GetEyePoses(ovrSession session, long long frameIndex, ovrBool latencyMarker,
const ovrVector3f hmdToEyeOffset[2],
ovrPosef outEyePoses[2],
double* outSensorSampleTime);
/// Tracking poses provided by the SDK come in a right-handed coordinate system. If an application
/// is passing in ovrProjection_LeftHanded into ovrMatrix4f_Projection, then it should also use
/// this function to flip the HMD tracking poses to be left-handed.
///
/// While this utility function is intended to convert a left-handed ovrPosef into a right-handed
/// coordinate system, it will also work for converting right-handed to left-handed since the
/// flip operation is the same for both cases.
///
/// \param[in] inPose that is right-handed
/// \param[out] outPose that is requested to be left-handed (can be the same pointer to inPose)
///
OVR_PUBLIC_FUNCTION(void) ovrPosef_FlipHandedness(const ovrPosef* inPose, ovrPosef* outPose);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // Header include guard

+ 3785
- 0
src/external/OculusSDK/LibOVR/Include/Extras/OVR_Math.h
文件差异内容过多而无法显示
查看文件


+ 70
- 0
src/external/OculusSDK/LibOVR/Include/Extras/OVR_StereoProjection.h 查看文件

@ -0,0 +1,70 @@
/************************************************************************************
Filename : OVR_StereoProjection.h
Content : Stereo projection functions
Created : November 30, 2013
Authors : Tom Fosyth
Copyright : Copyright 2014-2016 Oculus VR, LLC All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************************/
#ifndef OVR_StereoProjection_h
#define OVR_StereoProjection_h
#include "Extras/OVR_Math.h"
namespace OVR {
//-----------------------------------------------------------------------------------
// ***** Stereo Enumerations
// StereoEye specifies which eye we are rendering for; it is used to
// retrieve StereoEyeParams.
enum StereoEye
{
StereoEye_Left,
StereoEye_Right,
StereoEye_Center
};
//-----------------------------------------------------------------------------------
// ***** Propjection functions
Matrix4f CreateProjection ( bool rightHanded, bool isOpenGL, FovPort fov, StereoEye eye,
float zNear = 0.01f, float zFar = 10000.0f,
bool flipZ = false, bool farAtInfinity = false);
Matrix4f CreateOrthoSubProjection ( bool rightHanded, StereoEye eyeType,
float tanHalfFovX, float tanHalfFovY,
float unitsX, float unitsY, float distanceFromCamera,
float interpupillaryDistance, Matrix4f const &projection,
float zNear = 0.0f, float zFar = 0.0f,
bool flipZ = false, bool farAtInfinity = false);
ScaleAndOffset2D CreateNDCScaleAndOffsetFromFov ( FovPort fov );
} //namespace OVR
#endif // OVR_StereoProjection_h

+ 2116
- 0
src/external/OculusSDK/LibOVR/Include/OVR_CAPI.h
文件差异内容过多而无法显示
查看文件


+ 76
- 0
src/external/OculusSDK/LibOVR/Include/OVR_CAPI_Audio.h 查看文件

@ -0,0 +1,76 @@
/********************************************************************************//**
\file OVR_CAPI_Audio.h
\brief CAPI audio functions.
\copyright Copyright 2015 Oculus VR, LLC. All Rights reserved.
************************************************************************************/
#ifndef OVR_CAPI_Audio_h
#define OVR_CAPI_Audio_h
#ifdef _WIN32
#include <windows.h>
#include "OVR_CAPI.h"
#define OVR_AUDIO_MAX_DEVICE_STR_SIZE 128
/// Gets the ID of the preferred VR audio output device.
///
/// \param[out] deviceOutId The ID of the user's preferred VR audio device to use, which will be valid upon a successful return value, else it will be WAVE_MAPPER.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetAudioDeviceOutWaveId(UINT* deviceOutId);
/// Gets the ID of the preferred VR audio input device.
///
/// \param[out] deviceInId The ID of the user's preferred VR audio device to use, which will be valid upon a successful return value, else it will be WAVE_MAPPER.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetAudioDeviceInWaveId(UINT* deviceInId);
/// Gets the GUID of the preferred VR audio device as a string.
///
/// \param[out] deviceOutStrBuffer A buffer where the GUID string for the device will copied to.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetAudioDeviceOutGuidStr(WCHAR deviceOutStrBuffer[OVR_AUDIO_MAX_DEVICE_STR_SIZE]);
/// Gets the GUID of the preferred VR audio device.
///
/// \param[out] deviceOutGuid The GUID of the user's preferred VR audio device to use, which will be valid upon a successful return value, else it will be NULL.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetAudioDeviceOutGuid(GUID* deviceOutGuid);
/// Gets the GUID of the preferred VR microphone device as a string.
///
/// \param[out] deviceInStrBuffer A buffer where the GUID string for the device will copied to.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetAudioDeviceInGuidStr(WCHAR deviceInStrBuffer[OVR_AUDIO_MAX_DEVICE_STR_SIZE]);
/// Gets the GUID of the preferred VR microphone device.
///
/// \param[out] deviceInGuid The GUID of the user's preferred VR audio device to use, which will be valid upon a successful return value, else it will be NULL.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetAudioDeviceInGuid(GUID* deviceInGuid);
#endif //OVR_OS_MS
#endif // OVR_CAPI_Audio_h

+ 155
- 0
src/external/OculusSDK/LibOVR/Include/OVR_CAPI_D3D.h 查看文件

@ -0,0 +1,155 @@
/********************************************************************************//**
\file OVR_CAPI_D3D.h
\brief D3D specific structures used by the CAPI interface.
\copyright Copyright 2014-2016 Oculus VR, LLC All Rights reserved.
************************************************************************************/
#ifndef OVR_CAPI_D3D_h
#define OVR_CAPI_D3D_h
#include "OVR_CAPI.h"
#include "OVR_Version.h"
#if defined (_WIN32)
#include <Unknwn.h>
//-----------------------------------------------------------------------------------
// ***** Direct3D Specific
/// Create Texture Swap Chain suitable for use with Direct3D 11 and 12.
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] d3dPtr Specifies the application's D3D11Device to create resources with or the D3D12CommandQueue
/// which must be the same one the application renders to the eye textures with.
/// \param[in] desc Specifies requested texture properties. See notes for more info about texture format.
/// \param[in] bindFlags Specifies what ovrTextureBindFlags the application requires for this texture chain.
/// \param[out] out_TextureSwapChain Returns the created ovrTextureSwapChain, which will be valid upon a successful return value, else it will be NULL.
/// This texture chain must be eventually destroyed via ovr_DestroyTextureSwapChain before destroying the HMD with ovr_Destroy.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
/// \note The texture format provided in \a desc should be thought of as the format the distortion-compositor will use for the
/// ShaderResourceView when reading the contents of the texture. To that end, it is highly recommended that the application
/// requests texture swapchain formats that are in sRGB-space (e.g. OVR_FORMAT_R8G8B8A8_UNORM_SRGB) as the compositor
/// does sRGB-correct rendering. As such, the compositor relies on the GPU's hardware sampler to do the sRGB-to-linear
/// conversion. If the application still prefers to render to a linear format (e.g. OVR_FORMAT_R8G8B8A8_UNORM) while handling the
/// linear-to-gamma conversion via HLSL code, then the application must still request the corresponding sRGB format and also use
/// the \a ovrTextureMisc_DX_Typeless flag in the ovrTextureSwapChainDesc's Flag field. This will allow the application to create
/// a RenderTargetView that is the desired linear format while the compositor continues to treat it as sRGB. Failure to do so
/// will cause the compositor to apply unexpected gamma conversions leading to gamma-curve artifacts. The \a ovrTextureMisc_DX_Typeless
/// flag for depth buffer formats (e.g. OVR_FORMAT_D32_FLOAT) is ignored as they are always converted to be typeless.
///
/// \see ovr_GetTextureSwapChainLength
/// \see ovr_GetTextureSwapChainCurrentIndex
/// \see ovr_GetTextureSwapChainDesc
/// \see ovr_GetTextureSwapChainBufferDX
/// \see ovr_DestroyTextureSwapChain
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_CreateTextureSwapChainDX(ovrSession session,
IUnknown* d3dPtr,
const ovrTextureSwapChainDesc* desc,
ovrTextureSwapChain* out_TextureSwapChain);
/// Get a specific buffer within the chain as any compatible COM interface (similar to QueryInterface)
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] chain Specifies an ovrTextureSwapChain previously returned by ovr_CreateTextureSwapChainDX
/// \param[in] index Specifies the index within the chain to retrieve. Must be between 0 and length (see ovr_GetTextureSwapChainLength),
/// or may pass -1 to get the buffer at the CurrentIndex location. (Saving a call to GetTextureSwapChainCurrentIndex)
/// \param[in] iid Specifies the interface ID of the interface pointer to query the buffer for.
/// \param[out] out_Buffer Returns the COM interface pointer retrieved.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
/// <b>Example code</b>
/// \code{.cpp}
/// ovr_GetTextureSwapChainBufferDX(session, chain, 0, IID_ID3D11Texture2D, &d3d11Texture);
/// ovr_GetTextureSwapChainBufferDX(session, chain, 1, IID_PPV_ARGS(&dxgiResource));
/// \endcode
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetTextureSwapChainBufferDX(ovrSession session,
ovrTextureSwapChain chain,
int index,
IID iid,
void** out_Buffer);
/// Create Mirror Texture which is auto-refreshed to mirror Rift contents produced by this application.
///
/// A second call to ovr_CreateMirrorTextureDX for a given ovrSession before destroying the first one
/// is not supported and will result in an error return.
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] d3dPtr Specifies the application's D3D11Device to create resources with or the D3D12CommandQueue
/// which must be the same one the application renders to the textures with.
/// \param[in] desc Specifies requested texture properties. See notes for more info about texture format.
/// \param[out] out_MirrorTexture Returns the created ovrMirrorTexture, which will be valid upon a successful return value, else it will be NULL.
/// This texture must be eventually destroyed via ovr_DestroyMirrorTexture before destroying the HMD with ovr_Destroy.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
/// \note The texture format provided in \a desc should be thought of as the format the compositor will use for the RenderTargetView when
/// writing into mirror texture. To that end, it is highly recommended that the application requests a mirror texture format that is
/// in sRGB-space (e.g. OVR_FORMAT_R8G8B8A8_UNORM_SRGB) as the compositor does sRGB-correct rendering. If however the application wants
/// to still read the mirror texture as a linear format (e.g. OVR_FORMAT_R8G8B8A8_UNORM) and handle the sRGB-to-linear conversion in
/// HLSL code, then it is recommended the application still requests an sRGB format and also use the \a ovrTextureMisc_DX_Typeless flag in the
/// ovrMirrorTextureDesc's Flags field. This will allow the application to bind a ShaderResourceView that is a linear format while the
/// compositor continues to treat is as sRGB. Failure to do so will cause the compositor to apply unexpected gamma conversions leading to
/// gamma-curve artifacts.
///
///
/// <b>Example code</b>
/// \code{.cpp}
/// ovrMirrorTexture mirrorTexture = nullptr;
/// ovrMirrorTextureDesc mirrorDesc = {};
/// mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
/// mirrorDesc.Width = mirrorWindowWidth;
/// mirrorDesc.Height = mirrorWindowHeight;
/// ovrResult result = ovr_CreateMirrorTextureDX(session, d3d11Device, &mirrorDesc, &mirrorTexture);
/// [...]
/// // Destroy the texture when done with it.
/// ovr_DestroyMirrorTexture(session, mirrorTexture);
/// mirrorTexture = nullptr;
/// \endcode
///
/// \see ovr_GetMirrorTextureBufferDX
/// \see ovr_DestroyMirrorTexture
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_CreateMirrorTextureDX(ovrSession session,
IUnknown* d3dPtr,
const ovrMirrorTextureDesc* desc,
ovrMirrorTexture* out_MirrorTexture);
/// Get a the underlying buffer as any compatible COM interface (similar to QueryInterface)
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] mirrorTexture Specifies an ovrMirrorTexture previously returned by ovr_CreateMirrorTextureDX
/// \param[in] iid Specifies the interface ID of the interface pointer to query the buffer for.
/// \param[out] out_Buffer Returns the COM interface pointer retrieved.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
/// <b>Example code</b>
/// \code{.cpp}
/// ID3D11Texture2D* d3d11Texture = nullptr;
/// ovr_GetMirrorTextureBufferDX(session, mirrorTexture, IID_PPV_ARGS(&d3d11Texture));
/// d3d11DeviceContext->CopyResource(d3d11TextureBackBuffer, d3d11Texture);
/// d3d11Texture->Release();
/// dxgiSwapChain->Present(0, 0);
/// \endcode
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetMirrorTextureBufferDX(ovrSession session,
ovrMirrorTexture mirrorTexture,
IID iid,
void** out_Buffer);
#endif // _WIN32
#endif // OVR_CAPI_D3D_h

+ 99
- 0
src/external/OculusSDK/LibOVR/Include/OVR_CAPI_GL.h 查看文件

@ -0,0 +1,99 @@
/********************************************************************************//**
\file OVR_CAPI_GL.h
\brief OpenGL-specific structures used by the CAPI interface.
\copyright Copyright 2015 Oculus VR, LLC. All Rights reserved.
************************************************************************************/
#ifndef OVR_CAPI_GL_h
#define OVR_CAPI_GL_h
#include "OVR_CAPI.h"
/// Creates a TextureSwapChain suitable for use with OpenGL.
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] desc Specifies the requested texture properties. See notes for more info about texture format.
/// \param[out] out_TextureSwapChain Returns the created ovrTextureSwapChain, which will be valid upon
/// a successful return value, else it will be NULL. This texture swap chain must be eventually
/// destroyed via ovr_DestroyTextureSwapChain before destroying the HMD with ovr_Destroy.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
/// \note The \a format provided should be thought of as the format the distortion compositor will use when reading
/// the contents of the texture. To that end, it is highly recommended that the application requests texture swap chain
/// formats that are in sRGB-space (e.g. OVR_FORMAT_R8G8B8A8_UNORM_SRGB) as the distortion compositor does sRGB-correct
/// rendering. Furthermore, the app should then make sure "glEnable(GL_FRAMEBUFFER_SRGB);" is called before rendering
/// into these textures. Even though it is not recommended, if the application would like to treat the texture as a linear
/// format and do linear-to-gamma conversion in GLSL, then the application can avoid calling "glEnable(GL_FRAMEBUFFER_SRGB);",
/// but should still pass in an sRGB variant for the \a format. Failure to do so will cause the distortion compositor
/// to apply incorrect gamma conversions leading to gamma-curve artifacts.
///
/// \see ovr_GetTextureSwapChainLength
/// \see ovr_GetTextureSwapChainCurrentIndex
/// \see ovr_GetTextureSwapChainDesc
/// \see ovr_GetTextureSwapChainBufferGL
/// \see ovr_DestroyTextureSwapChain
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_CreateTextureSwapChainGL(ovrSession session,
const ovrTextureSwapChainDesc* desc,
ovrTextureSwapChain* out_TextureSwapChain);
/// Get a specific buffer within the chain as a GL texture name
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] chain Specifies an ovrTextureSwapChain previously returned by ovr_CreateTextureSwapChainGL
/// \param[in] index Specifies the index within the chain to retrieve. Must be between 0 and length (see ovr_GetTextureSwapChainLength)
/// or may pass -1 to get the buffer at the CurrentIndex location. (Saving a call to GetTextureSwapChainCurrentIndex)
/// \param[out] out_TexId Returns the GL texture object name associated with the specific index requested
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetTextureSwapChainBufferGL(ovrSession session,
ovrTextureSwapChain chain,
int index,
unsigned int* out_TexId);
/// Creates a Mirror Texture which is auto-refreshed to mirror Rift contents produced by this application.
///
/// A second call to ovr_CreateMirrorTextureGL for a given ovrSession before destroying the first one
/// is not supported and will result in an error return.
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] desc Specifies the requested mirror texture description.
/// \param[out] out_MirrorTexture Specifies the created ovrMirrorTexture, which will be valid upon a successful return value, else it will be NULL.
/// This texture must be eventually destroyed via ovr_DestroyMirrorTexture before destroying the HMD with ovr_Destroy.
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
/// \note The \a format provided should be thought of as the format the distortion compositor will use when writing into the mirror
/// texture. It is highly recommended that mirror textures are requested as sRGB formats because the distortion compositor
/// does sRGB-correct rendering. If the application requests a non-sRGB format (e.g. R8G8B8A8_UNORM) as the mirror texture,
/// then the application might have to apply a manual linear-to-gamma conversion when reading from the mirror texture.
/// Failure to do so can result in incorrect gamma conversions leading to gamma-curve artifacts and color banding.
///
/// \see ovr_GetMirrorTextureBufferGL
/// \see ovr_DestroyMirrorTexture
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_CreateMirrorTextureGL(ovrSession session,
const ovrMirrorTextureDesc* desc,
ovrMirrorTexture* out_MirrorTexture);
/// Get a the underlying buffer as a GL texture name
///
/// \param[in] session Specifies an ovrSession previously returned by ovr_Create.
/// \param[in] mirrorTexture Specifies an ovrMirrorTexture previously returned by ovr_CreateMirrorTextureGL
/// \param[out] out_TexId Specifies the GL texture object name associated with the mirror texture
///
/// \return Returns an ovrResult indicating success or failure. In the case of failure, use
/// ovr_GetLastErrorInfo to get more information.
///
OVR_PUBLIC_FUNCTION(ovrResult) ovr_GetMirrorTextureBufferGL(ovrSession session,
ovrMirrorTexture mirrorTexture,
unsigned int* out_TexId);
#endif // OVR_CAPI_GL_h

+ 53
- 0
src/external/OculusSDK/LibOVR/Include/OVR_CAPI_Keys.h 查看文件

@ -0,0 +1,53 @@
/********************************************************************************//**
\file OVR_CAPI.h
\brief Keys for CAPI proprty function calls
\copyright Copyright 2015 Oculus VR, LLC All Rights reserved.
************************************************************************************/
#ifndef OVR_CAPI_Keys_h
#define OVR_CAPI_Keys_h
#include "OVR_Version.h"
#define OVR_KEY_USER "User" // string
#define OVR_KEY_NAME "Name" // string
#define OVR_KEY_GENDER "Gender" // string "Male", "Female", or "Unknown"
#define OVR_DEFAULT_GENDER "Unknown"
#define OVR_KEY_PLAYER_HEIGHT "PlayerHeight" // float meters
#define OVR_DEFAULT_PLAYER_HEIGHT 1.778f
#define OVR_KEY_EYE_HEIGHT "EyeHeight" // float meters
#define OVR_DEFAULT_EYE_HEIGHT 1.675f
#define OVR_KEY_NECK_TO_EYE_DISTANCE "NeckEyeDistance" // float[2] meters
#define OVR_DEFAULT_NECK_TO_EYE_HORIZONTAL 0.0805f
#define OVR_DEFAULT_NECK_TO_EYE_VERTICAL 0.075f
#define OVR_KEY_EYE_TO_NOSE_DISTANCE "EyeToNoseDist" // float[2] meters
#define OVR_PERF_HUD_MODE "PerfHudMode" // int, allowed values are defined in enum ovrPerfHudMode
#define OVR_LAYER_HUD_MODE "LayerHudMode" // int, allowed values are defined in enum ovrLayerHudMode
#define OVR_LAYER_HUD_CURRENT_LAYER "LayerHudCurrentLayer" // int, The layer to show
#define OVR_LAYER_HUD_SHOW_ALL_LAYERS "LayerHudShowAll" // bool, Hide other layers when the hud is enabled
#define OVR_DEBUG_HUD_STEREO_MODE "DebugHudStereoMode" // int, allowed values are defined in enum ovrDebugHudStereoMode
#define OVR_DEBUG_HUD_STEREO_GUIDE_INFO_ENABLE "DebugHudStereoGuideInfoEnable" // bool
#define OVR_DEBUG_HUD_STEREO_GUIDE_SIZE "DebugHudStereoGuideSize2f" // float[2]
#define OVR_DEBUG_HUD_STEREO_GUIDE_POSITION "DebugHudStereoGuidePosition3f" // float[3]
#define OVR_DEBUG_HUD_STEREO_GUIDE_YAWPITCHROLL "DebugHudStereoGuideYawPitchRoll3f" // float[3]
#define OVR_DEBUG_HUD_STEREO_GUIDE_COLOR "DebugHudStereoGuideColor4f" // float[4]
#endif // OVR_CAPI_Keys_h

+ 209
- 0
src/external/OculusSDK/LibOVR/Include/OVR_ErrorCode.h 查看文件

@ -0,0 +1,209 @@
/********************************************************************************//**
\file OVR_ErrorCode.h
\brief This header provides LibOVR error code declarations.
\copyright Copyright 2015-2016 Oculus VR, LLC All Rights reserved.
*************************************************************************************/
#ifndef OVR_ErrorCode_h
#define OVR_ErrorCode_h
#include "OVR_Version.h"
#include <stdint.h>
#ifndef OVR_RESULT_DEFINED
#define OVR_RESULT_DEFINED ///< Allows ovrResult to be independently defined.
/// API call results are represented at the highest level by a single ovrResult.
typedef int32_t ovrResult;
#endif
/// \brief Indicates if an ovrResult indicates success.
///
/// Some functions return additional successful values other than ovrSucces and
/// require usage of this macro to indicate successs.
///
#if !defined(OVR_SUCCESS)
#define OVR_SUCCESS(result) (result >= 0)
#endif
/// \brief Indicates if an ovrResult indicates an unqualified success.
///
/// This is useful for indicating that the code intentionally wants to
/// check for result == ovrSuccess as opposed to OVR_SUCCESS(), which
/// checks for result >= ovrSuccess.
///
#if !defined(OVR_UNQUALIFIED_SUCCESS)
#define OVR_UNQUALIFIED_SUCCESS(result) (result == ovrSuccess)
#endif
/// \brief Indicates if an ovrResult indicates failure.
///
#if !defined(OVR_FAILURE)
#define OVR_FAILURE(result) (!OVR_SUCCESS(result))
#endif
// Success is a value greater or equal to 0, while all error types are negative values.
#ifndef OVR_SUCCESS_DEFINED
#define OVR_SUCCESS_DEFINED ///< Allows ovrResult to be independently defined.
typedef enum ovrSuccessType_
{
/// This is a general success result. Use OVR_SUCCESS to test for success.
ovrSuccess = 0,
/// Returned from a call to SubmitFrame. The call succeeded, but what the app
/// rendered will not be visible on the HMD. Ideally the app should continue
/// calling SubmitFrame, but not do any rendering. When the result becomes
/// ovrSuccess, rendering should continue as usual.
ovrSuccess_NotVisible = 1000,
ovrSuccess_HMDFirmwareMismatch = 4100, ///< The HMD Firmware is out of date but is acceptable.
ovrSuccess_TrackerFirmwareMismatch = 4101, ///< The Tracker Firmware is out of date but is acceptable.
ovrSuccess_ControllerFirmwareMismatch = 4104, ///< The controller firmware is out of date but is acceptable.
ovrSuccess_TrackerDriverNotFound = 4105, ///< The tracker driver interface was not found. Can be a temporary error
} ovrSuccessType;
#endif
typedef enum ovrErrorType_
{
/* General errors */
ovrError_MemoryAllocationFailure = -1000, ///< Failure to allocate memory.
ovrError_SocketCreationFailure = -1001, ///< Failure to create a socket.
ovrError_InvalidSession = -1002, ///< Invalid ovrSession parameter provided.
ovrError_Timeout = -1003, ///< The operation timed out.
ovrError_NotInitialized = -1004, ///< The system or component has not been initialized.
ovrError_InvalidParameter = -1005, ///< Invalid parameter provided. See error info or log for details.
ovrError_ServiceError = -1006, ///< Generic service error. See error info or log for details.
ovrError_NoHmd = -1007, ///< The given HMD doesn't exist.
ovrError_Unsupported = -1009, ///< Function call is not supported on this hardware/software
ovrError_DeviceUnavailable = -1010, ///< Specified device type isn't available.
ovrError_InvalidHeadsetOrientation = -1011, ///< The headset was in an invalid orientation for the requested operation (e.g. vertically oriented during ovr_RecenterPose).
ovrError_ClientSkippedDestroy = -1012, ///< The client failed to call ovr_Destroy on an active session before calling ovr_Shutdown. Or the client crashed.
ovrError_ClientSkippedShutdown = -1013, ///< The client failed to call ovr_Shutdown or the client crashed.
ovrError_ServiceDeadlockDetected = -1014, ///< The service watchdog discovered a deadlock.
/* Audio error range, reserved for Audio errors. */
ovrError_AudioReservedBegin = -2000, ///< First Audio error.
ovrError_AudioDeviceNotFound = -2001, ///< Failure to find the specified audio device.
ovrError_AudioComError = -2002, ///< Generic COM error.
ovrError_AudioReservedEnd = -2999, ///< Last Audio error.
/* Initialization errors. */
ovrError_Initialize = -3000, ///< Generic initialization error.
ovrError_LibLoad = -3001, ///< Couldn't load LibOVRRT.
ovrError_LibVersion = -3002, ///< LibOVRRT version incompatibility.
ovrError_ServiceConnection = -3003, ///< Couldn't connect to the OVR Service.
ovrError_ServiceVersion = -3004, ///< OVR Service version incompatibility.
ovrError_IncompatibleOS = -3005, ///< The operating system version is incompatible.
ovrError_DisplayInit = -3006, ///< Unable to initialize the HMD display.
ovrError_ServerStart = -3007, ///< Unable to start the server. Is it already running?
ovrError_Reinitialization = -3008, ///< Attempting to re-initialize with a different version.
ovrError_MismatchedAdapters = -3009, ///< Chosen rendering adapters between client and service do not match
ovrError_LeakingResources = -3010, ///< Calling application has leaked resources
ovrError_ClientVersion = -3011, ///< Client version too old to connect to service
ovrError_OutOfDateOS = -3012, ///< The operating system is out of date.
ovrError_OutOfDateGfxDriver = -3013, ///< The graphics driver is out of date.
ovrError_IncompatibleGPU = -3014, ///< The graphics hardware is not supported
ovrError_NoValidVRDisplaySystem = -3015, ///< No valid VR display system found.
ovrError_Obsolete = -3016, ///< Feature or API is obsolete and no longer supported.
ovrError_DisabledOrDefaultAdapter = -3017, ///< No supported VR display system found, but disabled or driverless adapter found.
ovrError_HybridGraphicsNotSupported = -3018, ///< The system is using hybrid graphics (Optimus, etc...), which is not support.
ovrError_DisplayManagerInit = -3019, ///< Initialization of the DisplayManager failed.
ovrError_TrackerDriverInit = -3020, ///< Failed to get the interface for an attached tracker
/* Hardware errors */
ovrError_InvalidBundleAdjustment = -4000, ///< Headset has no bundle adjustment data.
ovrError_USBBandwidth = -4001, ///< The USB hub cannot handle the camera frame bandwidth.
ovrError_USBEnumeratedSpeed = -4002, ///< The USB camera is not enumerating at the correct device speed.
ovrError_ImageSensorCommError = -4003, ///< Unable to communicate with the image sensor.
ovrError_GeneralTrackerFailure = -4004, ///< We use this to report various sensor issues that don't fit in an easily classifiable bucket.
ovrError_ExcessiveFrameTruncation = -4005, ///< A more than acceptable number of frames are coming back truncated.
ovrError_ExcessiveFrameSkipping = -4006, ///< A more than acceptable number of frames have been skipped.
ovrError_SyncDisconnected = -4007, ///< The sensor is not receiving the sync signal (cable disconnected?).
ovrError_TrackerMemoryReadFailure = -4008, ///< Failed to read memory from the sensor.
ovrError_TrackerMemoryWriteFailure = -4009, ///< Failed to write memory from the sensor.
ovrError_TrackerFrameTimeout = -4010, ///< Timed out waiting for a camera frame.
ovrError_TrackerTruncatedFrame = -4011, ///< Truncated frame returned from sensor.
ovrError_TrackerDriverFailure = -4012, ///< The sensor driver has encountered a problem.
ovrError_TrackerNRFFailure = -4013, ///< The sensor wireless subsystem has encountered a problem.
ovrError_HardwareGone = -4014, ///< The hardware has been unplugged
ovrError_NordicEnabledNoSync = -4015, ///< The nordic indicates that sync is enabled but it is not sending sync pulses
ovrError_NordicSyncNoFrames = -4016, ///< It looks like we're getting a sync signal, but no camera frames have been received
ovrError_CatastrophicFailure = -4017, ///< A catastrophic failure has occurred. We will attempt to recover by resetting the device
ovrError_CatastrophicTimeout = -4018, ///< The catastrophic recovery has timed out.
ovrError_RepeatCatastrophicFail = -4019, ///< Catastrophic failure has repeated too many times.
ovrError_USBOpenDeviceFailure = -4020, ///< Could not open handle for Rift device (likely already in use by another process).
ovrError_HMDGeneralFailure = -4021, ///< Unexpected HMD issues that don't fit a specific bucket.
ovrError_HMDFirmwareMismatch = -4100, ///< The HMD Firmware is out of date and is unacceptable.
ovrError_TrackerFirmwareMismatch = -4101, ///< The sensor Firmware is out of date and is unacceptable.
ovrError_BootloaderDeviceDetected = -4102, ///< A bootloader HMD is detected by the service.
ovrError_TrackerCalibrationError = -4103, ///< The sensor calibration is missing or incorrect.
ovrError_ControllerFirmwareMismatch = -4104, ///< The controller firmware is out of date and is unacceptable.
ovrError_DevManDeviceDetected = -4105, ///< A DeviceManagement mode HMD is detected by the service.
ovrError_RebootedBootloaderDevice = -4106, ///< Had to reboot bootloader device, which succeeded.
ovrError_FailedRebootBootloaderDev = -4107, ///< Had to reboot bootloader device, which failed. Device is stuck in bootloader mode.
ovrError_IMUTooManyLostSamples = -4200, ///< Too many lost IMU samples.
ovrError_IMURateError = -4201, ///< IMU rate is outside of the expected range.
ovrError_FeatureReportFailure = -4202, ///< A feature report has failed.
ovrError_HMDWirelessTimeout = -4203, ///< HMD wireless interface never returned from busy state.
ovrError_BootloaderAssertLog = -4300, ///< HMD Bootloader Assert Log was not empty.
ovrError_AppAssertLog = -4301, ///< HMD App Assert Log was not empty.
/* Synchronization errors */
ovrError_Incomplete = -5000, ///< Requested async work not yet complete.
ovrError_Abandoned = -5001, ///< Requested async work was abandoned and result is incomplete.
/* Rendering errors */
ovrError_DisplayLost = -6000, ///< In the event of a system-wide graphics reset or cable unplug this is returned to the app.
ovrError_TextureSwapChainFull = -6001, ///< ovr_CommitTextureSwapChain was called too many times on a texture swapchain without calling submit to use the chain.
ovrError_TextureSwapChainInvalid = -6002, ///< The ovrTextureSwapChain is in an incomplete or inconsistent state. Ensure ovr_CommitTextureSwapChain was called at least once first.
ovrError_GraphicsDeviceReset = -6003, ///< Graphics device has been reset (TDR, etc...)
ovrError_DisplayRemoved = -6004, ///< HMD removed from the display adapter
ovrError_ContentProtectionNotAvailable = -6005,///<Content protection is not available for the display
ovrError_ApplicationInvisible = -6006, ///< Application declared itself as an invisible type and is not allowed to submit frames.
ovrError_Disallowed = -6007, ///< The given request is disallowed under the current conditions.
ovrError_DisplayPluggedIncorrectly = -6008, ///< Display portion of HMD is plugged into an incompatible port (ex: IGP)
/* Fatal errors */
ovrError_RuntimeException = -7000, ///< A runtime exception occurred. The application is required to shutdown LibOVR and re-initialize it before this error state will be cleared.
ovrError_MetricsUnknownApp = -90000,
ovrError_MetricsDuplicateApp = -90001,
ovrError_MetricsNoEvents = -90002,
ovrError_MetricsRuntime = -90003,
ovrError_MetricsFile = -90004,
ovrError_MetricsNoClientInfo = -90005,
ovrError_MetricsNoAppMetaData = -90006,
ovrError_MetricsNoApp = -90007,
ovrError_MetricsOafFailure = -90008,
ovrError_MetricsSessionAlreadyActive = -90009,
ovrError_MetricsSessionNotActive = -90010,
} ovrErrorType;
/// Provides information about the last error.
/// \see ovr_GetLastErrorInfo
typedef struct ovrErrorInfo_
{
ovrResult Result; ///< The result from the last API call that generated an error ovrResult.
char ErrorString[512]; ///< A UTF8-encoded null-terminated English string describing the problem. The format of this string is subject to change in future versions.
} ovrErrorInfo;
#endif /* OVR_ErrorCode_h */

+ 60
- 0
src/external/OculusSDK/LibOVR/Include/OVR_Version.h 查看文件

@ -0,0 +1,60 @@
/********************************************************************************//**
\file OVR_Version.h
\brief This header provides LibOVR version identification.
\copyright Copyright 2014-2016 Oculus VR, LLC All Rights reserved.
*************************************************************************************/
#ifndef OVR_Version_h
#define OVR_Version_h
/// Conventional string-ification macro.
#if !defined(OVR_STRINGIZE)
#define OVR_STRINGIZEIMPL(x) #x
#define OVR_STRINGIZE(x) OVR_STRINGIZEIMPL(x)
#endif
// Master version numbers
#define OVR_PRODUCT_VERSION 1 // Product version doesn't participate in semantic versioning.
#define OVR_MAJOR_VERSION 1 // If you change these values then you need to also make sure to change LibOVR/Projects/Windows/LibOVR.props in parallel.
#define OVR_MINOR_VERSION 4 //
#define OVR_PATCH_VERSION 0
#define OVR_BUILD_NUMBER 0
// This is the ((product * 100) + major) version of the service that the DLL is compatible with.
// When we backport changes to old versions of the DLL we update the old DLLs
// to move this version number up to the latest version.
// The DLL is responsible for checking that the service is the version it supports
// and returning an appropriate error message if it has not been made compatible.
#define OVR_DLL_COMPATIBLE_VERSION 101
#define OVR_FEATURE_VERSION 0
/// "Major.Minor.Patch"
#if !defined(OVR_VERSION_STRING)
#define OVR_VERSION_STRING OVR_STRINGIZE(OVR_MAJOR_VERSION.OVR_MINOR_VERSION.OVR_PATCH_VERSION)
#endif
/// "Major.Minor.Patch.Build"
#if !defined(OVR_DETAILED_VERSION_STRING)
#define OVR_DETAILED_VERSION_STRING OVR_STRINGIZE(OVR_MAJOR_VERSION.OVR_MINOR_VERSION.OVR_PATCH_VERSION.OVR_BUILD_NUMBER)
#endif
/// \brief file description for version info
/// This appears in the user-visible file properties. It is intended to convey publicly
/// available additional information such as feature builds.
#if !defined(OVR_FILE_DESCRIPTION_STRING)
#if defined(_DEBUG)
#define OVR_FILE_DESCRIPTION_STRING "dev build debug"
#else
#define OVR_FILE_DESCRIPTION_STRING "dev build"
#endif
#endif
#endif // OVR_Version_h

二进制
src/external/OculusSDK/LibOVR/LibOVRRT32_1.dll 查看文件


+ 17
- 17
src/gestures.c 查看文件

@ -111,6 +111,19 @@ static double GetCurrentTime(void);
// Module Functions Definition
//----------------------------------------------------------------------------------
// Enable only desired getures to be detected
void SetGesturesEnabled(unsigned int gestureFlags)
{
enabledGestures = gestureFlags;
}
// Check if a gesture have been detected
bool IsGestureDetected(int gesture)
{
if ((enabledGestures & currentGesture) == gesture) return true;
else return false;
}
// Process gesture event and translate it into gestures
void ProcessGestureEvent(GestureEvent event)
{
@ -291,20 +304,6 @@ void UpdateGestures(void)
}
}
// Check if a gesture have been detected
bool IsGestureDetected(int gesture)
{
if ((enabledGestures & currentGesture) == gesture) return true;
else return false;
}
// Check gesture type
int GetGestureDetected(void)
{
// Get current gesture only if enabled
return (enabledGestures & currentGesture);
}
// Get number of touch points
int GetTouchPointsCount(void)
{
@ -313,10 +312,11 @@ int GetTouchPointsCount(void)
return pointCount;
}
// Enable only desired getures to be detected
void SetGesturesEnabled(unsigned int gestureFlags)
// Get latest detected gesture
int GetGestureDetected(void)
{
enabledGestures = gestureFlags;
// Get current gesture only if enabled
return (enabledGestures & currentGesture);
}
// Hold time measured in ms

+ 4
- 4
src/gestures.h 查看文件

@ -90,13 +90,13 @@ extern "C" { // Prevents name mangling of functions
//----------------------------------------------------------------------------------
// Module Functions Declaration
//----------------------------------------------------------------------------------
void SetGesturesEnabled(unsigned int gestureFlags); // Enable a set of gestures using flags
bool IsGestureDetected(int gesture); // Check if a gesture have been detected
void ProcessGestureEvent(GestureEvent event); // Process gesture event and translate it into gestures
void UpdateGestures(void); // Update gestures detected (must be called every frame)
bool IsGestureDetected(int gesture); // Check if a gesture have been detected
int GetGestureDetected(void); // Get latest detected gesture
void SetGesturesEnabled(unsigned int gestureFlags); // Enable a set of gestures using flags
int GetTouchPointsCount(void); // Get touch points count
int GetTouchPointsCount(void); // Get touch points count
int GetGestureDetected(void); // Get latest detected gesture
float GetGestureHoldDuration(void); // Get gesture hold time in milliseconds
Vector2 GetGestureDragVector(void); // Get gesture drag vector
float GetGestureDragAngle(void); // Get gesture drag angle

+ 107
- 101
src/raygui.h 查看文件

@ -242,106 +242,7 @@ typedef enum GuiProperty {
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
static const char *guiPropertyName[] = {
"GLOBAL_BASE_COLOR",
"GLOBAL_BORDER_COLOR",
"GLOBAL_TEXT_COLOR",
"GLOBAL_TEXT_FONTSIZE",
"GLOBAL_BORDER_WIDTH",
"BACKGROUND_COLOR",
"LABEL_BORDER_WIDTH",
"LABEL_TEXT_COLOR",
"LABEL_TEXT_PADDING",
"BUTTON_BORDER_WIDTH",
"BUTTON_TEXT_PADDING",
"BUTTON_DEFAULT_BORDER_COLOR",
"BUTTON_DEFAULT_INSIDE_COLOR",
"BUTTON_DEFAULT_TEXT_COLOR",
"BUTTON_HOVER_BORDER_COLOR",
"BUTTON_HOVER_INSIDE_COLOR",
"BUTTON_HOVER_TEXT_COLOR",
"BUTTON_PRESSED_BORDER_COLOR",
"BUTTON_PRESSED_INSIDE_COLOR",
"BUTTON_PRESSED_TEXT_COLOR",
"TOGGLE_TEXT_PADDING",
"TOGGLE_BORDER_WIDTH",
"TOGGLE_DEFAULT_BORDER_COLOR",
"TOGGLE_DEFAULT_INSIDE_COLOR",
"TOGGLE_DEFAULT_TEXT_COLOR",
"TOGGLE_HOVER_BORDER_COLOR",
"TOGGLE_HOVER_INSIDE_COLOR",
"TOGGLE_HOVER_TEXT_COLOR",
"TOGGLE_PRESSED_BORDER_COLOR",
"TOGGLE_PRESSED_INSIDE_COLOR",
"TOGGLE_PRESSED_TEXT_COLOR",
"TOGGLE_ACTIVE_BORDER_COLOR",
"TOGGLE_ACTIVE_INSIDE_COLOR",
"TOGGLE_ACTIVE_TEXT_COLOR",
"TOGGLEGROUP_PADDING",
"SLIDER_BORDER_WIDTH",
"SLIDER_BUTTON_BORDER_WIDTH",
"SLIDER_BORDER_COLOR",
"SLIDER_INSIDE_COLOR",
"SLIDER_DEFAULT_COLOR",
"SLIDER_HOVER_COLOR",
"SLIDER_ACTIVE_COLOR",
"SLIDERBAR_BORDER_COLOR",
"SLIDERBAR_INSIDE_COLOR",
"SLIDERBAR_DEFAULT_COLOR",
"SLIDERBAR_HOVER_COLOR",
"SLIDERBAR_ACTIVE_COLOR",
"SLIDERBAR_ZERO_LINE_COLOR",
"PROGRESSBAR_BORDER_COLOR",
"PROGRESSBAR_INSIDE_COLOR",
"PROGRESSBAR_PROGRESS_COLOR",
"PROGRESSBAR_BORDER_WIDTH",
"SPINNER_LABEL_BORDER_COLOR",
"SPINNER_LABEL_INSIDE_COLOR",
"SPINNER_DEFAULT_BUTTON_BORDER_COLOR",
"SPINNER_DEFAULT_BUTTON_INSIDE_COLOR",
"SPINNER_DEFAULT_SYMBOL_COLOR",
"SPINNER_DEFAULT_TEXT_COLOR",
"SPINNER_HOVER_BUTTON_BORDER_COLOR",
"SPINNER_HOVER_BUTTON_INSIDE_COLOR",
"SPINNER_HOVER_SYMBOL_COLOR",
"SPINNER_HOVER_TEXT_COLOR",
"SPINNER_PRESSED_BUTTON_BORDER_COLOR",
"SPINNER_PRESSED_BUTTON_INSIDE_COLOR",
"SPINNER_PRESSED_SYMBOL_COLOR",
"SPINNER_PRESSED_TEXT_COLOR",
"COMBOBOX_PADDING",
"COMBOBOX_BUTTON_WIDTH",
"COMBOBOX_BUTTON_HEIGHT",
"COMBOBOX_BORDER_WIDTH",
"COMBOBOX_DEFAULT_BORDER_COLOR",
"COMBOBOX_DEFAULT_INSIDE_COLOR",
"COMBOBOX_DEFAULT_TEXT_COLOR",
"COMBOBOX_DEFAULT_LIST_TEXT_COLOR",
"COMBOBOX_HOVER_BORDER_COLOR",
"COMBOBOX_HOVER_INSIDE_COLOR",
"COMBOBOX_HOVER_TEXT_COLOR",
"COMBOBOX_HOVER_LIST_TEXT_COLOR",
"COMBOBOX_PRESSED_BORDER_COLOR",
"COMBOBOX_PRESSED_INSIDE_COLOR",
"COMBOBOX_PRESSED_TEXT_COLOR",
"COMBOBOX_PRESSED_LIST_BORDER_COLOR",
"COMBOBOX_PRESSED_LIST_INSIDE_COLOR",
"COMBOBOX_PRESSED_LIST_TEXT_COLOR",
"CHECKBOX_DEFAULT_BORDER_COLOR",
"CHECKBOX_DEFAULT_INSIDE_COLOR",
"CHECKBOX_HOVER_BORDER_COLOR",
"CHECKBOX_HOVER_INSIDE_COLOR",
"CHECKBOX_CLICK_BORDER_COLOR",
"CHECKBOX_CLICK_INSIDE_COLOR",
"CHECKBOX_STATUS_ACTIVE_COLOR",
"CHECKBOX_INSIDE_WIDTH",
"TEXTBOX_BORDER_WIDTH",
"TEXTBOX_BORDER_COLOR",
"TEXTBOX_INSIDE_COLOR",
"TEXTBOX_TEXT_COLOR",
"TEXTBOX_LINE_COLOR",
"TEXTBOX_TEXT_FONTSIZE"
};
// ...
//----------------------------------------------------------------------------------
// Module Functions Declaration
@ -517,6 +418,108 @@ static int style[NUM_PROPERTIES] = {
10 // TEXTBOX_TEXT_FONTSIZE
};
// GUI property names (to read/write style text files)
static const char *guiPropertyName[] = {
"GLOBAL_BASE_COLOR",
"GLOBAL_BORDER_COLOR",
"GLOBAL_TEXT_COLOR",
"GLOBAL_TEXT_FONTSIZE",
"GLOBAL_BORDER_WIDTH",
"BACKGROUND_COLOR",
"LABEL_BORDER_WIDTH",
"LABEL_TEXT_COLOR",
"LABEL_TEXT_PADDING",
"BUTTON_BORDER_WIDTH",
"BUTTON_TEXT_PADDING",
"BUTTON_DEFAULT_BORDER_COLOR",
"BUTTON_DEFAULT_INSIDE_COLOR",
"BUTTON_DEFAULT_TEXT_COLOR",
"BUTTON_HOVER_BORDER_COLOR",
"BUTTON_HOVER_INSIDE_COLOR",
"BUTTON_HOVER_TEXT_COLOR",
"BUTTON_PRESSED_BORDER_COLOR",
"BUTTON_PRESSED_INSIDE_COLOR",
"BUTTON_PRESSED_TEXT_COLOR",
"TOGGLE_TEXT_PADDING",
"TOGGLE_BORDER_WIDTH",
"TOGGLE_DEFAULT_BORDER_COLOR",
"TOGGLE_DEFAULT_INSIDE_COLOR",
"TOGGLE_DEFAULT_TEXT_COLOR",
"TOGGLE_HOVER_BORDER_COLOR",
"TOGGLE_HOVER_INSIDE_COLOR",
"TOGGLE_HOVER_TEXT_COLOR",
"TOGGLE_PRESSED_BORDER_COLOR",
"TOGGLE_PRESSED_INSIDE_COLOR",
"TOGGLE_PRESSED_TEXT_COLOR",
"TOGGLE_ACTIVE_BORDER_COLOR",
"TOGGLE_ACTIVE_INSIDE_COLOR",
"TOGGLE_ACTIVE_TEXT_COLOR",
"TOGGLEGROUP_PADDING",
"SLIDER_BORDER_WIDTH",
"SLIDER_BUTTON_BORDER_WIDTH",
"SLIDER_BORDER_COLOR",
"SLIDER_INSIDE_COLOR",
"SLIDER_DEFAULT_COLOR",
"SLIDER_HOVER_COLOR",
"SLIDER_ACTIVE_COLOR",
"SLIDERBAR_BORDER_COLOR",
"SLIDERBAR_INSIDE_COLOR",
"SLIDERBAR_DEFAULT_COLOR",
"SLIDERBAR_HOVER_COLOR",
"SLIDERBAR_ACTIVE_COLOR",
"SLIDERBAR_ZERO_LINE_COLOR",
"PROGRESSBAR_BORDER_COLOR",
"PROGRESSBAR_INSIDE_COLOR",
"PROGRESSBAR_PROGRESS_COLOR",
"PROGRESSBAR_BORDER_WIDTH",
"SPINNER_LABEL_BORDER_COLOR",
"SPINNER_LABEL_INSIDE_COLOR",
"SPINNER_DEFAULT_BUTTON_BORDER_COLOR",
"SPINNER_DEFAULT_BUTTON_INSIDE_COLOR",
"SPINNER_DEFAULT_SYMBOL_COLOR",
"SPINNER_DEFAULT_TEXT_COLOR",
"SPINNER_HOVER_BUTTON_BORDER_COLOR",
"SPINNER_HOVER_BUTTON_INSIDE_COLOR",
"SPINNER_HOVER_SYMBOL_COLOR",
"SPINNER_HOVER_TEXT_COLOR",
"SPINNER_PRESSED_BUTTON_BORDER_COLOR",
"SPINNER_PRESSED_BUTTON_INSIDE_COLOR",
"SPINNER_PRESSED_SYMBOL_COLOR",
"SPINNER_PRESSED_TEXT_COLOR",
"COMBOBOX_PADDING",
"COMBOBOX_BUTTON_WIDTH",
"COMBOBOX_BUTTON_HEIGHT",
"COMBOBOX_BORDER_WIDTH",
"COMBOBOX_DEFAULT_BORDER_COLOR",
"COMBOBOX_DEFAULT_INSIDE_COLOR",
"COMBOBOX_DEFAULT_TEXT_COLOR",
"COMBOBOX_DEFAULT_LIST_TEXT_COLOR",
"COMBOBOX_HOVER_BORDER_COLOR",
"COMBOBOX_HOVER_INSIDE_COLOR",
"COMBOBOX_HOVER_TEXT_COLOR",
"COMBOBOX_HOVER_LIST_TEXT_COLOR",
"COMBOBOX_PRESSED_BORDER_COLOR",
"COMBOBOX_PRESSED_INSIDE_COLOR",
"COMBOBOX_PRESSED_TEXT_COLOR",
"COMBOBOX_PRESSED_LIST_BORDER_COLOR",
"COMBOBOX_PRESSED_LIST_INSIDE_COLOR",
"COMBOBOX_PRESSED_LIST_TEXT_COLOR",
"CHECKBOX_DEFAULT_BORDER_COLOR",
"CHECKBOX_DEFAULT_INSIDE_COLOR",
"CHECKBOX_HOVER_BORDER_COLOR",
"CHECKBOX_HOVER_INSIDE_COLOR",
"CHECKBOX_CLICK_BORDER_COLOR",
"CHECKBOX_CLICK_INSIDE_COLOR",
"CHECKBOX_STATUS_ACTIVE_COLOR",
"CHECKBOX_INSIDE_WIDTH",
"TEXTBOX_BORDER_WIDTH",
"TEXTBOX_BORDER_COLOR",
"TEXTBOX_INSIDE_COLOR",
"TEXTBOX_TEXT_COLOR",
"TEXTBOX_LINE_COLOR",
"TEXTBOX_TEXT_FONTSIZE"
};
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
@ -529,7 +532,9 @@ static bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if p
static const char *FormatText(const char *text, ...); // Formatting of text with variables to 'embed'
// NOTE: raygui depend on some raylib input and drawing functions
// TODO: Replace by your own functions
// TODO: To use raygui as standalone library, those functions must be overwrite by custom ones
// Input management functions
static Vector2 GetMousePosition() { return (Vector2){ 0.0f, 0.0f }; }
static int IsMouseButtonDown(int button) { return 0; }
static int IsMouseButtonPressed(int button) { return 0; }
@ -539,6 +544,7 @@ static int IsMouseButtonUp(int button) { return 0; }
static int GetKeyPressed(void) { return 0; } // NOTE: Only used by GuiTextBox()
static int IsKeyDown(int key) { return 0; } // NOTE: Only used by GuiSpinner()
// Drawing related functions
static int MeasureText(const char *text, int fontSize) { return 0; }
static void DrawText(const char *text, int posX, int posY, int fontSize, Color color) { }
static void DrawRectangleRec(Rectangle rec, Color color) { }

+ 16
- 11
src/raylib.h 查看文件

@ -64,7 +64,7 @@
//#define PLATFORM_ANDROID // Android device
//#define PLATFORM_RPI // Raspberry Pi
//#define PLATFORM_WEB // HTML5 (emscripten, asm.js)
//#define PLATFORM_OCULUS // Oculus Rift CV1
//#define RLGL_OCULUS_SUPPORT // Oculus Rift CV1 (complementary to PLATFORM_DESKTOP)
// Security check in case no PLATFORM_* defined
#if !defined(PLATFORM_DESKTOP) && !defined(PLATFORM_ANDROID) && !defined(PLATFORM_RPI) && !defined(PLATFORM_WEB)
@ -545,12 +545,6 @@ void InitWindow(int width, int height, struct android_app *state); // Init Andr
void InitWindow(int width, int height, const char *title); // Initialize Window and OpenGL Graphics
#endif
#if defined(PLATFORM_OCULUS)
void InitOculusDevice(void); // Init Oculus Rift device
void CloseOculusDevice(void); // Close Oculus Rift device
void UpdateOculusTracking(void); // Update Oculus Rift tracking (position and orientation)
#endif
void CloseWindow(void); // Close Window and Terminate Context
bool WindowShouldClose(void); // Detect if KEY_ESCAPE pressed or Close icon pressed
bool IsWindowMinimized(void); // Detect if window has been minimized (or lost focus)
@ -644,13 +638,13 @@ bool IsButtonReleased(int button); // Detect if an android
//------------------------------------------------------------------------------------
// Gestures and Touch Handling Functions (Module: gestures)
//------------------------------------------------------------------------------------
void SetGesturesEnabled(unsigned int gestureFlags); // Enable a set of gestures using flags
bool IsGestureDetected(int gesture); // Check if a gesture have been detected
void ProcessGestureEvent(GestureEvent event); // Process gesture event and translate it into gestures
void UpdateGestures(void); // Update gestures detected (called automatically in PollInputEvents())
bool IsGestureDetected(int gesture); // Check if a gesture have been detected
int GetGestureDetected(void); // Get latest detected gesture
void SetGesturesEnabled(unsigned int gestureFlags); // Enable a set of gestures using flags
int GetTouchPointsCount(void); // Get touch points count
int GetTouchPointsCount(void); // Get touch points count
int GetGestureDetected(void); // Get latest detected gesture
float GetGestureHoldDuration(void); // Get gesture hold time in milliseconds
Vector2 GetGestureDragVector(void); // Get gesture drag vector
float GetGestureDragAngle(void); // Get gesture drag angle
@ -852,6 +846,17 @@ void EndBlendMode(void); // End blend
Light CreateLight(int type, Vector3 position, Color diffuse); // Create a new light, initialize it and add to pool
void DestroyLight(Light light); // Destroy a light and take it out of the list
//------------------------------------------------------------------------------------
// Oculus Rift CV1 Functions (Module: rlgl)
// NOTE: This functions are useless when using OpenGL 1.1
//------------------------------------------------------------------------------------
void InitOculusDevice(void); // Init Oculus Rift device
void CloseOculusDevice(void); // Close Oculus Rift device
void UpdateOculusTracking(void); // Update Oculus Rift tracking (position and orientation)
void SetOculusMatrix(int eye); // Set internal projection and modelview matrix depending on eyes tracking data
void BeginOculusDrawing(void); // Begin Oculus drawing configuration
void EndOculusDrawing(void); // End Oculus drawing process (and desktop mirror)
//------------------------------------------------------------------------------------
// Audio Loading and Playing Functions (Module: audio)
//------------------------------------------------------------------------------------

+ 378
- 1
src/rlgl.c 查看文件

@ -72,6 +72,10 @@
#include "standard_shader.h" // Standard shader to embed
#endif
#if defined(RLGL_OCULUS_SUPPORT)
#include "external/OculusSDK/LibOVR/Include/OVR_CAPI_GL.h" // Oculus SDK for OpenGL
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
@ -172,6 +176,32 @@ typedef struct {
//Guint fboId;
} DrawCall;
#if defined(RLGL_OCULUS_SUPPORT)
typedef struct OculusBuffer {
ovrTextureSwapChain textureChain;
GLuint depthId;
GLuint fboId;
int width;
int height;
} OculusBuffer;
typedef struct OculusMirror {
ovrMirrorTexture texture;
GLuint fboId;
int width;
int height;
} OculusMirror;
typedef struct OculusLayer {
ovrViewScaleDesc viewScaleDesc;
ovrLayerEyeFov eyeLayer; // layer 0
//ovrLayerQuad quadLayer; // TODO: layer 1: '2D' quad for GUI
Matrix eyeProjections[2];
int width;
int height;
} OculusLayer;
#endif
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
@ -221,6 +251,17 @@ static Light lights[MAX_LIGHTS]; // Lights pool
static int lightsCount; // Counts current enabled physic objects
#endif
#if defined(RLGL_OCULUS_SUPPORT)
// OVR device variables
static ovrSession session; // Oculus session (pointer to ovrHmdStruct)
static ovrHmdDesc hmdDesc; // Oculus device descriptor parameters
static ovrGraphicsLuid luid; // Oculus locally unique identifier for the program (64 bit)
static OculusLayer layer; // Oculus drawing layer (similar to photoshop)
static OculusBuffer buffer; // Oculus internal buffers (texture chain and fbo)
static OculusMirror mirror; // Oculus mirror texture and fbo
static unsigned int frameIndex = 0; // Oculus frames counter, used to discard frames from chain
#endif
// Compressed textures support flags
static bool texCompDXTSupported = false; // DDS texture compression support
static bool npotSupported = false; // NPOT textures full support
@ -261,6 +302,16 @@ static void SetShaderLights(Shader shader); // Sets shader uniform values for li
static char *ReadTextFile(const char *fileName);
#endif
#if defined(RLGL_OCULUS_SUPPORT) // Oculus Rift functions
static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height); // Load Oculus required buffers
static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer); // Unload texture required buffers
static OculusMirror LoadOculusMirror(ovrSession session, int width, int height); // Load Oculus mirror buffers
static void UnloadOculusMirror(ovrSession session, OculusMirror mirror); // Unload Oculus mirror buffers
static void BlitOculusMirror(ovrSession session, OculusMirror mirror); // Copy Oculus screen buffer to mirror texture
static OculusLayer InitOculusLayer(ovrSession session); // Init Oculus layer (similar to photoshop)
static Matrix FromOvrMatrix(ovrMatrix4f ovrM); // Convert from Oculus ovrMatrix4f struct to raymath Matrix struct
#endif
#if defined(GRAPHICS_API_OPENGL_11)
static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight);
static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight);
@ -1153,6 +1204,23 @@ void rlglInitGraphics(int offsetX, int offsetY, int width, int height)
TraceLog(INFO, "OpenGL graphic device initialized successfully");
}
// Load OpenGL extensions
// NOTE: External loader function could be passed as a pointer
void rlglLoadExtensions(void *loader)
{
#if defined(GRAPHICS_API_OPENGL_33)
// NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions
if (!gladLoadGLLoader((GLADloadproc)loader)) TraceLog(WARNING, "GLAD: Cannot load OpenGL extensions");
else TraceLog(INFO, "GLAD: OpenGL extensions loaded successfully");
if (GLAD_GL_VERSION_3_3) TraceLog(INFO, "OpenGL 3.3 Core profile supported");
else TraceLog(ERROR, "OpenGL 3.3 Core profile not supported");
// With GLAD, we can check if an extension is supported using the GLAD_GL_xxx booleans
//if (GLAD_GL_ARB_vertex_array_object) // Use GL_ARB_vertex_array_object
#endif
}
// Get world coordinates from screen coordinates
Vector3 rlglUnproject(Vector3 source, Matrix proj, Matrix view)
{
@ -1184,11 +1252,13 @@ unsigned int rlglLoadTexture(void *data, int width, int height, int textureForma
GLuint id = 0;
// Check texture format support by OpenGL 1.1 (compressed textures not supported)
if ((rlGetVersion() == OPENGL_11) && (textureFormat >= 8))
#if defined(GRAPHICS_API_OPENGL_11)
if (textureFormat >= 8)
{
TraceLog(WARNING, "OpenGL 1.1 does not support GPU compressed texture formats");
return id;
}
#endif
if ((!texCompDXTSupported) && ((textureFormat == COMPRESSED_DXT1_RGB) || (textureFormat == COMPRESSED_DXT1_RGBA) ||
(textureFormat == COMPRESSED_DXT3_RGBA) || (textureFormat == COMPRESSED_DXT5_RGBA)))
@ -2391,6 +2461,132 @@ void DestroyLight(Light light)
#endif
}
#if defined(RLGL_OCULUS_SUPPORT)
// Init Oculus Rift device
// NOTE: Device initialization should be done before window creation?
void InitOculusDevice(void)
{
// Initialize Oculus device
ovrResult result = ovr_Initialize(NULL);
if (OVR_FAILURE(result)) TraceLog(WARNING, "OVR: Could not initialize Oculus device");
result = ovr_Create(&session, &luid);
if (OVR_FAILURE(result))
{
TraceLog(WARNING, "OVR: Could not create Oculus session");
ovr_Shutdown();
}
hmdDesc = ovr_GetHmdDesc(session);
TraceLog(INFO, "OVR: Product Name: %s", hmdDesc.ProductName);
TraceLog(INFO, "OVR: Manufacturer: %s", hmdDesc.Manufacturer);
TraceLog(INFO, "OVR: Product ID: %i", hmdDesc.ProductId);
TraceLog(INFO, "OVR: Product Type: %i", hmdDesc.Type);
//TraceLog(INFO, "OVR: Serial Number: %s", hmdDesc.SerialNumber);
TraceLog(INFO, "OVR: Resolution: %ix%i", hmdDesc.Resolution.w, hmdDesc.Resolution.h);
// NOTE: Oculus mirror is set to defined screenWidth and screenHeight...
// ...ideally, it should be (hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2)
// Initialize Oculus Buffers
layer = InitOculusLayer(session);
buffer = LoadOculusBuffer(session, layer.width, layer.height);
mirror = LoadOculusMirror(session, hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2); // NOTE: hardcoded...
layer.eyeLayer.ColorTexture[0] = buffer.textureChain; //SetOculusLayerTexture(eyeLayer, buffer.textureChain);
// Recenter OVR tracking origin
ovr_RecenterTrackingOrigin(session);
}
// Close Oculus Rift device
void CloseOculusDevice(void)
{
UnloadOculusMirror(session, mirror); // Unload Oculus mirror buffer
UnloadOculusBuffer(session, buffer); // Unload Oculus texture buffers
ovr_Destroy(session); // Free Oculus session data
ovr_Shutdown(); // Close Oculus device connection
}
// Update Oculus Rift tracking (position and orientation)
void UpdateOculusTracking(void)
{
frameIndex++;
ovrPosef eyePoses[2];
ovr_GetEyePoses(session, frameIndex, ovrTrue, layer.viewScaleDesc.HmdToEyeOffset, eyePoses, &layer.eyeLayer.SensorSampleTime);
layer.eyeLayer.RenderPose[0] = eyePoses[0];
layer.eyeLayer.RenderPose[1] = eyePoses[1];
}
void SetOculusMatrix(int eye)
{
rlViewport(layer.eyeLayer.Viewport[eye].Pos.x, layer.eyeLayer.Viewport[eye].Pos.y, layer.eyeLayer.Viewport[eye].Size.w, layer.eyeLayer.Viewport[eye].Size.h);
Quaternion eyeRPose = (Quaternion){ layer.eyeLayer.RenderPose[eye].Orientation.x,
layer.eyeLayer.RenderPose[eye].Orientation.y,
layer.eyeLayer.RenderPose[eye].Orientation.z,
layer.eyeLayer.RenderPose[eye].Orientation.w };
QuaternionInvert(&eyeRPose);
Matrix eyeOrientation = QuaternionToMatrix(eyeRPose);
Matrix eyeTranslation = MatrixTranslate(-layer.eyeLayer.RenderPose[eye].Position.x,
-layer.eyeLayer.RenderPose[eye].Position.y,
-layer.eyeLayer.RenderPose[eye].Position.z);
Matrix eyeView = MatrixMultiply(eyeTranslation, eyeOrientation);
Matrix modelEyeView = MatrixMultiply(modelview, eyeView); // Using internal camera modelview matrix
SetMatrixModelview(modelEyeView);
SetMatrixProjection(layer.eyeProjections[eye]);
}
void BeginOculusDrawing(void)
{
GLuint currentTexId;
int currentIndex;
ovr_GetTextureSwapChainCurrentIndex(session, buffer.textureChain, &currentIndex);
ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, currentIndex, &currentTexId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, currentTexId, 0);
//glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, buffer.depthId, 0); // Already binded
//glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye)
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Same as rlClearScreenBuffers()
// NOTE: If your application is configured to treat the texture as a linear format (e.g. GL_RGBA)
// and performs linear-to-gamma conversion in GLSL or does not care about gamma-correction, then:
// - Require OculusBuffer format to be OVR_FORMAT_R8G8B8A8_UNORM_SRGB
// - Do NOT enable GL_FRAMEBUFFER_SRGB
//glEnable(GL_FRAMEBUFFER_SRGB);
rlClearScreenBuffers(); // Clear current framebuffer(s)
}
void EndOculusDrawing(void)
{
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
ovr_CommitTextureSwapChain(session, buffer.textureChain);
ovrLayerHeader *layers = &layer.eyeLayer.Header;
ovr_SubmitFrame(session, frameIndex, &layer.viewScaleDesc, &layers, 1);
// Blit mirror texture to back buffer
BlitOculusMirror(session, mirror);
// Get session status information
ovrSessionStatus sessionStatus;
ovr_GetSessionStatus(session, &sessionStatus);
if (sessionStatus.ShouldQuit) TraceLog(WARNING, "OVR: Session should quit...");
if (sessionStatus.ShouldRecenter) ovr_RecenterTrackingOrigin(session);
}
#endif
//----------------------------------------------------------------------------------
// Module specific Functions Definition
//----------------------------------------------------------------------------------
@ -3371,6 +3567,187 @@ static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight)
}
#endif
#if defined(RLGL_OCULUS_SUPPORT)
// Load Oculus required buffers: texture-swap-chain, fbo, texture-depth
static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height)
{
OculusBuffer buffer;
buffer.width = width;
buffer.height = height;
// Create OVR texture chain
ovrTextureSwapChainDesc desc = {};
desc.Type = ovrTexture_2D;
desc.ArraySize = 1;
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; // Requires glEnable(GL_FRAMEBUFFER_SRGB);
desc.SampleCount = 1;
desc.StaticImage = ovrFalse;
ovrResult result = ovr_CreateTextureSwapChainGL(session, &desc, &buffer.textureChain);
if (!OVR_SUCCESS(result)) TraceLog(WARNING, "OVR: Failed to create swap textures buffer");
int textureCount = 0;
ovr_GetTextureSwapChainLength(session, buffer.textureChain, &textureCount);
if (!OVR_SUCCESS(result) || !textureCount) TraceLog(WARNING, "OVR: Unable to count swap chain textures");
for (int i = 0; i < textureCount; ++i)
{
GLuint chainTexId;
ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, i, &chainTexId);
glBindTexture(GL_TEXTURE_2D, chainTexId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
glBindTexture(GL_TEXTURE_2D, 0);
/*
// Setup framebuffer object (using depth texture)
glGenFramebuffers(1, &buffer.fboId);
glGenTextures(1, &buffer.depthId);
glBindTexture(GL_TEXTURE_2D, buffer.depthId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, buffer.width, buffer.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
*/
// Setup framebuffer object (using depth renderbuffer)
glGenFramebuffers(1, &buffer.fboId);
glGenRenderbuffers(1, &buffer.depthId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId);
glBindRenderbuffer(GL_RENDERBUFFER, buffer.depthId);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, buffer.width, buffer.height);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, buffer.depthId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
return buffer;
}
// Unload texture required buffers
static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer)
{
if (buffer.textureChain)
{
ovr_DestroyTextureSwapChain(session, buffer.textureChain);
buffer.textureChain = NULL;
}
if (buffer.depthId != 0) glDeleteTextures(1, &buffer.depthId);
if (buffer.fboId != 0) glDeleteFramebuffers(1, &buffer.fboId);
}
// Load Oculus mirror buffers
static OculusMirror LoadOculusMirror(ovrSession session, int width, int height)
{
OculusMirror mirror;
mirror.width = width;
mirror.height = height;
ovrMirrorTextureDesc mirrorDesc;
memset(&mirrorDesc, 0, sizeof(mirrorDesc));
mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
mirrorDesc.Width = mirror.width;
mirrorDesc.Height = mirror.height;
if (!OVR_SUCCESS(ovr_CreateMirrorTextureGL(session, &mirrorDesc, &mirror.texture))) TraceLog(WARNING, "Could not create mirror texture");
glGenFramebuffers(1, &mirror.fboId);
return mirror;
}
// Unload Oculus mirror buffers
static void UnloadOculusMirror(ovrSession session, OculusMirror mirror)
{
if (mirror.fboId != 0) glDeleteFramebuffers(1, &mirror.fboId);
if (mirror.texture) ovr_DestroyMirrorTexture(session, mirror.texture);
}
// Copy Oculus screen buffer to mirror texture
static void BlitOculusMirror(ovrSession session, OculusMirror mirror)
{
GLuint mirrorTextureId;
ovr_GetMirrorTextureBufferGL(session, mirror.texture, &mirrorTextureId);
glBindFramebuffer(GL_READ_FRAMEBUFFER, mirror.fboId);
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mirrorTextureId, 0);
glBlitFramebuffer(0, 0, mirror.width, mirror.height, 0, mirror.height, mirror.width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
// Init Oculus layer (similar to photoshop)
static OculusLayer InitOculusLayer(ovrSession session)
{
OculusLayer layer = { 0 };
layer.viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.0f;
memset(&layer.eyeLayer, 0, sizeof(ovrLayerEyeFov));
layer.eyeLayer.Header.Type = ovrLayerType_EyeFov;
layer.eyeLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft;
ovrEyeRenderDesc eyeRenderDescs[2];
for (int eye = 0; eye < 2; eye++)
{
eyeRenderDescs[eye] = ovr_GetRenderDesc(session, eye, hmdDesc.DefaultEyeFov[eye]);
ovrMatrix4f ovrPerspectiveProjection = ovrMatrix4f_Projection(eyeRenderDescs[eye].Fov, 0.01f, 10000.0f, ovrProjection_None); //ovrProjection_ClipRangeOpenGL);
layer.eyeProjections[eye] = FromOvrMatrix(ovrPerspectiveProjection); // NOTE: struct ovrMatrix4f { float M[4][4] } --> struct Matrix
layer.viewScaleDesc.HmdToEyeOffset[eye] = eyeRenderDescs[eye].HmdToEyeOffset;
layer.eyeLayer.Fov[eye] = eyeRenderDescs[eye].Fov;
ovrSizei eyeSize = ovr_GetFovTextureSize(session, eye, layer.eyeLayer.Fov[eye], 1.0f);
layer.eyeLayer.Viewport[eye].Size = eyeSize;
layer.eyeLayer.Viewport[eye].Pos.x = layer.width;
layer.eyeLayer.Viewport[eye].Pos.y = 0;
layer.height = eyeSize.h; //std::max(renderTargetSize.y, (uint32_t)eyeSize.h);
layer.width += eyeSize.w;
}
return layer;
}
// Convert from Oculus ovrMatrix4f struct to raymath Matrix struct
static Matrix FromOvrMatrix(ovrMatrix4f ovrmat)
{
Matrix rmat;
rmat.m0 = ovrmat.M[0][0];
rmat.m1 = ovrmat.M[1][0];
rmat.m2 = ovrmat.M[2][0];
rmat.m3 = ovrmat.M[3][0];
rmat.m4 = ovrmat.M[0][1];
rmat.m5 = ovrmat.M[1][1];
rmat.m6 = ovrmat.M[2][1];
rmat.m7 = ovrmat.M[3][1];
rmat.m8 = ovrmat.M[0][2];
rmat.m9 = ovrmat.M[1][2];
rmat.m10 = ovrmat.M[2][2];
rmat.m11 = ovrmat.M[3][2];
rmat.m12 = ovrmat.M[0][3];
rmat.m13 = ovrmat.M[1][3];
rmat.m14 = ovrmat.M[2][3];
rmat.m15 = ovrmat.M[3][3];
MatrixTranspose(&rmat);
return rmat;
}
#endif
#if defined(RLGL_STANDALONE)
// Output a trace log message
// NOTE: Expected msgType: (0)Info, (1)Error, (2)Warning

+ 11
- 1
src/rlgl.h 查看文件

@ -48,7 +48,7 @@
// Choose opengl version here or just define it at compile time: -DGRAPHICS_API_OPENGL_33
//#define GRAPHICS_API_OPENGL_11 // Only available on PLATFORM_DESKTOP
//#define GRAPHICS_API_OPENGL_33 // Only available on PLATFORM_DESKTOP
//#define GRAPHICS_API_OPENGL_33 // Only available on PLATFORM_DESKTOP or PLATFORM_OCULUS
//#define GRAPHICS_API_OPENGL_ES2 // Only available on PLATFORM_ANDROID or PLATFORM_RPI or PLATFORM_WEB
// Security check in case no GRAPHICS_API_OPENGL_* defined
@ -296,6 +296,7 @@ void rlglInit(void); // Initialize rlgl (shaders, VAO
void rlglClose(void); // De-init rlgl
void rlglDraw(void); // Draw VAO/VBO
void rlglInitGraphics(int offsetX, int offsetY, int width, int height); // Initialize Graphics (OpenGL stuff)
void rlglLoadExtensions(void *loader); // Load OpenGL extensions
unsigned int rlglLoadTexture(void *data, int width, int height, int textureFormat, int mipmapCount); // Load texture in GPU
RenderTexture2D rlglLoadRenderTexture(int width, int height); // Load a texture to be used for rendering (fbo with color and depth attachments)
@ -346,6 +347,15 @@ void DestroyLight(Light light); // Destroy a
void TraceLog(int msgType, const char *text, ...);
#endif
#if defined(RLGL_OCULUS_SUPPORT)
void InitOculusDevice(void); // Init Oculus Rift device
void CloseOculusDevice(void); // Close Oculus Rift device
void UpdateOculusTracking(void); // Update Oculus Rift tracking (position and orientation)
void SetOculusMatrix(int eye); // Set internal projection and modelview matrix depending on eyes tracking data
void BeginOculusDrawing(void); // Begin Oculus drawing configuration
void EndOculusDrawing(void); // End Oculus drawing process (and desktop mirror)
#endif
#ifdef __cplusplus
}
#endif

正在加载...
取消
保存