From 6b8af9cf83851c075c6c9514b1deaa931c2b19a4 Mon Sep 17 00:00:00 2001 From: Thomas Guillermo Albers Raviola Date: Fri, 16 Jan 2026 23:02:32 +0100 Subject: Initial commit --- 08-august/src/util/util.c | 87 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 08-august/src/util/util.c (limited to '08-august/src/util/util.c') diff --git a/08-august/src/util/util.c b/08-august/src/util/util.c new file mode 100644 index 0000000..ad0f1ce --- /dev/null +++ b/08-august/src/util/util.c @@ -0,0 +1,87 @@ +#include "util.h" + +#include + +#include +#include +#include +#include + +void Util_FatalError( const char *error, ... ) +{ + fprintf(stderr, "Fatal Error:\n"); + + va_list args; + va_start(args, error); + vfprintf(stderr, error, args); + va_end(args); + + SDL_Quit(); + exit(1); +} + +char *Util_LoadFile( const char *path ) +{ + FILE* file = fopen( path, "r" ); + + if(file == NULL) + { + Util_FatalError("File %s could not be found!\n", path); + } + + fseek( file, 0, SEEK_END ); + size_t sizeOfFile = ftell( file ); + fseek( file, 0, SEEK_SET ); + char* file_data = (char *) malloc( sizeof(char) * sizeOfFile + 1 ); + fread( file_data, sizeof(char), sizeOfFile, file ); + file_data[sizeOfFile] = '\0'; + fclose(file); + return file_data; +} + +float Util_RandomF(float min, float max) +{ + return ( min + (float)rand() ) / ( (float)RAND_MAX / (max-min) ); +} + +int Util_RandomI(int min, int max) +{ + return ( rand() % (max-min) ) + min; +} + +vec3_t +Util_GetMouseRay(int screenWidth, int screenHeigth, mat4_t *viewMatrix, mat4_t *projectionMatrix, + int mouseX, int mouseY) +{ + vec4_t eyeCoords; + vec3_t mouseRay; + /* Normalized device coords NOTE: -y becouse for SDL y = 0 is the top of the screen */ + GLfloat normalX = ( 2.0f * (GLfloat)mouseX ) / (GLfloat) screenWidth - 1.0f; + GLfloat normalY = 1.0f - (2.0f * (GLfloat)mouseY) / (GLfloat) screenHeigth; + + /* clipCoords include 4th component */ + vec4_t clipCoords = { normalX, normalY, -1.0f, 1.0f }; + + /* Remove perpective */ + { + mat4_t invertedProjection = mat4_inverse(projectionMatrix); + eyeCoords = mat4_mul_vec4(&invertedProjection, &clipCoords); + eyeCoords.z = -1.0f; + eyeCoords.w = 0.0f; + } + + /* Remove view matrix*/ + { + mat4_t invertedViewMatrix = mat4_inverse(viewMatrix); + vec4_t temp = mat4_mul_vec4(&invertedViewMatrix, &eyeCoords); + + mouseRay.x = temp.x; + mouseRay.y = temp.y; + mouseRay.z = temp.z; + + mouseRay = vec3_normalize(&mouseRay); + } + + /* Return the ray in world coordinates */ + return mouseRay; +} -- cgit v1.2.3