raylib 1.2

This is a huge update. Check CHANGELOG for details
This commit is contained in:
raysan5 2014-09-16 22:51:31 +02:00
parent 01651af08a
commit fc6081fe70
21 changed files with 2742 additions and 758 deletions

View file

@ -1,14 +1,14 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib.audio
*
* Basic functions to manage Audio: InitAudioDevice, LoadAudioFiles, PlayAudioFiles
*
* Uses external lib:
* OpenAL - Audio device management lib
* stb_vorbis - Ogg audio files loading
* OpenAL Soft - Audio device management lib (http://kcat.strangesoft.net/openal.html)
* stb_vorbis - Ogg audio files loading (http://www.nothings.org/stb_vorbis/)
*
* Copyright (c) 2013 Ramon Santamaria (Ray San - raysan@raysanweb.com)
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
* 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.
@ -29,22 +29,25 @@
#include "raylib.h"
#include <AL/al.h> // OpenAL basic header
#include <AL/alc.h> // OpenAL context header (like OpenGL, OpenAL requires a context to work)
#include "AL/al.h" // OpenAL basic header
#include "AL/alc.h" // OpenAL context header (like OpenGL, OpenAL requires a context to work)
#include <stdlib.h> // Declares malloc() and free() for memory management
#include <string.h> // Required for strcmp()
#include <stdio.h> // Used for .WAV loading
#include <stdlib.h> // Declares malloc() and free() for memory management
#include <string.h> // Required for strcmp()
#include <stdio.h> // Used for .WAV loading
#include "utils.h" // rRES data decompression utility function
#include "utils.h" // rRES data decompression utility function
// NOTE: Includes Android fopen function map
#include "stb_vorbis.h" // OGG loading functions
#include "stb_vorbis.h" // OGG loading functions
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
#define MUSIC_STREAM_BUFFERS 2
#define MUSIC_BUFFER_SIZE 4096*8 //4096*32
#define MUSIC_BUFFER_SIZE 4096*2 // PCM data buffer (short) - 16Kb
// NOTE: Reduced to avoid frame-stalls on RPI
//#define MUSIC_BUFFER_SIZE 4096*8 // PCM data buffer (short) - 64Kb
//----------------------------------------------------------------------------------
// Types and Structures Definition
@ -85,9 +88,9 @@ static Music currentMusic; // Current music loaded
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
static Wave LoadWAV(const char *fileName);
static Wave LoadOGG(char *fileName);
static void UnloadWave(Wave wave);
static Wave LoadWAV(const char *fileName); // Load WAV file
static Wave LoadOGG(char *fileName); // Load OGG file
static void UnloadWave(Wave wave); // Unload wave data
static bool BufferMusicStream(ALuint buffer); // Fill music buffers with data
static void EmptyMusicStream(void); // Empty music buffers
@ -116,7 +119,7 @@ void InitAudioDevice(void)
TraceLog(ERROR, "Could not setup audio context");
}
TraceLog(INFO, "Audio device and context initialized successfully: %s\n", alcGetString(device, ALC_DEVICE_SPECIFIER));
TraceLog(INFO, "Audio device and context initialized successfully: %s", alcGetString(device, ALC_DEVICE_SPECIFIER));
// Listener definition (just for 2D)
alListener3f(AL_POSITION, 0, 0, 0);
@ -151,6 +154,13 @@ Sound LoadSound(char *fileName)
Sound sound;
Wave wave;
// Init some default values for wave...
wave.data = NULL;
wave.dataSize = 0;
wave.sampleRate = 0;
wave.bitsPerSample = 0;
wave.channels = 0;
// NOTE: The entire file is loaded to memory to play it all at once (no-streaming)
// Audio file loading
@ -297,7 +307,6 @@ Sound LoadSoundFromRES(const char *rresName, int resId)
else if (wave.bitsPerSample == 16) format = AL_FORMAT_STEREO16;
}
// Create an audio source
ALuint source;
alGenSources(1, &source); // Generate pointer to audio source
@ -506,8 +515,23 @@ void StopMusicStream(void)
// Pause music playing
void PauseMusicStream(void)
{
// TODO: Record music is paused or check if music available!
alSourcePause(currentMusic.source);
// Pause music stream if music available!
if (musicEnabled)
{
TraceLog(INFO, "Pausing music stream");
alSourcePause(currentMusic.source);
}
}
// Resume music playing
void ResumeMusicStream(void)
{
// Resume music playing... if music available!
if (musicEnabled)
{
TraceLog(INFO, "Resume music stream");
alSourcePlay(currentMusic.source);
}
}
// Check if music is playing
@ -570,7 +594,7 @@ static bool BufferMusicStream(ALuint buffer)
else break;
}
TraceLog(DEBUG, "Streaming music data to buffer. Bytes streamed: %i", size);
//TraceLog(DEBUG, "Streaming music data to buffer. Bytes streamed: %i", size);
}
if (size > 0)
@ -754,6 +778,7 @@ static Wave LoadWAV(const char *fileName)
}
// Load OGG file into Wave structure
// NOTE: Using stb_vorbis library
static Wave LoadOGG(char *fileName)
{
Wave wave;

1448
src/core.c

File diff suppressed because it is too large Load diff

130
src/makefile Normal file
View file

@ -0,0 +1,130 @@
#**************************************************************************************************
#
# raylib for Raspberry Pi and Windows desktop
#
# makefile for library compilation (raylib.a)
#
# Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
#
# 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.
#
# Permission is granted to anyone to use this software for any purpose, including commercial
# applications, and to alter it and redistribute it freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not claim that you
# wrote the original software. If you use this software in a product, an acknowledgment
# in the product documentation would be appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be misrepresented
# as being the original software.
#
# 3. This notice may not be removed or altered from any source distribution.
#
#**************************************************************************************************
# define raylib platform (by default, compile for RPI)
# Other possible platform: PLATFORM_DESKTOP
PLATFORM ?= PLATFORM_RPI
# define raylib graphics api depending on selected platform
ifeq ($(PLATFORM),PLATFORM_RPI)
# define raylib graphics api to use (on RPI, OpenGL ES 2.0 must be used)
GRAPHICS = GRAPHICS_API_OPENGL_ES2
else
# define raylib graphics api to use (on Windows desktop, OpenGL 1.1 by default)
GRAPHICS = GRAPHICS_API_OPENGL_11
#GRAPHICS = GRAPHICS_API_OPENGL_33 # Uncomment to use OpenGL 3.3
endif
# NOTE: makefiles targets require tab indentation
# define compiler: gcc for C program, define as g++ for C++
CC = gcc
# define compiler flags:
# -O2 defines optimization level
# -Wall turns on most, but not all, compiler warnings
# -std=c99 use standard C from 1999 revision
ifeq ($(PLATFORM),PLATFORM_RPI)
CFLAGS = -O2 -Wall -std=gnu99 -fgnu89-inline
else
CFLAGS = -O2 -Wall -std=c99
endif
#CFLAGSEXTRA = -Wextra -Wmissing-prototypes -Wstrict-prototypes
# define any directories containing required header files
ifeq ($(PLATFORM),PLATFORM_RPI)
INCLUDES = -I. -I/opt/vc/include -I/opt/vc/include/interface/vcos/pthreads
else
INCLUDES = -I.
endif
# define all object files required
OBJS = core.o rlgl.o raymath.o shapes.o text.o textures.o models.o audio.o utils.o stb_image.o stb_vorbis.o
# typing 'make' will invoke the first target entry in the file,
# in this case, the 'default' target entry is raylib
default: raylib
# compile raylib library
raylib: $(OBJS)
ar rcs libraylib.a $(OBJS)
# compile core module
core.o: core.c
$(CC) -c core.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile rlgl module
rlgl.o: rlgl.c
$(CC) -c rlgl.c $(CFLAGS) $(INCLUDES) -D$(GRAPHICS)
# compile raymath module
raymath.o: raymath.c
$(CC) -c raymath.c $(CFLAGS) $(INCLUDES)
# compile shapes module
shapes.o: shapes.c
$(CC) -c shapes.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile textures module
textures.o: textures.c
$(CC) -c textures.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile text module
text.o: text.c
$(CC) -c text.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile models module
models.o: models.c
$(CC) -c models.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile audio module
audio.o: audio.c
$(CC) -c audio.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile utils module
utils.o: utils.c
$(CC) -c utils.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile stb_image library
stb_image.o: stb_image.c
$(CC) -c stb_image.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# compile stb_vorbis library
stb_vorbis.o: stb_vorbis.c
$(CC) -c stb_vorbis.c $(CFLAGS) $(INCLUDES) -D$(PLATFORM)
# clean everything
clean:
ifeq ($(PLATFORM),PLATFORM_RPI)
rm -f *.o libraylib.a
else
del *.o libraylib.a
endif
@echo Cleaning done
# instead of defining every module one by one, we can define a pattern
# this pattern below will automatically compile every module defined on $(OBJS)
#%.o : %.c
# $(CC) -c $< $(CFLAGS) $(INCLUDES) -D$(PLATFORM) -D$(GRAPHICS)

View file

@ -1,10 +1,10 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib.models
*
* Basic functions to draw 3d shapes and load/draw 3d models (.OBJ)
*
* Copyright (c) 2013 Ramon Santamaria (Ray San - raysan@raysanweb.com)
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
* 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.
@ -25,13 +25,17 @@
#include "raylib.h"
#include <stdio.h> // Standard input/output functions, used to read model files data
#include <stdlib.h> // Declares malloc() and free() for memory management
#include <string.h> // Required for strcmp()
#include <math.h> // Used for sin, cos, tan
#if defined(PLATFORM_ANDROID)
#include "utils.h" // Android fopen function map
#endif
#include "raymath.h" // Required for data type Matrix and Matrix functions
#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
#include <stdio.h> // Standard input/output functions, used to read model files data
#include <stdlib.h> // Declares malloc() and free() for memory management
#include <string.h> // Required for strcmp()
#include <math.h> // Used for sin, cos, tan
#include "raymath.h" // Required for data type Matrix and Matrix functions
#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
//----------------------------------------------------------------------------------
// Defines and Macros
@ -442,9 +446,11 @@ void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, fl
}
// Draw a plane
// TODO: Test this function
void DrawPlane(Vector3 centerPos, Vector2 size, Vector3 rotation, Color color)
{
// NOTE: QUADS usage require defining a texture
rlEnableTexture(1); // Default white texture
// NOTE: Plane is always created on XZ ground and then rotated
rlPushMatrix();
rlTranslatef(centerPos.x, centerPos.y, centerPos.z);
@ -459,11 +465,13 @@ void DrawPlane(Vector3 centerPos, Vector2 size, Vector3 rotation, Color color)
rlColor4ub(color.r, color.g, color.b, color.a);
rlNormal3f(0.0f, 1.0f, 0.0f);
rlTexCoord2f(0.0f, 0.0f); rlVertex3f(-0.5f, 0.0f, -0.5f);
rlTexCoord2f(1.0f, 0.0f); rlVertex3f(0.5f, 0.0f, -0.5f);
rlTexCoord2f(1.0f, 0.0f); rlVertex3f(-0.5f, 0.0f, 0.5f);
rlTexCoord2f(1.0f, 1.0f); rlVertex3f(0.5f, 0.0f, 0.5f);
rlTexCoord2f(0.0f, 1.0f); rlVertex3f(-0.5f, 0.0f, 0.5f);
rlTexCoord2f(0.0f, 1.0f); rlVertex3f(0.5f, 0.0f, -0.5f);
rlEnd();
rlPopMatrix();
rlDisableTexture();
}
// Draw a plane with divisions
@ -646,20 +654,15 @@ Model LoadModel(const char *fileName)
if (strcmp(GetExtension(fileName),"obj") == 0) vData = LoadOBJ(fileName);
else TraceLog(WARNING, "[%s] Model extension not recognized, it can't be loaded", fileName);
Model model;
// NOTE: At this point we have all vertex, texcoord, normal data for the model in vData struct
model.mesh = vData; // Model mesh is vertex data
model.textureId = 0;
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
model.vaoId = rlglLoadModel(vData); // Use loaded data to generate VAO
model.textureId = 1; // Default whiteTexture
Model model = rlglLoadModel(vData); // Upload vertex data to GPU
// Now that vertex data is uploaded to GPU, we can free arrays
// NOTE: Despite vertex data is useless on OpenGL 3.3 or ES2, we will keep it...
//free(vData.vertices);
//free(vData.texcoords);
//free(vData.normals);
#endif
return model;
}
@ -764,25 +767,19 @@ Model LoadHeightmap(Image heightmap, float maxHeight)
}
}
// NOTE: At this point we have all vertex, texcoord, normal data for the model in vData struct
// Fill color data
for (int i = 0; i < (4*vData.vertexCount); i++) vData.colors[i] = 255;
Model model;
model.mesh = vData; // Model mesh is vertex data
model.textureId = 0;
// NOTE: At this point we have all vertex, texcoord, normal data for the model in vData struct
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
model.vaoId = rlglLoadModel(vData); // Use loaded data to generate VAO
model.textureId = 1; // Default whiteTexture
Model model = rlglLoadModel(vData);
// Now that vertex data is uploaded to GPU, we can free arrays
// NOTE: Despite vertex data is useless on OpenGL 3.3 or ES2, we will keep it...
//free(vData.vertices);
//free(vData.texcoords);
//free(vData.normals);
#endif
return model;
}
@ -1092,20 +1089,13 @@ Model LoadCubesmap(Image cubesmap)
// NOTE: At this point we have all vertex, texcoord, normal data for the model in vData struct
Model model;
model.mesh = vData; // Model mesh is vertex data
model.textureId = 0;
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
model.vaoId = rlglLoadModel(vData); // Use loaded data to generate VAO
model.textureId = 1; // Default whiteTexture
Model model = rlglLoadModel(vData);
// Now that vertex data is uploaded to GPU, we can free arrays
// NOTE: Despite vertex data is useless on OpenGL 3.3 or ES2, we will keep it...
//free(vData.vertices);
//free(vData.texcoords);
//free(vData.normals);
#endif
return model;
}
@ -1117,9 +1107,11 @@ void UnloadModel(Model model)
free(model.mesh.texcoords);
free(model.mesh.normals);
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
rlDeleteBuffers(model.vboId[0]);
rlDeleteBuffers(model.vboId[1]);
rlDeleteBuffers(model.vboId[2]);
rlDeleteVertexArrays(model.vaoId);
#endif
}
void SetModelTexture(Model *model, Texture2D texture)
@ -1268,7 +1260,7 @@ static VertexData LoadOBJ(const char *fileName)
int numTexCoords = 0;
int numTriangles = 0;
FILE* objFile;
FILE *objFile;
objFile = fopen(fileName, "rt");
@ -1326,9 +1318,9 @@ static VertexData LoadOBJ(const char *fileName)
// Once we know the number of vertices to store, we create required arrays
Vector3 *midVertices = (Vector3 *)malloc(numVertex*sizeof(Vector3));
Vector3 *midNormals;
Vector3 *midNormals = NULL;
if (numNormals > 0) midNormals = (Vector3 *)malloc(numNormals*sizeof(Vector3));
Vector2 *midTexCoords;
Vector2 *midTexCoords = NULL;
if (numTexCoords > 0) midTexCoords = (Vector2 *)malloc(numTexCoords*sizeof(Vector2));
int countVertex = 0;

View file

@ -1,6 +1,6 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib 1.1 (www.raylib.com)
* raylib 1.2 (www.raylib.com)
*
* A simple and easy-to-use library to learn videogames programming
*
@ -31,7 +31,7 @@
* One custom default font is loaded automatically when InitWindow()
* If using OpenGL 3.3+ or ES2, one default shader is loaded automatically (internally defined)
*
* -- LICENSE (raylib v1.1, April 2014) --
* -- LICENSE (raylib v1.2, September 2014) --
*
* 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:
@ -58,6 +58,15 @@
#ifndef RAYLIB_H
#define RAYLIB_H
// Choose your platform here or just define it at compile time: -DPLATFORM_DESKTOP
//#define PLATFORM_DESKTOP // Windows, Linux or OSX
//#define PLATFORM_ANDROID // Android device
//#define PLATFORM_RPI // Raspberry Pi
#if defined(PLATFORM_ANDROID)
#include <android_native_app_glue.h> // Defines android_app struct
#endif
//----------------------------------------------------------------------------------
// Some basic Defines
//----------------------------------------------------------------------------------
@ -65,10 +74,10 @@
#define PI 3.14159265358979323846
#endif
#define DEG2RAD (PI / 180.0)
#define RAD2DEG (180.0 / PI)
#define DEG2RAD (PI / 180.0f)
#define RAD2DEG (180.0f / PI)
// Keyboard Function Keys
// Keyboard Function Keys
#define KEY_SPACE 32
#define KEY_ESCAPE 256
#define KEY_ENTER 257
@ -107,16 +116,16 @@
// Gamepad Buttons
// NOTE: Adjusted for a PS3 USB Controller
#define GAMEPAD_BUTTON_A 2
#define GAMEPAD_BUTTON_B 1
#define GAMEPAD_BUTTON_X 3
#define GAMEPAD_BUTTON_Y 4
#define GAMEPAD_BUTTON_R1 7
#define GAMEPAD_BUTTON_R2 5
#define GAMEPAD_BUTTON_L1 6
#define GAMEPAD_BUTTON_L2 8
#define GAMEPAD_BUTTON_SELECT 9
#define GAMEPAD_BUTTON_START 10
#define GAMEPAD_BUTTON_A 2
#define GAMEPAD_BUTTON_B 1
#define GAMEPAD_BUTTON_X 3
#define GAMEPAD_BUTTON_Y 4
#define GAMEPAD_BUTTON_R1 7
#define GAMEPAD_BUTTON_R2 5
#define GAMEPAD_BUTTON_L1 6
#define GAMEPAD_BUTTON_L2 8
#define GAMEPAD_BUTTON_SELECT 9
#define GAMEPAD_BUTTON_START 10
// TODO: Review Xbox360 USB Controller Buttons
@ -234,6 +243,7 @@ typedef struct VertexData {
typedef struct Model {
VertexData mesh;
unsigned int vaoId;
unsigned int vboId[4];
unsigned int textureId;
//Matrix transform;
} Model;
@ -256,14 +266,21 @@ extern "C" { // Prevents name mangling of functions
//------------------------------------------------------------------------------------
// Window and Graphics Device Functions (Module: core)
//------------------------------------------------------------------------------------
void InitWindow(int width, int height, const char *title); // Initialize Window and Graphics Context (OpenGL)
void InitWindowEx(int width, int height, const char* title, // Initialize Window and Graphics Context (OpenGL),...
bool resizable, const char *cursorImage); // ...define if windows-resizable and custom cursor
#if defined(PLATFORM_ANDROID)
void InitWindow(int width, int height, struct android_app *state); // Init Android activity
#elif defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI)
void InitWindow(int width, int height, const char *title); // Initialize Window and OpenGL Graphics
#endif
void CloseWindow(void); // Close Window and Terminate Context
bool WindowShouldClose(void); // Detect if KEY_ESCAPE pressed or Close icon pressed
void ToggleFullscreen(void); // Fullscreen toggle (by default F11)
void ToggleFullscreen(void); // Fullscreen toggle (only PLATFORM_DESKTOP)
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI)
void SetCustomCursor(const char *cursorImage); // Set a custom cursor icon/image
void SetExitKey(int key); // Set a custom key to exit program (default is ESC)
#endif
int GetScreenWidth(void); // Get current screen width
int GetScreenHeight(void); // Get current screen height
void ClearBackground(Color color); // Sets Background Color
void BeginDrawing(void); // Setup drawing canvas to start drawing
@ -280,13 +297,14 @@ Color GetColor(int hexValue); // Returns a Color s
int GetHexValue(Color color); // Returns hexadecimal value for a Color
int GetRandomValue(int min, int max); // Returns a random value between min and max (both included)
Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0 to 1.0
Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f
void ShowLogo(void); // Activates raylib logo at startup
//------------------------------------------------------------------------------------
// Input Handling Functions (Module: core)
//------------------------------------------------------------------------------------
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI)
bool IsKeyPressed(int key); // Detect if a key has been pressed once
bool IsKeyDown(int key); // Detect if a key is being pressed
bool IsKeyReleased(int key); // Detect if a key has been released once
@ -307,6 +325,13 @@ bool IsGamepadButtonPressed(int gamepad, int button); // Detect if a gamepad b
bool IsGamepadButtonDown(int gamepad, int button); // Detect if a gamepad button is being pressed
bool IsGamepadButtonReleased(int gamepad, int button); // Detect if a gamepad button has been released once
bool IsGamepadButtonUp(int gamepad, int button); // Detect if a gamepad button is NOT being pressed
#endif
#if defined(PLATFORM_ANDROID)
int GetTouchX(void); // Returns touch position X
int GetTouchY(void); // Returns touch position Y
Vector2 GetTouchPosition(void); // Returns touch position XY
#endif
//------------------------------------------------------------------------------------
// Basic Shapes Drawing Functions (Module: shapes)
@ -427,6 +452,7 @@ void SetSoundPitch(Sound sound, float pitch); // Set pitch for
void PlayMusicStream(char *fileName); // Start music playing (open stream)
void StopMusicStream(void); // Stop music playing (close stream)
void PauseMusicStream(void); // Pause music playing
void ResumeMusicStream(void); // Resume playing paused music
bool MusicIsPlaying(void); // Check if music is playing
void SetMusicVolume(float volume); // Set volume for music (1.0 is max level)
float GetMusicTimeLength(void); // Get current music time length (in seconds)

View file

@ -1,4 +1,4 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raymath
*
@ -85,17 +85,17 @@ Vector3 VectorPerpendicular(Vector3 v)
Vector3 result;
float min = fabs(v.x);
Vector3 cardinalAxis = {1.0, 0.0, 0.0};
Vector3 cardinalAxis = {1.0f, 0.0f, 0.0f};
if (fabs(v.y) < min)
{
min = fabs(v.y);
cardinalAxis = (Vector3){0.0, 1.0, 0.0};
cardinalAxis = (Vector3){0.0f, 1.0f, 0.0f};
}
if(fabs(v.z) < min)
{
cardinalAxis = (Vector3){0.0, 0.0, 1.0};
cardinalAxis = (Vector3){0.0f, 0.0f, 1.0f};
}
result = VectorCrossProduct(v, cardinalAxis);
@ -216,7 +216,7 @@ void VectorTransform(Vector3 *v, Matrix mat)
// Return a Vector3 init to zero
Vector3 VectorZero(void)
{
Vector3 zero = { 0.0, 0.0, 0.0 };
Vector3 zero = { 0.0f, 0.0f, 0.0f };
return zero;
}
@ -377,7 +377,7 @@ void MatrixNormalize(Matrix *mat)
}
// Returns identity matrix
Matrix MatrixIdentity()
Matrix MatrixIdentity(void)
{
Matrix result = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
@ -494,6 +494,7 @@ Matrix MatrixRotate(float angleX, float angleY, float angleZ)
// Create rotation matrix from axis and angle
// TODO: Test this function
// NOTE: NO prototype defined!
Matrix MatrixFromAxisAngle(Vector3 axis, float angle)
{
Matrix result;
@ -549,6 +550,7 @@ Matrix MatrixFromAxisAngle(Vector3 axis, float angle)
// Create rotation matrix from axis and angle (version 2)
// TODO: Test this function
// NOTE: NO prototype defined!
Matrix MatrixFromAxisAngle2(Vector3 axis, float angle)
{
Matrix result;
@ -725,21 +727,24 @@ Matrix MatrixFrustum(double left, double right, double bottom, double top, doubl
float tb = (top - bottom);
float fn = (far - near);
result.m0 = (near*2) / rl;
result.m0 = (near*2.0f) / rl;
result.m1 = 0;
result.m2 = 0;
result.m3 = 0;
result.m4 = 0;
result.m5 = (near*2) / tb;
result.m5 = (near*2.0f) / tb;
result.m6 = 0;
result.m7 = 0;
result.m8 = (right + left) / rl;
result.m9 = (top + bottom) / tb;
result.m10 = -(far + near) / fn;
result.m11 = -1;
result.m11 = -1.0f;
result.m12 = 0;
result.m13 = 0;
result.m14 = -(far*near*2) / fn;
result.m14 = -(far*near*2.0f) / fn;
result.m15 = 0;
return result;
@ -748,7 +753,7 @@ Matrix MatrixFrustum(double left, double right, double bottom, double top, doubl
// Returns perspective projection matrix
Matrix MatrixPerspective(double fovy, double aspect, double near, double far)
{
double top = near*tan(fovy*PI / 360.0);
double top = near*tanf(fovy*PI / 360.0f);
double right = top*aspect;
return MatrixFrustum(-right, right, -top, top, near, far);
@ -876,18 +881,18 @@ Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount)
float cosHalfTheta = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w;
if (abs(cosHalfTheta) >= 1.0) result = q1;
if (abs(cosHalfTheta) >= 1.0f) result = q1;
else
{
float halfTheta = acos(cosHalfTheta);
float sinHalfTheta = sqrt(1.0 - cosHalfTheta*cosHalfTheta);
float sinHalfTheta = sqrt(1.0f - cosHalfTheta*cosHalfTheta);
if (abs(sinHalfTheta) < 0.001)
if (abs(sinHalfTheta) < 0.001f)
{
result.x = (q1.x*0.5 + q2.x*0.5);
result.y = (q1.y*0.5 + q2.y*0.5);
result.z = (q1.z*0.5 + q2.z*0.5);
result.w = (q1.w*0.5 + q2.w*0.5);
result.x = (q1.x*0.5f + q2.x*0.5f);
result.y = (q1.y*0.5f + q2.y*0.5f);
result.z = (q1.z*0.5f + q2.z*0.5f);
result.w = (q1.w*0.5f + q2.w*0.5f);
}
else
{

View file

@ -1,4 +1,4 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raymath
*
@ -39,8 +39,8 @@
#define PI 3.14159265358979323846
#endif
#define DEG2RAD (PI / 180.0)
#define RAD2DEG (180.0 / PI)
#define DEG2RAD (PI / 180.0f)
#define RAD2DEG (180.0f / PI)
//----------------------------------------------------------------------------------
// Types and Structures Definition
@ -101,9 +101,9 @@ float *GetMatrixVector(Matrix mat); // Returns an OpenGL-rea
float MatrixDeterminant(Matrix mat); // Compute matrix determinant
float MatrixTrace(Matrix mat); // Returns the trace of the matrix (sum of the values along the diagonal)
void MatrixTranspose(Matrix *mat); // Transposes provided matrix
void MatrixInvert(Matrix *mat); // Invert provided matrix
void MatrixInvert(Matrix *mat); // Invert provided matrix
void MatrixNormalize(Matrix *mat); // Normalize provided matrix
Matrix MatrixIdentity(); // Returns identity matrix
Matrix MatrixIdentity(void); // Returns identity matrix
Matrix MatrixAdd(Matrix left, Matrix right); // Add two matrices
Matrix MatrixSubstract(Matrix left, Matrix right); // Substract two matrices (left - right)
Matrix MatrixTranslate(float x, float y, float z); // Returns translation matrix

BIN
src/resources Normal file

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
/*********************************************************************************************
/**********************************************************************************************
*
* rlgl - raylib OpenGL abstraction layer
*
* raylib now uses OpenGL 1.1 style functions (rlVertex) that are mapped to selected OpenGL version:
* OpenGL 1.1 - Direct map rl* -> gl*
* OpenGL 3.3+ - Vertex data is stored in VAOs, call rlglDraw() to render
* OpenGL ES 2 - Same behaviour as OpenGL 3.3+ (NOT TESTED)
* OpenGL ES 2 - Same behaviour as OpenGL 3.3+
*
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
@ -39,16 +39,49 @@
#include "raymath.h" // Required for data type Matrix and Matrix functions
// Select desired OpenGL version
//#define USE_OPENGL_11
//#define USE_OPENGL_33
//#define USE_OPENGL_ES2
// 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
//#define GRAPHICS_API_OPENGL_ES2 // Only available on PLATFORM_ANDROID or PLATFORM_RPI
// Security check in case no GRAPHICS_API_OPENGL_* defined
#if !defined(GRAPHICS_API_OPENGL_11) && !defined(GRAPHICS_API_OPENGL_33) && !defined(GRAPHICS_API_OPENGL_ES2)
#define GRAPHICS_API_OPENGL_11
#endif
// Security check in case no GRAPHICS_API_OPENGL_* defined
#if !defined(GRAPHICS_API_OPENGL_11) && !defined(GRAPHICS_API_OPENGL_33) && !defined(GRAPHICS_API_OPENGL_ES2)
#define GRAPHICS_API_OPENGL_11
#endif
// Security check in case multiple GRAPHICS_API_OPENGL_* defined
#if defined(GRAPHICS_API_OPENGL_11)
#if defined(GRAPHICS_API_OPENGL_33)
#undef GRAPHICS_API_OPENGL_33
#endif
#if defined(GRAPHICS_API_OPENGL_ES2)
#undef GRAPHICS_API_OPENGL_ES2
#endif
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
#define MAX_LINES_BATCH 8192 // NOTE: Be careful with limits!
#define MAX_TRIANGLES_BATCH 4096 // NOTE: Be careful with limits!
#define MAX_QUADS_BATCH 8192 // NOTE: Be careful with limits!
#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33)
// NOTE: This is the maximum amount of lines, triangles and quads per frame, be careful!
#define MAX_LINES_BATCH 8192
#define MAX_TRIANGLES_BATCH 4096
#define MAX_QUADS_BATCH 4096
#elif defined(GRAPHICS_API_OPENGL_ES2)
// NOTE: Reduce memory sizes for embedded systems (RPI)
#define MAX_LINES_BATCH 2048 // Critical for wire shapes (sphere)
#define MAX_TRIANGLES_BATCH 2048 // Critical for some shapes (sphere)
#define MAX_QUADS_BATCH 1024 // Be careful with text, every letter maps a quad
#endif
//----------------------------------------------------------------------------------
// Types and Structures Definition
@ -59,6 +92,8 @@ typedef enum { RL_PROJECTION, RL_MODELVIEW, RL_TEXTURE } MatrixMode;
typedef enum { RL_LINES, RL_TRIANGLES, RL_QUADS } DrawMode;
typedef enum { OPENGL_11 = 1, OPENGL_33, OPENGL_ES_20 } GlVersion;
#ifdef RLGL_STANDALONE
typedef struct {
int vertexCount;
@ -71,6 +106,7 @@ typedef enum { RL_LINES, RL_TRIANGLES, RL_QUADS } DrawMode;
typedef struct Model {
VertexData mesh;
unsigned int vaoId;
unsigned int vboId[4];
unsigned int textureId;
//Matrix transform;
} Model;
@ -112,31 +148,32 @@ void rlColor4f(float x, float y, float z, float w); // Define one vertex (color)
// Functions Declaration - OpenGL equivalent functions (common to 1.1, 3.3+, ES2)
// NOTE: This functions are used to completely abstract raylib code from OpenGL layer
//------------------------------------------------------------------------------------
void rlEnableTexture(unsigned int id); // Enable texture usage
void rlDisableTexture(void); // Disable texture usage
void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU
void rlDeleteVertexArrays(unsigned int id); // Unload vertex data from GPU memory
void rlEnableTexture(unsigned int id); // Enable texture usage
void rlDisableTexture(void); // Disable texture usage
void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU
void rlDeleteVertexArrays(unsigned int id); // Unload vertex data (VAO) from GPU memory
void rlDeleteBuffers(unsigned int id); // Unload vertex data (VBO) from GPU memory
void rlClearColor(byte r, byte g, byte b, byte a); // Clear color buffer with color
void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth)
void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth)
int rlGetVersion(void); // Returns current OpenGL version
//------------------------------------------------------------------------------------
// Functions Declaration - rlgl functionality
//------------------------------------------------------------------------------------
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
void rlglInit(void); // Initialize rlgl (shaders, VAO, VBO...)
void rlglClose(void); // De-init rlgl
void rlglDraw(void); // Draw VAOs
unsigned int rlglLoadModel(VertexData mesh);
unsigned int rlglLoadCompressedTexture(unsigned char *data, int width, int height, int mipmapCount, int format);
#endif
void rlglDraw(void); // Draw VAO/VBO
void rlglInitGraphics(int offsetX, int offsetY, int width, int height); // Initialize Graphics (OpenGL stuff)
unsigned int rlglLoadTexture(unsigned char *data, int width, int height, bool genMipmaps); // Load in GPU OpenGL texture
unsigned int rlglLoadCompressedTexture(unsigned char *data, int width, int height, int mipmapCount, int format);
Model rlglLoadModel(VertexData mesh); // Upload vertex data into GPU and provided VAO/VBO ids
void rlglDrawModel(Model model, Vector3 position, Vector3 rotation, Vector3 scale, Color color, bool wires);
void rlglInitGraphicsDevice(int fbWidth, int fbHeight); // Initialize Graphics Device (OpenGL stuff)
unsigned int rlglLoadTexture(unsigned char *data, int width, int height, bool genMipmaps); // Load in GPU OpenGL texture
byte *rlglReadScreenPixels(int width, int height); // Read screen pixel data (color buffer)
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
void PrintProjectionMatrix(void); // DEBUG: Print projection matrix
void PrintModelviewMatrix(void); // DEBUG: Print modelview matrix
#endif

View file

@ -1,10 +1,10 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib.shapes
*
* Basic functions to draw 2d Shapes and check collisions
*
* Copyright (c) 2013 Ramon Santamaria (Ray San - raysan@raysanweb.com)
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
* 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.
@ -31,11 +31,6 @@
#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
// Security check in case no USE_OPENGL_* defined
#if !defined(USE_OPENGL_11) && !defined(USE_OPENGL_33) && !defined(USE_OPENGL_ES2)
#define USE_OPENGL_11
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
@ -185,43 +180,44 @@ void DrawRectangleGradient(int posX, int posY, int width, int height, Color colo
// Draw a color-filled rectangle (Vector version)
void DrawRectangleV(Vector2 position, Vector2 size, Color color)
{
#ifdef USE_OPENGL_11
rlBegin(RL_TRIANGLES);
rlColor4ub(color.r, color.g, color.b, color.a);
if (rlGetVersion() == OPENGL_11)
{
rlBegin(RL_TRIANGLES);
rlColor4ub(color.r, color.g, color.b, color.a);
rlVertex2i(position.x, position.y);
rlVertex2i(position.x, position.y + size.y);
rlVertex2i(position.x + size.x, position.y + size.y);
rlVertex2i(position.x, position.y);
rlVertex2i(position.x, position.y + size.y);
rlVertex2i(position.x + size.x, position.y + size.y);
rlVertex2i(position.x, position.y);
rlVertex2i(position.x + size.x, position.y + size.y);
rlVertex2i(position.x + size.x, position.y);
rlEnd();
#endif
rlVertex2i(position.x, position.y);
rlVertex2i(position.x + size.x, position.y + size.y);
rlVertex2i(position.x + size.x, position.y);
rlEnd();
}
else if ((rlGetVersion() == OPENGL_33) || (rlGetVersion() == OPENGL_ES_20))
{
// NOTE: This shape uses QUADS to avoid drawing order issues (view rlglDraw)
rlEnableTexture(1); // Default white texture
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
// NOTE: This shape uses QUADS to avoid drawing order issues (view rlglDraw)
rlEnableTexture(1); // Default white texture
rlBegin(RL_QUADS);
rlColor4ub(color.r, color.g, color.b, color.a);
rlNormal3f(0.0f, 0.0f, 1.0f); // Normal Pointing Towards Viewer
rlBegin(RL_QUADS);
rlColor4ub(color.r, color.g, color.b, color.a);
rlNormal3f(0.0f, 0.0f, 1.0f); // Normal Pointing Towards Viewer
rlTexCoord2f(0.0f, 0.0f);
rlVertex2f(position.x, position.y);
rlTexCoord2f(0.0f, 0.0f);
rlVertex2f(position.x, position.y);
rlTexCoord2f(0.0f, 1.0f);
rlVertex2f(position.x, position.y + size.y);
rlTexCoord2f(0.0f, 1.0f);
rlVertex2f(position.x, position.y + size.y);
rlTexCoord2f(1.0f, 1.0f);
rlVertex2f(position.x + size.x, position.y + size.y);
rlTexCoord2f(1.0f, 1.0f);
rlVertex2f(position.x + size.x, position.y + size.y);
rlTexCoord2f(1.0f, 0.0f);
rlVertex2f(position.x + size.x, position.y);
rlEnd();
rlTexCoord2f(1.0f, 0.0f);
rlVertex2f(position.x + size.x, position.y);
rlEnd();
rlDisableTexture();
#endif
rlDisableTexture();
}
}
// Draw rectangle outline
@ -457,4 +453,4 @@ Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2)
}
return retRec;
}
}

View file

@ -151,14 +151,15 @@ static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_tga_info(stbi *s, int *x, int *y, int *comp);
static int stbi_psd_test(stbi *s);
static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_hdr_test(stbi *s);
static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_pic_test(stbi *s);
static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_gif_test(stbi *s);
static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);
static int stbi_gif_info(stbi *s, int *x, int *y, int *comp);
// RAY: Commented because not used
//static int stbi_hdr_test(stbi *s);
//static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);
// this is not threadsafe
static const char *failure_reason;
@ -2619,7 +2620,7 @@ static int shiftsigned(int v, int shift, int bits)
static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
{
uint8 *out;
unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
unsigned int mr=0,mg=0,mb=0,ma=0; //fake_a=0;
stbi_uc pal[256][4];
int psize=0,i,j,compress=0,width;
int bpp, flip_vertically, pad, target, offset, hsz;
@ -2668,7 +2669,7 @@ static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
mg = 0xffu << 8;
mb = 0xffu << 0;
ma = 0xffu << 24;
fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
//fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
} else {
mr = 31u << 10;
mg = 31u << 5;

View file

@ -183,7 +183,6 @@
// The three functions you must define are "read" (reads some bytes of data),
// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
#define STBI_NO_HDR // RaySan: not required by raylib
#ifndef STBI_NO_STDIO
@ -195,6 +194,11 @@
#include <stdio.h>
#endif
// NOTE: Added to work with raylib on Android
#if defined(PLATFORM_ANDROID)
#include "utils.h" // Android fopen function map
#endif
#define STBI_VERSION 1
enum

View file

@ -37,6 +37,11 @@
#include <stdio.h>
#endif
// NOTE: Added to work with raylib on Android
#if defined(PLATFORM_ANDROID)
#include "utils.h" // Android fopen function map
#endif
#ifdef __cplusplus
extern "C" {
#endif

View file

@ -1,13 +1,10 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib.text
*
* Basic functions to load SpriteFonts and draw Text
*
* Uses external lib:
* stb_image - Multiple formats image loading (JPEG, PNG, BMP, TGA, PSD, GIF, HDR, PIC)
*
* Copyright (c) 2013 Ramon Santamaria (Ray San - raysan@raysanweb.com)
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
* 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.
@ -31,10 +28,9 @@
#include <stdlib.h> // Declares malloc() and free() for memory management
#include <string.h> // String management functions (just strlen() is used)
#include <stdarg.h> // Used for functions with variable number of parameters (FormatText())
#include "stb_image.h" // Used to read image data (multiple formats support)
#include <stdio.h> // Standard input / output lib
#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
#include "utils.h" // Required for function GetExtendion()
//----------------------------------------------------------------------------------
@ -79,6 +75,9 @@ static int ParseImageData(Color *imgDataPixel, int imgWidth, int imgHeight, Char
static int GetNextPOT(int num); // Calculate next power-of-two value for a given value
static SpriteFont LoadRBMF(const char *fileName); // Load a rBMF font file (raylib BitMap Font)
extern void LoadDefaultFont(void);
extern void UnloadDefaultFont(void);
//----------------------------------------------------------------------------------
// Module Functions Definition
//----------------------------------------------------------------------------------
@ -188,53 +187,29 @@ extern void UnloadDefaultFont(void)
}
// Get the default font, useful to be used with extended parameters
SpriteFont GetDefaultFont(void)
SpriteFont GetDefaultFont()
{
return defaultFont;
}
// Load a SpriteFont image into GPU memory
SpriteFont LoadSpriteFont(const char* fileName)
SpriteFont LoadSpriteFont(const char *fileName)
{
SpriteFont spriteFont;
Image image;
// Check file extension
if (strcmp(GetExtension(fileName),"rbmf") == 0) spriteFont = LoadRBMF(fileName);
else
{
// Use stb_image to load image data!
int imgWidth;
int imgHeight;
int imgBpp;
byte *imgData = stbi_load(fileName, &imgWidth, &imgHeight, &imgBpp, 4); // Force loading to 4 components (RGBA)
// Convert array to pixel array for working convenience
Color *imgDataPixel = (Color *)malloc(imgWidth * imgHeight * sizeof(Color));
Color *imgDataPixelPOT = NULL;
int pix = 0;
for (int i = 0; i < (imgWidth * imgHeight * 4); i += 4)
{
imgDataPixel[pix].r = imgData[i];
imgDataPixel[pix].g = imgData[i+1];
imgDataPixel[pix].b = imgData[i+2];
imgDataPixel[pix].a = imgData[i+3];
pix++;
}
stbi_image_free(imgData);
Image image = LoadImage(fileName);
// At this point we have a pixel array with all the data...
TraceLog(INFO, "[%s] SpriteFont image loaded: %i x %i", fileName, imgWidth, imgHeight);
TraceLog(INFO, "[%s] SpriteFont image loaded: %i x %i", fileName, image.width, image.height);
// Process bitmap Font pixel data to get measures (Character array)
// spriteFont.charSet data is filled inside the function and memory is allocated!
int numChars = ParseImageData(imgDataPixel, imgWidth, imgHeight, &spriteFont.charSet);
int numChars = ParseImageData(image.pixels, image.width, image.height, &spriteFont.charSet);
TraceLog(INFO, "[%s] SpriteFont data parsed correctly", fileName);
TraceLog(INFO, "[%s] SpriteFont num chars detected: %i", fileName, numChars);
@ -242,13 +217,17 @@ SpriteFont LoadSpriteFont(const char* fileName)
spriteFont.numChars = numChars;
// Convert image font to POT image before conversion to texture
// NOTE: Not required, we skip this step
/*
// Just add the required amount of pixels at the right and bottom sides of image...
int potWidth = GetNextPOT(imgWidth);
int potHeight = GetNextPOT(imgHeight);
int potWidth = GetNextPOT(image.width);
int potHeight = GetNextPOT(image.height);
// Check if POT texture generation is required (if texture is not already POT)
if ((potWidth != imgWidth) || (potHeight != imgHeight))
if ((potWidth != image.width) || (potHeight != image.height))
{
Color *imgDataPixelPOT = NULL;
// Generate POT array from NPOT data
imgDataPixelPOT = (Color *)malloc(potWidth * potHeight * sizeof(Color));
@ -256,20 +235,20 @@ SpriteFont LoadSpriteFont(const char* fileName)
{
for (int i = 0; i < potWidth; i++)
{
if ((j < imgHeight) && (i < imgWidth)) imgDataPixelPOT[j*potWidth + i] = imgDataPixel[j*imgWidth + i];
if ((j < image.height) && (i < image.width)) imgDataPixelPOT[j*potWidth + i] = image.pixels[j*image.width + i];
else imgDataPixelPOT[j*potWidth + i] = MAGENTA;
}
}
TraceLog(WARNING, "SpriteFont texture converted to POT: %ix%i", potWidth, potHeight);
free(image.pixels);
image.pixels = imgDataPixelPOT;
image.width = potWidth;
image.height = potHeight;
}
free(imgDataPixel);
image.pixels = imgDataPixelPOT;
image.width = potWidth;
image.height = potHeight;
*/
spriteFont.texture = CreateTexture(image, false); // Convert loaded image to OpenGL texture
UnloadImage(image);
}
@ -287,7 +266,7 @@ void UnloadSpriteFont(SpriteFont spriteFont)
// Draw text (using default font)
// NOTE: fontSize work like in any drawing program but if fontSize is lower than font-base-size, then font-base-size is used
// NOTE: chars spacing is proportional to fontSize
void DrawText(const char* text, int posX, int posY, int fontSize, Color color)
void DrawText(const char *text, int posX, int posY, int fontSize, Color color)
{
Vector2 position = { (float)posX, (float)posY };
@ -303,7 +282,7 @@ void DrawText(const char* text, int posX, int posY, int fontSize, Color color)
// Draw text using SpriteFont
// NOTE: If font size is lower than base size, base size is used
// NOTE: chars spacing is NOT proportional to fontSize
void DrawTextEx(SpriteFont spriteFont, const char* text, Vector2 position, int fontSize, int spacing, Color tint)
void DrawTextEx(SpriteFont spriteFont, const char *text, Vector2 position, int fontSize, int spacing, Color tint)
{
int length = strlen(text);
int positionX = (int)position.x;
@ -398,13 +377,15 @@ int GetFontBaseSize(SpriteFont spriteFont)
// NOTE: Uses default font
void DrawFPS(int posX, int posY)
{
// NOTE: We are rendering fps every second for better viewing on high framerates
static float fps;
static int counter = 0;
static int refreshRate = 0;
char buffer[20];
// NOTE: We are rendering fps every second for better viewing on high framerates
// TODO: Not working properly on ANDROID and RPI
static float fps = 0.0f;
static int counter = 0;
static int refreshRate = 20;
if (counter < refreshRate)
{
counter++;

View file

@ -1,4 +1,4 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib.textures
*
@ -6,8 +6,9 @@
*
* Uses external lib:
* stb_image - Multiple formats image loading (JPEG, PNG, BMP, TGA, PSD, GIF, PIC)
* NOTE: stb_image has been slightly modified, original library: https://github.com/nothings/stb
*
* Copyright (c) 2013 Ramon Santamaria (Ray San - raysan@raysanweb.com)
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
* 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.
@ -30,15 +31,12 @@
#include <stdlib.h> // Declares malloc() and free() for memory management
#include <string.h> // Required for strcmp(), strrchr(), strncmp()
#include "stb_image.h" // Used to read image data (multiple formats support)
#include "utils.h" // rRES data decompression utility function
#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
#include "utils.h" // rRES data decompression utility function
// NOTE: Includes Android fopen function map
// Security check in case no USE_OPENGL_* defined
#if !defined(USE_OPENGL_11) && !defined(USE_OPENGL_33) && !defined(USE_OPENGL_ES2)
#define USE_OPENGL_11
#endif
#include "stb_image.h" // Used to read image data (multiple formats support)
//----------------------------------------------------------------------------------
// Defines and Macros
@ -73,7 +71,8 @@ typedef struct {
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
static ImageEx LoadDDS(const char *fileName);
static ImageEx LoadDDS(const char *fileName); // Load DDS file
static ImageEx LoadPKM(const char *fileName); // Load PKM file
//----------------------------------------------------------------------------------
// Module Functions Definition
@ -155,14 +154,18 @@ Image LoadImage(const char *fileName)
free(imageDDS.data);
TraceLog(INFO, "[%s] Image loaded successfully", fileName);
TraceLog(INFO, "[%s] DDS Image loaded successfully (uncompressed, no mipmaps)", fileName);
}
else TraceLog(WARNING, "[%s] Compressed image data could not be loaded", fileName);
else TraceLog(WARNING, "[%s] DDS Compressed image data could not be loaded", fileName);
}
else if (strcmp(GetExtension(fileName),"pkm") == 0)
{
TraceLog(INFO, "[%s] PKM Compressed image data could not be loaded", fileName);
}
else TraceLog(WARNING, "[%s] Image extension not recognized, it can't be loaded", fileName);
// ALTERNATIVE: We can load pixel data directly into Color struct pixels array,
// to do that struct data alignment should be the right one (4 byte); it is.
// to do that, struct data alignment should be the right one (4 byte); it is.
//image.pixels = stbi_load(fileName, &imgWidth, &imgHeight, &imgBpp, 4);
return image;
@ -302,9 +305,7 @@ Texture2D LoadTexture(const char *fileName)
}
else
{
#if defined(USE_OPENGL_33) || defined(USE_OPENGL_ES2)
texture.id = rlglLoadCompressedTexture(image.data, image.width, image.height, image.mipmaps, image.compFormat);
#endif
}
texture.width = image.width;
@ -315,6 +316,20 @@ Texture2D LoadTexture(const char *fileName)
free(image.data);
}
else if (strcmp(GetExtension(fileName),"pkm") == 0)
{
ImageEx image = LoadPKM(fileName);
texture.id = rlglLoadCompressedTexture(image.data, image.width, image.height, image.mipmaps, image.compFormat);
texture.width = image.width;
texture.height = image.height;
if (texture.id == 0) TraceLog(WARNING, "[%s] PKM texture could not be loaded", fileName);
else TraceLog(INFO, "[%s] PKM texture loaded successfully", fileName);
free(image.data);
}
else
{
Image image = LoadImage(fileName);
@ -453,8 +468,6 @@ Texture2D CreateTexture(Image image, bool genMipmaps)
texture.width = image.width;
texture.height = image.height;
TraceLog(INFO, "[ID %i] Texture created successfully", texture.id);
free(imgData);
}
else TraceLog(WARNING, "Texture could not be created, image data is not valid");
@ -471,15 +484,15 @@ ImageEx LoadDDS(const char *fileName)
#define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#endif
#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
#endif
// DDS Pixel Format
@ -582,11 +595,9 @@ ImageEx LoadDDS(const char *fileName)
}
else if ((header.ddspf.flags == 0x04) && (header.ddspf.fourCC > 0))
{
#ifdef USE_OPENGL_11
TraceLog(WARNING, "[%s] DDS image uses compression, not supported by current OpenGL version", fileName);
TraceLog(WARNING, "[%s] DDS image uses compression, not supported on OpenGL 1.1", fileName);
TraceLog(WARNING, "[%s] DDS compressed files require OpenGL 3.2+ or ES 2.0", fileName);
fclose(ddsFile);
#else
int bufsize;
// Calculate data size, including all mipmaps
@ -614,10 +625,96 @@ ImageEx LoadDDS(const char *fileName)
// NOTE: Image num color components not required... for now...
//if (fourCC == FOURCC_DXT1) image.components = 3;
//else image.components = 4;
#endif
}
}
}
return image;
}
// 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)
ImageEx LoadPKM(const char *fileName)
{
// If OpenGL ES 2.0. the following format could be supported (ETC1):
//GL_ETC1_RGB8_OES
#ifndef GL_ETC1_RGB8_OES
#define GL_ETC1_RGB8_OES 0x8D64
#endif
// If OpenGL ES 3.0, the following formats are supported (ETC2/EAC):
//GL_COMPRESSED_RGB8_ETC2
//GL_COMPRESSED_RGBA8_ETC2
//GL_COMPRESSED_RG11_EAC
//...
// PKM file (ETC1) Header (16 bytes)
typedef struct {
char id[4]; // "PKM "
char version[2]; // "10"
unsigned short format; // Format = number of mipmaps = 0 (ETC1_RGB_NO_MIPMAPS)
unsigned short extWidth; // Texture width (big-endian)
unsigned short extHeight; // Texture height (big-endian)
unsigned short origWidth; // Original width (big-endian)
unsigned short origHeight; // Original height (big-endian)
} pkmHeader;
// NOTE: The extended width and height are the widths rounded up to a multiple of 4.
// NOTE: ETC is always 4bit per pixel (64 bits for each 4x4 block of pixels)
// Bytes Swap (little-endian <-> big-endian)
//unsigned short data;
//unsigned short swap = ((data & 0x00FF) << 8) | ((data & 0xFF00) >> 8);
ImageEx image;
unsigned short width;
unsigned short height;
unsigned short useless;
FILE *pkmFile = fopen(fileName, "rb");
if (pkmFile == NULL)
{
TraceLog(WARNING, "[%s] PKM File could not be opened", fileName);
}
else
{
// Verify the type of file
char filecode[4];
fread(filecode, 1, 4, pkmFile);
if (strncmp(filecode, "PKM ", 4) != 0)
{
TraceLog(WARNING, "[%s] PKM File does not seem to be valid", fileName);
fclose(pkmFile);
}
else
{
// Get the surface descriptor
fread(&useless, sizeof(unsigned short), 1, pkmFile); // Discard version
fread(&useless, sizeof(unsigned short), 1, pkmFile); // Discard format
fread(&width, sizeof(unsigned short), 1, pkmFile); // Read extended width
fread(&height, sizeof(unsigned short), 1, pkmFile); // Read extended height
int size = (width/4)*(height/4)*8; // Total data size in bytes
image.data = (unsigned char*)malloc(size * sizeof(unsigned char));
fread(image.data, 1, size, pkmFile);
fclose(pkmFile); // Close file pointer
image.width = width;
image.height = height;
image.mipmaps = 1;
image.compFormat = GL_ETC1_RGB8_OES;
}
}
return image;
}

View file

@ -1,4 +1,4 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib.utils
*
@ -8,7 +8,7 @@
* tinfl - zlib DEFLATE algorithm decompression lib
* stb_image_write - PNG writting functions
*
* Copyright (c) 2013 Ramon Santamaria (Ray San - raysan@raysanweb.com)
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
* 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.
@ -29,20 +29,40 @@
#include "utils.h"
#if defined(PLATFORM_ANDROID)
#include <errno.h>
#include <android/log.h>
#include <android/asset_manager.h>
#endif
#include <stdlib.h> // malloc(), free()
#include <stdio.h> // printf(), fprintf()
#include <stdarg.h> // Used for functions with variable number of parameters (TraceLog())
//#include <string.h> // String management functions: strlen(), strrchr(), strcmp()
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h" // Create PNG file
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI)
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h" // Create PNG file
#endif
#include "tinfl.c"
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
static FILE *logstream = NULL;
#if defined(PLATFORM_ANDROID)
AAssetManager *assetManager;
#endif
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
#if defined(PLATFORM_ANDROID)
static int android_read(void *cookie, char *buf, int size);
static int android_write(void *cookie, const char *buf, int size);
static fpos_t android_seek(void *cookie, fpos_t offset, int whence);
static int android_close(void *cookie);
#endif
//----------------------------------------------------------------------------------
// Module Functions Definition - Utilities
@ -87,6 +107,7 @@ unsigned char *DecompressData(const unsigned char *data, unsigned long compSize,
return pUncomp;
}
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI)
// Creates a bitmap (BMP) file from an array of pixel data
// NOTE: This function is not explicitly available to raylib users
void WriteBitmap(const char *fileName, unsigned char *imgData, int width, int height)
@ -148,52 +169,90 @@ void TraceLog(int msgType, const char *text, ...)
traceDebugMsgs = 0;
#endif
// NOTE: If trace log file not set, output redirected to stdout
if (logstream == NULL) logstream = stdout;
switch(msgType)
{
case INFO: fprintf(logstream, "INFO: "); break;
case ERROR: fprintf(logstream, "ERROR: "); break;
case WARNING: fprintf(logstream, "WARNING: "); break;
case DEBUG: if (traceDebugMsgs) fprintf(logstream, "DEBUG: "); break;
case INFO: fprintf(stdout, "INFO: "); break;
case ERROR: fprintf(stdout, "ERROR: "); break;
case WARNING: fprintf(stdout, "WARNING: "); break;
case DEBUG: if (traceDebugMsgs) fprintf(stdout, "DEBUG: "); break;
default: break;
}
if ((msgType != DEBUG) || ((msgType == DEBUG) && (traceDebugMsgs)))
{
va_start(args, text);
vfprintf(logstream, text, args);
vfprintf(stdout, text, args);
va_end(args);
fprintf(logstream, "\n");
fprintf(stdout, "\n");
}
if (msgType == ERROR) exit(1); // If ERROR message, exit program
}
#endif
// Open a trace log file (if desired)
void TraceLogOpen(const char *logFileName)
#if defined(PLATFORM_ANDROID)
void TraceLog(int msgType, const char *text, ...)
{
// stdout redirected to stream file
FILE *logstream = fopen(logFileName, "w");
static char buffer[100];
if (logstream == NULL) TraceLog(WARNING, "Unable to open log file");
switch(msgType)
{
case INFO: strcpy(buffer, "INFO: "); break;
case ERROR: strcpy(buffer, "ERROR: "); break;
case WARNING: strcpy(buffer, "WARNING: "); break;
case DEBUG: strcpy(buffer, "DEBUG: "); break;
default: break;
}
strcat(buffer, text);
strcat(buffer, "\n");
va_list args;
va_start(args, buffer);
switch(msgType)
{
case INFO: __android_log_vprint(ANDROID_LOG_INFO, "raylib", buffer, args); break;
case ERROR: __android_log_vprint(ANDROID_LOG_ERROR, "raylib", buffer, args); break;
case WARNING: __android_log_vprint(ANDROID_LOG_WARN, "raylib", buffer, args); break;
case DEBUG: __android_log_vprint(ANDROID_LOG_DEBUG, "raylib", buffer, args); break;
default: break;
}
va_end(args);
if (msgType == ERROR) exit(1);
}
// Close the trace log file
void TraceLogClose()
// Initialize asset manager from android app
void InitAssetManager(AAssetManager *manager)
{
if (logstream != NULL) fclose(logstream);
assetManager = manager;
}
// Replacement for fopen
FILE *android_fopen(const char *fileName, const char *mode)
{
if (mode[0] == 'w') return NULL;
AAsset *asset = AAssetManager_open(assetManager, fileName, 0);
if(!asset) return NULL;
return funopen(asset, android_read, android_write, android_seek, android_close);
}
#endif
// Keep track of memory allocated
// NOTE: mallocType defines the type of data allocated
/*
void RecordMalloc(int mallocType, int mallocSize, const char *msg)
{
// TODO: Investigate how to record memory allocation data...
// Maybe creating my own malloc function...
}
*/
// Get the extension for a filename
const char *GetExtension(const char *fileName)
@ -203,3 +262,30 @@ const char *GetExtension(const char *fileName)
return (dot + 1);
}
//----------------------------------------------------------------------------------
// Module specific Functions Definition
//----------------------------------------------------------------------------------
#if defined(PLATFORM_ANDROID)
static int android_read(void *cookie, char *buf, int size)
{
return AAsset_read((AAsset *)cookie, buf, size);
}
static int android_write(void *cookie, const char *buf, int size)
{
TraceLog(ERROR, "Can't provide write access to the APK");
return EACCES;
}
static fpos_t android_seek(void *cookie, fpos_t offset, int whence)
{
return AAsset_seek((AAsset *)cookie, offset, whence);
}
static int android_close(void *cookie)
{
AAsset_close((AAsset *)cookie);
return 0;
}
#endif

View file

@ -1,10 +1,10 @@
/*********************************************************************************************
/**********************************************************************************************
*
* raylib.utils
*
* Some utility functions: rRES files data decompression
*
* Copyright (c) 2013 Ramon Santamaria (Ray San - raysan@raysanweb.com)
* Copyright (c) 2014 Ramon Santamaria (Ray San - raysan@raysanweb.com)
*
* 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.
@ -26,11 +26,20 @@
#ifndef UTILS_H
#define UTILS_H
#if defined(PLATFORM_ANDROID)
#include <stdio.h> // Defines FILE struct
#include <android/asset_manager.h> // defines AAssetManager struct
#endif
//----------------------------------------------------------------------------------
// Some basic Defines
//----------------------------------------------------------------------------------
#define DO_NOT_TRACE_DEBUG_MSGS // Use this define to avoid DEBUG tracing
#if defined(PLATFORM_ANDROID)
#define fopen(name, mode) android_fopen(name, mode)
#endif
//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
@ -61,14 +70,18 @@ extern "C" { // Prevents name mangling of functions
//----------------------------------------------------------------------------------
unsigned char *DecompressData(const unsigned char *data, unsigned long compSize, int uncompSize);
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI)
void WriteBitmap(const char *fileName, unsigned char *imgData, int width, int height);
void WritePNG(const char *fileName, unsigned char *imgData, int width, int height);
#endif
void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message
void TraceLogOpen(const char *logFileName); // Open a trace log file (if desired)
void TraceLogClose(); // Close the trace log file
const char *GetExtension(const char *fileName); // Returns extension of a filename
const char *GetExtension(const char *fileName);
#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()
#endif
#ifdef __cplusplus
}