From 59038bae96bf8e9ae96ce3432ddbde96590f4642 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 5 Mar 2017 21:04:07 +0100 Subject: Added function: DrawLineEx() Supports line thickness --- src/raylib.h | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index beda833c..b0f03bbe 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -98,13 +98,13 @@ #define RAD2DEG (180.0f/PI) // raylib Config Flags -#define FLAG_SHOW_LOGO 1 // Set this flag to show raylib logo at startup -#define FLAG_FULLSCREEN_MODE 2 // Set this flag to run program in fullscreen -#define FLAG_WINDOW_RESIZABLE 4 // Set this flag to allow resizable window -#define FLAG_WINDOW_DECORATED 8 // Set this flag to show window decoration (frame and buttons) -#define FLAG_WINDOW_TRANSPARENT 16 // Set this flag to allow transparent window -#define FLAG_MSAA_4X_HINT 32 // Set this flag to try enabling MSAA 4X -#define FLAG_VSYNC_HINT 64 // Set this flag to try enabling V-Sync on GPU +#define FLAG_SHOW_LOGO 1 // Set to show raylib logo at startup +#define FLAG_FULLSCREEN_MODE 2 // Set to run program in fullscreen +#define FLAG_WINDOW_RESIZABLE 4 // Set to allow resizable window +#define FLAG_WINDOW_DECORATED 8 // Set to show window decoration (frame and buttons) +#define FLAG_WINDOW_TRANSPARENT 16 // Set to allow transparent window +#define FLAG_MSAA_4X_HINT 32 // Set to try enabling MSAA 4X +#define FLAG_VSYNC_HINT 64 // Set to try enabling V-Sync on GPU // Keyboard Function Keys #define KEY_SPACE 32 @@ -763,6 +763,7 @@ RLAPI void DrawPixel(int posX, int posY, Color color); RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel (Vector version) RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (Vector version) +RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line defining thickness RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2); // Draw a gradient-filled circle RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) -- cgit v1.2.3 From 3813722f170066c3113d4a3ef6a21ec53af71034 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Tue, 14 Mar 2017 00:22:53 +0100 Subject: Added function: DrawLineBezier() --- src/raylib.h | 1 + src/shapes.c | 42 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index b0f03bbe..85689378 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -764,6 +764,7 @@ RLAPI void DrawPixelV(Vector2 position, Color color); RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (Vector version) RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line defining thickness +RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line using cubic-bezier curves in-out RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2); // Draw a gradient-filled circle RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) diff --git a/src/shapes.c b/src/shapes.c index 9cbe1da4..5ed633f6 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -57,7 +57,7 @@ //---------------------------------------------------------------------------------- // Module specific Functions Declaration //---------------------------------------------------------------------------------- -// No private (static) functions in this module (.c file) +static float EaseCubicInOut(float t, float b, float c, float d); // Cubic easing //---------------------------------------------------------------------------------- // Module Functions Definition @@ -106,6 +106,13 @@ void DrawLineV(Vector2 startPos, Vector2 endPos, Color color) // Draw a line defining thickness void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color) { + if (startPos.x > endPos.x) + { + Vector2 tempPos = startPos; + startPos = endPos; + endPos = tempPos; + } + float dx = endPos.x - startPos.x; float dy = endPos.y - startPos.y; @@ -133,6 +140,27 @@ void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color) rlDisableTexture(); } +// Draw line using cubic-bezier curves in-out +void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color) +{ + #define LINE_DIVISIONS 24 // Bezier line divisions + + Vector2 previous = startPos; + Vector2 current; + + for (int i = 1; i <= LINE_DIVISIONS; i++) + { + // Cubic easing in-out + // NOTE: Easing is calcutated only for y position value + current.y = EaseCubicInOut(i, startPos.y, endPos.y - startPos.y, LINE_DIVISIONS); + current.x = previous.x + (endPos.x - startPos.x)/LINE_DIVISIONS; + + DrawLineEx(previous, current, thick, color); + + previous = current; + } +} + // Draw a color-filled circle void DrawCircle(int centerX, int centerY, float radius, Color color) { @@ -590,3 +618,15 @@ Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2) return retRec; } + +//---------------------------------------------------------------------------------- +// Module specific Functions Definition +//---------------------------------------------------------------------------------- + +// Cubic easing in-out +// NOTE: Required for DrawLineBezier() +static float EaseCubicInOut(float t, float b, float c, float d) +{ + if ((t/=d/2) < 1) return (c/2*t*t*t + b); + return (c/2*((t-=2)*t*t + 2) + b); +} \ No newline at end of file -- cgit v1.2.3 From 5d1f6616618d52f173a918f6a0378aeae1cb05ad Mon Sep 17 00:00:00 2001 From: raysan5 Date: Tue, 14 Mar 2017 01:05:22 +0100 Subject: Remove Oculus support from code Moved to custom example, now raylib only supports simulated VR rendering. Oculus code was too device dependant... waiting for OpenXR. --- examples/core_oculus_rift.c | 469 ++++++++++++++++++++++++++++- src/core.c | 7 +- src/raylib.h | 14 +- src/rlgl.c | 703 +++++++++----------------------------------- src/rlgl.h | 15 +- 5 files changed, 610 insertions(+), 598 deletions(-) (limited to 'src/raylib.h') diff --git a/examples/core_oculus_rift.c b/examples/core_oculus_rift.c index eb628cd7..f1b0bd3b 100644 --- a/examples/core_oculus_rift.c +++ b/examples/core_oculus_rift.c @@ -3,7 +3,12 @@ * 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 +* gcc -o $(NAME_PART).exe $(FILE_NAME) -I..\src\external -I..\src\external\OculusSDK\LibOVR\Include / +* -L. -L..\src\external\OculusSDK\LibOVR -lLibOVRRT32_1 -lraylib -lglfw3 -lopengl32 -lgdi32 -std=c99 / +* -Wl,-allow-multiple-definition +* +* #define SUPPORT_OCULUS_RIFT_CV1 / RLGL_OCULUS_SUPPORT +* Enable Oculus Rift CV1 functionality * * 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) @@ -14,6 +19,95 @@ #include "raylib.h" +#include "glad.h" // Required for: OpenGL types and functions declarations +#include "raymath.h" // Required for: Vector3, Quaternion and Matrix functionality + +#include // Required for: memset() +#include // Required for: exit() +#include // required for: vfprintf() +#include // Required for: va_list, va_start(), vfprintf(), va_end() + +#define RLGL_OCULUS_SUPPORT // Enable Oculus Rift code +#if defined(RLGL_OCULUS_SUPPORT) + #include "OVR_CAPI_GL.h" // Oculus SDK for OpenGL +#endif + +//---------------------------------------------------------------------------------- +// Defines and Macros +//---------------------------------------------------------------------------------- +// ... + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- + +// TraceLog message types +typedef enum { INFO = 0, ERROR, WARNING, DEBUG, OTHER } TraceLogType; + +#if defined(RLGL_OCULUS_SUPPORT) +// Oculus buffer type +typedef struct OculusBuffer { + ovrTextureSwapChain textureChain; + GLuint depthId; + GLuint fboId; + int width; + int height; +} OculusBuffer; + +// Oculus mirror texture type +typedef struct OculusMirror { + ovrMirrorTexture texture; + GLuint fboId; + int width; + int height; +} OculusMirror; + +// Oculus layer type +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 +//---------------------------------------------------------------------------------- +#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 + +//---------------------------------------------------------------------------------- +// Module specific Functions Declaration +//---------------------------------------------------------------------------------- +#if defined(RLGL_OCULUS_SUPPORT) +static bool InitOculusDevice(void); // Initialize Oculus device (returns true if success) +static void CloseOculusDevice(void); // Close Oculus device +static void UpdateOculusTracking(Camera *camera); // Update Oculus head position-orientation tracking +static void BeginOculusDrawing(void); // Setup Oculus buffers for drawing +static void EndOculusDrawing(void); // Finish Oculus drawing and blit framebuffer to mirror + +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 + +static void TraceLog(int msgType, const char *text, ...); + int main() { // Initialization @@ -25,8 +119,9 @@ int main() InitWindow(screenWidth, screenHeight, "raylib [core] example - oculus rift"); - // NOTE: If device is not available, it fallbacks to default device (simulator) - InitVrDevice(HMD_OCULUS_RIFT_CV1); // Init VR device (Oculus Rift CV1) + bool vrDeviceReady = InitOculusDevice(); // Init VR device Oculus Rift CV1 + + if (!vrDeviceReady) InitVrSimulator(HMD_OCULUS_RIFT_CV1); // Init VR simulator if device fails // Define the camera to look into our 3d world Camera camera; @@ -47,10 +142,10 @@ int main() { // Update //---------------------------------------------------------------------------------- - if (IsVrSimulator()) UpdateCamera(&camera); // Update camera (simulator mode) - else if (IsVrDeviceReady()) UpdateVrTracking(&camera); // Update camera with device tracking data - - if (IsKeyPressed(KEY_SPACE)) ToggleVrMode(); // Toggle VR mode + if (!vrDeviceReady) UpdateCamera(&camera); // Update camera (simulator mode) + else UpdateOculusTracking(&camera); // Update camera with device tracking data + + if (IsKeyPressed(KEY_SPACE)) ToggleVrMode(); // Toggle VR mode //---------------------------------------------------------------------------------- // Draw @@ -58,6 +153,9 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); + + if (vrDeviceReady) BeginOculusDrawing(); + else BeginVrDrawing(); Begin3dMode(camera); @@ -67,6 +165,9 @@ int main() DrawGrid(40, 1.0f); End3dMode(); + + if (vrDeviceReady) EndOculusDrawing(); + else EndVrDrawing(); DrawFPS(10, 10); @@ -76,10 +177,362 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- - CloseVrDevice(); // Close VR device + if (vrDeviceReady) CloseOculusDevice(); + else CloseVrSimulator(); CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- return 0; } + +//---------------------------------------------------------------------------------- +// Module specific Functions Definition +//---------------------------------------------------------------------------------- + +#if defined(RLGL_OCULUS_SUPPORT) +// Set internal projection and modelview matrix depending on eyes tracking data +static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView) +{ + Matrix eyeProjection = matProjection; + Matrix eyeModelView = matModelView; + + glViewport(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 eyeRenderPose = (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(&eyeRenderPose); + Matrix eyeOrientation = QuaternionToMatrix(eyeRenderPose); + 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 containing eye-head movement + eyeModelView = MatrixMultiply(matModelView, eyeView); // Combine internal camera matrix (modelview) wih eye-head movement + + eyeProjection = layer.eyeProjections[eye]; +} + +// Initialize Oculus device (returns true if success) +static bool InitOculusDevice(void) +{ + bool oculusReady = false; + + ovrResult result = ovr_Initialize(NULL); + + if (OVR_FAILURE(result)) TraceLog(WARNING, "OVR: Could not initialize Oculus device"); + else + { + result = ovr_Create(&session, &luid); + if (OVR_FAILURE(result)) + { + TraceLog(WARNING, "OVR: Could not create Oculus session"); + ovr_Shutdown(); + } + else + { + 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); + + oculusReady = true; + } + } + + return oculusReady; +} + +// Close Oculus device (and unload buffers) +static 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 head position-orientation tracking +static void UpdateOculusTracking(Camera *camera) +{ + 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]; + + // TODO: Update external camera with eyePoses data (position, orientation) + // NOTE: We can simplify to simple camera if we consider IPD and HMD device configuration again later + // it will be useful for the user to draw, lets say, billboards oriented to camera + + // 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); + //if (sessionStatus.HmdPresent) // HMD is present. + //if (sessionStatus.DisplayLost) // HMD was unplugged or the display driver was manually disabled or encountered a TDR. + //if (sessionStatus.HmdMounted) // HMD is on the user's head. + //if (sessionStatus.IsVisible) // the game or experience has VR focus and is visible in the HMD. +} + +// Setup Oculus buffers for drawing +static void BeginOculusDrawing(void) +{ + GLuint currentTexId; + int currentIndex; + + ovr_GetTextureSwapChainCurrentIndex(session, buffer.textureChain, ¤tIndex); + ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, currentIndex, ¤tTexId); + + 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 +} + +// Finish Oculus drawing and blit framebuffer to mirror +static void EndOculusDrawing(void) +{ + // Unbind current framebuffer (Oculus buffer) + 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); +} + +// 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); +#if defined(GRAPHICS_API_OPENGL_33) + // NOTE: glBlitFramebuffer() requires extension: GL_EXT_framebuffer_blit (not available in OpenGL ES 2.0) + glBlitFramebuffer(0, 0, mirror.width, mirror.height, 0, mirror.height, mirror.width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST); +#endif + 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 + +// Output a trace log message +// NOTE: Expected msgType: (0)Info, (1)Error, (2)Warning +static void TraceLog(int msgType, const char *text, ...) +{ + va_list args; + va_start(args, text); + + switch (msgType) + { + case INFO: fprintf(stdout, "INFO: "); break; + case ERROR: fprintf(stdout, "ERROR: "); break; + case WARNING: fprintf(stdout, "WARNING: "); break; + case DEBUG: fprintf(stdout, "DEBUG: "); break; + default: break; + } + + vfprintf(stdout, text, args); + fprintf(stdout, "\n"); + + va_end(args); + + if (msgType == ERROR) exit(1); +} + diff --git a/src/core.c b/src/core.c index c0f5be83..38549354 100644 --- a/src/core.c +++ b/src/core.c @@ -755,11 +755,8 @@ void End2dMode(void) void Begin3dMode(Camera camera) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - - if (IsVrDeviceReady() || IsVrSimulator()) BeginVrDrawing(); - + rlMatrixMode(RL_PROJECTION); // Switch to projection matrix - rlPushMatrix(); // Save previous matrix, which contains the settings for the 2d ortho projection rlLoadIdentity(); // Reset current matrix (PROJECTION) @@ -786,8 +783,6 @@ void End3dMode(void) { rlglDraw(); // Process internal buffers (update + draw) - if (IsVrDeviceReady() || IsVrSimulator()) EndVrDrawing(); - rlMatrixMode(RL_PROJECTION); // Switch to projection matrix rlPopMatrix(); // Restore previous matrix (PROJECTION) from matrix stack diff --git a/src/raylib.h b/src/raylib.h index 85689378..e679e011 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -687,6 +687,7 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) +//RLAPI void TraceLog(int logType, const char *text, ...); // Trace log messages showing (INFO, WARNING, ERROR, DEBUG) RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window RLAPI char **GetDroppedFiles(int *count); // Retrieve dropped files into window @@ -944,12 +945,13 @@ RLAPI void EndBlendMode(void); // End // VR experience Functions (Module: rlgl) // NOTE: This functions are useless when using OpenGL 1.1 //------------------------------------------------------------------------------------ -RLAPI void InitVrDevice(int vdDevice); // Init VR device -RLAPI void CloseVrDevice(void); // Close VR device -RLAPI bool IsVrDeviceReady(void); // Detect if VR device is ready -RLAPI bool IsVrSimulator(void); // Detect if VR simulator is running -RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -RLAPI void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) +RLAPI void InitVrSimulator(int vrDevice); // Init VR simulator for selected device +RLAPI void CloseVrSimulator(void); // Close VR simulator for current device +RLAPI bool IsVrSimulatorReady(void); // Detect if VR device is ready +RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera +RLAPI void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) +RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering +RLAPI void EndVrDrawing(void); // End VR simulator stereo rendering //------------------------------------------------------------------------------------ // Audio Loading and Playing Functions (Module: audio) diff --git a/src/rlgl.c b/src/rlgl.c index ffc9d741..00998624 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -37,9 +37,7 @@ * * #define SUPPORT_SHADER_DISTORTION * -* -* #define SUPPORT_OCULUS_RIFT_CV1 / RLGL_OCULUS_SUPPORT -* Enable Oculus Rift CV1 functionality +* #define SUPPORT_VR_SIMULATION * * #define SUPPORT_STEREO_RENDERING * @@ -121,17 +119,6 @@ #include "shader_distortion.h" // Distortion shader to be embedded #endif -//#define RLGL_OCULUS_SUPPORT // Enable Oculus Rift code -#if defined(RLGL_OCULUS_SUPPORT) - #include "external/OculusSDK/LibOVR/Include/OVR_CAPI_GL.h" // Oculus SDK for OpenGL -#endif - -#if defined(RLGL_STANDALONE) - #define OCULUSAPI -#else - #define OCULUSAPI static -#endif - //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- @@ -187,15 +174,15 @@ #endif #if defined(GRAPHICS_API_OPENGL_11) - #define GL_UNSIGNED_SHORT_5_6_5 0x8363 - #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 - #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 + #define GL_UNSIGNED_SHORT_5_6_5 0x8363 + #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 + #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #endif #if defined(GRAPHICS_API_OPENGL_ES2) - #define glClearDepth glClearDepthf - #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER - #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER + #define glClearDepth glClearDepthf + #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER + #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #endif // Default vertex attribute names on shader to set location points @@ -267,32 +254,6 @@ typedef struct VrStereoConfig { Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices } VrStereoConfig; -#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 //---------------------------------------------------------------------------------- @@ -343,24 +304,11 @@ static float maxAnisotropicLevel = 0.0f; // Maximum anisotropy level supp // Extension supported flag: Clamp mirror wrap mode static bool texClampMirrorSupported = false; // Clamp mirror wrap mode supported -#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 - // VR global variables static VrDeviceInfo hmd; // Current VR device info static VrStereoConfig vrConfig; // VR stereo configuration for simulator -static bool vrDeviceReady = false; // VR device ready flag -static bool vrSimulator = false; // VR simulator enabled flag -static bool vrEnabled = false; // VR experience enabled (device or simulator) -static bool vrRendering = true; // VR stereo rendering enabled/disabled flag +static bool vrSimulatorReady = false; // VR simulator ready flag +static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag // NOTE: This flag is useful to render data over stereo image (i.e. FPS) #if defined(GRAPHICS_API_OPENGL_ES2) @@ -380,7 +328,7 @@ static int blendMode = 0; // Track current blending mode // White texture useful for plain color polys (required by shader) static unsigned int whiteTexture; -// Default framebuffer size (required by Oculus device) +// Default framebuffer size static int screenWidth; // Default framebuffer width static int screenHeight; // Default framebuffer height @@ -397,7 +345,7 @@ static void UnloadDefaultShader(void); // Unload default shader static void LoadDefaultBuffers(void); // Load default internal buffers (lines, triangles, quads) static void UpdateDefaultBuffers(void); // Update default internal buffers (VAOs/VBOs) with vertex data -static void DrawDefaultBuffers(int eyesCount); // Draw default internal buffers vertex data +static void DrawDefaultBuffers(void); // Draw default internal buffers vertex data static void UnloadDefaultBuffers(void); // Unload default internal buffers vertex data from CPU and GPU // Configure stereo rendering (including distortion shader) with HMD device parameters @@ -407,26 +355,6 @@ static void SetStereoConfig(VrDeviceInfo info); static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView); #endif -#if defined(RLGL_OCULUS_SUPPORT) -#if !defined(RLGL_STANDALONE) -static bool InitOculusDevice(void); // Initialize Oculus device (returns true if success) -static void CloseOculusDevice(void); // Close Oculus device -static void UpdateOculusTracking(Camera *camera); // Update Oculus head position-orientation tracking -static void BeginOculusDrawing(void); // Setup Oculus buffers for drawing -static void EndOculusDrawing(void); // Finish Oculus drawing and blit framebuffer to mirror -#endif - -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); @@ -1352,9 +1280,7 @@ void rlglDraw(void) // NOTE: Default buffers upload and draw UpdateDefaultBuffers(); - - if (vrEnabled && vrRendering) DrawDefaultBuffers(2); - else DrawDefaultBuffers(1); + DrawDefaultBuffers(); // NOTE: Stereo rendering is checked inside #endif } @@ -2018,9 +1944,6 @@ void rlglDrawMesh(Mesh mesh, Material material, Matrix transform) #endif #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int eyesCount = 1; - if (vrEnabled) eyesCount = 2; - glUseProgram(material.shader.id); // Upload to shader material.colDiffuse @@ -2153,6 +2076,9 @@ void rlglDrawMesh(Mesh mesh, Material material, Matrix transform) if (mesh.indices != NULL) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quads.vboId[3]); } + int eyesCount = 1; + if (vrStereoRender) eyesCount = 2; + for (int eye = 0; eye < eyesCount; eye++) { if (eyesCount == 2) SetStereoView(eye, matProjection, matModelView); @@ -2617,146 +2543,119 @@ void EndBlendMode(void) BeginBlendMode(BLEND_ALPHA); } -// Init VR device (or simulator) -// NOTE: If device is not available, it fallbacks to default device (simulator) +// Init VR simulator for selected device // NOTE: It modifies the global variable: VrDeviceInfo hmd -void InitVrDevice(int vrDevice) +void InitVrSimulator(int vrDevice) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (vrDevice) - { - case HMD_DEFAULT_DEVICE: TraceLog(INFO, "Initializing default VR Device (Oculus Rift CV1)"); - case HMD_OCULUS_RIFT_DK2: - case HMD_OCULUS_RIFT_CV1: - { -#if defined(RLGL_OCULUS_SUPPORT) - vrDeviceReady = InitOculusDevice(); -#else - TraceLog(WARNING, "Oculus Rift not supported by default, recompile raylib with Oculus support"); -#endif - } break; - case HMD_VALVE_HTC_VIVE: - case HMD_SAMSUNG_GEAR_VR: - case HMD_GOOGLE_CARDBOARD: - case HMD_SONY_PLAYSTATION_VR: - case HMD_RAZER_OSVR: - case HMD_FOVE_VR: TraceLog(WARNING, "VR Device not supported"); - default: break; - } - - if (!vrDeviceReady) - { - TraceLog(WARNING, "VR Device not found: Initializing VR Simulator (Oculus Rift CV1)"); - - if (vrDevice == HMD_OCULUS_RIFT_DK2) - { - // Oculus Rift DK2 parameters - hmd.hResolution = 1280; // HMD horizontal resolution in pixels - hmd.vResolution = 800; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.14976f; // HMD horizontal size in meters - hmd.vScreenSize = 0.09356f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters - hmd.lensSeparationDistance = 0.0635f; // HMD lens separation distance in meters - hmd.interpupillaryDistance = 0.064f; // HMD IPD (distance between pupils) in meters - hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 - hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 - hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 - } - else if ((vrDevice == HMD_DEFAULT_DEVICE) || (vrDevice == HMD_OCULUS_RIFT_CV1)) - { - // Oculus Rift CV1 parameters - // NOTE: CV1 represents a complete HMD redesign compared to previous versions, - // new Fresnel-hybrid-asymmetric lenses have been added and, consequently, - // previous parameters (DK2) and distortion shader (DK2) doesn't work any more. - // I just defined a set of parameters for simulator that approximate to CV1 stereo rendering - // but result is not the same obtained with Oculus PC SDK. - hmd.hResolution = 2160; // HMD horizontal resolution in pixels - hmd.vResolution = 1200; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.133793f; // HMD horizontal size in meters - hmd.vScreenSize = 0.0669f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters - hmd.lensSeparationDistance = 0.07f; // HMD lens separation distance in meters - hmd.interpupillaryDistance = 0.07f; // HMD IPD (distance between pupils) in meters - hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 - hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 - hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 - } - - // Initialize framebuffer and textures for stereo rendering - // NOTE: screen size should match HMD aspect ratio - vrConfig.stereoFbo = rlglLoadRenderTexture(screenWidth, screenHeight); - - // Load distortion shader (initialized by default with Oculus Rift CV1 parameters) - vrConfig.distortionShader.id = LoadShaderProgram(vDistortionShaderStr, fDistortionShaderStr); - if (vrConfig.distortionShader.id != 0) LoadDefaultShaderLocations(&vrConfig.distortionShader); - - SetStereoConfig(hmd); - - vrSimulator = true; - vrEnabled = true; - } + if (vrDevice == HMD_OCULUS_RIFT_DK2) + { + // Oculus Rift DK2 parameters + hmd.hResolution = 1280; // HMD horizontal resolution in pixels + hmd.vResolution = 800; // HMD vertical resolution in pixels + hmd.hScreenSize = 0.14976f; // HMD horizontal size in meters + hmd.vScreenSize = 0.09356f; // HMD vertical size in meters + hmd.vScreenCenter = 0.04678f; // HMD screen center in meters + hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters + hmd.lensSeparationDistance = 0.0635f; // HMD lens separation distance in meters + hmd.interpupillaryDistance = 0.064f; // HMD IPD (distance between pupils) in meters + hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 + hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 + hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 + hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 + hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 + hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 + hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 + hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 + + TraceLog(WARNING, "Initializing VR Simulator (Oculus Rift DK2)"); + } + else if ((vrDevice == HMD_DEFAULT_DEVICE) || (vrDevice == HMD_OCULUS_RIFT_CV1)) + { + // Oculus Rift CV1 parameters + // NOTE: CV1 represents a complete HMD redesign compared to previous versions, + // new Fresnel-hybrid-asymmetric lenses have been added and, consequently, + // previous parameters (DK2) and distortion shader (DK2) doesn't work any more. + // I just defined a set of parameters for simulator that approximate to CV1 stereo rendering + // but result is not the same obtained with Oculus PC SDK. + hmd.hResolution = 2160; // HMD horizontal resolution in pixels + hmd.vResolution = 1200; // HMD vertical resolution in pixels + hmd.hScreenSize = 0.133793f; // HMD horizontal size in meters + hmd.vScreenSize = 0.0669f; // HMD vertical size in meters + hmd.vScreenCenter = 0.04678f; // HMD screen center in meters + hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters + hmd.lensSeparationDistance = 0.07f; // HMD lens separation distance in meters + hmd.interpupillaryDistance = 0.07f; // HMD IPD (distance between pupils) in meters + hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 + hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 + hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 + hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 + hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 + hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 + hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 + hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 + + TraceLog(WARNING, "Initializing VR Simulator (Oculus Rift CV1)"); + } + else + { + TraceLog(WARNING, "VR Simulator doesn't support current device yet,"); + TraceLog(WARNING, "using default VR Simulator parameters"); + } + + // Initialize framebuffer and textures for stereo rendering + // NOTE: screen size should match HMD aspect ratio + vrConfig.stereoFbo = rlglLoadRenderTexture(screenWidth, screenHeight); + + // Load distortion shader (initialized by default with Oculus Rift CV1 parameters) + vrConfig.distortionShader.id = LoadShaderProgram(vDistortionShaderStr, fDistortionShaderStr); + if (vrConfig.distortionShader.id != 0) LoadDefaultShaderLocations(&vrConfig.distortionShader); + + SetStereoConfig(hmd); + + vrSimulatorReady = true; #endif #if defined(GRAPHICS_API_OPENGL_11) - TraceLog(WARNING, "VR device or simulator not supported on OpenGL 1.1"); + TraceLog(WARNING, "VR Simulator not supported on OpenGL 1.1"); #endif } -// Close VR device (or simulator) -void CloseVrDevice(void) +// Close VR simulator for current device +void CloseVrSimulator(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) CloseOculusDevice(); - else -#endif + if (vrSimulatorReady) { rlDeleteRenderTextures(vrConfig.stereoFbo); // Unload stereo framebuffer and texture UnloadShader(vrConfig.distortionShader); // Unload distortion shader } #endif - vrDeviceReady = false; -} - -// Detect if VR device is available -bool IsVrDeviceReady(void) -{ - return (vrDeviceReady && vrEnabled); } // Detect if VR simulator is running -bool IsVrSimulator(void) +bool IsVrSimulatorReady(void) { - return (vrSimulator && vrEnabled); + return vrSimulatorReady; } // Enable/Disable VR experience (device or simulator) void ToggleVrMode(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (vrDeviceReady || vrSimulator) vrEnabled = !vrEnabled; - else vrEnabled = false; + vrSimulatorReady = !vrSimulatorReady; - if (!vrEnabled) + if (!vrSimulatorReady) { + vrStereoRender = false; + // Reset viewport and default projection-modelview matrices rlViewport(0, 0, screenWidth, screenHeight); projection = MatrixOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); MatrixTranspose(&projection); modelview = MatrixIdentity(); } + else vrStereoRender = true; #endif } @@ -2764,37 +2663,29 @@ void ToggleVrMode(void) // NOTE: Camera (position, target, up) gets update with head tracking information void UpdateVrTracking(Camera *camera) { -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) UpdateOculusTracking(camera); -#endif + // TODO: Simulate 1st person camera system } // Begin Oculus drawing configuration void BeginVrDrawing(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) - { - BeginOculusDrawing(); - } - else -#endif + if (vrSimulatorReady) { // Setup framebuffer for stereo rendering rlEnableRenderTexture(vrConfig.stereoFbo.id); - } - // 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); + // 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); - //glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye) - rlClearScreenBuffers(); // Clear current framebuffer(s) - - vrRendering = true; + //glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye) + rlClearScreenBuffers(); // Clear current framebuffer(s) + + vrStereoRender = true; + } #endif } @@ -2802,18 +2693,13 @@ void BeginVrDrawing(void) void EndVrDrawing(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) - { - EndOculusDrawing(); - } - else -#endif + if (vrSimulatorReady) { - // Unbind current framebuffer - rlDisableRenderTexture(); + vrStereoRender = false; // Disable stereo render + + rlDisableRenderTexture(); // Unbind current framebuffer - rlClearScreenBuffers(); // Clear current framebuffer + rlClearScreenBuffers(); // Clear current framebuffer // Set viewport to default framebuffer size (screen size) rlViewport(0, 0, screenWidth, screenHeight); @@ -2855,15 +2741,21 @@ void EndVrDrawing(void) rlDisableTexture(); + // Update and draw render texture fbo with distortion to backbuffer UpdateDefaultBuffers(); - DrawDefaultBuffers(1); - + DrawDefaultBuffers(); + + // Restore defaultShader currentShader = defaultShader; - } - - rlDisableDepthTest(); - vrRendering = false; + // Reset viewport and default projection-modelview matrices + rlViewport(0, 0, screenWidth, screenHeight); + projection = MatrixOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); + MatrixTranspose(&projection); + modelview = MatrixIdentity(); + + rlDisableDepthTest(); + } #endif } @@ -3405,10 +3297,13 @@ static void UpdateDefaultBuffers(void) // Draw default internal buffers vertex data // NOTE: We draw in this order: lines, triangles, quads -static void DrawDefaultBuffers(int eyesCount) +static void DrawDefaultBuffers() { Matrix matProjection = projection; Matrix matModelView = modelview; + + int eyesCount = 1; + if (vrStereoRender) eyesCount = 2; for (int eye = 0; eye < eyesCount; eye++) { @@ -3693,47 +3588,19 @@ static void SetStereoConfig(VrDeviceInfo hmd) // Set internal projection and modelview matrix depending on eyes tracking data static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView) { - if (vrEnabled) - { - Matrix eyeProjection = matProjection; - Matrix eyeModelView = matModelView; + Matrix eyeProjection = matProjection; + Matrix eyeModelView = matModelView; -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) - { - 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 eyeRenderPose = (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(&eyeRenderPose); - Matrix eyeOrientation = QuaternionToMatrix(eyeRenderPose); - 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 containing eye-head movement - eyeModelView = MatrixMultiply(matModelView, eyeView); // Combine internal camera matrix (modelview) wih eye-head movement - - eyeProjection = layer.eyeProjections[eye]; - } - else -#endif - { - // Setup viewport and projection/modelview matrices using tracking data - rlViewport(eye*screenWidth/2, 0, screenWidth/2, screenHeight); + // Setup viewport and projection/modelview matrices using tracking data + rlViewport(eye*screenWidth/2, 0, screenWidth/2, screenHeight); - // Apply view offset to modelview matrix - eyeModelView = MatrixMultiply(matModelView, vrConfig.eyesViewOffset[eye]); + // Apply view offset to modelview matrix + eyeModelView = MatrixMultiply(matModelView, vrConfig.eyesViewOffset[eye]); - eyeProjection = vrConfig.eyesProjection[eye]; - } + eyeProjection = vrConfig.eyesProjection[eye]; - SetMatrixModelview(eyeModelView); - SetMatrixProjection(eyeProjection); - } + SetMatrixModelview(eyeModelView); + SetMatrixProjection(eyeProjection); } #endif //defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) @@ -3864,304 +3731,6 @@ static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight) } #endif -#if defined(RLGL_OCULUS_SUPPORT) -// Initialize Oculus device (returns true if success) -OCULUSAPI bool InitOculusDevice(void) -{ - bool oculusReady = false; - - ovrResult result = ovr_Initialize(NULL); - - if (OVR_FAILURE(result)) TraceLog(WARNING, "OVR: Could not initialize Oculus device"); - else - { - result = ovr_Create(&session, &luid); - if (OVR_FAILURE(result)) - { - TraceLog(WARNING, "OVR: Could not create Oculus session"); - ovr_Shutdown(); - } - else - { - 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); - - oculusReady = true; - vrEnabled = true; - } - } - - return oculusReady; -} - -// Close Oculus device (and unload buffers) -OCULUSAPI 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 head position-orientation tracking -OCULUSAPI void UpdateOculusTracking(Camera *camera) -{ - 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]; - - // TODO: Update external camera with eyePoses data (position, orientation) - // NOTE: We can simplify to simple camera if we consider IPD and HMD device configuration again later - // it will be useful for the user to draw, lets say, billboards oriented to camera - - // 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); - //if (sessionStatus.HmdPresent) // HMD is present. - //if (sessionStatus.DisplayLost) // HMD was unplugged or the display driver was manually disabled or encountered a TDR. - //if (sessionStatus.HmdMounted) // HMD is on the user's head. - //if (sessionStatus.IsVisible) // the game or experience has VR focus and is visible in the HMD. -} - -// Setup Oculus buffers for drawing -OCULUSAPI void BeginOculusDrawing(void) -{ - GLuint currentTexId; - int currentIndex; - - ovr_GetTextureSwapChainCurrentIndex(session, buffer.textureChain, ¤tIndex); - ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, currentIndex, ¤tTexId); - - 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 -} - -// Finish Oculus drawing and blit framebuffer to mirror -OCULUSAPI void EndOculusDrawing(void) -{ - // Unbind current framebuffer (Oculus buffer) - 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); -} - -// 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); -#if defined(GRAPHICS_API_OPENGL_33) - // NOTE: glBlitFramebuffer() requires extension: GL_EXT_framebuffer_blit (not available in OpenGL ES 2.0) - glBlitFramebuffer(0, 0, mirror.width, mirror.height, 0, mirror.height, mirror.width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST); -#endif - 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 diff --git a/src/rlgl.h b/src/rlgl.h index 41f671e6..344da987 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -399,19 +399,12 @@ void EndBlendMode(void); // End blend void TraceLog(int msgType, const char *text, ...); float *MatrixToFloat(Matrix mat); -void InitVrDevice(int vrDevice); // Init VR device -void CloseVrDevice(void); // Close VR device -bool IsVrDeviceReady(void); // Detect if VR device is ready -bool IsVrSimulator(void); // Detect if VR simulator is running +void InitVrSimulator(int vrDevice); // Init VR simulator for selected device +void CloseVrSimulator(void); // Close VR simulator for current device void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) - -// Oculus Rift API for direct access the device (no simulator) -bool InitOculusDevice(void); // Initialize Oculus device (returns true if success) -void CloseOculusDevice(void); // Close Oculus device -void UpdateOculusTracking(Camera *camera); // Update Oculus head position-orientation tracking (and camera) -void BeginOculusDrawing(void); // Setup Oculus buffers for drawing -void EndOculusDrawing(void); // Finish Oculus drawing and blit framebuffer to mirror +void BeginVrDrawing(void); // Begin VR stereo rendering +void EndVrDrawing(void); // End VR stereo rendering #endif #ifdef __cplusplus -- cgit v1.2.3 From 8f5ff64420dda659583c156b9c5e42e60384e247 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 19 Mar 2017 12:52:58 +0100 Subject: Working on file header comments... --- src/audio.c | 41 ++++++++++++++++++++------------------ src/audio.h | 28 +++++++++++++++----------- src/core.c | 11 ++++++++-- src/easings.h | 2 +- src/models.c | 4 +++- src/raylib.h | 64 ++++++++++++++++++++++++++++++----------------------------- src/utils.c | 19 ++++++++++++++---- src/utils.h | 6 ++++++ 8 files changed, 105 insertions(+), 70 deletions(-) (limited to 'src/raylib.h') diff --git a/src/audio.c b/src/audio.c index 659ead0f..e0964e02 100644 --- a/src/audio.c +++ b/src/audio.c @@ -1,26 +1,24 @@ /********************************************************************************************** * -* raylib.audio +* raylib.audio - Basic funtionality to work with audio * -* This module provides basic functionality to work with audio: -* Manage audio device (init/close) -* Load and Unload audio files (WAV, OGG, FLAC, XM, MOD) -* Play/Stop/Pause/Resume loaded audio -* Manage mixing channels -* Manage raw audio context +* DESCRIPTION: * -* NOTES: -* -* Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) -* Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) +* This module provides basic functionality to: +* - Manage audio device (init/close) +* - Load and unload audio files +* - Format wave data (sample rate, size, channels) +* - Play/Stop/Pause/Resume loaded audio +* - Manage mixing channels +* - Manage raw audio context * * CONFIGURATION: * * #define AUDIO_STANDALONE -* If defined, the module can be used as standalone library (independently of raylib). +* Define to use the module as standalone library (independently of raylib). * Required types and functions are defined in the same module. * -* #define SUPPORT_FILEFORMAT_WAV / SUPPORT_LOAD_WAV / ENABLE_LOAD_WAV +* #define SUPPORT_FILEFORMAT_WAV / SUPPORT_LOAD_WAV * #define SUPPORT_FILEFORMAT_OGG * #define SUPPORT_FILEFORMAT_XM * #define SUPPORT_FILEFORMAT_MOD @@ -29,6 +27,12 @@ * supported by default, to remove support, just comment unrequired #define in this module * * #define SUPPORT_RAW_AUDIO_BUFFERS +* Support creating raw audio buffers to send raw data. Buffers must be managed by the user, +* it means initialization, refilling and cleaning. +* +* LIMITATIONS: +* Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) +* Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) * * DEPENDENCIES: * OpenAL Soft - Audio device management (http://kcat.strangesoft.net/openal.html) @@ -38,12 +42,11 @@ * dr_flac - FLAC audio file loading * * CONTRIBUTORS: -* -* Many thanks to Joshua Reisenauer (github: @kd7tck) for the following additions: -* XM audio module support (jar_xm) -* MOD audio module support (jar_mod) -* Mixing channels support -* Raw audio context support +* Joshua Reisenauer (github: @kd7tck): +* - XM audio module support (jar_xm) +* - MOD audio module support (jar_mod) +* - Mixing channels support +* - Raw audio context support * * * LICENSE: zlib/libpng diff --git a/src/audio.h b/src/audio.h index 01ed9f72..a0279e3a 100644 --- a/src/audio.h +++ b/src/audio.h @@ -1,13 +1,16 @@ /********************************************************************************************** * -* raylib.audio +* raylib.audio - Basic funtionality to work with audio * -* This module provides basic functionality to work with audio: -* Manage audio device (init/close) -* Load and Unload audio files (WAV, OGG, FLAC, XM, MOD) -* Play/Stop/Pause/Resume loaded audio -* Manage mixing channels -* Manage raw audio context +* DESCRIPTION: +* +* This module provides basic functionality to: +* - Manage audio device (init/close) +* - Load and unload audio files +* - Format wave data (sample rate, size, channels) +* - Play/Stop/Pause/Resume loaded audio +* - Manage mixing channels +* - Manage raw audio context * * DEPENDENCIES: * OpenAL Soft - Audio device management (http://kcat.strangesoft.net/openal.html) @@ -16,11 +19,12 @@ * jar_mod - MOD audio file loading * dr_flac - FLAC audio file loading * -* Many thanks to Joshua Reisenauer (github: @kd7tck) for the following additions: -* XM audio module support (jar_xm) -* MOD audio module support (jar_mod) -* Mixing channels support -* Raw audio context support +* CONTRIBUTORS: +* Joshua Reisenauer (github: @kd7tck): +* - XM audio module support (jar_xm) +* - MOD audio module support (jar_mod) +* - Mixing channels support +* - Raw audio context support * * * LICENSE: zlib/libpng diff --git a/src/core.c b/src/core.c index 38549354..f55a70db 100644 --- a/src/core.c +++ b/src/core.c @@ -2,7 +2,14 @@ * * raylib.core - Basic functions to manage windows, OpenGL context and input on multiple platforms * -* The following platforms are supported: Windows, Linux, Mac (OSX), Android, Raspberry Pi, HTML5, Oculus Rift CV1 +* The following platforms are supported: +* Windows (win32/Win64) +* Linux (tested on Ubuntu) +* Mac (OSX) +* Android (API Level 9 or greater) +* Raspberry Pi (Raspbian) +* HTML5 (Chrome, Firefox) +* Oculus Rift CV1 * * CONFIGURATION: * @@ -2006,7 +2013,7 @@ static double GetTime(void) // Wait for some milliseconds (stop program execution) static void Wait(float ms) { -#define SUPPORT_BUSY_WAIT_LOOP +//#define SUPPORT_BUSY_WAIT_LOOP #if defined(SUPPORT_BUSY_WAIT_LOOP) double prevTime = GetTime(); double nextTime = 0.0; diff --git a/src/easings.h b/src/easings.h index 527970ab..9ad27313 100644 --- a/src/easings.h +++ b/src/easings.h @@ -122,7 +122,7 @@ EASEDEF float EaseCubicOut(float t, float b, float c, float d) { return (c*((t=t EASEDEF float EaseCubicInOut(float t, float b, float c, float d) { if ((t/=d/2) < 1) return (c/2*t*t*t + b); - return (c/2*((t-=2)*t*t + 2) + b); + return (c/2*((t-=2)*t*t + 2) + b); } // Quadratic Easing functions diff --git a/src/models.c b/src/models.c index bef19e10..8297358b 100644 --- a/src/models.c +++ b/src/models.c @@ -1,12 +1,14 @@ /********************************************************************************************** * -* raylib.models - Basic functions to draw 3d shapes and 3d models +* raylib.models - Basic functions to deal with 3d shapes and 3d models * * CONFIGURATION: * * #define SUPPORT_FILEFORMAT_OBJ / SUPPORT_LOAD_OBJ +* Selected desired fileformats to be supported for loading. * * #define SUPPORT_FILEFORMAT_MTL +* Selected desired fileformats to be supported for loading. * * * LICENSE: zlib/libpng diff --git a/src/raylib.h b/src/raylib.h index e679e011..4fd4b5df 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1,43 +1,45 @@ /********************************************************************************************** * -* raylib v1.7.0 (www.raylib.com) +* raylib v1.7.0 * -* A simple and easy-to-use library to learn videogames programming +* A simple and easy-to-use library to learn videogames programming (www.raylib.com) * * FEATURES: -* Library written in plain C code (C99) -* Uses PascalCase/camelCase notation -* Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES 2.0) -* Unique OpenGL abstraction layer (usable as standalone module): [rlgl] -* Powerful fonts module with SpriteFonts support (XNA bitmap fonts, AngelCode fonts, TTF) -* Multiple textures support, including compressed formats and mipmaps generation -* Basic 3d support for Shapes, Models, Billboards, Heightmaps and Cubicmaps -* Powerful math module for Vector, Matrix and Quaternion operations: [raymath] -* Audio loading and playing with streaming support and mixing channels [audio] -* VR stereo rendering support with configurable HMD device parameters -* Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi, HTML5 and Oculus Rift CV1 -* Custom color palette for fancy visuals on raywhite background -* Minimal external dependencies (GLFW3, OpenGL, OpenAL) -* Complete binding for Lua [rlua] +* - Library written in plain C code (C99) +* - Uses PascalCase/camelCase notation +* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES 2.0) +* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] +* - Powerful fonts module with SpriteFonts support (XNA bitmap fonts, AngelCode fonts, TTF) +* - Multiple textures support, including compressed formats and mipmaps generation +* - Basic 3d support for Shapes, Models, Billboards, Heightmaps and Cubicmaps +* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] +* - Audio loading and playing with streaming support and mixing channels [audio] +* - VR stereo rendering support with configurable HMD device parameters +* - Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi, HTML5 and Oculus Rift CV1 +* - Custom color palette for fancy visuals on raywhite background +* - Minimal external dependencies (GLFW3, OpenGL, OpenAL) +* - Complete bindings for Lua, Go and Pascal * * NOTES: -* 32bit Colors - All defined color are always RGBA (struct Color is 4 byte) -* One custom default font could be loaded automatically when InitWindow() [core] -* If using OpenGL 3.3 or ES2, several vertex buffers (VAO/VBO) are created to manage lines-triangles-quads -* If using OpenGL 3.3 or ES2, two default shaders could be loaded automatically (internally defined) +* 32bit Colors - All defined color are always RGBA (struct Color is 4 byte) +* One custom default font could be loaded automatically when InitWindow() [core] +* If using OpenGL 3.3 or ES2, several vertex buffers (VAO/VBO) are created to manage lines-triangles-quads +* If using OpenGL 3.3 or ES2, two default shaders could be loaded automatically (internally defined) * * DEPENDENCIES: -* GLFW3 (www.glfw.org) for window/context management and input [core] -* GLAD for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) [rlgl] -* stb_image (Sean Barret) for images loading (JPEG, PNG, BMP, TGA) [textures] -* stb_image_write (Sean Barret) for image writting (PNG) [utils] -* stb_truetype (Sean Barret) for ttf fonts loading [text] -* stb_vorbis (Sean Barret) for ogg audio loading [audio] -* jar_xm (Joshua Reisenauer) for XM audio module loading [audio] -* jar_mod (Joshua Reisenauer) for MOD audio module loading [audio] -* dr_flac (David Reid) for FLAC audio file loading [audio] -* OpenAL Soft for audio device/context management [audio] -* tinfl for data decompression (DEFLATE algorithm) [utils] +* GLFW3 (www.glfw.org) for window/context management and input [core] +* GLAD for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) [rlgl] +* OpenAL Soft for audio device/context management [audio] +* +* OPTIONAL DEPENDENCIES: +* stb_image (Sean Barret) for images loading (JPEG, PNG, BMP, TGA) [textures] +* stb_image_write (Sean Barret) for image writting (PNG) [utils] +* stb_truetype (Sean Barret) for ttf fonts loading [text] +* stb_vorbis (Sean Barret) for ogg audio loading [audio] +* jar_xm (Joshua Reisenauer) for XM audio module loading [audio] +* jar_mod (Joshua Reisenauer) for MOD audio module loading [audio] +* dr_flac (David Reid) for FLAC audio file loading [audio] +* tinfl for data decompression (DEFLATE algorithm) [rres] * * * LICENSE: zlib/libpng diff --git a/src/utils.c b/src/utils.c index 9a2a723a..54923e34 100644 --- a/src/utils.c +++ b/src/utils.c @@ -4,14 +4,20 @@ * * CONFIGURATION: * -* #define SUPPORT_SAVE_PNG -* Enable saving PNG fileformat +* #define SUPPORT_SAVE_PNG (defined by default) +* Support saving image data as PNG fileformat * NOTE: Requires stb_image_write library * * #define SUPPORT_SAVE_BMP +* Support saving image data as BMP fileformat +* NOTE: Requires stb_image_write library +* +* #define SUPPORT_TRACELOG +* Show TraceLog() output messages +* NOTE: By default DEBUG traces not shown * -* #define DO_NOT_TRACE_DEBUG_MSGS -* Avoid showing DEBUG TraceLog() messages +* #define SUPPORT_TRACELOG_DEBUG +* Show TraceLog() DEBUG messages * * DEPENDENCIES: * stb_image_write - PNG writting functions @@ -129,18 +135,23 @@ void TraceLog(int msgType, const char *text, ...) } #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) + +#if defined(SUPPORT_SAVE_BMP) // Creates a BMP image file from an array of pixel data void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize) { stbi_write_bmp(fileName, width, height, compSize, imgData); } +#endif +#if defined(SUPPORT_SAVE_PNG) // Creates a PNG image file from an array of pixel data void SavePNG(const char *fileName, unsigned char *imgData, int width, int height, int compSize) { stbi_write_png(fileName, width, height, compSize, imgData, width*compSize); } #endif +#endif #if defined(PLATFORM_ANDROID) // Initialize asset manager from android app diff --git a/src/utils.h b/src/utils.h index 3ffd025c..037d7e94 100644 --- a/src/utils.h +++ b/src/utils.h @@ -33,6 +33,8 @@ #include "rres.h" +#define SUPPORT_SAVE_PNG + //---------------------------------------------------------------------------------- // Some basic Defines //---------------------------------------------------------------------------------- @@ -61,9 +63,13 @@ void TraceLog(int msgType, const char *text, ...); // Outputs a trace log messa const char *GetExtension(const char *fileName); // Returns extension of a filename #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) +#if defined(SUPPORT_SAVE_BMP) void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize); +#endif +#if defined(SUPPORT_SAVE_PNG) void SavePNG(const char *fileName, unsigned char *imgData, int width, int height, int compSize); #endif +#endif #if defined(PLATFORM_ANDROID) void InitAssetManager(AAssetManager *manager); // Initialize asset manager from android app -- cgit v1.2.3 From 59652c75b43d0437217c0000b03428545905801e Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 20 Mar 2017 20:34:44 +0100 Subject: Review some comments --- src/audio.c | 18 ++++++++---------- src/audio.h | 2 +- src/camera.h | 4 ++-- src/core.c | 18 +++++++++--------- src/gestures.h | 4 ++-- src/models.c | 2 +- src/raylib.h | 2 +- src/raymath.h | 2 +- src/rlgl.c | 47 ++++++++++++++++++----------------------------- src/rlgl.h | 45 +++++++++++++++++++++++++++++++-------------- src/rres.h | 4 +--- src/shapes.c | 2 +- src/text.c | 2 +- src/textures.c | 2 +- src/utils.c | 2 +- src/utils.h | 7 ++++--- 16 files changed, 83 insertions(+), 80 deletions(-) (limited to 'src/raylib.h') diff --git a/src/audio.c b/src/audio.c index e0964e02..68bd88e9 100644 --- a/src/audio.c +++ b/src/audio.c @@ -2,15 +2,13 @@ * * raylib.audio - Basic funtionality to work with audio * -* DESCRIPTION: -* -* This module provides basic functionality to: -* - Manage audio device (init/close) -* - Load and unload audio files -* - Format wave data (sample rate, size, channels) -* - Play/Stop/Pause/Resume loaded audio -* - Manage mixing channels -* - Manage raw audio context +* FEATURES: +* - Manage audio device (init/close) +* - Load and unload audio files +* - Format wave data (sample rate, size, channels) +* - Play/Stop/Pause/Resume loaded audio +* - Manage mixing channels +* - Manage raw audio context * * CONFIGURATION: * @@ -51,7 +49,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/audio.h b/src/audio.h index a0279e3a..8047d9bb 100644 --- a/src/audio.h +++ b/src/audio.h @@ -29,7 +29,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/camera.h b/src/camera.h index 87ba1942..e1b00ac2 100644 --- a/src/camera.h +++ b/src/camera.h @@ -1,6 +1,6 @@ /******************************************************************************************* * -* raylib Camera System - Camera Modes Setup and Control Functions +* raylib.camera - Camera system with multiple modes support * * NOTE: Memory footprint of this library is aproximately 52 bytes (global variables) * @@ -22,7 +22,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2015-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2015-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/core.c b/src/core.c index f55a70db..5b892cdf 100644 --- a/src/core.c +++ b/src/core.c @@ -2,14 +2,14 @@ * * raylib.core - Basic functions to manage windows, OpenGL context and input on multiple platforms * -* The following platforms are supported: -* Windows (win32/Win64) -* Linux (tested on Ubuntu) -* Mac (OSX) -* Android (API Level 9 or greater) -* Raspberry Pi (Raspbian) -* HTML5 (Chrome, Firefox) -* Oculus Rift CV1 +* PLATFORMS SUPPORTED: +* - Windows (win32/Win64) +* - Linux (tested on Ubuntu) +* - Mac (OSX) +* - Android (API Level 9 or greater) +* - Raspberry Pi (Raspbian) +* - HTML5 (Chrome, Firefox) +* - Oculus Rift CV1 * * CONFIGURATION: * @@ -49,7 +49,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/gestures.h b/src/gestures.h index 99f49d2a..42ced889 100644 --- a/src/gestures.h +++ b/src/gestures.h @@ -1,6 +1,6 @@ /********************************************************************************************** * -* raylib Gestures System - Gestures Processing based on input gesture events (touch/mouse) +* raylib.gestures - Gestures system, gestures processing based on input events (touch/mouse) * * NOTE: Memory footprint of this library is aproximately 128 bytes (global variables) * @@ -24,7 +24,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/models.c b/src/models.c index 8297358b..67e1693c 100644 --- a/src/models.c +++ b/src/models.c @@ -13,7 +13,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/raylib.h b/src/raylib.h index 4fd4b5df..cdefceb2 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -47,7 +47,7 @@ * raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, * BSD-like license that allows static linking with closed source software: * -* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/raymath.h b/src/raymath.h index a2263f19..7e760957 100644 --- a/src/raymath.h +++ b/src/raymath.h @@ -1,6 +1,6 @@ /********************************************************************************************** * -* raymath v1.0 - Some useful functions to work with Vector3, Matrix and Quaternions +* raymath v1.0 - Math functions to work with Vector3, Matrix and Quaternions * * CONFIGURATION: * diff --git a/src/rlgl.c b/src/rlgl.c index 00998624..d76f90bb 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -2,10 +2,8 @@ * * rlgl - raylib OpenGL abstraction layer * -* DESCRIPTION: -* -* rlgl allows usage of OpenGL 1.1 style functions (rlVertex) that are internally mapped to -* selected OpenGL version (1.1, 2.1, 3.3 Core, ES 2.0). +* rlgl is a wrapper for multiple OpenGL versions (1.1, 2.1, 3.3 Core, ES 2.0) to +* pseudo-OpenGL 1.1 style functions (rlVertex, rlTranslate, rlRotate...). * * When chosing an OpenGL version greater than OpenGL 1.1, rlgl stores vertex data on internal * VBO buffers (and VAOs if available). It requires calling 3 functions: @@ -16,32 +14,19 @@ * CONFIGURATION: * * #define GRAPHICS_API_OPENGL_11 -* Use OpenGL 1.1 backend -* * #define GRAPHICS_API_OPENGL_21 -* Use OpenGL 2.1 backend -* * #define GRAPHICS_API_OPENGL_33 -* Use OpenGL 3.3 Core profile backend -* * #define GRAPHICS_API_OPENGL_ES2 -* Use OpenGL ES 2.0 backend +* Use selected OpenGL backend * * #define RLGL_STANDALONE * Use rlgl as standalone library (no raylib dependency) * -* #define RLGL_NO_DISTORTION_SHADER -* Avoid stereo rendering distortion sahder (shader_distortion.h) inclusion -* -* #define SUPPORT_SHADER_DEFAULT / ENABLE_SHADER_DEFAULT +* #define SUPPORT_VR_SIMULATION / SUPPORT_STEREO_RENDERING +* Support VR simulation functionality (stereo rendering) * * #define SUPPORT_SHADER_DISTORTION -* -* #define SUPPORT_VR_SIMULATION -* -* #define SUPPORT_STEREO_RENDERING -* -* #define RLGL_NO_DEFAULT_SHADER +* Include stereo rendering distortion shader (shader_distortion.h) * * DEPENDENCIES: * raymath - 3D math functionality (Vector3, Matrix, Quaternion) @@ -50,7 +35,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -295,6 +280,13 @@ static bool texCompETC1Supported = false; // ETC1 texture compression support static bool texCompETC2Supported = false; // ETC2/EAC texture compression support static bool texCompPVRTSupported = false; // PVR texture compression support static bool texCompASTCSupported = false; // ASTC texture compression support + +// VR global variables +static VrDeviceInfo hmd; // Current VR device info +static VrStereoConfig vrConfig; // VR stereo configuration for simulator +static bool vrSimulatorReady = false; // VR simulator ready flag +static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag + // NOTE: This flag is useful to render data over stereo image (i.e. FPS) #endif // Extension supported flag: Anisotropic filtering @@ -304,13 +296,6 @@ static float maxAnisotropicLevel = 0.0f; // Maximum anisotropy level supp // Extension supported flag: Clamp mirror wrap mode static bool texClampMirrorSupported = false; // Clamp mirror wrap mode supported -// VR global variables -static VrDeviceInfo hmd; // Current VR device info -static VrStereoConfig vrConfig; // VR stereo configuration for simulator -static bool vrSimulatorReady = false; // VR simulator ready flag -static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag - // NOTE: This flag is useful to render data over stereo image (i.e. FPS) - #if defined(GRAPHICS_API_OPENGL_ES2) // NOTE: VAO functionality is exposed through extensions (OES) static PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays; @@ -2636,7 +2621,11 @@ void CloseVrSimulator(void) // Detect if VR simulator is running bool IsVrSimulatorReady(void) { +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) return vrSimulatorReady; +#else + return false; +#endif } // Enable/Disable VR experience (device or simulator) diff --git a/src/rlgl.h b/src/rlgl.h index 344da987..a870a907 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -2,8 +2,8 @@ * * rlgl - raylib OpenGL abstraction layer * -* rlgl allows usage of OpenGL 1.1 style functions (rlVertex) that are internally mapped to -* selected OpenGL version (1.1, 2.1, 3.3 Core, ES 2.0). +* rlgl is a wrapper for multiple OpenGL versions (1.1, 2.1, 3.3 Core, ES 2.0) to +* pseudo-OpenGL 1.1 style functions (rlVertex, rlTranslate, rlRotate...). * * When chosing an OpenGL version greater than OpenGL 1.1, rlgl stores vertex data on internal * VBO buffers (and VAOs if available). It requires calling 3 functions: @@ -11,18 +11,29 @@ * rlglDraw() - Process internal buffers and send required draw calls * rlglClose() - De-initialize internal buffers data and other auxiliar resources * -* External libs: +* CONFIGURATION: +* +* #define GRAPHICS_API_OPENGL_11 +* #define GRAPHICS_API_OPENGL_21 +* #define GRAPHICS_API_OPENGL_33 +* #define GRAPHICS_API_OPENGL_ES2 +* Use selected OpenGL backend +* +* #define RLGL_STANDALONE +* Use rlgl as standalone library (no raylib dependency) +* +* #define SUPPORT_VR_SIMULATION / SUPPORT_STEREO_RENDERING +* Support VR simulation functionality (stereo rendering) +* +* #define SUPPORT_SHADER_DISTORTION +* Include stereo rendering distortion shader (shader_distortion.h) +* +* DEPENDENCIES: * raymath - 3D math functionality (Vector3, Matrix, Quaternion) * GLAD - OpenGL extensions loading (OpenGL 3.3 Core only) * -* Module Configuration Flags: -* GRAPHICS_API_OPENGL_11 - Use OpenGL 1.1 backend -* GRAPHICS_API_OPENGL_21 - Use OpenGL 2.1 backend -* GRAPHICS_API_OPENGL_33 - Use OpenGL 3.3 Core profile backend -* GRAPHICS_API_OPENGL_ES2 - Use OpenGL ES 2.0 backend -* -* RLGL_STANDALONE - Use rlgl as standalone library (no raylib dependency) * +* LICENSE: zlib/libpng * * Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) * @@ -124,15 +135,21 @@ #define RL_WRAP_CLAMP 0x812F // GL_CLAMP_TO_EDGE #define RL_WRAP_CLAMP_MIRROR 0x8742 // GL_MIRROR_CLAMP_EXT +// Matrix modes (equivalent to OpenGL) +#define RL_MODELVIEW 0x1700 // GL_MODELVIEW +#define RL_PROJECTION 0x1701 // GL_PROJECTION +#define RL_TEXTURE 0x1702 // GL_TEXTURE + +// Primitive assembly draw modes +#define RL_LINES 0x0001 // GL_LINES +#define RL_TRIANGLES 0x0004 // GL_TRIANGLES +#define RL_QUADS 0x0007 // GL_QUADS + //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- typedef enum { OPENGL_11 = 1, OPENGL_21, OPENGL_33, OPENGL_ES_20 } GlVersion; -typedef enum { RL_PROJECTION, RL_MODELVIEW, RL_TEXTURE } MatrixMode; - -typedef enum { RL_LINES, RL_TRIANGLES, RL_QUADS } DrawMode; - typedef unsigned char byte; #if defined(RLGL_STANDALONE) diff --git a/src/rres.h b/src/rres.h index 362da10d..65ebdbba 100644 --- a/src/rres.h +++ b/src/rres.h @@ -1,8 +1,6 @@ /********************************************************************************************** * -* rres - raylib Resource custom format management functions -* -* Basic functions to load/save rRES resource files +* rres v1.0 - raylib resource (rRES) custom fileformat management functions * * CONFIGURATION: * diff --git a/src/shapes.c b/src/shapes.c index 5ed633f6..2a924476 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -13,7 +13,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/text.c b/src/text.c index 18ebf482..2d249b6d 100644 --- a/src/text.c +++ b/src/text.c @@ -18,7 +18,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/textures.c b/src/textures.c index 7db3bf56..f323f352 100644 --- a/src/textures.c +++ b/src/textures.c @@ -31,7 +31,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/utils.c b/src/utils.c index 54923e34..4d30cbc7 100644 --- a/src/utils.c +++ b/src/utils.c @@ -25,7 +25,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/utils.h b/src/utils.h index 037d7e94..45ffcf81 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,10 +1,11 @@ /********************************************************************************************** * -* raylib.utils +* raylib.utils - Some common utility functions * -* Some utility functions * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* LICENSE: zlib/libpng +* +* Copyright (c) 2014-2017 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. -- cgit v1.2.3 From 5387b4543175bee9d195b24e250a0ef863a63555 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 25 Mar 2017 12:01:01 +0100 Subject: Working on configuration flags --- src/core.c | 6 +- src/raylib.h | 2 +- src/rlgl.c | 21 +++- src/textures.c | 345 ++++++++++++++++++++++++++++++++++----------------------- src/utils.c | 2 +- 5 files changed, 228 insertions(+), 148 deletions(-) (limited to 'src/raylib.h') diff --git a/src/core.c b/src/core.c index 1a0e5a66..5a1ab77f 100644 --- a/src/core.c +++ b/src/core.c @@ -70,13 +70,13 @@ * **********************************************************************************************/ -// Default supported features -//------------------------------------- +// Default configuration flags (supported features) +//------------------------------------------------- #define SUPPORT_DEFAULT_FONT #define SUPPORT_MOUSE_GESTURES #define SUPPORT_CAMERA_SYSTEM #define SUPPORT_GESTURES_SYSTEM -//------------------------------------- +//------------------------------------------------- #include "raylib.h" diff --git a/src/raylib.h b/src/raylib.h index cdefceb2..24d6e1fd 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -13,7 +13,7 @@ * - Multiple textures support, including compressed formats and mipmaps generation * - Basic 3d support for Shapes, Models, Billboards, Heightmaps and Cubicmaps * - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] -* - Audio loading and playing with streaming support and mixing channels [audio] +* - Audio loading and playing with streaming support and mixing channels: [audio] * - VR stereo rendering support with configurable HMD device parameters * - Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi, HTML5 and Oculus Rift CV1 * - Custom color palette for fancy visuals on raywhite background diff --git a/src/rlgl.c b/src/rlgl.c index a937bdec..546fbe6e 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -25,7 +25,7 @@ * #define SUPPORT_VR_SIMULATION / SUPPORT_STEREO_RENDERING * Support VR simulation functionality (stereo rendering) * -* #define SUPPORT_SHADER_DISTORTION +* #define SUPPORT_DISTORTION_SHADER * Include stereo rendering distortion shader (shader_distortion.h) * * DEPENDENCIES: @@ -54,6 +54,11 @@ * **********************************************************************************************/ +// Default configuration flags (supported features) +//------------------------------------------------- +#define SUPPORT_VR_SIMULATION +//------------------------------------------------- + #include "rlgl.h" #include // Required for: fopen(), fclose(), fread()... [Used only on LoadText()] @@ -100,7 +105,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() [Used only on TraceLog()] #endif -#if !defined(GRAPHICS_API_OPENGL_11) && !defined(RLGL_NO_DISTORTION_SHADER) +#if !defined(GRAPHICS_API_OPENGL_11) && defined(SUPPORT_DISTORTION_SHADER) #include "shader_distortion.h" // Distortion shader to be embedded #endif @@ -2591,10 +2596,12 @@ void InitVrSimulator(int vrDevice) // Initialize framebuffer and textures for stereo rendering // NOTE: screen size should match HMD aspect ratio vrConfig.stereoFbo = rlglLoadRenderTexture(screenWidth, screenHeight); - + +#if defined(SUPPORT_DISTORTION_SHADER) // Load distortion shader (initialized by default with Oculus Rift CV1 parameters) vrConfig.distortionShader.id = LoadShaderProgram(vDistortionShaderStr, fDistortionShaderStr); if (vrConfig.distortionShader.id != 0) LoadDefaultShaderLocations(&vrConfig.distortionShader); +#endif SetStereoConfig(hmd); @@ -2613,7 +2620,9 @@ void CloseVrSimulator(void) if (vrSimulatorReady) { rlDeleteRenderTextures(vrConfig.stereoFbo); // Unload stereo framebuffer and texture + #if defined(SUPPORT_DISTORTION_SHADER) UnloadShader(vrConfig.distortionShader); // Unload distortion shader + #endif } #endif } @@ -2700,8 +2709,12 @@ void EndVrDrawing(void) rlMatrixMode(RL_MODELVIEW); // Enable internal modelview matrix rlLoadIdentity(); // Reset internal modelview matrix +#if defined(SUPPORT_DISTORTION_SHADER) // Draw RenderTexture (stereoFbo) using distortion shader currentShader = vrConfig.distortionShader; +#else + currentShader = GetDefaultShader(); +#endif rlEnableTexture(vrConfig.stereoFbo.texture.id); @@ -3536,6 +3549,7 @@ static void SetStereoConfig(VrDeviceInfo hmd) TraceLog(DEBUG, "VR: Distortion Shader: Scale = { %f, %f }", scale[0], scale[1]); TraceLog(DEBUG, "VR: Distortion Shader: ScaleIn = { %f, %f }", scaleIn[0], scaleIn[1]); +#if defined(SUPPORT_DISTORTION_SHADER) // Update distortion shader with lens and distortion-scale parameters SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "leftLensCenter"), leftLensCenter, 2); SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "rightLensCenter"), rightLensCenter, 2); @@ -3546,6 +3560,7 @@ static void SetStereoConfig(VrDeviceInfo hmd) SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "scaleIn"), scaleIn, 2); SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "hmdWarpParam"), hmd.distortionK, 4); SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "chromaAbParam"), hmd.chromaAbCorrection, 4); +#endif // Fovy is normally computed with: 2*atan2(hmd.vScreenSize, 2*hmd.eyeToScreenDistance)*RAD2DEG // ...but with lens distortion it is increased (see Oculus SDK Documentation) diff --git a/src/textures.c b/src/textures.c index f323f352..6fff8e75 100644 --- a/src/textures.c +++ b/src/textures.c @@ -4,24 +4,24 @@ * * CONFIGURATION: * -* #define SUPPORT_STB_IMAGE / INCLUDE_STB_IMAGE -* -* #define SUPPORT_FILEFORMAT_BMP / SUPPORT_LOAD_BMP -* #define SUPPORT_FILEFORMAT_PNG / SUPPORT_LOAD_PNG +* #define SUPPORT_FILEFORMAT_BMP +* #define SUPPORT_FILEFORMAT_PNG * #define SUPPORT_FILEFORMAT_TGA -* #define SUPPORT_FILEFORMAT_JPG / ENABLE_LOAD_JPG +* #define SUPPORT_FILEFORMAT_JPG * #define SUPPORT_FILEFORMAT_GIF +* #define SUPPORT_FILEFORMAT_PSD * #define SUPPORT_FILEFORMAT_HDR -* #define SUPPORT_FILEFORMAT_DDS / ENABLE_LOAD_DDS +* #define SUPPORT_FILEFORMAT_DDS * #define SUPPORT_FILEFORMAT_PKM * #define SUPPORT_FILEFORMAT_KTX * #define SUPPORT_FILEFORMAT_PVR * #define SUPPORT_FILEFORMAT_ASTC -* Selected desired fileformats to be supported for loading. Some of those formats are +* Selecte desired fileformats to be supported for image data loading. Some of those formats are * supported by default, to remove support, just comment unrequired #define in this module * -* #define SUPPORT_IMAGE_RESIZE / INCLUDE_STB_IMAGE_RESIZE * #define SUPPORT_IMAGE_MANIPULATION +* Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop... +* If not defined only three image editing functions supported: ImageFormat(), ImageAlphaMask(), ImageToPOT() * * DEPENDENCIES: * stb_image - Multiple image formats loading (JPEG, PNG, BMP, TGA, PSD, GIF, PIC) @@ -50,6 +50,12 @@ * **********************************************************************************************/ +// Default configuration flags (supported features) +//------------------------------------------------- +#define SUPPORT_FILEFORMAT_PNG +#define SUPPORT_IMAGE_MANIPULATION +//------------------------------------------------- + #include "raylib.h" #include // Required for: malloc(), free() @@ -61,23 +67,46 @@ #include "utils.h" // Required for: fopen() Android mapping, TraceLog() -// Support only desired texture formats, by default: JPEG, PNG, BMP, TGA -//#define STBI_NO_JPEG // Image format .jpg and .jpeg -//#define STBI_NO_PNG -//#define STBI_NO_BMP -//#define STBI_NO_TGA -#define STBI_NO_PSD -#define STBI_NO_GIF -#define STBI_NO_HDR +// Support only desired texture formats on stb_image +#if !defined(SUPPORT_FILEFORMAT_BMP) + #define STBI_NO_BMP +#endif +#if !defined(SUPPORT_FILEFORMAT_PNG) + #define STBI_NO_PNG +#endif +#if !defined(SUPPORT_FILEFORMAT_TGA) + #define STBI_NO_TGA +#endif +#if !defined(SUPPORT_FILEFORMAT_JPG) + #define STBI_NO_JPEG // Image format .jpg and .jpeg +#endif +#if !defined(SUPPORT_FILEFORMAT_PSD) + #define STBI_NO_PSD +#endif +#if !defined(SUPPORT_FILEFORMAT_GIF) + #define STBI_NO_GIF +#endif +#if !defined(SUPPORT_FILEFORMAT_HDR) + #define STBI_NO_HDR +#endif + +// Image fileformats not supported by default #define STBI_NO_PIC #define STBI_NO_PNM // Image format .ppm and .pgm -#define STB_IMAGE_IMPLEMENTATION -#include "external/stb_image.h" // Required for: stbi_load() - // NOTE: Used to read image data (multiple formats support) -#define STB_IMAGE_RESIZE_IMPLEMENTATION -#include "external/stb_image_resize.h" // Required for: stbir_resize_uint8() - // NOTE: Used for image scaling on ImageResize() +#if (defined(SUPPORT_FILEFORMAT_BMP) || defined(SUPPORT_FILEFORMAT_PNG) || defined(SUPPORT_FILEFORMAT_TGA) || \ + defined(SUPPORT_FILEFORMAT_JPG) || defined(SUPPORT_FILEFORMAT_PSD) || defined(SUPPORT_FILEFORMAT_GIF) || \ + defined(SUPPORT_FILEFORMAT_HDR)) + #define STB_IMAGE_IMPLEMENTATION + #include "external/stb_image.h" // Required for: stbi_load() + // NOTE: Used to read image data (multiple formats support) +#endif + +#if defined(SUPPORT_IMAGE_MANIPULATION) + #define STB_IMAGE_RESIZE_IMPLEMENTATION + #include "external/stb_image_resize.h" // Required for: stbir_resize_uint8() + // NOTE: Used for image scaling on ImageResize() +#endif //---------------------------------------------------------------------------------- // Defines and Macros @@ -102,11 +131,21 @@ //---------------------------------------------------------------------------------- // Module specific Functions Declaration //---------------------------------------------------------------------------------- +#if defined(SUPPORT_FILEFORMAT_DDS) static Image LoadDDS(const char *fileName); // Load DDS file +#endif +#if defined(SUPPORT_FILEFORMAT_PKM) static Image LoadPKM(const char *fileName); // Load PKM file +#endif +#if defined(SUPPORT_FILEFORMAT_KTX) static Image LoadKTX(const char *fileName); // Load KTX file +#endif +#if defined(SUPPORT_FILEFORMAT_PVR) static Image LoadPVR(const char *fileName); // Load PVR file +#endif +#if defined(SUPPORT_FILEFORMAT_ASTC) static Image LoadASTC(const char *fileName); // Load ASTC file +#endif //---------------------------------------------------------------------------------- // Module Functions Definition @@ -124,18 +163,21 @@ Image LoadImage(const char *fileName) image.mipmaps = 0; image.format = 0; - if ((strcmp(GetExtension(fileName),"png") == 0) || - (strcmp(GetExtension(fileName),"bmp") == 0) || - (strcmp(GetExtension(fileName),"tga") == 0) || - (strcmp(GetExtension(fileName),"jpg") == 0) -#ifndef STBI_NO_GIF + if ((strcmp(GetExtension(fileName),"png") == 0) +#if defined(SUPPORT_FILEFORMAT_BMP) + || (strcmp(GetExtension(fileName),"bmp") == 0) +#endif +#if defined(SUPPORT_FILEFORMAT_TGA) + || (strcmp(GetExtension(fileName),"tga") == 0) +#endif +#if defined(SUPPORT_FILEFORMAT_JPG) + || (strcmp(GetExtension(fileName),"jpg") == 0) +#endif +#if defined(SUPPORT_FILEFORMAT_DDS) || (strcmp(GetExtension(fileName),"gif") == 0) #endif -#ifndef STBI_NO_PSD +#if defined(SUPPORT_FILEFORMAT_PSD) || (strcmp(GetExtension(fileName),"psd") == 0) -#endif -#ifndef STBI_NO_PIC - || (strcmp(GetExtension(fileName),"pic") == 0) #endif ) { @@ -155,11 +197,21 @@ Image LoadImage(const char *fileName) else if (imgBpp == 3) image.format = UNCOMPRESSED_R8G8B8; else if (imgBpp == 4) image.format = UNCOMPRESSED_R8G8B8A8; } +#if defined(SUPPORT_FILEFORMAT_DDS) else if (strcmp(GetExtension(fileName),"dds") == 0) image = LoadDDS(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_PKM) else if (strcmp(GetExtension(fileName),"pkm") == 0) image = LoadPKM(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_KTX) else if (strcmp(GetExtension(fileName),"ktx") == 0) image = LoadKTX(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_PVR) else if (strcmp(GetExtension(fileName),"pvr") == 0) image = LoadPVR(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_ASTC) else if (strcmp(GetExtension(fileName),"astc") == 0) image = LoadASTC(fileName); +#endif else if (strcmp(GetExtension(fileName),"rres") == 0) { RRES rres = LoadResource(fileName, 0); @@ -171,6 +223,7 @@ Image LoadImage(const char *fileName) UnloadResource(rres); } + else TraceLog("[%s] Image fileformat not supported", fileName); if (image.data != NULL) TraceLog(INFO, "[%s] Image loaded successfully (%ix%i)", fileName, image.width, image.height); else TraceLog(WARNING, "[%s] Image could not be loaded", fileName); @@ -664,115 +717,6 @@ void ImageAlphaMask(Image *image, Image alphaMask) } } -// Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -// NOTE: In case selected bpp do not represent an known 16bit format, -// dithered data is stored in the LSB part of the unsigned short -void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) -{ - if (image->format >= COMPRESSED_DXT1_RGB) - { - TraceLog(WARNING, "Compressed data formats can not be dithered"); - return; - } - - if ((rBpp+gBpp+bBpp+aBpp) > 16) - { - TraceLog(WARNING, "Unsupported dithering bpps (%ibpp), only 16bpp or lower modes supported", (rBpp+gBpp+bBpp+aBpp)); - } - else - { - Color *pixels = GetImageData(*image); - - free(image->data); // free old image data - - if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8)) - { - TraceLog(WARNING, "Image format is already 16bpp or lower, dithering could have no effect"); - } - - // Define new image format, check if desired bpp match internal known format - if ((rBpp == 5) && (gBpp == 6) && (bBpp == 5) && (aBpp == 0)) image->format = UNCOMPRESSED_R5G6B5; - else if ((rBpp == 5) && (gBpp == 5) && (bBpp == 5) && (aBpp == 1)) image->format = UNCOMPRESSED_R5G5B5A1; - else if ((rBpp == 4) && (gBpp == 4) && (bBpp == 4) && (aBpp == 4)) image->format = UNCOMPRESSED_R4G4B4A4; - else - { - image->format = 0; - TraceLog(WARNING, "Unsupported dithered OpenGL internal format: %ibpp (R%iG%iB%iA%i)", (rBpp+gBpp+bBpp+aBpp), rBpp, gBpp, bBpp, aBpp); - } - - // NOTE: We will store the dithered data as unsigned short (16bpp) - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); - - Color oldPixel = WHITE; - Color newPixel = WHITE; - - int rError, gError, bError; - unsigned short rPixel, gPixel, bPixel, aPixel; // Used for 16bit pixel composition - - #define MIN(a,b) (((a)<(b))?(a):(b)) - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - oldPixel = pixels[y*image->width + x]; - - // NOTE: New pixel obtained by bits truncate, it would be better to round values (check ImageFormat()) - newPixel.r = oldPixel.r >> (8 - rBpp); // R bits - newPixel.g = oldPixel.g >> (8 - gBpp); // G bits - newPixel.b = oldPixel.b >> (8 - bBpp); // B bits - newPixel.a = oldPixel.a >> (8 - aBpp); // A bits (not used on dithering) - - // NOTE: Error must be computed between new and old pixel but using same number of bits! - // We want to know how much color precision we have lost... - rError = (int)oldPixel.r - (int)(newPixel.r << (8 - rBpp)); - gError = (int)oldPixel.g - (int)(newPixel.g << (8 - gBpp)); - bError = (int)oldPixel.b - (int)(newPixel.b << (8 - bBpp)); - - pixels[y*image->width + x] = newPixel; - - // NOTE: Some cases are out of the array and should be ignored - if (x < (image->width - 1)) - { - pixels[y*image->width + x+1].r = MIN((int)pixels[y*image->width + x+1].r + (int)((float)rError*7.0f/16), 0xff); - pixels[y*image->width + x+1].g = MIN((int)pixels[y*image->width + x+1].g + (int)((float)gError*7.0f/16), 0xff); - pixels[y*image->width + x+1].b = MIN((int)pixels[y*image->width + x+1].b + (int)((float)bError*7.0f/16), 0xff); - } - - if ((x > 0) && (y < (image->height - 1))) - { - pixels[(y+1)*image->width + x-1].r = MIN((int)pixels[(y+1)*image->width + x-1].r + (int)((float)rError*3.0f/16), 0xff); - pixels[(y+1)*image->width + x-1].g = MIN((int)pixels[(y+1)*image->width + x-1].g + (int)((float)gError*3.0f/16), 0xff); - pixels[(y+1)*image->width + x-1].b = MIN((int)pixels[(y+1)*image->width + x-1].b + (int)((float)bError*3.0f/16), 0xff); - } - - if (y < (image->height - 1)) - { - pixels[(y+1)*image->width + x].r = MIN((int)pixels[(y+1)*image->width + x].r + (int)((float)rError*5.0f/16), 0xff); - pixels[(y+1)*image->width + x].g = MIN((int)pixels[(y+1)*image->width + x].g + (int)((float)gError*5.0f/16), 0xff); - pixels[(y+1)*image->width + x].b = MIN((int)pixels[(y+1)*image->width + x].b + (int)((float)bError*5.0f/16), 0xff); - } - - if ((x < (image->width - 1)) && (y < (image->height - 1))) - { - pixels[(y+1)*image->width + x+1].r = MIN((int)pixels[(y+1)*image->width + x+1].r + (int)((float)rError*1.0f/16), 0xff); - pixels[(y+1)*image->width + x+1].g = MIN((int)pixels[(y+1)*image->width + x+1].g + (int)((float)gError*1.0f/16), 0xff); - pixels[(y+1)*image->width + x+1].b = MIN((int)pixels[(y+1)*image->width + x+1].b + (int)((float)bError*1.0f/16), 0xff); - } - - rPixel = (unsigned short)newPixel.r; - gPixel = (unsigned short)newPixel.g; - bPixel = (unsigned short)newPixel.b; - aPixel = (unsigned short)newPixel.a; - - ((unsigned short *)image->data)[y*image->width + x] = (rPixel << (gBpp + bBpp + aBpp)) | (gPixel << (bBpp + aBpp)) | (bPixel << aBpp) | aPixel; - } - } - - free(pixels); - } -} - // Convert image to POT (power-of-two) // NOTE: It could be useful on OpenGL ES 2.0 (RPI, HTML5) void ImageToPOT(Image *image, Color fillColor) @@ -818,6 +762,7 @@ void ImageToPOT(Image *image, Color fillColor) } } +#if defined(SUPPORT_IMAGE_MANIPULATION) // Copy an image to a new image Image ImageCopy(Image image) { @@ -1203,6 +1148,115 @@ void ImageFlipHorizontal(Image *image) image->data = processed.data; } +// Dither image data to 16bpp or lower (Floyd-Steinberg dithering) +// NOTE: In case selected bpp do not represent an known 16bit format, +// dithered data is stored in the LSB part of the unsigned short +void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) +{ + if (image->format >= COMPRESSED_DXT1_RGB) + { + TraceLog(WARNING, "Compressed data formats can not be dithered"); + return; + } + + if ((rBpp+gBpp+bBpp+aBpp) > 16) + { + TraceLog(WARNING, "Unsupported dithering bpps (%ibpp), only 16bpp or lower modes supported", (rBpp+gBpp+bBpp+aBpp)); + } + else + { + Color *pixels = GetImageData(*image); + + free(image->data); // free old image data + + if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8)) + { + TraceLog(WARNING, "Image format is already 16bpp or lower, dithering could have no effect"); + } + + // Define new image format, check if desired bpp match internal known format + if ((rBpp == 5) && (gBpp == 6) && (bBpp == 5) && (aBpp == 0)) image->format = UNCOMPRESSED_R5G6B5; + else if ((rBpp == 5) && (gBpp == 5) && (bBpp == 5) && (aBpp == 1)) image->format = UNCOMPRESSED_R5G5B5A1; + else if ((rBpp == 4) && (gBpp == 4) && (bBpp == 4) && (aBpp == 4)) image->format = UNCOMPRESSED_R4G4B4A4; + else + { + image->format = 0; + TraceLog(WARNING, "Unsupported dithered OpenGL internal format: %ibpp (R%iG%iB%iA%i)", (rBpp+gBpp+bBpp+aBpp), rBpp, gBpp, bBpp, aBpp); + } + + // NOTE: We will store the dithered data as unsigned short (16bpp) + image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); + + Color oldPixel = WHITE; + Color newPixel = WHITE; + + int rError, gError, bError; + unsigned short rPixel, gPixel, bPixel, aPixel; // Used for 16bit pixel composition + + #define MIN(a,b) (((a)<(b))?(a):(b)) + + for (int y = 0; y < image->height; y++) + { + for (int x = 0; x < image->width; x++) + { + oldPixel = pixels[y*image->width + x]; + + // NOTE: New pixel obtained by bits truncate, it would be better to round values (check ImageFormat()) + newPixel.r = oldPixel.r >> (8 - rBpp); // R bits + newPixel.g = oldPixel.g >> (8 - gBpp); // G bits + newPixel.b = oldPixel.b >> (8 - bBpp); // B bits + newPixel.a = oldPixel.a >> (8 - aBpp); // A bits (not used on dithering) + + // NOTE: Error must be computed between new and old pixel but using same number of bits! + // We want to know how much color precision we have lost... + rError = (int)oldPixel.r - (int)(newPixel.r << (8 - rBpp)); + gError = (int)oldPixel.g - (int)(newPixel.g << (8 - gBpp)); + bError = (int)oldPixel.b - (int)(newPixel.b << (8 - bBpp)); + + pixels[y*image->width + x] = newPixel; + + // NOTE: Some cases are out of the array and should be ignored + if (x < (image->width - 1)) + { + pixels[y*image->width + x+1].r = MIN((int)pixels[y*image->width + x+1].r + (int)((float)rError*7.0f/16), 0xff); + pixels[y*image->width + x+1].g = MIN((int)pixels[y*image->width + x+1].g + (int)((float)gError*7.0f/16), 0xff); + pixels[y*image->width + x+1].b = MIN((int)pixels[y*image->width + x+1].b + (int)((float)bError*7.0f/16), 0xff); + } + + if ((x > 0) && (y < (image->height - 1))) + { + pixels[(y+1)*image->width + x-1].r = MIN((int)pixels[(y+1)*image->width + x-1].r + (int)((float)rError*3.0f/16), 0xff); + pixels[(y+1)*image->width + x-1].g = MIN((int)pixels[(y+1)*image->width + x-1].g + (int)((float)gError*3.0f/16), 0xff); + pixels[(y+1)*image->width + x-1].b = MIN((int)pixels[(y+1)*image->width + x-1].b + (int)((float)bError*3.0f/16), 0xff); + } + + if (y < (image->height - 1)) + { + pixels[(y+1)*image->width + x].r = MIN((int)pixels[(y+1)*image->width + x].r + (int)((float)rError*5.0f/16), 0xff); + pixels[(y+1)*image->width + x].g = MIN((int)pixels[(y+1)*image->width + x].g + (int)((float)gError*5.0f/16), 0xff); + pixels[(y+1)*image->width + x].b = MIN((int)pixels[(y+1)*image->width + x].b + (int)((float)bError*5.0f/16), 0xff); + } + + if ((x < (image->width - 1)) && (y < (image->height - 1))) + { + pixels[(y+1)*image->width + x+1].r = MIN((int)pixels[(y+1)*image->width + x+1].r + (int)((float)rError*1.0f/16), 0xff); + pixels[(y+1)*image->width + x+1].g = MIN((int)pixels[(y+1)*image->width + x+1].g + (int)((float)gError*1.0f/16), 0xff); + pixels[(y+1)*image->width + x+1].b = MIN((int)pixels[(y+1)*image->width + x+1].b + (int)((float)bError*1.0f/16), 0xff); + } + + rPixel = (unsigned short)newPixel.r; + gPixel = (unsigned short)newPixel.g; + bPixel = (unsigned short)newPixel.b; + aPixel = (unsigned short)newPixel.a; + + ((unsigned short *)image->data)[y*image->width + x] = (rPixel << (gBpp + bBpp + aBpp)) | (gPixel << (bBpp + aBpp)) | (bPixel << aBpp) | aPixel; + } + } + + free(pixels); + } +} + // Modify image color: tint void ImageColorTint(Image *image, Color color) { @@ -1359,6 +1413,7 @@ void ImageColorBrightness(Image *image, int brightness) image->data = processed.data; } +#endif // SUPPORT_IMAGE_MANIPULATION // Generate GPU mipmaps for a texture void GenTextureMipmaps(Texture2D *texture) @@ -1547,6 +1602,7 @@ void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, V // Module specific Functions Definition //---------------------------------------------------------------------------------- +#if defined(SUPPORT_FILEFORMAT_DDS) // Loading DDS image data (compressed or uncompressed) static Image LoadDDS(const char *fileName) { @@ -1744,7 +1800,9 @@ static Image LoadDDS(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_PKM) // Loading PKM image data (ETC1/ETC2 compression) // NOTE: KTX is the standard Khronos Group compression format (ETC1/ETC2, mipmaps) // PKM is a much simpler file format used mainly to contain a single ETC1/ETC2 compressed image (no mipmaps) @@ -1836,7 +1894,9 @@ static Image LoadPKM(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_KTX) // Load KTX compressed image data (ETC1/ETC2 compression) static Image LoadKTX(const char *fileName) { @@ -1929,7 +1989,9 @@ static Image LoadKTX(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_PVR) // Loading PVR image data (uncompressed or PVRT compression) // NOTE: PVR v2 not supported, use PVR v3 instead static Image LoadPVR(const char *fileName) @@ -2087,7 +2149,9 @@ static Image LoadPVR(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_ASTC) // Load ASTC compressed image data (ASTC compression) static Image LoadASTC(const char *fileName) { @@ -2170,3 +2234,4 @@ static Image LoadASTC(const char *fileName) return image; } +#endif \ No newline at end of file diff --git a/src/utils.c b/src/utils.c index 4d30cbc7..b6b309cc 100644 --- a/src/utils.c +++ b/src/utils.c @@ -20,7 +20,7 @@ * Show TraceLog() DEBUG messages * * DEPENDENCIES: -* stb_image_write - PNG writting functions +* stb_image_write - BMP/PNG writting functions * * * LICENSE: zlib/libpng -- cgit v1.2.3 From 080a79f0b03bd40a4ac6dfb8c6f90a3a7379d7ad Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 Mar 2017 00:35:42 +0200 Subject: Added IsFileExtension() Replaced old GetExtension() function Make IsFileExtension() public to the API --- src/audio.c | 39 +++++++++++++++++++++------------------ src/audio.h | 7 ++++--- src/core.c | 22 ++++++++++++++++++---- src/models.c | 4 ++-- src/raylib.h | 5 +++-- src/text.c | 10 +++++----- src/textures.c | 46 +++++++++++++++++++++++----------------------- src/utils.c | 22 +++++----------------- src/utils.h | 5 ++--- 9 files changed, 83 insertions(+), 77 deletions(-) (limited to 'src/raylib.h') diff --git a/src/audio.c b/src/audio.c index 5edabf41..34be4789 100644 --- a/src/audio.c +++ b/src/audio.c @@ -24,7 +24,6 @@ * Selected desired fileformats to be supported for loading. Some of those formats are * supported by default, to remove support, just comment unrequired #define in this module * -* * LIMITATIONS: * Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) * Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) @@ -65,8 +64,6 @@ * **********************************************************************************************/ -//#define AUDIO_STANDALONE // NOTE: To use the audio module as standalone lib, just uncomment this line - // Default configuration flags (supported features) //------------------------------------------------- #define SUPPORT_FILEFORMAT_WAV @@ -194,8 +191,8 @@ static Wave LoadFLAC(const char *fileName); // Load FLAC file #endif #if defined(AUDIO_STANDALONE) -const char *GetExtension(const char *fileName); // Get the extension for a filename -void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message (INFO, ERROR, WARNING) +bool IsFileExtension(const char *fileName, const char *ext); // Check file extension +void TraceLog(int msgType, const char *text, ...); // Outputs trace log message (INFO, ERROR, WARNING) #endif //---------------------------------------------------------------------------------- @@ -285,15 +282,15 @@ Wave LoadWave(const char *fileName) { Wave wave = { 0 }; - if (strcmp(GetExtension(fileName), "wav") == 0) wave = LoadWAV(fileName); + if (IsFileExtension(fileName, ".wav")) wave = LoadWAV(fileName); #if defined(SUPPORT_FILEFORMAT_OGG) - else if (strcmp(GetExtension(fileName), "ogg") == 0) wave = LoadOGG(fileName); + else if (IsFileExtension(fileName, ".ogg")) wave = LoadOGG(fileName); #endif #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (strcmp(GetExtension(fileName), "flac") == 0) wave = LoadFLAC(fileName); + else if (IsFileExtension(fileName, ".flac")) wave = LoadFLAC(fileName); #endif #if !defined(AUDIO_STANDALONE) - else if (strcmp(GetExtension(fileName),"rres") == 0) + else if (IsFileExtension(fileName, ".rres")) { RRES rres = LoadResource(fileName, 0); @@ -672,7 +669,7 @@ Music LoadMusicStream(const char *fileName) { Music music = (MusicData *)malloc(sizeof(MusicData)); - if (strcmp(GetExtension(fileName), "ogg") == 0) + if (IsFileExtension(fileName, ".ogg")) { // Open ogg audio stream music->ctxOgg = stb_vorbis_open_filename(fileName, NULL, NULL); @@ -696,7 +693,7 @@ Music LoadMusicStream(const char *fileName) } } #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (strcmp(GetExtension(fileName), "flac") == 0) + else if (IsFileExtension(fileName, ".flac")) { music->ctxFlac = drflac_open_file(fileName); @@ -717,7 +714,7 @@ Music LoadMusicStream(const char *fileName) } #endif #if defined(SUPPORT_FILEFORMAT_XM) - else if (strcmp(GetExtension(fileName), "xm") == 0) + else if (IsFileExtension(fileName, ".xm")) { int result = jar_xm_create_context_from_file(&music->ctxXm, 48000, fileName); @@ -739,7 +736,7 @@ Music LoadMusicStream(const char *fileName) } #endif #if defined(SUPPORT_FILEFORMAT_MOD) - else if (strcmp(GetExtension(fileName), "mod") == 0) + else if (IsFileExtension(fileName, ".mod")) { jar_mod_init(&music->ctxMod); @@ -1310,12 +1307,18 @@ static Wave LoadFLAC(const char *fileName) // Some required functions for audio standalone module version #if defined(AUDIO_STANDALONE) -// Get the extension for a filename -const char *GetExtension(const char *fileName) +// Check file extension +bool IsFileExtension(const char *fileName, const char *ext) { - const char *dot = strrchr(fileName, '.'); - if (!dot || dot == fileName) return ""; - return (dot + 1); + bool result = false; + const char *fileExt; + + if ((fileExt = strrchr(fileName, '.')) != NULL) + { + if (strcmp(fileExt, ext) == 0) result = true; + } + + return result; } // Outputs a trace log message (INFO, ERROR, WARNING) diff --git a/src/audio.h b/src/audio.h index 51f858da..48ef7403 100644 --- a/src/audio.h +++ b/src/audio.h @@ -123,7 +123,7 @@ Wave LoadWave(const char *fileName); // Load wave dat Wave LoadWaveEx(void *data, int sampleCount, int sampleRate, int sampleSize, int channels); // Load wave data from raw array data Sound LoadSound(const char *fileName); // Load sound from file Sound LoadSoundFromWave(Wave wave); // Load sound from wave data -void UpdateSound(Sound sound, const void *data, int samplesCount); // Update sound buffer with new data +void UpdateSound(Sound sound, const void *data, int samplesCount);// Update sound buffer with new data void UnloadWave(Wave wave); // Unload wave data void UnloadSound(Sound sound); // Unload sound void PlaySound(Sound sound); // Play a sound @@ -151,9 +151,10 @@ void SetMusicLoopCount(Music music, float count); // Set music loo float GetMusicTimeLength(Music music); // Get music time length (in seconds) float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) +// Raw audio stream functions AudioStream InitAudioStream(unsigned int sampleRate, - unsigned int sampleSize, - unsigned int channels); // Init audio stream (to stream raw audio pcm data) + unsigned int sampleSize, + unsigned int channels); // Init audio stream (to stream raw audio pcm data) void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data void CloseAudioStream(AudioStream stream); // Close audio stream and free memory bool IsAudioBufferProcessed(AudioStream stream); // Check if any audio stream buffers requires refill diff --git a/src/core.c b/src/core.c index b8d822a8..b9ea9315 100644 --- a/src/core.c +++ b/src/core.c @@ -102,7 +102,7 @@ #include // Required for: typedef unsigned long long int uint64_t, used by hi-res timer #include // Required for: time() - Android/RPI hi-res timer (NOTE: Linux only!) #include // Required for: tan() [Used in Begin3dMode() to set perspective] -#include // Required for: strcmp() +#include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes #if defined __linux__ || defined(PLATFORM_WEB) @@ -978,6 +978,12 @@ Color Fade(Color color, float alpha) return (Color){color.r, color.g, color.b, (unsigned char)colorAlpha}; } +// Activates raylib logo at startup +void ShowLogo(void) +{ + showLogo = true; +} + // Enable some window/system configurations void SetConfigFlags(char flags) { @@ -987,10 +993,18 @@ void SetConfigFlags(char flags) if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; } -// Activates raylib logo at startup -void ShowLogo(void) +// Check file extension +bool IsFileExtension(const char *fileName, const char *ext) { - showLogo = true; + bool result = false; + const char *fileExt; + + if ((fileExt = strrchr(fileName, '.')) != NULL) + { + if (strcmp(fileExt, ext) == 0) result = true; + } + + return result; } #if defined(PLATFORM_DESKTOP) diff --git a/src/models.c b/src/models.c index 6aff59c4..47220af8 100644 --- a/src/models.c +++ b/src/models.c @@ -593,7 +593,7 @@ Mesh LoadMesh(const char *fileName) Mesh mesh = { 0 }; #if defined(SUPPORT_FILEFORMAT_OBJ) - if (strcmp(GetExtension(fileName), "obj") == 0) mesh = LoadOBJ(fileName); + if (IsFileExtension(fileName, ".obj")) mesh = LoadOBJ(fileName); #else TraceLog(WARNING, "[%s] Mesh fileformat not supported, it can't be loaded", fileName); #endif @@ -706,7 +706,7 @@ Material LoadMaterial(const char *fileName) Material material = { 0 }; #if defined(SUPPORT_FILEFORMAT_MTL) - if (strcmp(GetExtension(fileName), "mtl") == 0) material = LoadMTL(fileName); + if (IsFileExtension(fileName, ".mtl")) material = LoadMTL(fileName); #else TraceLog(WARNING, "[%s] Material fileformat not supported, it can't be loaded", fileName); #endif diff --git a/src/raylib.h b/src/raylib.h index 24d6e1fd..3e6c68ff 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -687,9 +687,10 @@ RLAPI float *MatrixToFloat(Matrix mat); // Converts Ma RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) RLAPI Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f -RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) -//RLAPI void TraceLog(int logType, const char *text, ...); // Trace log messages showing (INFO, WARNING, ERROR, DEBUG) +RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags +//RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) +RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window RLAPI char **GetDroppedFiles(int *count); // Retrieve dropped files into window diff --git a/src/text.c b/src/text.c index c736d5ad..09f69ff6 100644 --- a/src/text.c +++ b/src/text.c @@ -48,7 +48,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() #include // Required for: FILE, fopen(), fclose(), fscanf(), feof(), rewind(), fgets() -#include "utils.h" // Required for: GetExtension() +#include "utils.h" // Required for: IsFileExtension() #if defined(SUPPORT_FILEFORMAT_TTF) // Following libs are used on LoadTTF() @@ -287,7 +287,7 @@ SpriteFont LoadSpriteFont(const char *fileName) SpriteFont spriteFont = { 0 }; // Check file extension - if (strcmp(GetExtension(fileName),"rres") == 0) + if (IsFileExtension(fileName, ".rres")) { // TODO: Read multiple resource blocks from file (RRES_FONT_IMAGE, RRES_FONT_CHARDATA) RRES rres = LoadResource(fileName, 0); @@ -314,10 +314,10 @@ SpriteFont LoadSpriteFont(const char *fileName) //UnloadResource(rres[0]); } #if defined(SUPPORT_FILEFORMAT_TTF) - else if (strcmp(GetExtension(fileName),"ttf") == 0) spriteFont = LoadSpriteFontTTF(fileName, DEFAULT_TTF_FONTSIZE, 0, NULL); + else if (IsFileExtension(fileName, ".ttf")) spriteFont = LoadSpriteFontTTF(fileName, DEFAULT_TTF_FONTSIZE, 0, NULL); #endif #if defined(SUPPORT_FILEFORMAT_FNT) - else if (strcmp(GetExtension(fileName),"fnt") == 0) spriteFont = LoadBMFont(fileName); + else if (IsFileExtension(fileName, ".fnt")) spriteFont = LoadBMFont(fileName); #endif else { @@ -344,7 +344,7 @@ SpriteFont LoadSpriteFontTTF(const char *fileName, int fontSize, int charsCount, SpriteFont spriteFont = { 0 }; #if defined(SUPPORT_FILEFORMAT_TTF) - if (strcmp(GetExtension(fileName),"ttf") == 0) + if (IsFileExtension(fileName, ".ttf")) { if ((fontChars == NULL) || (charsCount == 0)) { diff --git a/src/textures.c b/src/textures.c index 6fff8e75..fff0e4e9 100644 --- a/src/textures.c +++ b/src/textures.c @@ -163,21 +163,32 @@ Image LoadImage(const char *fileName) image.mipmaps = 0; image.format = 0; - if ((strcmp(GetExtension(fileName),"png") == 0) + if (IsFileExtension(fileName, ".rres")) + { + RRES rres = LoadResource(fileName, 0); + + // NOTE: Parameters for RRES_TYPE_IMAGE are: width, height, format, mipmaps + + if (rres[0].type == RRES_TYPE_IMAGE) image = LoadImagePro(rres[0].data, rres[0].param1, rres[0].param2, rres[0].param3); + else TraceLog(WARNING, "[%s] Resource file does not contain image data", fileName); + + UnloadResource(rres); + } + else if ((IsFileExtension(fileName, ".png")) #if defined(SUPPORT_FILEFORMAT_BMP) - || (strcmp(GetExtension(fileName),"bmp") == 0) + || (IsFileExtension(fileName, ".bmp")) #endif #if defined(SUPPORT_FILEFORMAT_TGA) - || (strcmp(GetExtension(fileName),"tga") == 0) + || (IsFileExtension(fileName, ".tga")) #endif #if defined(SUPPORT_FILEFORMAT_JPG) - || (strcmp(GetExtension(fileName),"jpg") == 0) + || (IsFileExtension(fileName, ".jpg")) #endif #if defined(SUPPORT_FILEFORMAT_DDS) - || (strcmp(GetExtension(fileName),"gif") == 0) + || (IsFileExtension(fileName, ".gif")) #endif #if defined(SUPPORT_FILEFORMAT_PSD) - || (strcmp(GetExtension(fileName),"psd") == 0) + || (IsFileExtension(fileName, ".psd")) #endif ) { @@ -198,32 +209,21 @@ Image LoadImage(const char *fileName) else if (imgBpp == 4) image.format = UNCOMPRESSED_R8G8B8A8; } #if defined(SUPPORT_FILEFORMAT_DDS) - else if (strcmp(GetExtension(fileName),"dds") == 0) image = LoadDDS(fileName); + else if (IsFileExtension(fileName, ".dds")) image = LoadDDS(fileName); #endif #if defined(SUPPORT_FILEFORMAT_PKM) - else if (strcmp(GetExtension(fileName),"pkm") == 0) image = LoadPKM(fileName); + else if (IsFileExtension(fileName, ".pkm")) image = LoadPKM(fileName); #endif #if defined(SUPPORT_FILEFORMAT_KTX) - else if (strcmp(GetExtension(fileName),"ktx") == 0) image = LoadKTX(fileName); + else if (IsFileExtension(fileName, ".ktx")) image = LoadKTX(fileName); #endif #if defined(SUPPORT_FILEFORMAT_PVR) - else if (strcmp(GetExtension(fileName),"pvr") == 0) image = LoadPVR(fileName); + else if (IsFileExtension(fileName, ".pvr")) image = LoadPVR(fileName); #endif #if defined(SUPPORT_FILEFORMAT_ASTC) - else if (strcmp(GetExtension(fileName),"astc") == 0) image = LoadASTC(fileName); + else if (IsFileExtension(fileName, ".astc")) image = LoadASTC(fileName); #endif - else if (strcmp(GetExtension(fileName),"rres") == 0) - { - RRES rres = LoadResource(fileName, 0); - - // NOTE: Parameters for RRES_TYPE_IMAGE are: width, height, format, mipmaps - - if (rres[0].type == RRES_TYPE_IMAGE) image = LoadImagePro(rres[0].data, rres[0].param1, rres[0].param2, rres[0].param3); - else TraceLog(WARNING, "[%s] Resource file does not contain image data", fileName); - - UnloadResource(rres); - } - else TraceLog("[%s] Image fileformat not supported", fileName); + else TraceLog(WARNING, "[%s] Image fileformat not supported", fileName); if (image.data != NULL) TraceLog(INFO, "[%s] Image loaded successfully (%ix%i)", fileName, image.width, image.height); else TraceLog(WARNING, "[%s] Image could not be loaded", fileName); diff --git a/src/utils.c b/src/utils.c index 6a07f301..649fda4f 100644 --- a/src/utils.c +++ b/src/utils.c @@ -88,14 +88,15 @@ static int android_close(void *cookie); //---------------------------------------------------------------------------------- // Module Functions Definition - Utilities //---------------------------------------------------------------------------------- -// Outputs a trace log message + +// Output trace log messages void TraceLog(int msgType, const char *text, ...) { -#if !defined(NO_TRACELOG) +#if defined(SUPPORT_TRACELOG) static char buffer[128]; int traceDebugMsgs = 1; -#ifdef DO_NOT_TRACE_DEBUG_MSGS +#if defined(SUPPORT_TRACELOG_DEBUG) traceDebugMsgs = 0; #endif @@ -131,7 +132,7 @@ void TraceLog(int msgType, const char *text, ...) if (msgType == ERROR) exit(1); // If ERROR message, exit program -#endif // NO_TRACELOG +#endif // SUPPORT_TRACELOG } #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) @@ -163,19 +164,6 @@ void RecordMalloc(int mallocType, int mallocSize, const char *msg) } */ -bool IsFileExtension(const char *fileName, const char *ext) -{ - return (strcmp(GetExtension(fileName), ext) == 0); -} - -// Get the extension for a filename -const char *GetExtension(const char *fileName) -{ - const char *dot = strrchr(fileName, '.'); - if (!dot || dot == fileName) return ""; - return (dot + 1); -} - #if defined(PLATFORM_ANDROID) // Initialize asset manager from android app void InitAssetManager(AAssetManager *manager) diff --git a/src/utils.h b/src/utils.h index 45ffcf81..2b4d838b 100644 --- a/src/utils.h +++ b/src/utils.h @@ -60,8 +60,7 @@ extern "C" { // Prevents name mangling of functions //---------------------------------------------------------------------------------- // Module Functions Declaration //---------------------------------------------------------------------------------- -void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message -const char *GetExtension(const char *fileName); // Returns extension of a filename +void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) #if defined(SUPPORT_SAVE_BMP) @@ -74,7 +73,7 @@ void SavePNG(const char *fileName, unsigned char *imgData, int width, int height #if defined(PLATFORM_ANDROID) void InitAssetManager(AAssetManager *manager); // Initialize asset manager from android app -FILE *android_fopen(const char *fileName, const char *mode); // Replacement for fopen() +FILE *android_fopen(const char *fileName, const char *mode); // Replacement for fopen() #endif #ifdef __cplusplus -- cgit v1.2.3 From c3b8a41f952f1d6da8d943ebfed9163898824fc0 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 3 Apr 2017 23:10:49 +0200 Subject: Remove function declaration --- src/raylib.h | 1 - 1 file changed, 1 deletion(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index 3e6c68ff..e8f301ec 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -892,7 +892,6 @@ RLAPI void UnloadMesh(Mesh *mesh); RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) RLAPI Material LoadMaterial(const char *fileName); // Load material from file -RLAPI Material LoadMaterialEx(Shader shader, Texture2D diffuse, Color color); // Load material from basic shading data RLAPI Material LoadDefaultMaterial(void); // Load default material (uses default models shader) RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) -- cgit v1.2.3 From 7e65c300b6927bff3fb9cfa84e98fd662941fc20 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 16 Apr 2017 13:47:49 +0200 Subject: Make public TakeScreenshot() function --- src/core.c | 47 ++++++++++++++++++++++------------------------- src/raylib.h | 1 + 2 files changed, 23 insertions(+), 25 deletions(-) (limited to 'src/raylib.h') diff --git a/src/core.c b/src/core.c index c73a9418..3f3bc6ea 100644 --- a/src/core.c +++ b/src/core.c @@ -316,9 +316,6 @@ static void PollInputEvents(void); // Register user events static void SwapBuffers(void); // Copy back buffer to front buffers static void LogoAnimation(void); // Plays raylib logo appearing animation static void SetupViewport(void); // Set viewport parameters -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) -static void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable -#endif #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) static void ErrorCallback(int error, const char *description); // GLFW3 Error Callback, runs on GLFW3 error @@ -1001,6 +998,28 @@ void SetConfigFlags(char flags) if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; } +// Takes a screenshot and saves it in the same folder as executable +void TakeScreenshot(void) +{ +#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) + static int shotNum = 0; // Screenshot number, increments every screenshot take during program execution + char buffer[20]; // Buffer to store file name + + unsigned char *imgData = rlglReadScreenPixels(renderWidth, renderHeight); + + sprintf(buffer, "screenshot%03i.png", shotNum); + + // Save image as PNG + SavePNG(buffer, imgData, renderWidth, renderHeight, 4); + + free(imgData); + + shotNum++; + + TraceLog(INFO, "[%s] Screenshot taken #03i", buffer, shotNum); +#endif +} + // Check file extension bool IsFileExtension(const char *fileName, const char *ext) { @@ -2284,28 +2303,6 @@ static void SwapBuffers(void) #endif } -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) -// Takes a screenshot and saves it in the same folder as executable -static void TakeScreenshot(void) -{ - static int shotNum = 0; // Screenshot number, increments every screenshot take during program execution - char buffer[20]; // Buffer to store file name - - unsigned char *imgData = rlglReadScreenPixels(renderWidth, renderHeight); - - sprintf(buffer, "screenshot%03i.png", shotNum); - - // Save image as PNG - SavePNG(buffer, imgData, renderWidth, renderHeight, 4); - - free(imgData); - - shotNum++; - - TraceLog(INFO, "[%s] Screenshot taken!", buffer); -} -#endif - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) // GLFW3 Error Callback, runs on GLFW3 error static void ErrorCallback(int error, const char *description) diff --git a/src/raylib.h b/src/raylib.h index e8f301ec..b82ec342 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -690,6 +690,7 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags //RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) +RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window -- cgit v1.2.3 From ecfe31bf1d2647dc52b8e1584e4b7f022049e09b Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 21 Apr 2017 00:08:00 +0200 Subject: Make TraceLog() public to the API enum LogType could require some revision... --- src/audio.c | 2 +- src/core.c | 2 +- src/raylib.h | 28 ++++++++++++++++++++++++---- src/text.c | 2 +- src/textures.c | 2 +- src/utils.h | 4 ---- 6 files changed, 28 insertions(+), 12 deletions(-) (limited to 'src/raylib.h') diff --git a/src/audio.c b/src/audio.c index 34be4789..9a7779f4 100644 --- a/src/audio.c +++ b/src/audio.c @@ -75,7 +75,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() #else #include "raylib.h" - #include "utils.h" // Required for: fopen() Android mapping, TraceLog() + #include "utils.h" // Required for: fopen() Android mapping #endif #ifdef __APPLE__ diff --git a/src/core.c b/src/core.c index 3f3bc6ea..ee069d97 100644 --- a/src/core.c +++ b/src/core.c @@ -81,7 +81,7 @@ #include "raylib.h" #include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2 -#include "utils.h" // Required for: fopen() Android mapping, TraceLog() +#include "utils.h" // Required for: fopen() Android mapping #define RAYMATH_IMPLEMENTATION // Use raymath as a header-only library (includes implementation) #define RAYMATH_EXTERN_INLINE // Compile raymath functions as static inline (remember, it's a compiler hint) diff --git a/src/raylib.h b/src/raylib.h index b82ec342..286494c7 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -295,7 +295,7 @@ #define RAYWHITE CLITERAL{ 245, 245, 245, 255 } // My own White (raylib logo) //---------------------------------------------------------------------------------- -// Types and Structures Definition +// Structures Definition //---------------------------------------------------------------------------------- #ifndef __cplusplus // Boolean type @@ -516,6 +516,18 @@ typedef struct AudioStream { unsigned int buffers[2]; // OpenAL audio buffers (double buffering) } AudioStream; +//---------------------------------------------------------------------------------- +// Enumerators Definition +//---------------------------------------------------------------------------------- +// Trace log type +typedef enum { + INFO = 0, + WARNING, + ERROR, + DEBUG, + OTHER +} LogType; + // Texture formats // NOTE: Support depends on OpenGL version and platform typedef enum { @@ -552,10 +564,18 @@ typedef enum { } TextureFilterMode; // Texture parameters: wrap mode -typedef enum { WRAP_REPEAT = 0, WRAP_CLAMP, WRAP_MIRROR } TextureWrapMode; +typedef enum { + WRAP_REPEAT = 0, + WRAP_CLAMP, + WRAP_MIRROR +} TextureWrapMode; // Color blending modes (pre-defined) -typedef enum { BLEND_ALPHA = 0, BLEND_ADDITIVE, BLEND_MULTIPLIED } BlendMode; +typedef enum { + BLEND_ALPHA = 0, + BLEND_ADDITIVE, + BLEND_MULTIPLIED +} BlendMode; // Gestures type // NOTE: It could be used as flags to enable only some gestures @@ -689,7 +709,7 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags -//RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) +RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension diff --git a/src/text.c b/src/text.c index a057e347..ebc8b0ff 100644 --- a/src/text.c +++ b/src/text.c @@ -50,7 +50,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() #include // Required for: FILE, fopen(), fclose(), fscanf(), feof(), rewind(), fgets() -#include "utils.h" // Required for: IsFileExtension() +#include "utils.h" // Required for: fopen() Android mapping #if defined(SUPPORT_FILEFORMAT_TTF) // Following libs are used on LoadTTF() diff --git a/src/textures.c b/src/textures.c index af95f9dc..7013038d 100644 --- a/src/textures.c +++ b/src/textures.c @@ -65,7 +65,7 @@ // Required for: rlglLoadTexture() rlDeleteTextures(), // rlglGenerateMipmaps(), some funcs for DrawTexturePro() -#include "utils.h" // Required for: fopen() Android mapping, TraceLog() +#include "utils.h" // Required for: fopen() Android mapping // Support only desired texture formats on stb_image #if !defined(SUPPORT_FILEFORMAT_BMP) diff --git a/src/utils.h b/src/utils.h index 2b4d838b..64592c73 100644 --- a/src/utils.h +++ b/src/utils.h @@ -46,8 +46,6 @@ //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- -typedef enum { INFO = 0, ERROR, WARNING, DEBUG, OTHER } TraceLogType; - #ifdef __cplusplus extern "C" { // Prevents name mangling of functions #endif @@ -60,8 +58,6 @@ extern "C" { // Prevents name mangling of functions //---------------------------------------------------------------------------------- // Module Functions Declaration //---------------------------------------------------------------------------------- -void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) #if defined(SUPPORT_SAVE_BMP) void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize); -- cgit v1.2.3 From b0f8ea27e3d7417c0f0c9795aa315dac399c97bf Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sat, 22 Apr 2017 19:04:54 +0200 Subject: Renamed function for lib consistency LoadSpriteFontTTF() --> LoadSpriteFontEx() --- docs/examples/src/text/text_ttf_loading.c | 4 ++-- docs/examples/web/text/text_ttf_loading.c | 4 ++-- docs/examples/web/textures/textures_raw_data.c | 2 +- examples/text/text_ttf_loading.c | 4 ++-- src/raylib.h | 2 +- src/text.c | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) (limited to 'src/raylib.h') diff --git a/docs/examples/src/text/text_ttf_loading.c b/docs/examples/src/text/text_ttf_loading.c index 4e490399..02b7f95f 100644 --- a/docs/examples/src/text/text_ttf_loading.c +++ b/docs/examples/src/text/text_ttf_loading.c @@ -25,7 +25,7 @@ int main() // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) // TTF SpriteFont loading with custom generation parameters - SpriteFont font = LoadSpriteFontTTF("resources/KAISG.ttf", 96, 0, 0); + SpriteFont font = LoadSpriteFontEx("resources/KAISG.ttf", 96, 0, 0); // Generate mipmap levels to use trilinear filtering // NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR @@ -82,7 +82,7 @@ int main() if (count == 1) // Only support one ttf file dropped { UnloadSpriteFont(font); - font = LoadSpriteFontTTF(droppedFiles[0], fontSize, 0, 0); + font = LoadSpriteFontEx(droppedFiles[0], fontSize, 0, 0); ClearDroppedFiles(); } } diff --git a/docs/examples/web/text/text_ttf_loading.c b/docs/examples/web/text/text_ttf_loading.c index 9dfdcac2..02097437 100644 --- a/docs/examples/web/text/text_ttf_loading.c +++ b/docs/examples/web/text/text_ttf_loading.c @@ -52,7 +52,7 @@ int main() // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) // TTF SpriteFont loading with custom generation parameters - font = LoadSpriteFontTTF("resources/KAISG.ttf", 96, 0, 0); + font = LoadSpriteFontEx("resources/KAISG.ttf", 96, 0, 0); // Generate mipmap levels to use trilinear filtering // NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR @@ -130,7 +130,7 @@ void UpdateDrawFrame(void) if (count == 1) // Only support one ttf file dropped { UnloadSpriteFont(font); - font = LoadSpriteFontTTF(droppedFiles[0], fontSize, 0, 0); + font = LoadSpriteFontEx(droppedFiles[0], fontSize, 0, 0); ClearDroppedFiles(); } } diff --git a/docs/examples/web/textures/textures_raw_data.c b/docs/examples/web/textures/textures_raw_data.c index 245af2e3..f06c798b 100644 --- a/docs/examples/web/textures/textures_raw_data.c +++ b/docs/examples/web/textures/textures_raw_data.c @@ -111,7 +111,7 @@ void UpdateDrawFrame(void) ClearBackground(RAYWHITE); - DrawTexture(checked, screenWidth/2 - checked.width/2, screenHeight/2 - checked.height/2, WHITE); + DrawTexture(checked, screenWidth/2 - checked.width/2, screenHeight/2 - checked.height/2, Fade(WHITE, 0.5f)); DrawTexture(fudesumi, 430, -30, WHITE); DrawText("CHECKED TEXTURE ", 84, 100, 30, BROWN); diff --git a/examples/text/text_ttf_loading.c b/examples/text/text_ttf_loading.c index 4e490399..02b7f95f 100644 --- a/examples/text/text_ttf_loading.c +++ b/examples/text/text_ttf_loading.c @@ -25,7 +25,7 @@ int main() // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) // TTF SpriteFont loading with custom generation parameters - SpriteFont font = LoadSpriteFontTTF("resources/KAISG.ttf", 96, 0, 0); + SpriteFont font = LoadSpriteFontEx("resources/KAISG.ttf", 96, 0, 0); // Generate mipmap levels to use trilinear filtering // NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR @@ -82,7 +82,7 @@ int main() if (count == 1) // Only support one ttf file dropped { UnloadSpriteFont(font); - font = LoadSpriteFontTTF(droppedFiles[0], fontSize, 0, 0); + font = LoadSpriteFontEx(droppedFiles[0], fontSize, 0, 0); ClearDroppedFiles(); } } diff --git a/src/raylib.h b/src/raylib.h index 286494c7..41e1ccb7 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -867,7 +867,7 @@ RLAPI void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle dest //------------------------------------------------------------------------------------ RLAPI SpriteFont GetDefaultFont(void); // Get the default SpriteFont RLAPI SpriteFont LoadSpriteFont(const char *fileName); // Load SpriteFont from file into GPU memory (VRAM) -RLAPI SpriteFont LoadSpriteFontTTF(const char *fileName, int fontSize, int charsCount, int *fontChars); // Load SpriteFont from TTF font file with generation parameters +RLAPI SpriteFont LoadSpriteFontEx(const char *fileName, int fontSize, int charsCount, int *fontChars); // Load SpriteFont from file with extended parameters RLAPI void UnloadSpriteFont(SpriteFont spriteFont); // Unload SpriteFont from GPU memory (VRAM) RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) diff --git a/src/text.c b/src/text.c index ebc8b0ff..cba9a7d6 100644 --- a/src/text.c +++ b/src/text.c @@ -316,7 +316,7 @@ SpriteFont LoadSpriteFont(const char *fileName) //UnloadResource(rres[0]); } #if defined(SUPPORT_FILEFORMAT_TTF) - else if (IsFileExtension(fileName, ".ttf")) spriteFont = LoadSpriteFontTTF(fileName, DEFAULT_TTF_FONTSIZE, 0, NULL); + else if (IsFileExtension(fileName, ".ttf")) spriteFont = LoadSpriteFontEx(fileName, DEFAULT_TTF_FONTSIZE, 0, NULL); #endif #if defined(SUPPORT_FILEFORMAT_FNT) else if (IsFileExtension(fileName, ".fnt")) spriteFont = LoadBMFont(fileName); @@ -341,7 +341,7 @@ SpriteFont LoadSpriteFont(const char *fileName) // Load SpriteFont from TTF font file with generation parameters // NOTE: You can pass an array with desired characters, those characters should be available in the font // if array is NULL, default char set is selected 32..126 -SpriteFont LoadSpriteFontTTF(const char *fileName, int fontSize, int charsCount, int *fontChars) +SpriteFont LoadSpriteFontEx(const char *fileName, int fontSize, int charsCount, int *fontChars) { SpriteFont spriteFont = { 0 }; -- cgit v1.2.3 From cfec2b40a42c3848d3fc8bd16eb5b7443591fc5a Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sat, 22 Apr 2017 22:35:19 +0200 Subject: Organize structs vs enums --- src/raylib.h | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index 41e1ccb7..18d442d1 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -74,7 +74,6 @@ //#define PLATFORM_ANDROID // Android device //#define PLATFORM_RPI // Raspberry Pi //#define PLATFORM_WEB // HTML5 (emscripten, asm.js) -//#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) @@ -516,12 +515,28 @@ typedef struct AudioStream { unsigned int buffers[2]; // OpenAL audio buffers (double buffering) } AudioStream; +// rRES data returned when reading a resource, +// it contains all required data for user (24 byte) +typedef struct RRESData { + unsigned int type; // Resource type (4 byte) + + unsigned int param1; // Resouce parameter 1 (4 byte) + unsigned int param2; // Resouce parameter 2 (4 byte) + unsigned int param3; // Resouce parameter 3 (4 byte) + unsigned int param4; // Resouce parameter 4 (4 byte) + + void *data; // Resource data pointer (4 byte) +} RRESData; + +// RRES type (pointer to RRESData array) +typedef struct RRESData *RRES; + //---------------------------------------------------------------------------------- // Enumerators Definition //---------------------------------------------------------------------------------- // Trace log type typedef enum { - INFO = 0, + INFO = 0, WARNING, ERROR, DEBUG, @@ -615,19 +630,6 @@ typedef enum { HMD_FOVE_VR, } VrDevice; -// rRES data returned when reading a resource, -// it contains all required data for user (24 byte) -typedef struct RRESData { - unsigned int type; // Resource type (4 byte) - - unsigned int param1; // Resouce parameter 1 (4 byte) - unsigned int param2; // Resouce parameter 2 (4 byte) - unsigned int param3; // Resouce parameter 3 (4 byte) - unsigned int param4; // Resouce parameter 4 (4 byte) - - void *data; // Resource data pointer (4 byte) -} RRESData; - // RRESData type typedef enum { RRES_TYPE_RAW = 0, @@ -640,9 +642,6 @@ typedef enum { RRES_TYPE_DIRECTORY } RRESDataType; -// RRES type (pointer to RRESData array) -typedef struct RRESData *RRES; - #ifdef __cplusplus extern "C" { // Prevents name mangling of functions #endif -- cgit v1.2.3 From d593bd0081ea2dcafe3182ffc874882b5b7110b4 Mon Sep 17 00:00:00 2001 From: Ray Date: Sun, 30 Apr 2017 13:03:31 +0200 Subject: Some code tweaks --- src/raylib.h | 2 +- src/rlgl.c | 2 +- src/rlgl.h | 118 +++++++++++++++++++++++++++++---------------------------- src/textures.c | 39 ++++--------------- 4 files changed, 70 insertions(+), 91 deletions(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index 18d442d1..6f510f9f 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -351,7 +351,7 @@ typedef struct Image { int format; // Data format (TextureFormat type) } Image; -// Texture2D type, bpp always RGBA (32bit) +// Texture2D type // NOTE: Data stored in GPU memory typedef struct Texture2D { unsigned int id; // OpenGL texture id diff --git a/src/rlgl.c b/src/rlgl.c index b336571f..1dc83314 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -64,7 +64,7 @@ #include // Required for: fopen(), fclose(), fread()... [Used only on LoadText()] #include // Required for: malloc(), free(), rand() -#include // Required for: strcmp(), strlen(), strtok() +#include // Required for: strcmp(), strlen(), strtok() [Used only in extensions loading] #include // Required for: atan2() #ifndef RLGL_STANDALONE diff --git a/src/rlgl.h b/src/rlgl.h index f3fd6b22..8358efb8 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -17,7 +17,9 @@ * #define GRAPHICS_API_OPENGL_21 * #define GRAPHICS_API_OPENGL_33 * #define GRAPHICS_API_OPENGL_ES2 -* Use selected OpenGL backend +* Use selected OpenGL graphics backend, should be supported by platform +* Those preprocessor defines are only used on rlgl module, if OpenGL version is +* required by any other module, use rlGetVersion() tocheck it * * #define RLGL_STANDALONE * Use rlgl as standalone library (no raylib dependency) @@ -57,11 +59,8 @@ #ifndef RLGL_H #define RLGL_H -//#define RLGL_STANDALONE // NOTE: To use rlgl as standalone lib, just uncomment this line - #ifndef RLGL_STANDALONE - #include "raylib.h" // Required for: Model, Shader, Texture2D - #include "utils.h" // Required for: TraceLog() + #include "raylib.h" // Required for: Model, Shader, Texture2D, TraceLog() #endif #ifdef RLGL_STANDALONE @@ -70,15 +69,6 @@ #include "raymath.h" // Required for: Vector3, Matrix -// Select desired OpenGL version -// NOTE: Those preprocessor defines are only used on rlgl module, -// if OpenGL version is required by any other module, it uses rlGetVersion() - -// 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 and RLGL_OCULUS_SUPPORT -//#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 #if !defined(GRAPHICS_API_OPENGL_11) && !defined(GRAPHICS_API_OPENGL_21) && !defined(GRAPHICS_API_OPENGL_33) && !defined(GRAPHICS_API_OPENGL_ES2) #define GRAPHICS_API_OPENGL_11 @@ -165,28 +155,23 @@ typedef unsigned char byte; unsigned char b; unsigned char a; } Color; + + // Texture2D type + // NOTE: Data stored in GPU memory + typedef struct Texture2D { + unsigned int id; // OpenGL texture id + int width; // Texture base width + int height; // Texture base height + int mipmaps; // Mipmap levels, 1 by default + int format; // Data format (TextureFormat) + } Texture2D; - // Texture formats (support depends on OpenGL version) - typedef enum { - UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - UNCOMPRESSED_GRAY_ALPHA, - UNCOMPRESSED_R5G6B5, // 16 bpp - UNCOMPRESSED_R8G8B8, // 24 bpp - UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - UNCOMPRESSED_R8G8B8A8, // 32 bpp - COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - COMPRESSED_DXT3_RGBA, // 8 bpp - COMPRESSED_DXT5_RGBA, // 8 bpp - COMPRESSED_ETC1_RGB, // 4 bpp - COMPRESSED_ETC2_RGB, // 4 bpp - COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - COMPRESSED_PVRT_RGB, // 4 bpp - COMPRESSED_PVRT_RGBA, // 4 bpp - COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - COMPRESSED_ASTC_8x8_RGBA // 2 bpp - } TextureFormat; + // RenderTexture2D type, for texture rendering + typedef struct RenderTexture2D { + unsigned int id; // Render texture (fbo) id + Texture2D texture; // Color buffer attachment texture + Texture2D depth; // Depth buffer attachment texture + } RenderTexture2D; // Vertex data definning a mesh typedef struct Mesh { @@ -228,23 +213,6 @@ typedef unsigned char byte; int mapTexture2Loc; // Map texture uniform location point (default-texture-unit = 2) } Shader; - // Texture2D type - // NOTE: Data stored in GPU memory - typedef struct Texture2D { - unsigned int id; // OpenGL texture id - int width; // Texture base width - int height; // Texture base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (TextureFormat) - } Texture2D; - - // RenderTexture2D type, for texture rendering - typedef struct RenderTexture2D { - unsigned int id; // Render texture (fbo) id - Texture2D texture; // Color buffer attachment texture - Texture2D depth; // Depth buffer attachment texture - } RenderTexture2D; - // Material type typedef struct Material { Shader shader; // Standard shader (supports 3 map types: diffuse, normal, specular) @@ -267,6 +235,37 @@ typedef unsigned char byte; Vector3 up; // Camera up vector (rotation over its axis) float fovy; // Camera field-of-view apperture in Y (degrees) } Camera; + + // TraceLog message types + typedef enum { + INFO = 0, + ERROR, + WARNING, + DEBUG, + OTHER + } TraceLogType; + + // Texture formats (support depends on OpenGL version) + typedef enum { + UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) + UNCOMPRESSED_GRAY_ALPHA, + UNCOMPRESSED_R5G6B5, // 16 bpp + UNCOMPRESSED_R8G8B8, // 24 bpp + UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) + UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) + UNCOMPRESSED_R8G8B8A8, // 32 bpp + COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) + COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) + COMPRESSED_DXT3_RGBA, // 8 bpp + COMPRESSED_DXT5_RGBA, // 8 bpp + COMPRESSED_ETC1_RGB, // 4 bpp + COMPRESSED_ETC2_RGB, // 4 bpp + COMPRESSED_ETC2_EAC_RGBA, // 8 bpp + COMPRESSED_PVRT_RGB, // 4 bpp + COMPRESSED_PVRT_RGBA, // 4 bpp + COMPRESSED_ASTC_4x4_RGBA, // 8 bpp + COMPRESSED_ASTC_8x8_RGBA // 2 bpp + } TextureFormat; // Texture parameters: filter mode // NOTE 1: Filtering considers mipmaps if available in the texture @@ -281,13 +280,18 @@ typedef unsigned char byte; } TextureFilterMode; // Texture parameters: wrap mode - typedef enum { WRAP_REPEAT = 0, WRAP_CLAMP, WRAP_MIRROR } TextureWrapMode; + typedef enum { + WRAP_REPEAT = 0, + WRAP_CLAMP, + WRAP_MIRROR + } TextureWrapMode; // Color blending modes (pre-defined) - typedef enum { BLEND_ALPHA = 0, BLEND_ADDITIVE, BLEND_MULTIPLIED } BlendMode; - - // TraceLog message types - typedef enum { INFO = 0, ERROR, WARNING, DEBUG, OTHER } TraceLogType; + typedef enum { + BLEND_ALPHA = 0, + BLEND_ADDITIVE, + BLEND_MULTIPLIED + } BlendMode; // VR Head Mounted Display devices typedef enum { diff --git a/src/textures.c b/src/textures.c index 6c56d6c5..2b61c241 100644 --- a/src/textures.c +++ b/src/textures.c @@ -154,14 +154,7 @@ static Image LoadASTC(const char *fileName); // Load ASTC file // Load image from file into CPU memory (RAM) Image LoadImage(const char *fileName) { - Image image; - - // Initialize image default values - image.data = NULL; - image.width = 0; - image.height = 0; - image.mipmaps = 0; - image.format = 0; + Image image = { 0 }; if (IsFileExtension(fileName, ".rres")) { @@ -282,13 +275,7 @@ Image LoadImagePro(void *data, int width, int height, int format) // Load an image from RAW file data Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize) { - Image image; - - image.data = NULL; - image.width = 0; - image.height = 0; - image.mipmaps = 0; - image.format = 0; + Image image = { 0 }; FILE *rawFile = fopen(fileName, "rb"); @@ -342,7 +329,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int // Load texture from file into GPU memory (VRAM) Texture2D LoadTexture(const char *fileName) { - Texture2D texture; + Texture2D texture = { 0 }; Image image = LoadImage(fileName); @@ -351,11 +338,7 @@ Texture2D LoadTexture(const char *fileName) texture = LoadTextureFromImage(image); UnloadImage(image); } - else - { - TraceLog(WARNING, "Texture could not be created"); - texture.id = 0; - } + else TraceLog(WARNING, "Texture could not be created"); return texture; } @@ -364,14 +347,7 @@ Texture2D LoadTexture(const char *fileName) // NOTE: image is not unloaded, it must be done manually Texture2D LoadTextureFromImage(Image image) { - Texture2D texture; - - // Init texture to default values - texture.id = 0; - texture.width = 0; - texture.height = 0; - texture.mipmaps = 0; - texture.format = 0; + Texture2D texture = { 0 }; texture.id = rlglLoadTexture(image.data, image.width, image.height, image.format, image.mipmaps); @@ -510,9 +486,8 @@ Color *GetImageData(Image image) // NOTE: Compressed texture formats not supported Image GetTextureData(Texture2D texture) { - Image image; - image.data = NULL; - + Image image = { 0 }; + if (texture.format < 8) { image.data = rlglReadTexturePixels(texture); -- cgit v1.2.3 From e197665e1dc3ec895b14b901884fee058dc1b4e9 Mon Sep 17 00:00:00 2001 From: victorfisac Date: Tue, 2 May 2017 15:04:32 +0200 Subject: Added function to set window minimum dimensions... useful when using FLAG_WINDOW_RESIZABLE. --- src/core.c | 9 +++++++++ src/raylib.h | 1 + 2 files changed, 10 insertions(+) (limited to 'src/raylib.h') diff --git a/src/core.c b/src/core.c index 1bad2369..d7cf1f79 100644 --- a/src/core.c +++ b/src/core.c @@ -629,6 +629,15 @@ void SetWindowMonitor(int monitor) #endif } +// Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +void SetWindowMinSize(int width, int height) +{ +#if defined(PLATFORM_DESKTOP) + const GLFWvidmode *mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + glfwSetWindowSizeLimits(window, width, height, mode->width, mode->height); +#endif +} + // Get current screen width int GetScreenWidth(void) { diff --git a/src/raylib.h b/src/raylib.h index 6f510f9f..3107661f 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -667,6 +667,7 @@ RLAPI void ToggleFullscreen(void); // Fullscreen RLAPI void SetWindowIcon(Image image); // Set icon for window (only PLATFORM_DESKTOP) RLAPI void SetWindowPosition(int x, int y); // Set window position on screen (only PLATFORM_DESKTOP) RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window (fullscreen mode) +RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) RLAPI int GetScreenWidth(void); // Get current screen width RLAPI int GetScreenHeight(void); // Get current screen height -- cgit v1.2.3 From 50c887cb0a0aa80eae78c56198cbfe29280102ea Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 May 2017 12:31:47 +0200 Subject: Support HDR R32G32B32 float textures loading --- src/raylib.h | 1 + src/rlgl.c | 18 ++++++++++++------ src/rlgl.h | 1 + src/textures.c | 22 ++++++++++++++++++++++ 4 files changed, 36 insertions(+), 6 deletions(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index 3107661f..4038215e 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -553,6 +553,7 @@ typedef enum { UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) UNCOMPRESSED_R8G8B8A8, // 32 bpp + UNCOMPRESSED_R32G32B32, // 32 bit per channel (float) - HDR COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) COMPRESSED_DXT3_RGBA, // 8 bpp diff --git a/src/rlgl.c b/src/rlgl.c index edf9e60b..323a95b1 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -317,7 +317,8 @@ static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays; // Compressed textures support flags static bool texCompDXTSupported = false; // DDS texture compression support -static bool npotSupported = false; // NPOT textures full support +static bool texNPOTSupported = false; // NPOT textures full support +static bool texFloatSupported = false; // float textures support (32 bit per channel) static int blendMode = 0; // Track current blending mode @@ -1050,7 +1051,7 @@ void rlglInit(int width, int height) // NOTE: On OpenGL 3.3 VAO and NPOT are supported by default vaoSupported = true; - npotSupported = true; + texNPOTSupported = true; // We get a list of available extensions and we check for some of them (compressed textures) // NOTE: We don't need to check again supported extensions but we do (GLAD already dealt with that) @@ -1119,7 +1120,10 @@ void rlglInit(int width, int height) // Check NPOT textures support // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) npotSupported = true; + if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) texNPOTSupported = true; + + // Check texture float support + if (strcmp(extList[i], (const char *)"OES_texture_float") == 0) texFloatSupported = true; #endif // DDS texture compression support @@ -1159,7 +1163,7 @@ void rlglInit(int width, int height) if (vaoSupported) TraceLog(INFO, "[EXTENSION] VAO extension detected, VAO functions initialized successfully"); else TraceLog(WARNING, "[EXTENSION] VAO extension not found, VAO usage not supported"); - if (npotSupported) TraceLog(INFO, "[EXTENSION] NPOT textures extension detected, full NPOT textures supported"); + if (texNPOTSupported) TraceLog(INFO, "[EXTENSION] NPOT textures extension detected, full NPOT textures supported"); else TraceLog(WARNING, "[EXTENSION] NPOT textures extension not found, limited NPOT support (no-mipmaps, no-repeat)"); #endif @@ -1421,6 +1425,7 @@ unsigned int rlglLoadTexture(void *data, int width, int height, int format, int case UNCOMPRESSED_R5G5B5A1: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB5_A1, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, (unsigned short *)data); break; case UNCOMPRESSED_R4G4B4A4: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, (unsigned short *)data); break; case UNCOMPRESSED_R8G8B8A8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; + case UNCOMPRESSED_R32G32B32: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, (float *)data); break; case COMPRESSED_DXT1_RGB: if (texCompDXTSupported) LoadCompressedTexture((unsigned char *)data, width, height, mipmapCount, GL_COMPRESSED_RGB_S3TC_DXT1_EXT); break; case COMPRESSED_DXT1_RGBA: if (texCompDXTSupported) LoadCompressedTexture((unsigned char *)data, width, height, mipmapCount, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); break; case COMPRESSED_DXT3_RGBA: if (texCompDXTSupported) LoadCompressedTexture((unsigned char *)data, width, height, mipmapCount, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); break; @@ -1446,6 +1451,7 @@ unsigned int rlglLoadTexture(void *data, int width, int height, int format, int case UNCOMPRESSED_R4G4B4A4: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, (unsigned short *)data); break; case UNCOMPRESSED_R8G8B8A8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; #if defined(GRAPHICS_API_OPENGL_ES2) + case UNCOMPRESSED_R32G32B32: if (texFloatSupported) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, (float *)data); break; // Requries extension OES_texture_float case COMPRESSED_DXT1_RGB: if (texCompDXTSupported) LoadCompressedTexture((unsigned char *)data, width, height, mipmapCount, GL_COMPRESSED_RGB_S3TC_DXT1_EXT); break; case COMPRESSED_DXT1_RGBA: if (texCompDXTSupported) LoadCompressedTexture((unsigned char *)data, width, height, mipmapCount, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); break; case COMPRESSED_DXT3_RGBA: if (texCompDXTSupported) LoadCompressedTexture((unsigned char *)data, width, height, mipmapCount, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); break; // NOTE: Not supported by WebGL @@ -1466,7 +1472,7 @@ unsigned int rlglLoadTexture(void *data, int width, int height, int format, int // NOTE: glTexParameteri does NOT affect texture uploading, just the way it's used #if defined(GRAPHICS_API_OPENGL_ES2) // NOTE: OpenGL ES 2.0 with no GL_OES_texture_npot support (i.e. WebGL) has limited NPOT support, so CLAMP_TO_EDGE must be used - if (npotSupported) + if (texNPOTSupported) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis @@ -1646,7 +1652,7 @@ void rlglGenerateMipmaps(Texture2D *texture) if (((texture->width > 0) && ((texture->width & (texture->width - 1)) == 0)) && ((texture->height > 0) && ((texture->height & (texture->height - 1)) == 0))) texIsPOT = true; - if ((texIsPOT) || (npotSupported)) + if ((texIsPOT) || (texNPOTSupported)) { #if defined(GRAPHICS_API_OPENGL_11) // Compute required mipmaps diff --git a/src/rlgl.h b/src/rlgl.h index b51d1c49..6d6ad516 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -252,6 +252,7 @@ typedef unsigned char byte; UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) UNCOMPRESSED_R8G8B8A8, // 32 bpp + UNCOMPRESSED_R32G32B32, // 32 bit per channel (float) - HDR COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) COMPRESSED_DXT3_RGBA, // 8 bpp diff --git a/src/textures.c b/src/textures.c index d944bd64..3c336587 100644 --- a/src/textures.c +++ b/src/textures.c @@ -53,6 +53,7 @@ // Default configuration flags (supported features) //------------------------------------------------- #define SUPPORT_FILEFORMAT_PNG +#define SUPPORT_FILEFORMAT_HDR #define SUPPORT_IMAGE_MANIPULATION //------------------------------------------------- @@ -205,6 +206,25 @@ Image LoadImage(const char *fileName) else if (imgBpp == 3) image.format = UNCOMPRESSED_R8G8B8; else if (imgBpp == 4) image.format = UNCOMPRESSED_R8G8B8A8; } +#if defined(SUPPORT_FILEFORMAT_HDR) + else if (IsFileExtension(fileName, ".hdr")) + { + int imgBpp = 0; + + FILE *imFile = fopen(fileName, "rb"); + + // Load 32 bit per channel floats data + image.data = stbi_loadf(imFile, &image.width, &image.height, &imgBpp, 0); + + if (imgBpp == 3) image.format = UNCOMPRESSED_R32G32B32; + else + { + // TODO: Support different number of channels at 32 bit float + TraceLog(WARNING, "[%s] Image fileformat not supported (only 3 channel 32 bit floats)", fileName); + UnloadImage(image); + } + } +#endif #if defined(SUPPORT_FILEFORMAT_DDS) else if (IsFileExtension(fileName, ".dds")) image = LoadDDS(fileName); #endif @@ -298,6 +318,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int case UNCOMPRESSED_R5G5B5A1: image.data = (unsigned short *)malloc(size); break; // 16 bpp (1 bit alpha) case UNCOMPRESSED_R4G4B4A4: image.data = (unsigned short *)malloc(size); break; // 16 bpp (4 bit alpha) case UNCOMPRESSED_R8G8B8A8: image.data = (unsigned char *)malloc(size*4); size *= 4; break; // 32 bpp + case UNCOMPRESSED_R32G32B32: image.data = (float *)malloc(size*12); size *= 12; break; // 4 byte per channel (12 byte) default: TraceLog(WARNING, "Image format not suported"); break; } @@ -762,6 +783,7 @@ Image ImageCopy(Image image) case UNCOMPRESSED_R4G4B4A4: byteSize *= 2; break; // 16 bpp (2 bytes) case UNCOMPRESSED_R8G8B8: byteSize *= 3; break; // 24 bpp (3 bytes) case UNCOMPRESSED_R8G8B8A8: byteSize *= 4; break; // 32 bpp (4 bytes) + case UNCOMPRESSED_R32G32B32: byteSize *= 12; break; // 4 byte per channel (12 bytes) case COMPRESSED_DXT3_RGBA: case COMPRESSED_DXT5_RGBA: case COMPRESSED_ETC2_EAC_RGBA: -- cgit v1.2.3 From bac50fbba5940de6e536157243f3e4ec3dee9d98 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 9 May 2017 22:03:46 +0200 Subject: Review functions descriptions --- src/core.c | 261 ++++++++++++++++++++++++++++++----------------------------- src/raylib.h | 48 +++++------ 2 files changed, 155 insertions(+), 154 deletions(-) (limited to 'src/raylib.h') diff --git a/src/core.c b/src/core.c index 08f3a71d..cca8a1ac 100644 --- a/src/core.c +++ b/src/core.c @@ -380,7 +380,7 @@ static void *GamepadThread(void *arg); // Mouse reading thread // Module Functions Definition - Window and OpenGL Context Functions //---------------------------------------------------------------------------------- #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) -// Initialize Window and Graphics Context (OpenGL) +// Initialize window and OpenGL context void InitWindow(int width, int height, const char *title) { TraceLog(INFO, "Initializing raylib (v1.7.0)"); @@ -443,7 +443,7 @@ void InitWindow(int width, int height, const char *title) #endif #if defined(PLATFORM_ANDROID) -// Android activity initialization +// Initialize Android activity void InitWindow(int width, int height, void *state) { TraceLog(INFO, "Initializing raylib (v1.7.0)"); @@ -506,7 +506,7 @@ void InitWindow(int width, int height, void *state) } #endif -// Close Window and Terminate Context +// Close window and unload OpenGL context void CloseWindow(void) { #if defined(SUPPORT_DEFAULT_FONT) @@ -562,7 +562,7 @@ void CloseWindow(void) TraceLog(INFO, "Window closed successfully"); } -// Detect if KEY_ESCAPE pressed or Close icon pressed +// Check if KEY_ESCAPE pressed or Close icon pressed bool WindowShouldClose(void) { #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) @@ -577,7 +577,7 @@ bool WindowShouldClose(void) #endif } -// Detect if window has been minimized (or lost focus) +// Check if window has been minimized (or lost focus) bool IsWindowMinimized(void) { #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) @@ -587,7 +587,7 @@ bool IsWindowMinimized(void) #endif } -// Fullscreen toggle (only PLATFORM_DESKTOP) +// Toggle fullscreen mode (only PLATFORM_DESKTOP) void ToggleFullscreen(void) { #if defined(PLATFORM_DESKTOP) @@ -646,7 +646,7 @@ void SetWindowMonitor(int monitor) #endif } -// Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +// Set window minimum dimensions (FLAG_WINDOW_RESIZABLE) void SetWindowMinSize(int width, int height) { #if defined(PLATFORM_DESKTOP) @@ -681,7 +681,7 @@ void ShowCursor() cursorHidden = false; } -// Hide mouse cursor +// Hides mouse cursor void HideCursor() { #if defined(PLATFORM_DESKTOP) @@ -701,13 +701,13 @@ void HideCursor() cursorHidden = true; } -// Check if mouse cursor is hidden +// Check if cursor is not visible bool IsCursorHidden() { return cursorHidden; } -// Enable mouse cursor +// Enables cursor (unlock cursor) void EnableCursor() { #if defined(PLATFORM_DESKTOP) @@ -719,7 +719,7 @@ void EnableCursor() cursorHidden = false; } -// Disable mouse cursor +// Disables cursor (lock cursor) void DisableCursor() { #if defined(PLATFORM_DESKTOP) @@ -732,14 +732,14 @@ void DisableCursor() } #endif // !defined(PLATFORM_ANDROID) -// Sets Background Color +// Set background color (framebuffer clear color) void ClearBackground(Color color) { // Clear full framebuffer (not only render area) to color rlClearColor(color.r, color.g, color.b, color.a); } -// Setup drawing canvas to start drawing +// Setup canvas (framebuffer) to start drawing void BeginDrawing(void) { currentTime = GetTime(); // Number of elapsed seconds since InitTimer() was called @@ -754,7 +754,7 @@ void BeginDrawing(void) // NOTE: Not required with OpenGL 3.3+ } -// End canvas drawing and Swap Buffers (Double Buffering) +// End canvas drawing and swap buffers (double buffering) void EndDrawing(void) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -782,7 +782,7 @@ void EndDrawing(void) } } -// Initialize 2D mode with custom camera +// Initialize 2D mode with custom camera (2D) void Begin2dMode(Camera2D camera) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -800,7 +800,7 @@ void Begin2dMode(Camera2D camera) rlMultMatrixf(MatrixToFloat(matTransform)); } -// Ends 2D mode custom camera usage +// Ends 2D mode with custom camera void End2dMode(void) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -808,7 +808,7 @@ void End2dMode(void) rlLoadIdentity(); // Reset current matrix (MODELVIEW) } -// Initializes 3D mode for drawing (Camera setup) +// Initializes 3D mode with custom camera (3D) void Begin3dMode(Camera camera) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -897,7 +897,107 @@ void EndTextureMode(void) rlLoadIdentity(); // Reset current matrix (MODELVIEW) } -// Set target FPS for the game +// Returns a ray trace from mouse position +Ray GetMouseRay(Vector2 mousePosition, Camera camera) +{ + Ray ray; + + // Calculate normalized device coordinates + // NOTE: y value is negative + float x = (2.0f*mousePosition.x)/(float)GetScreenWidth() - 1.0f; + float y = 1.0f - (2.0f*mousePosition.y)/(float)GetScreenHeight(); + float z = 1.0f; + + // Store values in a vector + Vector3 deviceCoords = { x, y, z }; + + TraceLog(DEBUG, "Device coordinates: (%f, %f, %f)", deviceCoords.x, deviceCoords.y, deviceCoords.z); + + // Calculate projection matrix (from perspective instead of frustum) + Matrix matProj = MatrixPerspective(camera.fovy, ((double)GetScreenWidth()/(double)GetScreenHeight()), 0.01, 1000.0); + + // Calculate view matrix from camera look at + Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); + + // Do I need to transpose it? It seems that yes... + // NOTE: matrix order may be incorrect... In OpenGL to get world position from + // camera view it just needs to get inverted, but here we need to transpose it too. + // For example, if you get view matrix, transpose and inverted and you transform it + // to a vector, you will get its 3d world position coordinates (camera.position). + // If you don't transpose, final position will be wrong. + MatrixTranspose(&matView); + +//#define USE_RLGL_UNPROJECT +#if defined(USE_RLGL_UNPROJECT) // OPTION 1: Use rlglUnproject() + + Vector3 nearPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView); + Vector3 farPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView); + +#else // OPTION 2: Compute unprojection directly here + + // Calculate unproject matrix (multiply projection matrix and view matrix) and invert it + Matrix matProjView = MatrixMultiply(matProj, matView); + MatrixInvert(&matProjView); + + // Calculate far and near points + Quaternion qNear = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; + Quaternion qFar = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; + + // Multiply points by unproject matrix + QuaternionTransform(&qNear, matProjView); + QuaternionTransform(&qFar, matProjView); + + // Calculate normalized world points in vectors + Vector3 nearPoint = { qNear.x/qNear.w, qNear.y/qNear.w, qNear.z/qNear.w}; + Vector3 farPoint = { qFar.x/qFar.w, qFar.y/qFar.w, qFar.z/qFar.w}; +#endif + + // Calculate normalized direction vector + Vector3 direction = VectorSubtract(farPoint, nearPoint); + VectorNormalize(&direction); + + // Apply calculated vectors to ray + ray.position = camera.position; + ray.direction = direction; + + return ray; +} + +// Returns the screen space position from a 3d world space position +Vector2 GetWorldToScreen(Vector3 position, Camera camera) +{ + // Calculate projection matrix (from perspective instead of frustum + Matrix matProj = MatrixPerspective(camera.fovy, (double)GetScreenWidth()/(double)GetScreenHeight(), 0.01, 1000.0); + + // Calculate view matrix from camera look at (and transpose it) + Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); + MatrixTranspose(&matView); + + // Convert world position vector to quaternion + Quaternion worldPos = { position.x, position.y, position.z, 1.0f }; + + // Transform world position to view + QuaternionTransform(&worldPos, matView); + + // Transform result to projection (clip space position) + QuaternionTransform(&worldPos, matProj); + + // Calculate normalized device coordinates (inverted y) + Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w }; + + // Calculate 2d screen position vector + Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)GetScreenWidth(), (ndcPos.y + 1.0f)/2.0f*(float)GetScreenHeight() }; + + return screenPosition; +} + +// Get transform matrix for camera +Matrix GetCameraMatrix(Camera camera) +{ + return MatrixLookAt(camera.position, camera.target, camera.up); +} + +// Set target FPS (maximum) void SetTargetFPS(int fps) { if (fps < 1) targetTime = 0.0; @@ -912,7 +1012,7 @@ int GetFPS(void) return (int)(1.0f/GetFrameTime()); } -// Returns time in seconds for one frame +// Returns time in seconds for last frame drawn float GetFrameTime(void) { // NOTE: We round value to milliseconds @@ -944,7 +1044,6 @@ float *VectorToFloat(Vector3 vec) return buffer; } -// Converts Matrix to float array // NOTE: Returned vector is a transposed version of the Matrix struct, // it should be this way because, despite raymath use OpenGL column-major convention, // Matrix struct memory alignment and variables naming are not coherent @@ -1004,7 +1103,7 @@ int GetRandomValue(int min, int max) return (rand()%(abs(max-min)+1) + min); } -// Fades color by a percentadge +// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f Color Fade(Color color, float alpha) { if (alpha < 0.0f) alpha = 0.0f; @@ -1015,13 +1114,13 @@ Color Fade(Color color, float alpha) return (Color){color.r, color.g, color.b, (unsigned char)colorAlpha}; } -// Activates raylib logo at startup +// Activate raylib logo at startup (can be done with flags) void ShowLogo(void) { showLogo = true; } -// Enable some window/system configurations +// Setup window configuration flags (view FLAGS) void SetConfigFlags(char flags) { configFlags = flags; @@ -1030,6 +1129,8 @@ void SetConfigFlags(char flags) if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; } +// NOTE TraceLog() function is located in [utils.h] + // Takes a screenshot and saves it in the same folder as executable void TakeScreenshot(void) { @@ -1067,14 +1168,14 @@ bool IsFileExtension(const char *fileName, const char *ext) } #if defined(PLATFORM_DESKTOP) -// Check if a file have been dropped into window +// Check if a file has been dropped into window bool IsFileDropped(void) { if (dropFilesCount > 0) return true; else return false; } -// Retrieve dropped files into window +// Get dropped files names char **GetDroppedFiles(int *count) { *count = dropFilesCount; @@ -1095,7 +1196,7 @@ void ClearDroppedFiles(void) } #endif -// Storage save integer value (to defined position) +// Save integer value to storage file (to defined position) // NOTE: Storage positions is directly related to file memory layout (4 bytes each integer) void StorageSaveValue(int position, int value) { @@ -1135,7 +1236,7 @@ void StorageSaveValue(int position, int value) } } -// Storage load integer value (from defined position) +// Load integer value from storage file (from defined position) // NOTE: If requested position could not be found, value 0 is returned int StorageLoadValue(int position) { @@ -1174,106 +1275,6 @@ int StorageLoadValue(int position) return value; } -// Returns a ray trace from mouse position -Ray GetMouseRay(Vector2 mousePosition, Camera camera) -{ - Ray ray; - - // Calculate normalized device coordinates - // NOTE: y value is negative - float x = (2.0f*mousePosition.x)/(float)GetScreenWidth() - 1.0f; - float y = 1.0f - (2.0f*mousePosition.y)/(float)GetScreenHeight(); - float z = 1.0f; - - // Store values in a vector - Vector3 deviceCoords = { x, y, z }; - - TraceLog(DEBUG, "Device coordinates: (%f, %f, %f)", deviceCoords.x, deviceCoords.y, deviceCoords.z); - - // Calculate projection matrix (from perspective instead of frustum) - Matrix matProj = MatrixPerspective(camera.fovy, ((double)GetScreenWidth()/(double)GetScreenHeight()), 0.01, 1000.0); - - // Calculate view matrix from camera look at - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - - // Do I need to transpose it? It seems that yes... - // NOTE: matrix order may be incorrect... In OpenGL to get world position from - // camera view it just needs to get inverted, but here we need to transpose it too. - // For example, if you get view matrix, transpose and inverted and you transform it - // to a vector, you will get its 3d world position coordinates (camera.position). - // If you don't transpose, final position will be wrong. - MatrixTranspose(&matView); - -//#define USE_RLGL_UNPROJECT -#if defined(USE_RLGL_UNPROJECT) // OPTION 1: Use rlglUnproject() - - Vector3 nearPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView); - Vector3 farPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView); - -#else // OPTION 2: Compute unprojection directly here - - // Calculate unproject matrix (multiply projection matrix and view matrix) and invert it - Matrix matProjView = MatrixMultiply(matProj, matView); - MatrixInvert(&matProjView); - - // Calculate far and near points - Quaternion qNear = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; - Quaternion qFar = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; - - // Multiply points by unproject matrix - QuaternionTransform(&qNear, matProjView); - QuaternionTransform(&qFar, matProjView); - - // Calculate normalized world points in vectors - Vector3 nearPoint = { qNear.x/qNear.w, qNear.y/qNear.w, qNear.z/qNear.w}; - Vector3 farPoint = { qFar.x/qFar.w, qFar.y/qFar.w, qFar.z/qFar.w}; -#endif - - // Calculate normalized direction vector - Vector3 direction = VectorSubtract(farPoint, nearPoint); - VectorNormalize(&direction); - - // Apply calculated vectors to ray - ray.position = camera.position; - ray.direction = direction; - - return ray; -} - -// Returns the screen space position from a 3d world space position -Vector2 GetWorldToScreen(Vector3 position, Camera camera) -{ - // Calculate projection matrix (from perspective instead of frustum - Matrix matProj = MatrixPerspective(camera.fovy, (double)GetScreenWidth()/(double)GetScreenHeight(), 0.01, 1000.0); - - // Calculate view matrix from camera look at (and transpose it) - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - MatrixTranspose(&matView); - - // Convert world position vector to quaternion - Quaternion worldPos = { position.x, position.y, position.z, 1.0f }; - - // Transform world position to view - QuaternionTransform(&worldPos, matView); - - // Transform result to projection (clip space position) - QuaternionTransform(&worldPos, matProj); - - // Calculate normalized device coordinates (inverted y) - Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w }; - - // Calculate 2d screen position vector - Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)GetScreenWidth(), (ndcPos.y + 1.0f)/2.0f*(float)GetScreenHeight() }; - - return screenPosition; -} - -// Get transform matrix for camera -Matrix GetCameraMatrix(Camera camera) -{ - return MatrixLookAt(camera.position, camera.target, camera.up); -} - //---------------------------------------------------------------------------------- // Module Functions Definition - Input (Keyboard, Mouse, Gamepad) Functions //---------------------------------------------------------------------------------- @@ -1559,7 +1560,7 @@ int GetMouseWheelMove(void) #endif } -// Returns touch position X +// Returns touch position X for touch point 0 (relative to screen size) int GetTouchX(void) { #if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) @@ -1569,7 +1570,7 @@ int GetTouchX(void) #endif } -// Returns touch position Y +// Returns touch position Y for touch point 0 (relative to screen size) int GetTouchY(void) { #if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) @@ -1579,7 +1580,7 @@ int GetTouchY(void) #endif } -// Returns touch position XY +// Returns touch position XY for a touch point index (relative to screen size) // TODO: Touch position should be scaled depending on display size and render size Vector2 GetTouchPosition(int index) { diff --git a/src/raylib.h b/src/raylib.h index 4038215e..b8913c8d 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -656,15 +656,15 @@ extern "C" { // Prevents name mangling of functions // Window and Graphics Device Functions (Module: core) //------------------------------------------------------------------------------------ #if defined(PLATFORM_ANDROID) -RLAPI void InitWindow(int width, int height, void *state); // Init Android Activity and OpenGL Graphics (struct android_app) +RLAPI void InitWindow(int width, int height, void *state); // Initialize Android activity #elif defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) -RLAPI void InitWindow(int width, int height, const char *title); // Initialize Window and OpenGL Graphics +RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context #endif -RLAPI void CloseWindow(void); // Close Window and Terminate Context -RLAPI bool WindowShouldClose(void); // Detect if KEY_ESCAPE pressed or Close icon pressed -RLAPI bool IsWindowMinimized(void); // Detect if window has been minimized (or lost focus) -RLAPI void ToggleFullscreen(void); // Fullscreen toggle (only PLATFORM_DESKTOP) +RLAPI void CloseWindow(void); // Close window and unload OpenGL context +RLAPI bool WindowShouldClose(void); // Check if KEY_ESCAPE pressed or Close icon pressed +RLAPI bool IsWindowMinimized(void); // Check if window has been minimized (or lost focus) +RLAPI void ToggleFullscreen(void); // Toggle fullscreen mode (only PLATFORM_DESKTOP) RLAPI void SetWindowIcon(Image image); // Set icon for window (only PLATFORM_DESKTOP) RLAPI void SetWindowPosition(int x, int y); // Set window position on screen (only PLATFORM_DESKTOP) RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window (fullscreen mode) @@ -675,29 +675,29 @@ RLAPI int GetScreenHeight(void); // Get current #if !defined(PLATFORM_ANDROID) RLAPI void ShowCursor(void); // Shows cursor RLAPI void HideCursor(void); // Hides cursor -RLAPI bool IsCursorHidden(void); // Returns true if cursor is not visible -RLAPI void EnableCursor(void); // Enables cursor -RLAPI void DisableCursor(void); // Disables cursor +RLAPI bool IsCursorHidden(void); // Check if cursor is not visible +RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) +RLAPI void DisableCursor(void); // Disables cursor (lock cursor) #endif -RLAPI void ClearBackground(Color color); // Sets Background Color -RLAPI void BeginDrawing(void); // Setup drawing canvas to start drawing -RLAPI void EndDrawing(void); // End canvas drawing and Swap Buffers (Double Buffering) +RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) +RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing +RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) -RLAPI void Begin2dMode(Camera2D camera); // Initialize 2D mode with custom camera -RLAPI void End2dMode(void); // Ends 2D mode custom camera usage -RLAPI void Begin3dMode(Camera camera); // Initializes 3D mode for drawing (Camera setup) +RLAPI void Begin2dMode(Camera2D camera); // Initialize 2D mode with custom camera (2D) +RLAPI void End2dMode(void); // Ends 2D mode with custom camera +RLAPI void Begin3dMode(Camera camera); // Initializes 3D mode with custom camera (3D) RLAPI void End3dMode(void); // Ends 3D mode and returns to default 2D orthographic mode RLAPI void BeginTextureMode(RenderTexture2D target); // Initializes render texture for drawing RLAPI void EndTextureMode(void); // Ends drawing to render texture RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Returns a ray trace from mouse position -RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position from a 3d world space position +RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position for a 3d world space position RLAPI Matrix GetCameraMatrix(Camera camera); // Returns camera transform matrix (view matrix) RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) RLAPI int GetFPS(void); // Returns current FPS -RLAPI float GetFrameTime(void); // Returns time in seconds for one frame +RLAPI float GetFrameTime(void); // Returns time in seconds for last frame drawn RLAPI Color GetColor(int hexValue); // Returns a Color struct from hexadecimal value RLAPI int GetHexValue(Color color); // Returns hexadecimal value for a Color @@ -708,18 +708,18 @@ RLAPI float *MatrixToFloat(Matrix mat); // Converts Ma RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) RLAPI Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f -RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) -RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags +RLAPI void ShowLogo(void); // Activate raylib logo at startup (can be done with flags) +RLAPI void SetConfigFlags(char flags); // Setup window configuration flags (view FLAGS) RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension -RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window -RLAPI char **GetDroppedFiles(int *count); // Retrieve dropped files into window +RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window +RLAPI char **GetDroppedFiles(int *count); // Get dropped files names RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer -RLAPI void StorageSaveValue(int position, int value); // Storage save integer value (to defined position) -RLAPI int StorageLoadValue(int position); // Storage load integer value (from defined position) +RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) +RLAPI int StorageLoadValue(int position); // Load integer value from storage file (from defined position) //------------------------------------------------------------------------------------ // Input Handling Functions (Module: core) @@ -877,7 +877,7 @@ RLAPI void DrawTextEx(SpriteFont spriteFont, const char* text, Vector2 position, RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font RLAPI Vector2 MeasureTextEx(SpriteFont spriteFont, const char *text, float fontSize, int spacing); // Measure string size for SpriteFont -RLAPI void DrawFPS(int posX, int posY); // Shows current FPS on top-left corner +RLAPI void DrawFPS(int posX, int posY); // Shows current FPS RLAPI const char *FormatText(const char *text, ...); // Formatting of text with variables to 'embed' RLAPI const char *SubText(const char *text, int position, int length); // Get a piece of a text string -- cgit v1.2.3 From 0880be638e94bafb49aaa7465973716938306145 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 10 May 2017 00:57:48 +0200 Subject: Renamed RayHitInfo variables --- src/models.c | 10 +++++----- src/raylib.h | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src/raylib.h') diff --git a/src/models.c b/src/models.c index 2459edf1..0a692f5c 100644 --- a/src/models.c +++ b/src/models.c @@ -1541,11 +1541,11 @@ RayHitInfo GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3) result.hit = true; result.distance = t; result.hit = true; - result.hitNormal = VectorCrossProduct(edge1, edge2); - VectorNormalize(&result.hitNormal); + result.normal = VectorCrossProduct(edge1, edge2); + VectorNormalize(&result.normal); Vector3 rayDir = ray.direction; VectorScale(&rayDir, t); - result.hitPosition = VectorAdd(ray.position, rayDir); + result.position = VectorAdd(ray.position, rayDir); } return result; @@ -1568,8 +1568,8 @@ RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight) VectorScale(&rayDir, t); result.hit = true; result.distance = t; - result.hitNormal = (Vector3){ 0.0, 1.0, 0.0 }; - result.hitPosition = VectorAdd(ray.position, rayDir); + result.normal = (Vector3){ 0.0, 1.0, 0.0 }; + result.position = VectorAdd(ray.position, rayDir); } } diff --git a/src/raylib.h b/src/raylib.h index b8913c8d..e49081b5 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -479,8 +479,8 @@ typedef struct Ray { typedef struct RayHitInfo { bool hit; // Did the ray hit something? float distance; // Distance to nearest hit - Vector3 hitPosition; // Position of nearest hit - Vector3 hitNormal; // Surface normal of hit + Vector3 position; // Position of nearest hit + Vector3 normal; // Surface normal of hit } RayHitInfo; // Wave type, defines audio wave data -- cgit v1.2.3 From 35fe34ba0f4a8de97e0854a64c52eca88bab98cf Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 11 May 2017 16:24:40 +0200 Subject: Added some useful functions --- src/core.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++-------------- src/raylib.h | 7 ++++-- 2 files changed, 62 insertions(+), 19 deletions(-) (limited to 'src/raylib.h') diff --git a/src/core.c b/src/core.c index cca8a1ac..fa368747 100644 --- a/src/core.c +++ b/src/core.c @@ -108,6 +108,16 @@ #include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes +#ifdef _WIN32 + #include // Required for: _getch(), _chdir() + #define GETCWD _getcwd // NOTE: MSDN recommends not to use getcwd(), chdir() + #define CHDIR _chdir +#else + #include "unistd.h" // Required for: getch(), chdir() (POSIX) + #define GETCWD getcwd + #define CHDIR chdir +#endif + #if defined(__linux__) || defined(PLATFORM_WEB) #include // Required for: timespec, nanosleep(), select() - POSIX #elif defined(__APPLE__) @@ -259,6 +269,7 @@ static Matrix downscaleView; // Matrix to downscale view (in case static const char *windowTitle; // Window text title... static bool cursorOnScreen = false; // Tracks if cursor is inside client area static bool cursorHidden = false; // Track if cursor is hidden +static int screenshotCounter = 0; // Screenshots counter // Register mouse states static char previousMouseState[3] = { 0 }; // Registers previous mouse button state @@ -1131,25 +1142,15 @@ void SetConfigFlags(char flags) // NOTE TraceLog() function is located in [utils.h] -// Takes a screenshot and saves it in the same folder as executable -void TakeScreenshot(void) +// Takes a screenshot of current screen (saved a .png) +void TakeScreenshot(const char *fileName) { #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) - static int shotNum = 0; // Screenshot number, increments every screenshot take during program execution - char buffer[20]; // Buffer to store file name - unsigned char *imgData = rlglReadScreenPixels(renderWidth, renderHeight); - - sprintf(buffer, "screenshot%03i.png", shotNum); - - // Save image as PNG - SavePNG(buffer, imgData, renderWidth, renderHeight, 4); - + SavePNG(fileName, imgData, renderWidth, renderHeight, 4); // Save image as PNG free(imgData); - shotNum++; - - TraceLog(INFO, "[%s] Screenshot taken #03i", buffer, shotNum); + TraceLog(INFO, "Screenshot taken: %s", fileName); #endif } @@ -1167,6 +1168,37 @@ bool IsFileExtension(const char *fileName, const char *ext) return result; } +// Get directory for a given fileName (with path) +const char *GetDirectoryPath(const char *fileName) +{ + char *lastSlash = NULL; + static char filePath[256]; // MAX_DIRECTORY_PATH_SIZE = 256 + memset(filePath, 0, 256); + + lastSlash = strrchr(fileName, '\\'); + strncpy(filePath, fileName, strlen(fileName) - (strlen(lastSlash) - 1)); + filePath[strlen(fileName) - strlen(lastSlash)] = '\0'; + + return filePath; +} + +// Get current working directory +const char *GetWorkingDirectory(void) +{ + static char currentDir[256]; // MAX_DIRECTORY_PATH_SIZE = 256 + memset(currentDir, 0, 256); + + GETCWD(currentDir, 256 - 1); + + return currentDir; +} + +// Change working directory, returns true if success +bool ChangeDirectory(const char *dir) +{ + return (CHDIR(dir) == 0); +} + #if defined(PLATFORM_DESKTOP) // Check if a file has been dropped into window bool IsFileDropped(void) @@ -2363,7 +2395,11 @@ static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, i // NOTE: Before closing window, while loop must be left! } #if defined(PLATFORM_DESKTOP) - else if (key == GLFW_KEY_F12 && action == GLFW_PRESS) TakeScreenshot(); + else if (key == GLFW_KEY_F12 && action == GLFW_PRESS) + { + TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); + screenshotCounter++; + } #endif else { @@ -3003,8 +3039,12 @@ static void ProcessKeyboard(void) // Check exit key (same functionality as GLFW3 KeyCallback()) if (currentKeyState[exitKey] == 1) windowShouldClose = true; - // Check screen capture key - if (currentKeyState[301] == 1) TakeScreenshot(); // raylib key: KEY_F12 (GLFW_KEY_F12) + // Check screen capture key (raylib key: KEY_F12) + if (currentKeyState[301] == 1) + { + TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); + screenshotCounter++; + } } // Restore default keyboard input diff --git a/src/raylib.h b/src/raylib.h index e49081b5..a3276d8e 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -711,9 +711,12 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void ShowLogo(void); // Activate raylib logo at startup (can be done with flags) RLAPI void SetConfigFlags(char flags); // Setup window configuration flags (view FLAGS) RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) -RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable -RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension +RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (saved a .png) +RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension +RLAPI const char *GetDirectoryPath(const char *fileName); // Get directory for a given fileName (with path) +RLAPI const char *GetWorkingDirectory(void); // Get current working directory +RLAPI bool ChangeDirectory(const char *dir); // Change working directory, returns true if success RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window RLAPI char **GetDroppedFiles(int *count); // Get dropped files names RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer -- cgit v1.2.3 From 026f9829e567749a786cfea134e0e480cf5ba704 Mon Sep 17 00:00:00 2001 From: Ray Date: Sun, 14 May 2017 18:30:51 +0200 Subject: Review header comments --- src/raylib.h | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index a3276d8e..429c26ca 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -6,25 +6,23 @@ * * FEATURES: * - Library written in plain C code (C99) -* - Uses PascalCase/camelCase notation +* - Multiple platforms supported: Windows, Linux, Mac, Android, Raspberry Pi, HTML5. * - Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES 2.0) * - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] * - Powerful fonts module with SpriteFonts support (XNA bitmap fonts, AngelCode fonts, TTF) * - Multiple textures support, including compressed formats and mipmaps generation * - Basic 3d support for Shapes, Models, Billboards, Heightmaps and Cubicmaps -* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] +* - Powerful math module for Vector2, Vector3, Matrix and Quaternion operations: [raymath] * - Audio loading and playing with streaming support and mixing channels: [audio] * - VR stereo rendering support with configurable HMD device parameters -* - Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi, HTML5 and Oculus Rift CV1 -* - Custom color palette for fancy visuals on raywhite background * - Minimal external dependencies (GLFW3, OpenGL, OpenAL) * - Complete bindings for Lua, Go and Pascal * * NOTES: -* 32bit Colors - All defined color are always RGBA (struct Color is 4 byte) -* One custom default font could be loaded automatically when InitWindow() [core] +* 32bit Colors - Any defined Color is always RGBA (4 byte) +* One custom font is loaded by default when InitWindow() [core] +* If using OpenGL 3.3 or ES2, one default shader is loaded automatically (internally defined) [rlgl] * If using OpenGL 3.3 or ES2, several vertex buffers (VAO/VBO) are created to manage lines-triangles-quads -* If using OpenGL 3.3 or ES2, two default shaders could be loaded automatically (internally defined) * * DEPENDENCIES: * GLFW3 (www.glfw.org) for window/context management and input [core] -- cgit v1.2.3 From 5f09c71f983be066207522818f7be504a1b4592e Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 15 May 2017 11:30:09 +0200 Subject: Review comments for better organization --- src/raylib.h | 71 +++++++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 56 insertions(+), 15 deletions(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index 429c26ca..203872f0 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -653,12 +653,13 @@ extern "C" { // Prevents name mangling of functions //------------------------------------------------------------------------------------ // Window and Graphics Device Functions (Module: core) //------------------------------------------------------------------------------------ + +// Window-related functions #if defined(PLATFORM_ANDROID) RLAPI void InitWindow(int width, int height, void *state); // Initialize Android activity #elif defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context #endif - RLAPI void CloseWindow(void); // Close window and unload OpenGL context RLAPI bool WindowShouldClose(void); // Check if KEY_ESCAPE pressed or Close icon pressed RLAPI bool IsWindowMinimized(void); // Check if window has been minimized (or lost focus) @@ -671,6 +672,7 @@ RLAPI int GetScreenWidth(void); // Get current RLAPI int GetScreenHeight(void); // Get current screen height #if !defined(PLATFORM_ANDROID) +// Cursor-related functions RLAPI void ShowCursor(void); // Shows cursor RLAPI void HideCursor(void); // Hides cursor RLAPI bool IsCursorHidden(void); // Check if cursor is not visible @@ -678,10 +680,10 @@ RLAPI void EnableCursor(void); // Enables cur RLAPI void DisableCursor(void); // Disables cursor (lock cursor) #endif +// Drawing-related functions RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) - RLAPI void Begin2dMode(Camera2D camera); // Initialize 2D mode with custom camera (2D) RLAPI void End2dMode(void); // Ends 2D mode with custom camera RLAPI void Begin3dMode(Camera camera); // Initializes 3D mode with custom camera (3D) @@ -689,28 +691,33 @@ RLAPI void End3dMode(void); // Ends 3D mod RLAPI void BeginTextureMode(RenderTexture2D target); // Initializes render texture for drawing RLAPI void EndTextureMode(void); // Ends drawing to render texture +// Screen-space-related functions RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Returns a ray trace from mouse position RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position for a 3d world space position RLAPI Matrix GetCameraMatrix(Camera camera); // Returns camera transform matrix (view matrix) +// Timming-related functions RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) RLAPI int GetFPS(void); // Returns current FPS RLAPI float GetFrameTime(void); // Returns time in seconds for last frame drawn -RLAPI Color GetColor(int hexValue); // Returns a Color struct from hexadecimal value +// Color-related functions RLAPI int GetHexValue(Color color); // Returns hexadecimal value for a Color +RLAPI Color GetColor(int hexValue); // Returns a Color struct from hexadecimal value +RLAPI Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f RLAPI float *ColorToFloat(Color color); // Converts Color to float array and normalizes RLAPI float *VectorToFloat(Vector3 vec); // Converts Vector3 to float array RLAPI float *MatrixToFloat(Matrix mat); // Converts Matrix to float array -RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) -RLAPI Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f - +// Misc. functions RLAPI void ShowLogo(void); // Activate raylib logo at startup (can be done with flags) RLAPI void SetConfigFlags(char flags); // Setup window configuration flags (view FLAGS) RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (saved a .png) +RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) + +// Files management functions RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI const char *GetDirectoryPath(const char *fileName); // Get directory for a given fileName (with path) RLAPI const char *GetWorkingDirectory(void); // Get current working directory @@ -719,12 +726,15 @@ RLAPI bool IsFileDropped(void); // Check if a RLAPI char **GetDroppedFiles(int *count); // Get dropped files names RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer +// Persistent storage management RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) RLAPI int StorageLoadValue(int position); // Load integer value from storage file (from defined position) //------------------------------------------------------------------------------------ // Input Handling Functions (Module: core) //------------------------------------------------------------------------------------ + +// Input-related functions: keyboard RLAPI bool IsKeyPressed(int key); // Detect if a key has been pressed once RLAPI bool IsKeyDown(int key); // Detect if a key is being pressed RLAPI bool IsKeyReleased(int key); // Detect if a key has been released once @@ -732,6 +742,7 @@ RLAPI bool IsKeyUp(int key); // Detect if a key RLAPI int GetKeyPressed(void); // Get latest key pressed RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) +// Input-related functions: gamepads RLAPI bool IsGamepadAvailable(int gamepad); // Detect if a gamepad is available RLAPI bool IsGamepadName(int gamepad, const char *name); // Check gamepad name (if available) RLAPI const char *GetGamepadName(int gamepad); // Return gamepad internal name id @@ -743,6 +754,7 @@ RLAPI int GetGamepadButtonPressed(void); // Get the last ga RLAPI int GetGamepadAxisCount(int gamepad); // Return gamepad axis count for a gamepad RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Return axis movement value for a gamepad axis +// Input-related functions: mouse RLAPI bool IsMouseButtonPressed(int button); // Detect if a mouse button has been pressed once RLAPI bool IsMouseButtonDown(int button); // Detect if a mouse button is being pressed RLAPI bool IsMouseButtonReleased(int button); // Detect if a mouse button has been released once @@ -753,6 +765,7 @@ RLAPI Vector2 GetMousePosition(void); // Returns mouse p RLAPI void SetMousePosition(Vector2 position); // Set mouse position XY RLAPI int GetMouseWheelMove(void); // Returns mouse wheel movement Y +// Input-related functions: touch RLAPI int GetTouchX(void); // Returns touch position X for touch point 0 (relative to screen size) RLAPI int GetTouchY(void); // Returns touch position Y for touch point 0 (relative to screen size) RLAPI Vector2 GetTouchPosition(int index); // Returns touch position XY for a touch point index (relative to screen size) @@ -786,6 +799,8 @@ RLAPI void SetCameraMoveControls(int frontKey, int backKey, //------------------------------------------------------------------------------------ // Basic Shapes Drawing Functions (Module: shapes) //------------------------------------------------------------------------------------ + +// Basic shapes drawing functions RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel (Vector version) RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line @@ -808,6 +823,7 @@ RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Col RLAPI void DrawPolyEx(Vector2 *points, int numPoints, Color color); // Draw a closed polygon defined by points RLAPI void DrawPolyExLines(Vector2 *points, int numPoints, Color color); // Draw polygon lines +// Basic shapes collision detection functions RLAPI bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2); // Check collision between two rectangles RLAPI bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2); // Check collision between two circles RLAPI bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec); // Check collision between circle and rectangle @@ -819,6 +835,8 @@ RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Ve //------------------------------------------------------------------------------------ // Texture Loading and Drawing Functions (Module: textures) //------------------------------------------------------------------------------------ + +// Image/Texture2D data loading/unloading functions RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM) RLAPI Image LoadImageEx(Color *pixels, int width, int height); // Load image from Color array data (RGBA - 32bit) RLAPI Image LoadImagePro(void *data, int width, int height, int format); // Load image from raw data with parameters @@ -832,6 +850,8 @@ RLAPI void UnloadRenderTexture(RenderTexture2D target); RLAPI Color *GetImageData(Image image); // Get pixel data from image as a Color struct array RLAPI Image GetTextureData(Texture2D texture); // Get pixel data from GPU texture and return an Image RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data + +// Image manipulation functions RLAPI void ImageToPOT(Image *image, Color fillColor); // Convert image to POT (power-of-two) RLAPI void ImageFormat(Image *image, int newFormat); // Convert image data to desired format RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image @@ -853,10 +873,13 @@ RLAPI void ImageColorInvert(Image *image); RLAPI void ImageColorGrayscale(Image *image); // Modify image color: grayscale RLAPI void ImageColorContrast(Image *image, float contrast); // Modify image color: contrast (-100 to 100) RLAPI void ImageColorBrightness(Image *image, int brightness); // Modify image color: brightness (-255 to 255) + +// Texture2D configuration functions RLAPI void GenTextureMipmaps(Texture2D *texture); // Generate GPU mipmaps for a texture RLAPI void SetTextureFilter(Texture2D texture, int filterMode); // Set texture scaling filter mode RLAPI void SetTextureWrap(Texture2D texture, int wrapMode); // Set texture wrapping mode +// Texture2D drawing functions RLAPI void DrawTexture(Texture2D texture, int posX, int posY, Color tint); // Draw a Texture2D RLAPI void DrawTextureV(Texture2D texture, Vector2 position, Color tint); // Draw a Texture2D with position defined as Vector2 RLAPI void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint); // Draw a Texture2D with extended parameters @@ -867,24 +890,30 @@ RLAPI void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle dest //------------------------------------------------------------------------------------ // Font Loading and Text Drawing Functions (Module: text) //------------------------------------------------------------------------------------ + +// SpriteFont loading/unloading functions RLAPI SpriteFont GetDefaultFont(void); // Get the default SpriteFont RLAPI SpriteFont LoadSpriteFont(const char *fileName); // Load SpriteFont from file into GPU memory (VRAM) RLAPI SpriteFont LoadSpriteFontEx(const char *fileName, int fontSize, int charsCount, int *fontChars); // Load SpriteFont from file with extended parameters RLAPI void UnloadSpriteFont(SpriteFont spriteFont); // Unload SpriteFont from GPU memory (VRAM) +// Text drawing functions +RLAPI void DrawFPS(int posX, int posY); // Shows current FPS RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) RLAPI void DrawTextEx(SpriteFont spriteFont, const char* text, Vector2 position, // Draw text using SpriteFont and additional parameters float fontSize, int spacing, Color tint); + +// Text misc. functions RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font RLAPI Vector2 MeasureTextEx(SpriteFont spriteFont, const char *text, float fontSize, int spacing); // Measure string size for SpriteFont - -RLAPI void DrawFPS(int posX, int posY); // Shows current FPS RLAPI const char *FormatText(const char *text, ...); // Formatting of text with variables to 'embed' RLAPI const char *SubText(const char *text, int position, int length); // Get a piece of a text string //------------------------------------------------------------------------------------ // Basic 3d Shapes Drawing Functions (Module: models) //------------------------------------------------------------------------------------ + +// Basic geometric 3D shapes drawing functions RLAPI void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color); // Draw a line in 3D world space RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color); // Draw a circle in 3D world space RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube @@ -905,6 +934,8 @@ RLAPI void DrawGizmo(Vector3 position); //------------------------------------------------------------------------------------ // Model 3d Loading and Drawing Functions (Module: models) //------------------------------------------------------------------------------------ + +// Model loading/unloading functions RLAPI Mesh LoadMesh(const char *fileName); // Load mesh from file RLAPI Mesh LoadMeshEx(int numVertex, float *vData, float *vtData, float *vnData, Color *cData); // Load mesh from vertex data RLAPI Model LoadModel(const char *fileName); // Load model from file @@ -914,10 +945,12 @@ RLAPI Model LoadCubicmap(Image cubicmap); RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) +// Material loading/unloading functions RLAPI Material LoadMaterial(const char *fileName); // Load material from file RLAPI Material LoadDefaultMaterial(void); // Load default material (uses default models shader) RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) +// Model drawing functions RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) RLAPI void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model with extended parameters @@ -930,6 +963,7 @@ RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 center, float RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRec, Vector3 center, float size, Color tint); // Draw a billboard texture defined by sourceRec +// Collision detection functions RLAPI BoundingBox CalculateBoundingBox(Mesh mesh); // Calculate mesh bounding box limits RLAPI bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB); // Detect collision between two spheres RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Detect collision between two bounding boxes @@ -946,6 +980,8 @@ RLAPI RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight); // Shaders System Functions (Module: rlgl) // NOTE: This functions are useless when using OpenGL 1.1 //------------------------------------------------------------------------------------ + +// Shader loading/unloading functions RLAPI char *LoadText(const char *fileName); // Load chars array from text file RLAPI Shader LoadShader(char *vsFileName, char *fsFileName); // Load shader from files and bind default locations RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) @@ -953,23 +989,21 @@ RLAPI void UnloadShader(Shader shader); // Unl RLAPI Shader GetDefaultShader(void); // Get default shader RLAPI Texture2D GetDefaultTexture(void); // Get default texture +// Shader configuration functions RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location RLAPI void SetShaderValue(Shader shader, int uniformLoc, float *value, int size); // Set shader uniform value (float) RLAPI void SetShaderValuei(Shader shader, int uniformLoc, int *value, int size); // Set shader uniform value (int) RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) - RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) +// Shading begin/end functions RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied) RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) -//------------------------------------------------------------------------------------ -// VR experience Functions (Module: rlgl) -// NOTE: This functions are useless when using OpenGL 1.1 -//------------------------------------------------------------------------------------ +// VR control functions RLAPI void InitVrSimulator(int vrDevice); // Init VR simulator for selected device RLAPI void CloseVrSimulator(void); // Close VR simulator for current device RLAPI bool IsVrSimulatorReady(void); // Detect if VR device is ready @@ -981,11 +1015,14 @@ RLAPI void EndVrDrawing(void); // End VR simulator stereo r //------------------------------------------------------------------------------------ // Audio Loading and Playing Functions (Module: audio) //------------------------------------------------------------------------------------ + +// Audio device management functions RLAPI void InitAudioDevice(void); // Initialize audio device and context RLAPI void CloseAudioDevice(void); // Close the audio device and context RLAPI bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully RLAPI void SetMasterVolume(float volume); // Set master volume (listener) +// Wave/Sound loading/unloading functions RLAPI Wave LoadWave(const char *fileName); // Load wave data from file RLAPI Wave LoadWaveEx(void *data, int sampleCount, int sampleRate, int sampleSize, int channels); // Load wave data from raw array data RLAPI Sound LoadSound(const char *fileName); // Load sound from file @@ -993,6 +1030,8 @@ RLAPI Sound LoadSoundFromWave(Wave wave); // Load so RLAPI void UpdateSound(Sound sound, const void *data, int samplesCount);// Update sound buffer with new data RLAPI void UnloadWave(Wave wave); // Unload wave data RLAPI void UnloadSound(Sound sound); // Unload sound + +// Wave/Sound management functions RLAPI void PlaySound(Sound sound); // Play a sound RLAPI void PauseSound(Sound sound); // Pause a sound RLAPI void ResumeSound(Sound sound); // Resume a paused sound @@ -1004,6 +1043,8 @@ RLAPI void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); RLAPI Wave WaveCopy(Wave wave); // Copy a wave to a new wave RLAPI void WaveCrop(Wave *wave, int initSample, int finalSample); // Crop a wave to defined samples range RLAPI float *GetWaveData(Wave wave); // Get samples data from wave as a floats array + +// Music management functions RLAPI Music LoadMusicStream(const char *fileName); // Load music stream from file RLAPI void UnloadMusicStream(Music music); // Unload music stream RLAPI void PlayMusicStream(Music music); // Start music playing @@ -1018,8 +1059,8 @@ RLAPI void SetMusicLoopCount(Music music, float count); // Set mus RLAPI float GetMusicTimeLength(Music music); // Get music time length (in seconds) RLAPI float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) -RLAPI AudioStream InitAudioStream(unsigned int sampleRate, - unsigned int sampleSize, +// AudioStream management functions +RLAPI AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Init audio stream (to stream raw audio pcm data) RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data RLAPI void CloseAudioStream(AudioStream stream); // Close audio stream and free memory -- cgit v1.2.3 From 9819614276c277b7a31eb919342e0380c2814cb0 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 17 May 2017 00:33:40 +0200 Subject: Comments tweaks --- src/raylib.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'src/raylib.h') diff --git a/src/raylib.h b/src/raylib.h index 203872f0..0b1a6b19 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -473,7 +473,7 @@ typedef struct Ray { Vector3 direction; // Ray direction } Ray; -// Information returned from a raycast +// Raycast hit information typedef struct RayHitInfo { bool hit; // Did the ray hit something? float distance; // Distance to nearest hit @@ -958,7 +958,6 @@ RLAPI void DrawModelWires(Model model, Vector3 position, float scale, Color tint RLAPI void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model wires (with texture if set) with extended parameters RLAPI void DrawBoundingBox(BoundingBox box, Color color); // Draw bounding box (wires) - RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 center, float size, Color tint); // Draw a billboard texture RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRec, Vector3 center, float size, Color tint); // Draw a billboard texture defined by sourceRec @@ -1006,9 +1005,9 @@ RLAPI void EndBlendMode(void); // End // VR control functions RLAPI void InitVrSimulator(int vrDevice); // Init VR simulator for selected device RLAPI void CloseVrSimulator(void); // Close VR simulator for current device -RLAPI bool IsVrSimulatorReady(void); // Detect if VR device is ready +RLAPI bool IsVrSimulatorReady(void); // Detect if VR simulator is ready RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -RLAPI void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) +RLAPI void ToggleVrMode(void); // Enable/Disable VR experience RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering RLAPI void EndVrDrawing(void); // End VR simulator stereo rendering -- cgit v1.2.3