Support custom memory management macros

Users can define their custom memory management macros.

NOTE: Most external libraries support custom macros in the same way, raylib should redefine those macros to raylib ones, to unify custom memory loading. That redefinition is only implemented as example for stb_image.h in [textures] module.
This commit is contained in:
Ray 2019-04-23 14:55:35 +02:00
parent 8ed71b9d5a
commit e67ebabb02
9 changed files with 364 additions and 338 deletions

View file

@ -1113,7 +1113,7 @@ void EndDrawing(void)
unsigned char *screenData = rlReadScreenPixels(screenWidth, screenHeight); unsigned char *screenData = rlReadScreenPixels(screenWidth, screenHeight);
GifWriteFrame(screenData, screenWidth, screenHeight, 10, 8, false); GifWriteFrame(screenData, screenWidth, screenHeight, 10, 8, false);
free(screenData); // Free image data RL_FREE(screenData); // Free image data
} }
if (((gifFramesCounter/15)%2) == 1) if (((gifFramesCounter/15)%2) == 1)
@ -1595,7 +1595,7 @@ void TakeScreenshot(const char *fileName)
#endif #endif
ExportImage(image, path); ExportImage(image, path);
free(imgData); RL_FREE(imgData);
#if defined(PLATFORM_WEB) #if defined(PLATFORM_WEB)
// Download file from MEMFS (emscripten memory filesystem) // Download file from MEMFS (emscripten memory filesystem)
@ -1742,8 +1742,8 @@ char **GetDirectoryFiles(const char *dirPath, int *fileCount)
ClearDirectoryFiles(); ClearDirectoryFiles();
// Memory allocation for MAX_DIRECTORY_FILES // Memory allocation for MAX_DIRECTORY_FILES
dirFilesPath = (char **)malloc(sizeof(char *)*MAX_DIRECTORY_FILES); dirFilesPath = (char **)RL_MALLOC(sizeof(char *)*MAX_DIRECTORY_FILES);
for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)malloc(sizeof(char)*MAX_FILEPATH_LENGTH); for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH);
int counter = 0; int counter = 0;
struct dirent *ent; struct dirent *ent;
@ -1776,9 +1776,9 @@ void ClearDirectoryFiles(void)
{ {
if (dirFilesCount > 0) if (dirFilesCount > 0)
{ {
for (int i = 0; i < dirFilesCount; i++) free(dirFilesPath[i]); for (int i = 0; i < dirFilesCount; i++) RL_FREE(dirFilesPath[i]);
free(dirFilesPath); RL_FREE(dirFilesPath);
dirFilesCount = 0; dirFilesCount = 0;
} }
} }
@ -1808,9 +1808,9 @@ void ClearDroppedFiles(void)
{ {
if (dropFilesCount > 0) if (dropFilesCount > 0)
{ {
for (int i = 0; i < dropFilesCount; i++) free(dropFilesPath[i]); for (int i = 0; i < dropFilesCount; i++) RL_FREE(dropFilesPath[i]);
free(dropFilesPath); RL_FREE(dropFilesPath);
dropFilesCount = 0; dropFilesCount = 0;
} }
@ -1925,7 +1925,7 @@ void OpenURL(const char *url)
} }
else else
{ {
char *cmd = (char *)calloc(strlen(url) + 10, sizeof(char)); char *cmd = (char *)RL_CALLOC(strlen(url) + 10, sizeof(char));
#if defined(_WIN32) #if defined(_WIN32)
sprintf(cmd, "explorer %s", url); sprintf(cmd, "explorer %s", url);
@ -1935,7 +1935,7 @@ void OpenURL(const char *url)
sprintf(cmd, "open '%s'", url); sprintf(cmd, "open '%s'", url);
#endif #endif
system(cmd); system(cmd);
free(cmd); RL_FREE(cmd);
} }
} }
@ -3455,11 +3455,11 @@ static void WindowDropCallback(GLFWwindow *window, int count, const char **paths
{ {
ClearDroppedFiles(); ClearDroppedFiles();
dropFilesPath = (char **)malloc(sizeof(char *)*count); dropFilesPath = (char **)RL_MALLOC(sizeof(char *)*count);
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
{ {
dropFilesPath[i] = (char *)malloc(sizeof(char)*MAX_FILEPATH_LENGTH); dropFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH);
strcpy(dropFilesPath[i], paths[i]); strcpy(dropFilesPath[i], paths[i]);
} }

View file

@ -651,7 +651,7 @@ Model LoadModel(const char *fileName)
TraceLog(LOG_WARNING, "[%s] No meshes can be loaded, default to cube mesh", fileName); TraceLog(LOG_WARNING, "[%s] No meshes can be loaded, default to cube mesh", fileName);
model.meshCount = 1; model.meshCount = 1;
model.meshes = (Mesh *)calloc(model.meshCount, sizeof(Mesh)); model.meshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh));
model.meshes[0] = GenMeshCube(1.0f, 1.0f, 1.0f); model.meshes[0] = GenMeshCube(1.0f, 1.0f, 1.0f);
} }
else else
@ -665,10 +665,10 @@ Model LoadModel(const char *fileName)
TraceLog(LOG_WARNING, "[%s] No materials can be loaded, default to white material", fileName); TraceLog(LOG_WARNING, "[%s] No materials can be loaded, default to white material", fileName);
model.materialCount = 1; model.materialCount = 1;
model.materials = (Material *)calloc(model.materialCount, sizeof(Material)); model.materials = (Material *)RL_CALLOC(model.materialCount, sizeof(Material));
model.materials[0] = LoadMaterialDefault(); model.materials[0] = LoadMaterialDefault();
model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
} }
return model; return model;
@ -685,14 +685,14 @@ Model LoadModelFromMesh(Mesh mesh)
model.transform = MatrixIdentity(); model.transform = MatrixIdentity();
model.meshCount = 1; model.meshCount = 1;
model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); model.meshes = (Mesh *)RL_MALLOC(model.meshCount*sizeof(Mesh));
model.meshes[0] = mesh; model.meshes[0] = mesh;
model.materialCount = 1; model.materialCount = 1;
model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); model.materials = (Material *)RL_MALLOC(model.materialCount*sizeof(Material));
model.materials[0] = LoadMaterialDefault(); model.materials[0] = LoadMaterialDefault();
model.meshMaterial = (int *)malloc(model.meshCount*sizeof(int)); model.meshMaterial = (int *)RL_MALLOC(model.meshCount*sizeof(int));
model.meshMaterial[0] = 0; // First material index model.meshMaterial[0] = 0; // First material index
return model; return model;
@ -704,13 +704,13 @@ void UnloadModel(Model model)
for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]); for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]);
for (int i = 0; i < model.materialCount; i++) UnloadMaterial(model.materials[i]); for (int i = 0; i < model.materialCount; i++) UnloadMaterial(model.materials[i]);
free(model.meshes); RL_FREE(model.meshes);
free(model.materials); RL_FREE(model.materials);
free(model.meshMaterial); RL_FREE(model.meshMaterial);
// Unload animation data // Unload animation data
free(model.bones); RL_FREE(model.bones);
free(model.bindPose); RL_FREE(model.bindPose);
TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM");
} }
@ -866,7 +866,7 @@ void SetModelMeshMaterial(Model *model, int meshId, int materialId)
// Load model animations from file // Load model animations from file
ModelAnimation *LoadModelAnimations(const char *filename, int *animCount) ModelAnimation *LoadModelAnimations(const char *filename, int *animCount)
{ {
ModelAnimation *animations = (ModelAnimation *)malloc(1*sizeof(ModelAnimation)); ModelAnimation *animations = (ModelAnimation *)RL_MALLOC(1*sizeof(ModelAnimation));
int count = 1; int count = 1;
#define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number
@ -935,12 +935,12 @@ ModelAnimation *LoadModelAnimations(const char *filename, int *animCount)
// bones // bones
IQMPose *poses; IQMPose *poses;
poses = malloc(sizeof(IQMPose)*iqm.num_poses); poses = RL_MALLOC(sizeof(IQMPose)*iqm.num_poses);
fseek(iqmFile, iqm.ofs_poses, SEEK_SET); fseek(iqmFile, iqm.ofs_poses, SEEK_SET);
fread(poses, sizeof(IQMPose)*iqm.num_poses, 1, iqmFile); fread(poses, sizeof(IQMPose)*iqm.num_poses, 1, iqmFile);
animation.boneCount = iqm.num_poses; animation.boneCount = iqm.num_poses;
animation.bones = malloc(sizeof(BoneInfo)*iqm.num_poses); animation.bones = RL_MALLOC(sizeof(BoneInfo)*iqm.num_poses);
for (int j = 0; j < iqm.num_poses; j++) for (int j = 0; j < iqm.num_poses; j++)
{ {
@ -957,12 +957,12 @@ ModelAnimation *LoadModelAnimations(const char *filename, int *animCount)
//animation.framerate = anim.framerate; //animation.framerate = anim.framerate;
// frameposes // frameposes
unsigned short *framedata = malloc(sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels); unsigned short *framedata = RL_MALLOC(sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels);
fseek(iqmFile, iqm.ofs_frames, SEEK_SET); fseek(iqmFile, iqm.ofs_frames, SEEK_SET);
fread(framedata, sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels, 1, iqmFile); fread(framedata, sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels, 1, iqmFile);
animation.framePoses = malloc(sizeof(Transform*)*anim.num_frames); animation.framePoses = RL_MALLOC(sizeof(Transform*)*anim.num_frames);
for (int j = 0; j < anim.num_frames; j++) animation.framePoses[j] = malloc(sizeof(Transform)*iqm.num_poses); for (int j = 0; j < anim.num_frames; j++) animation.framePoses[j] = RL_MALLOC(sizeof(Transform)*iqm.num_poses);
int dcounter = anim.first_frame*iqm.num_framechannels; int dcounter = anim.first_frame*iqm.num_framechannels;
@ -1069,8 +1069,8 @@ ModelAnimation *LoadModelAnimations(const char *filename, int *animCount)
} }
} }
free(framedata); RL_FREE(framedata);
free(poses); RL_FREE(poses);
fclose(iqmFile); fclose(iqmFile);
@ -1145,10 +1145,10 @@ void UpdateModelAnimation(Model model, ModelAnimation anim, int frame)
// Unload animation data // Unload animation data
void UnloadModelAnimation(ModelAnimation anim) void UnloadModelAnimation(ModelAnimation anim)
{ {
for (int i = 0; i < anim.frameCount; i++) free(anim.framePoses[i]); for (int i = 0; i < anim.frameCount; i++) RL_FREE(anim.framePoses[i]);
free(anim.bones); RL_FREE(anim.bones);
free(anim.framePoses); RL_FREE(anim.framePoses);
} }
// Check model animation skeleton match // Check model animation skeleton match
@ -1177,7 +1177,7 @@ Mesh GenMeshPoly(int sides, float radius)
int vertexCount = sides*3; int vertexCount = sides*3;
// Vertices definition // Vertices definition
Vector3 *vertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); Vector3 *vertices = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
for (int i = 0, v = 0; i < 360; i += 360/sides, v += 3) for (int i = 0, v = 0; i < 360; i += 360/sides, v += 3)
{ {
vertices[v] = (Vector3){ 0.0f, 0.0f, 0.0f }; vertices[v] = (Vector3){ 0.0f, 0.0f, 0.0f };
@ -1186,18 +1186,18 @@ Mesh GenMeshPoly(int sides, float radius)
} }
// Normals definition // Normals definition
Vector3 *normals = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); Vector3 *normals = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up; for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up;
// TexCoords definition // TexCoords definition
Vector2 *texcoords = (Vector2 *)malloc(vertexCount*sizeof(Vector2)); Vector2 *texcoords = (Vector2 *)RL_MALLOC(vertexCount*sizeof(Vector2));
for (int n = 0; n < vertexCount; n++) texcoords[n] = (Vector2){ 0.0f, 0.0f }; for (int n = 0; n < vertexCount; n++) texcoords[n] = (Vector2){ 0.0f, 0.0f };
mesh.vertexCount = vertexCount; mesh.vertexCount = vertexCount;
mesh.triangleCount = sides; mesh.triangleCount = sides;
mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
// Mesh vertices position array // Mesh vertices position array
for (int i = 0; i < mesh.vertexCount; i++) for (int i = 0; i < mesh.vertexCount; i++)
@ -1222,9 +1222,9 @@ Mesh GenMeshPoly(int sides, float radius)
mesh.normals[3*i + 2] = normals[i].z; mesh.normals[3*i + 2] = normals[i].z;
} }
free(vertices); RL_FREE(vertices);
free(normals); RL_FREE(normals);
free(texcoords); RL_FREE(texcoords);
// Upload vertex data to GPU (static mesh) // Upload vertex data to GPU (static mesh)
rlLoadMesh(&mesh, false); rlLoadMesh(&mesh, false);
@ -1245,7 +1245,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ)
// Vertices definition // Vertices definition
int vertexCount = resX*resZ; // vertices get reused for the faces int vertexCount = resX*resZ; // vertices get reused for the faces
Vector3 *vertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); Vector3 *vertices = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
for (int z = 0; z < resZ; z++) for (int z = 0; z < resZ; z++)
{ {
// [-length/2, length/2] // [-length/2, length/2]
@ -1259,11 +1259,11 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ)
} }
// Normals definition // Normals definition
Vector3 *normals = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); Vector3 *normals = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up; for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up;
// TexCoords definition // TexCoords definition
Vector2 *texcoords = (Vector2 *)malloc(vertexCount*sizeof(Vector2)); Vector2 *texcoords = (Vector2 *)RL_MALLOC(vertexCount*sizeof(Vector2));
for (int v = 0; v < resZ; v++) for (int v = 0; v < resZ; v++)
{ {
for (int u = 0; u < resX; u++) for (int u = 0; u < resX; u++)
@ -1274,7 +1274,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ)
// Triangles definition (indices) // Triangles definition (indices)
int numFaces = (resX - 1)*(resZ - 1); int numFaces = (resX - 1)*(resZ - 1);
int *triangles = (int *)malloc(numFaces*6*sizeof(int)); int *triangles = (int *)RL_MALLOC(numFaces*6*sizeof(int));
int t = 0; int t = 0;
for (int face = 0; face < numFaces; face++) for (int face = 0; face < numFaces; face++)
{ {
@ -1292,10 +1292,10 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ)
mesh.vertexCount = vertexCount; mesh.vertexCount = vertexCount;
mesh.triangleCount = numFaces*2; mesh.triangleCount = numFaces*2;
mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.indices = (unsigned short *)malloc(mesh.triangleCount*3*sizeof(unsigned short)); mesh.indices = (unsigned short *)RL_MALLOC(mesh.triangleCount*3*sizeof(unsigned short));
// Mesh vertices position array // Mesh vertices position array
for (int i = 0; i < mesh.vertexCount; i++) for (int i = 0; i < mesh.vertexCount; i++)
@ -1323,10 +1323,10 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ)
// Mesh indices array initialization // Mesh indices array initialization
for (int i = 0; i < mesh.triangleCount*3; i++) mesh.indices[i] = triangles[i]; for (int i = 0; i < mesh.triangleCount*3; i++) mesh.indices[i] = triangles[i];
free(vertices); RL_FREE(vertices);
free(normals); RL_FREE(normals);
free(texcoords); RL_FREE(texcoords);
free(triangles); RL_FREE(triangles);
#else // Use par_shapes library to generate plane mesh #else // Use par_shapes library to generate plane mesh
@ -1335,9 +1335,9 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ)
par_shapes_rotate(plane, -PI/2.0f, (float[]){ 1, 0, 0 }); par_shapes_rotate(plane, -PI/2.0f, (float[]){ 1, 0, 0 });
par_shapes_translate(plane, -width/2, 0.0f, length/2); par_shapes_translate(plane, -width/2, 0.0f, length/2);
mesh.vertices = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(plane->ntriangles*3*3*sizeof(float));
mesh.texcoords = (float *)malloc(plane->ntriangles*3*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(plane->ntriangles*3*2*sizeof(float));
mesh.normals = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(plane->ntriangles*3*3*sizeof(float));
mesh.vertexCount = plane->ntriangles*3; mesh.vertexCount = plane->ntriangles*3;
mesh.triangleCount = plane->ntriangles; mesh.triangleCount = plane->ntriangles;
@ -1453,16 +1453,16 @@ Mesh GenMeshCube(float width, float height, float length)
-1.0f, 0.0f, 0.0f -1.0f, 0.0f, 0.0f
}; };
mesh.vertices = (float *)malloc(24*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(24*3*sizeof(float));
memcpy(mesh.vertices, vertices, 24*3*sizeof(float)); memcpy(mesh.vertices, vertices, 24*3*sizeof(float));
mesh.texcoords = (float *)malloc(24*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(24*2*sizeof(float));
memcpy(mesh.texcoords, texcoords, 24*2*sizeof(float)); memcpy(mesh.texcoords, texcoords, 24*2*sizeof(float));
mesh.normals = (float *)malloc(24*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(24*3*sizeof(float));
memcpy(mesh.normals, normals, 24*3*sizeof(float)); memcpy(mesh.normals, normals, 24*3*sizeof(float));
mesh.indices = (unsigned short *)malloc(36*sizeof(unsigned short)); mesh.indices = (unsigned short *)RL_MALLOC(36*sizeof(unsigned short));
int k = 0; int k = 0;
@ -1500,9 +1500,9 @@ par_shapes_mesh* par_shapes_create_icosahedron(); // 20 sides polyhedron
par_shapes_translate(cube, -width/2, 0.0f, -length/2); par_shapes_translate(cube, -width/2, 0.0f, -length/2);
par_shapes_compute_normals(cube); par_shapes_compute_normals(cube);
mesh.vertices = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(cube->ntriangles*3*3*sizeof(float));
mesh.texcoords = (float *)malloc(cube->ntriangles*3*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(cube->ntriangles*3*2*sizeof(float));
mesh.normals = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(cube->ntriangles*3*3*sizeof(float));
mesh.vertexCount = cube->ntriangles*3; mesh.vertexCount = cube->ntriangles*3;
mesh.triangleCount = cube->ntriangles; mesh.triangleCount = cube->ntriangles;
@ -1539,9 +1539,9 @@ RLAPI Mesh GenMeshSphere(float radius, int rings, int slices)
par_shapes_scale(sphere, radius, radius, radius); par_shapes_scale(sphere, radius, radius, radius);
// NOTE: Soft normals are computed internally // NOTE: Soft normals are computed internally
mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(sphere->ntriangles*3*2*sizeof(float));
mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
mesh.vertexCount = sphere->ntriangles*3; mesh.vertexCount = sphere->ntriangles*3;
mesh.triangleCount = sphere->ntriangles; mesh.triangleCount = sphere->ntriangles;
@ -1577,9 +1577,9 @@ RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices)
par_shapes_scale(sphere, radius, radius, radius); par_shapes_scale(sphere, radius, radius, radius);
// NOTE: Soft normals are computed internally // NOTE: Soft normals are computed internally
mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(sphere->ntriangles*3*2*sizeof(float));
mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
mesh.vertexCount = sphere->ntriangles*3; mesh.vertexCount = sphere->ntriangles*3;
mesh.triangleCount = sphere->ntriangles; mesh.triangleCount = sphere->ntriangles;
@ -1635,9 +1635,9 @@ Mesh GenMeshCylinder(float radius, float height, int slices)
par_shapes_merge_and_free(cylinder, capTop); par_shapes_merge_and_free(cylinder, capTop);
par_shapes_merge_and_free(cylinder, capBottom); par_shapes_merge_and_free(cylinder, capBottom);
mesh.vertices = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(cylinder->ntriangles*3*3*sizeof(float));
mesh.texcoords = (float *)malloc(cylinder->ntriangles*3*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(cylinder->ntriangles*3*2*sizeof(float));
mesh.normals = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(cylinder->ntriangles*3*3*sizeof(float));
mesh.vertexCount = cylinder->ntriangles*3; mesh.vertexCount = cylinder->ntriangles*3;
mesh.triangleCount = cylinder->ntriangles; mesh.triangleCount = cylinder->ntriangles;
@ -1677,9 +1677,9 @@ Mesh GenMeshTorus(float radius, float size, int radSeg, int sides)
par_shapes_mesh *torus = par_shapes_create_torus(radSeg, sides, radius); par_shapes_mesh *torus = par_shapes_create_torus(radSeg, sides, radius);
par_shapes_scale(torus, size/2, size/2, size/2); par_shapes_scale(torus, size/2, size/2, size/2);
mesh.vertices = (float *)malloc(torus->ntriangles*3*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(torus->ntriangles*3*3*sizeof(float));
mesh.texcoords = (float *)malloc(torus->ntriangles*3*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(torus->ntriangles*3*2*sizeof(float));
mesh.normals = (float *)malloc(torus->ntriangles*3*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(torus->ntriangles*3*3*sizeof(float));
mesh.vertexCount = torus->ntriangles*3; mesh.vertexCount = torus->ntriangles*3;
mesh.triangleCount = torus->ntriangles; mesh.triangleCount = torus->ntriangles;
@ -1717,9 +1717,9 @@ Mesh GenMeshKnot(float radius, float size, int radSeg, int sides)
par_shapes_mesh *knot = par_shapes_create_trefoil_knot(radSeg, sides, radius); par_shapes_mesh *knot = par_shapes_create_trefoil_knot(radSeg, sides, radius);
par_shapes_scale(knot, size, size, size); par_shapes_scale(knot, size, size, size);
mesh.vertices = (float *)malloc(knot->ntriangles*3*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(knot->ntriangles*3*3*sizeof(float));
mesh.texcoords = (float *)malloc(knot->ntriangles*3*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(knot->ntriangles*3*2*sizeof(float));
mesh.normals = (float *)malloc(knot->ntriangles*3*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(knot->ntriangles*3*3*sizeof(float));
mesh.vertexCount = knot->ntriangles*3; mesh.vertexCount = knot->ntriangles*3;
mesh.triangleCount = knot->ntriangles; mesh.triangleCount = knot->ntriangles;
@ -1764,9 +1764,9 @@ Mesh GenMeshHeightmap(Image heightmap, Vector3 size)
mesh.vertexCount = mesh.triangleCount*3; mesh.vertexCount = mesh.triangleCount*3;
mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
mesh.colors = NULL; mesh.colors = NULL;
int vCounter = 0; // Used to count vertices float by float int vCounter = 0; // Used to count vertices float by float
@ -1848,7 +1848,7 @@ Mesh GenMeshHeightmap(Image heightmap, Vector3 size)
} }
} }
free(pixels); RL_FREE(pixels);
// Upload vertex data to GPU (static mesh) // Upload vertex data to GPU (static mesh)
rlLoadMesh(&mesh, false); rlLoadMesh(&mesh, false);
@ -1878,9 +1878,9 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)
float h = cubeSize.z; float h = cubeSize.z;
float h2 = cubeSize.y; float h2 = cubeSize.y;
Vector3 *mapVertices = (Vector3 *)malloc(maxTriangles*3*sizeof(Vector3)); Vector3 *mapVertices = (Vector3 *)RL_MALLOC(maxTriangles*3*sizeof(Vector3));
Vector2 *mapTexcoords = (Vector2 *)malloc(maxTriangles*3*sizeof(Vector2)); Vector2 *mapTexcoords = (Vector2 *)RL_MALLOC(maxTriangles*3*sizeof(Vector2));
Vector3 *mapNormals = (Vector3 *)malloc(maxTriangles*3*sizeof(Vector3)); Vector3 *mapNormals = (Vector3 *)RL_MALLOC(maxTriangles*3*sizeof(Vector3));
// Define the 6 normals of the cube, we will combine them accordingly later... // Define the 6 normals of the cube, we will combine them accordingly later...
Vector3 n1 = { 1.0f, 0.0f, 0.0f }; Vector3 n1 = { 1.0f, 0.0f, 0.0f };
@ -2167,9 +2167,9 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)
mesh.vertexCount = vCounter; mesh.vertexCount = vCounter;
mesh.triangleCount = vCounter/3; mesh.triangleCount = vCounter/3;
mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
mesh.colors = NULL; mesh.colors = NULL;
int fCounter = 0; int fCounter = 0;
@ -2204,11 +2204,11 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)
fCounter += 2; fCounter += 2;
} }
free(mapVertices); RL_FREE(mapVertices);
free(mapNormals); RL_FREE(mapNormals);
free(mapTexcoords); RL_FREE(mapTexcoords);
free(cubicmapPixels); // Free image pixel data RL_FREE(cubicmapPixels); // Free image pixel data
// Upload vertex data to GPU (static mesh) // Upload vertex data to GPU (static mesh)
rlLoadMesh(&mesh, false); rlLoadMesh(&mesh, false);
@ -2250,11 +2250,11 @@ BoundingBox MeshBoundingBox(Mesh mesh)
// Implementation base don: https://answers.unity.com/questions/7789/calculating-tangents-vector4.html // Implementation base don: https://answers.unity.com/questions/7789/calculating-tangents-vector4.html
void MeshTangents(Mesh *mesh) void MeshTangents(Mesh *mesh)
{ {
if (mesh->tangents == NULL) mesh->tangents = (float *)malloc(mesh->vertexCount*4*sizeof(float)); if (mesh->tangents == NULL) mesh->tangents = (float *)RL_MALLOC(mesh->vertexCount*4*sizeof(float));
else TraceLog(LOG_WARNING, "Mesh tangents already exist"); else TraceLog(LOG_WARNING, "Mesh tangents already exist");
Vector3 *tan1 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); Vector3 *tan1 = (Vector3 *)RL_MALLOC(mesh->vertexCount*sizeof(Vector3));
Vector3 *tan2 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); Vector3 *tan2 = (Vector3 *)RL_MALLOC(mesh->vertexCount*sizeof(Vector3));
for (int i = 0; i < mesh->vertexCount; i += 3) for (int i = 0; i < mesh->vertexCount; i += 3)
{ {
@ -2318,8 +2318,8 @@ void MeshTangents(Mesh *mesh)
#endif #endif
} }
free(tan1); RL_FREE(tan1);
free(tan2); RL_FREE(tan2);
// Load a new tangent attributes buffer // Load a new tangent attributes buffer
mesh->vboId[LOC_VERTEX_TANGENT] = rlLoadAttribBuffer(mesh->vaoId, LOC_VERTEX_TANGENT, mesh->tangents, mesh->vertexCount*4*sizeof(float), false); mesh->vboId[LOC_VERTEX_TANGENT] = rlLoadAttribBuffer(mesh->vaoId, LOC_VERTEX_TANGENT, mesh->tangents, mesh->vertexCount*4*sizeof(float), false);
@ -2746,7 +2746,7 @@ static Model LoadOBJ(const char *fileName)
long length = ftell(objFile); // Get file size long length = ftell(objFile); // Get file size
fseek(objFile, 0, SEEK_SET); // Reset file pointer fseek(objFile, 0, SEEK_SET); // Reset file pointer
data = (char *)malloc(length); data = (char *)RL_MALLOC(length);
fread(data, length, 1, objFile); fread(data, length, 1, objFile);
dataLength = length; dataLength = length;
@ -2763,12 +2763,12 @@ static Model LoadOBJ(const char *fileName)
// Init model meshes array // Init model meshes array
model.meshCount = meshCount; model.meshCount = meshCount;
model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); model.meshes = (Mesh *)RL_MALLOC(model.meshCount*sizeof(Mesh));
// Init model materials array // Init model materials array
model.materialCount = materialCount; model.materialCount = materialCount;
model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); model.materials = (Material *)RL_MALLOC(model.materialCount*sizeof(Material));
model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
/* /*
// Multiple meshes data reference // Multiple meshes data reference
@ -2787,9 +2787,9 @@ static Model LoadOBJ(const char *fileName)
memset(&mesh, 0, sizeof(Mesh)); memset(&mesh, 0, sizeof(Mesh));
mesh.vertexCount = attrib.num_faces*3; mesh.vertexCount = attrib.num_faces*3;
mesh.triangleCount = attrib.num_faces; mesh.triangleCount = attrib.num_faces;
mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
int vCount = 0; int vCount = 0;
int vtCount = 0; int vtCount = 0;
@ -2934,17 +2934,26 @@ static Model LoadIQM(const char *fileName)
typedef struct IQMTriangle { typedef struct IQMTriangle {
unsigned int vertex[3]; unsigned int vertex[3];
} IQMTriangle; } IQMTriangle;
// NOTE: Adjacency unused by default
typedef struct IQMAdjacency {
unsigned int triangle[3];
} IQMAdjacency;
typedef struct IQMJoint { typedef struct IQMJoint {
unsigned int name; unsigned int name;
int parent; int parent;
float translate[3], rotate[4], scale[3]; float translate[3], rotate[4], scale[3];
} IQMJoint; } IQMJoint;
typedef struct IQMVertexArray {
unsigned int type;
unsigned int flags;
unsigned int format;
unsigned int size;
unsigned int offset;
} IQMVertexArray;
// NOTE: Below IQM structures are not used but listed for reference
/*
typedef struct IQMAdjacency {
unsigned int triangle[3];
} IQMAdjacency;
typedef struct IQMPose { typedef struct IQMPose {
int parent; int parent;
@ -2960,19 +2969,11 @@ static Model LoadIQM(const char *fileName)
unsigned int flags; unsigned int flags;
} IQMAnim; } IQMAnim;
typedef struct IQMVertexArray {
unsigned int type;
unsigned int flags;
unsigned int format;
unsigned int size;
unsigned int offset;
} IQMVertexArray;
// NOTE: Bounds unused by default
typedef struct IQMBounds { typedef struct IQMBounds {
float bbmin[3], bbmax[3]; float bbmin[3], bbmax[3];
float xyradius, radius; float xyradius, radius;
} IQMBounds; } IQMBounds;
*/
//----------------------------------------------------------------------------------- //-----------------------------------------------------------------------------------
// IQM vertex data types // IQM vertex data types
@ -3028,12 +3029,12 @@ static Model LoadIQM(const char *fileName)
} }
// Meshes data processing // Meshes data processing
imesh = malloc(sizeof(IQMMesh)*iqm.num_meshes); imesh = RL_MALLOC(sizeof(IQMMesh)*iqm.num_meshes);
fseek(iqmFile, iqm.ofs_meshes, SEEK_SET); fseek(iqmFile, iqm.ofs_meshes, SEEK_SET);
fread(imesh, sizeof(IQMMesh)*iqm.num_meshes, 1, iqmFile); fread(imesh, sizeof(IQMMesh)*iqm.num_meshes, 1, iqmFile);
model.meshCount = iqm.num_meshes; model.meshCount = iqm.num_meshes;
model.meshes = malloc(model.meshCount*sizeof(Mesh)); model.meshes = RL_MALLOC(model.meshCount*sizeof(Mesh));
char name[MESH_NAME_LENGTH]; char name[MESH_NAME_LENGTH];
@ -3043,24 +3044,24 @@ static Model LoadIQM(const char *fileName)
fread(name, sizeof(char)*MESH_NAME_LENGTH, 1, iqmFile); // Mesh name not used... fread(name, sizeof(char)*MESH_NAME_LENGTH, 1, iqmFile); // Mesh name not used...
model.meshes[i].vertexCount = imesh[i].num_vertexes; model.meshes[i].vertexCount = imesh[i].num_vertexes;
model.meshes[i].vertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions model.meshes[i].vertices = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions
model.meshes[i].normals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals model.meshes[i].normals = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals
model.meshes[i].texcoords = malloc(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords model.meshes[i].texcoords = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords
model.meshes[i].boneIds = malloc(sizeof(int)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! model.meshes[i].boneIds = RL_MALLOC(sizeof(int)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported!
model.meshes[i].boneWeights = malloc(sizeof(float)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! model.meshes[i].boneWeights = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported!
model.meshes[i].triangleCount = imesh[i].num_triangles; model.meshes[i].triangleCount = imesh[i].num_triangles;
model.meshes[i].indices = malloc(sizeof(unsigned short)*model.meshes[i].triangleCount*3); model.meshes[i].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[i].triangleCount*3);
// Animated verted data, what we actually process for rendering // Animated verted data, what we actually process for rendering
// NOTE: Animated vertex should be re-uploaded to GPU (if not using GPU skinning) // NOTE: Animated vertex should be re-uploaded to GPU (if not using GPU skinning)
model.meshes[i].animVertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); model.meshes[i].animVertices = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3);
model.meshes[i].animNormals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); model.meshes[i].animNormals = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3);
} }
// Triangles data processing // Triangles data processing
tri = malloc(sizeof(IQMTriangle)*iqm.num_triangles); tri = RL_MALLOC(sizeof(IQMTriangle)*iqm.num_triangles);
fseek(iqmFile, iqm.ofs_triangles, SEEK_SET); fseek(iqmFile, iqm.ofs_triangles, SEEK_SET);
fread(tri, sizeof(IQMTriangle)*iqm.num_triangles, 1, iqmFile); fread(tri, sizeof(IQMTriangle)*iqm.num_triangles, 1, iqmFile);
@ -3079,7 +3080,7 @@ static Model LoadIQM(const char *fileName)
} }
// Vertex arrays data processing // Vertex arrays data processing
va = malloc(sizeof(IQMVertexArray)*iqm.num_vertexarrays); va = RL_MALLOC(sizeof(IQMVertexArray)*iqm.num_vertexarrays);
fseek(iqmFile, iqm.ofs_vertexarrays, SEEK_SET); fseek(iqmFile, iqm.ofs_vertexarrays, SEEK_SET);
fread(va, sizeof(IQMVertexArray)*iqm.num_vertexarrays, 1, iqmFile); fread(va, sizeof(IQMVertexArray)*iqm.num_vertexarrays, 1, iqmFile);
@ -3089,7 +3090,7 @@ static Model LoadIQM(const char *fileName)
{ {
case IQM_POSITION: case IQM_POSITION:
{ {
vertex = malloc(sizeof(float)*iqm.num_vertexes*3); vertex = RL_MALLOC(sizeof(float)*iqm.num_vertexes*3);
fseek(iqmFile, va[i].offset, SEEK_SET); fseek(iqmFile, va[i].offset, SEEK_SET);
fread(vertex, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); fread(vertex, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile);
@ -3106,7 +3107,7 @@ static Model LoadIQM(const char *fileName)
} break; } break;
case IQM_NORMAL: case IQM_NORMAL:
{ {
normal = malloc(sizeof(float)*iqm.num_vertexes*3); normal = RL_MALLOC(sizeof(float)*iqm.num_vertexes*3);
fseek(iqmFile, va[i].offset, SEEK_SET); fseek(iqmFile, va[i].offset, SEEK_SET);
fread(normal, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); fread(normal, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile);
@ -3123,7 +3124,7 @@ static Model LoadIQM(const char *fileName)
} break; } break;
case IQM_TEXCOORD: case IQM_TEXCOORD:
{ {
text = malloc(sizeof(float)*iqm.num_vertexes*2); text = RL_MALLOC(sizeof(float)*iqm.num_vertexes*2);
fseek(iqmFile, va[i].offset, SEEK_SET); fseek(iqmFile, va[i].offset, SEEK_SET);
fread(text, sizeof(float)*iqm.num_vertexes*2, 1, iqmFile); fread(text, sizeof(float)*iqm.num_vertexes*2, 1, iqmFile);
@ -3139,7 +3140,7 @@ static Model LoadIQM(const char *fileName)
} break; } break;
case IQM_BLENDINDEXES: case IQM_BLENDINDEXES:
{ {
blendi = malloc(sizeof(char)*iqm.num_vertexes*4); blendi = RL_MALLOC(sizeof(char)*iqm.num_vertexes*4);
fseek(iqmFile, va[i].offset, SEEK_SET); fseek(iqmFile, va[i].offset, SEEK_SET);
fread(blendi, sizeof(char)*iqm.num_vertexes*4, 1, iqmFile); fread(blendi, sizeof(char)*iqm.num_vertexes*4, 1, iqmFile);
@ -3155,7 +3156,7 @@ static Model LoadIQM(const char *fileName)
} break; } break;
case IQM_BLENDWEIGHTS: case IQM_BLENDWEIGHTS:
{ {
blendw = malloc(sizeof(unsigned char)*iqm.num_vertexes*4); blendw = RL_MALLOC(sizeof(unsigned char)*iqm.num_vertexes*4);
fseek(iqmFile,va[i].offset,SEEK_SET); fseek(iqmFile,va[i].offset,SEEK_SET);
fread(blendw,sizeof(unsigned char)*iqm.num_vertexes*4,1,iqmFile); fread(blendw,sizeof(unsigned char)*iqm.num_vertexes*4,1,iqmFile);
@ -3173,13 +3174,13 @@ static Model LoadIQM(const char *fileName)
} }
// Bones (joints) data processing // Bones (joints) data processing
ijoint = malloc(sizeof(IQMJoint)*iqm.num_joints); ijoint = RL_MALLOC(sizeof(IQMJoint)*iqm.num_joints);
fseek(iqmFile, iqm.ofs_joints, SEEK_SET); fseek(iqmFile, iqm.ofs_joints, SEEK_SET);
fread(ijoint, sizeof(IQMJoint)*iqm.num_joints, 1, iqmFile); fread(ijoint, sizeof(IQMJoint)*iqm.num_joints, 1, iqmFile);
model.boneCount = iqm.num_joints; model.boneCount = iqm.num_joints;
model.bones = malloc(sizeof(BoneInfo)*iqm.num_joints); model.bones = RL_MALLOC(sizeof(BoneInfo)*iqm.num_joints);
model.bindPose = malloc(sizeof(Transform)*iqm.num_joints); model.bindPose = RL_MALLOC(sizeof(Transform)*iqm.num_joints);
for (int i = 0; i < iqm.num_joints; i++) for (int i = 0; i < iqm.num_joints; i++)
{ {
@ -3216,15 +3217,15 @@ static Model LoadIQM(const char *fileName)
} }
fclose(iqmFile); fclose(iqmFile);
free(imesh); RL_FREE(imesh);
free(tri); RL_FREE(tri);
free(va); RL_FREE(va);
free(vertex); RL_FREE(vertex);
free(normal); RL_FREE(normal);
free(text); RL_FREE(text);
free(blendi); RL_FREE(blendi);
free(blendw); RL_FREE(blendw);
free(ijoint); RL_FREE(ijoint);
return model; return model;
} }
@ -3249,7 +3250,7 @@ static Model LoadGLTF(const char *fileName)
int size = ftell(gltfFile); int size = ftell(gltfFile);
fseek(gltfFile, 0, SEEK_SET); fseek(gltfFile, 0, SEEK_SET);
void *buffer = malloc(size); void *buffer = RL_MALLOC(size);
fread(buffer, size, 1, gltfFile); fread(buffer, size, 1, gltfFile);
fclose(gltfFile); fclose(gltfFile);
@ -3259,7 +3260,7 @@ static Model LoadGLTF(const char *fileName)
cgltf_data *data; cgltf_data *data;
cgltf_result result = cgltf_parse(&options, buffer, size, &data); cgltf_result result = cgltf_parse(&options, buffer, size, &data);
free(buffer); RL_FREE(buffer);
if (result == cgltf_result_success) if (result == cgltf_result_success)
{ {
@ -3270,7 +3271,7 @@ static Model LoadGLTF(const char *fileName)
// Process glTF data and map to model // Process glTF data and map to model
model.meshCount = data->meshes_count; model.meshCount = data->meshes_count;
model.meshes = malloc(model.meshCount*sizeof(Mesh)); model.meshes = RL_MALLOC(model.meshCount*sizeof(Mesh));
for (int i = 0; i < model.meshCount; i++) for (int i = 0; i < model.meshCount; i++)
{ {
@ -3282,11 +3283,11 @@ static Model LoadGLTF(const char *fileName)
model.meshes[i].triangleCount = data->meshes[i].primitives_count; model.meshes[i].triangleCount = data->meshes[i].primitives_count;
// data.meshes[i].weights not used (array of weights to be applied to the Morph Targets) // data.meshes[i].weights not used (array of weights to be applied to the Morph Targets)
model.meshes[i].vertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions model.meshes[i].vertices = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions
model.meshes[i].normals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals model.meshes[i].normals = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals
model.meshes[i].texcoords = malloc(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords model.meshes[i].texcoords = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords
model.meshes[i].indices = malloc(sizeof(unsigned short)*model.meshes[i].triangleCount*3); model.meshes[i].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[i].triangleCount*3);
} }
} }

View file

@ -567,7 +567,7 @@ void SetMasterVolume(float volume)
// Create a new audio buffer. Initially filled with silence // Create a new audio buffer. Initially filled with silence
AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 bufferSizeInFrames, AudioBufferUsage usage) AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 bufferSizeInFrames, AudioBufferUsage usage)
{ {
AudioBuffer *audioBuffer = (AudioBuffer *)calloc(sizeof(*audioBuffer) + (bufferSizeInFrames*channels*ma_get_bytes_per_sample(format)), 1); AudioBuffer *audioBuffer = (AudioBuffer *)RL_CALLOC(sizeof(*audioBuffer) + (bufferSizeInFrames*channels*ma_get_bytes_per_sample(format)), 1);
if (audioBuffer == NULL) if (audioBuffer == NULL)
{ {
TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to allocate memory for audio buffer"); TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to allocate memory for audio buffer");
@ -591,7 +591,7 @@ AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 s
if (result != MA_SUCCESS) if (result != MA_SUCCESS)
{ {
TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to create data conversion pipeline"); TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to create data conversion pipeline");
free(audioBuffer); RL_FREE(audioBuffer);
return NULL; return NULL;
} }
@ -623,7 +623,7 @@ void DeleteAudioBuffer(AudioBuffer *audioBuffer)
} }
UntrackAudioBuffer(audioBuffer); UntrackAudioBuffer(audioBuffer);
free(audioBuffer); RL_FREE(audioBuffer);
} }
// Check if an audio buffer is playing // Check if an audio buffer is playing
@ -863,7 +863,7 @@ Sound LoadSoundFromWave(Wave wave)
// Unload wave data // Unload wave data
void UnloadWave(Wave wave) void UnloadWave(Wave wave)
{ {
if (wave.data != NULL) free(wave.data); if (wave.data != NULL) RL_FREE(wave.data);
TraceLog(LOG_INFO, "Unloaded wave data from RAM"); TraceLog(LOG_INFO, "Unloaded wave data from RAM");
} }
@ -1017,7 +1017,7 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
return; return;
} }
void *data = malloc(frameCount*channels*(sampleSize/8)); void *data = RL_MALLOC(frameCount*channels*(sampleSize/8));
frameCount = (ma_uint32)ma_convert_frames(data, formatOut, channels, sampleRate, wave->data, formatIn, wave->channels, wave->sampleRate, frameCountIn); frameCount = (ma_uint32)ma_convert_frames(data, formatOut, channels, sampleRate, wave->data, formatIn, wave->channels, wave->sampleRate, frameCountIn);
if (frameCount == 0) if (frameCount == 0)
@ -1030,7 +1030,7 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
wave->sampleSize = sampleSize; wave->sampleSize = sampleSize;
wave->sampleRate = sampleRate; wave->sampleRate = sampleRate;
wave->channels = channels; wave->channels = channels;
free(wave->data); RL_FREE(wave->data);
wave->data = data; wave->data = data;
} }
@ -1039,7 +1039,7 @@ Wave WaveCopy(Wave wave)
{ {
Wave newWave = { 0 }; Wave newWave = { 0 };
newWave.data = malloc(wave.sampleCount*wave.sampleSize/8*wave.channels); newWave.data = RL_MALLOC(wave.sampleCount*wave.sampleSize/8*wave.channels);
if (newWave.data != NULL) if (newWave.data != NULL)
{ {
@ -1064,11 +1064,11 @@ void WaveCrop(Wave *wave, int initSample, int finalSample)
{ {
int sampleCount = finalSample - initSample; int sampleCount = finalSample - initSample;
void *data = malloc(sampleCount*wave->sampleSize/8*wave->channels); void *data = RL_MALLOC(sampleCount*wave->sampleSize/8*wave->channels);
memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->channels*wave->sampleSize/8); memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->channels*wave->sampleSize/8);
free(wave->data); RL_FREE(wave->data);
wave->data = data; wave->data = data;
} }
else TraceLog(LOG_WARNING, "Wave crop range out of bounds"); else TraceLog(LOG_WARNING, "Wave crop range out of bounds");
@ -1078,7 +1078,7 @@ void WaveCrop(Wave *wave, int initSample, int finalSample)
// NOTE: Returned sample values are normalized to range [-1..1] // NOTE: Returned sample values are normalized to range [-1..1]
float *GetWaveData(Wave wave) float *GetWaveData(Wave wave)
{ {
float *samples = (float *)malloc(wave.sampleCount*wave.channels*sizeof(float)); float *samples = (float *)RL_MALLOC(wave.sampleCount*wave.channels*sizeof(float));
for (unsigned int i = 0; i < wave.sampleCount; i++) for (unsigned int i = 0; i < wave.sampleCount; i++)
{ {
@ -1100,7 +1100,7 @@ float *GetWaveData(Wave wave)
// Load music stream from file // Load music stream from file
Music LoadMusicStream(const char *fileName) Music LoadMusicStream(const char *fileName)
{ {
Music music = (MusicData *)malloc(sizeof(MusicData)); Music music = (MusicData *)RL_MALLOC(sizeof(MusicData));
bool musicLoaded = true; bool musicLoaded = true;
#if defined(SUPPORT_FILEFORMAT_OGG) #if defined(SUPPORT_FILEFORMAT_OGG)
@ -1228,7 +1228,7 @@ Music LoadMusicStream(const char *fileName)
if (false) {} if (false) {}
#endif #endif
#if defined(SUPPORT_FILEFORMAT_FLAC) #if defined(SUPPORT_FILEFORMAT_FLAC)
else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_free(music->ctxFlac); else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_RL_FREE(music->ctxFlac);
#endif #endif
#if defined(SUPPORT_FILEFORMAT_MP3) #if defined(SUPPORT_FILEFORMAT_MP3)
else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3); else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3);
@ -1240,7 +1240,7 @@ Music LoadMusicStream(const char *fileName)
else if (music->ctxType == MUSIC_MODULE_MOD) jar_mod_unload(&music->ctxMod); else if (music->ctxType == MUSIC_MODULE_MOD) jar_mod_unload(&music->ctxMod);
#endif #endif
free(music); RL_FREE(music);
music = NULL; music = NULL;
TraceLog(LOG_WARNING, "[%s] Music file could not be opened", fileName); TraceLog(LOG_WARNING, "[%s] Music file could not be opened", fileName);
@ -1262,7 +1262,7 @@ void UnloadMusicStream(Music music)
if (false) {} if (false) {}
#endif #endif
#if defined(SUPPORT_FILEFORMAT_FLAC) #if defined(SUPPORT_FILEFORMAT_FLAC)
else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_free(music->ctxFlac); else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_RL_FREE(music->ctxFlac);
#endif #endif
#if defined(SUPPORT_FILEFORMAT_MP3) #if defined(SUPPORT_FILEFORMAT_MP3)
else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3); else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3);
@ -1274,7 +1274,7 @@ void UnloadMusicStream(Music music)
else if (music->ctxType == MUSIC_MODULE_MOD) jar_mod_unload(&music->ctxMod); else if (music->ctxType == MUSIC_MODULE_MOD) jar_mod_unload(&music->ctxMod);
#endif #endif
free(music); RL_FREE(music);
} }
// Start music playing (open stream) // Start music playing (open stream)
@ -1357,7 +1357,7 @@ void UpdateMusicStream(Music music)
unsigned int subBufferSizeInFrames = ((AudioBuffer *)music->stream.audioBuffer)->bufferSizeInFrames/2; unsigned int subBufferSizeInFrames = ((AudioBuffer *)music->stream.audioBuffer)->bufferSizeInFrames/2;
// NOTE: Using dynamic allocation because it could require more than 16KB // NOTE: Using dynamic allocation because it could require more than 16KB
void *pcm = calloc(subBufferSizeInFrames*music->stream.channels*music->stream.sampleSize/8, 1); void *pcm = RL_CALLOC(subBufferSizeInFrames*music->stream.channels*music->stream.sampleSize/8, 1);
int samplesCount = 0; // Total size of data steamed in L+R samples for xm floats, individual L or R for ogg shorts int samplesCount = 0; // Total size of data steamed in L+R samples for xm floats, individual L or R for ogg shorts
@ -1427,7 +1427,7 @@ void UpdateMusicStream(Music music)
} }
// Free allocated pcm data // Free allocated pcm data
free(pcm); RL_FREE(pcm);
// Reset audio stream for looping // Reset audio stream for looping
if (streamEnding) if (streamEnding)
@ -1750,7 +1750,7 @@ static Wave LoadWAV(const char *fileName)
else else
{ {
// Allocate memory for data // Allocate memory for data
wave.data = malloc(wavData.subChunkSize); wave.data = RL_MALLOC(wavData.subChunkSize);
// Read in the sound data into the soundData variable // Read in the sound data into the soundData variable
fread(wave.data, wavData.subChunkSize, 1, wavFile); fread(wave.data, wavData.subChunkSize, 1, wavFile);
@ -1891,7 +1891,7 @@ static Wave LoadOGG(const char *fileName)
float totalSeconds = stb_vorbis_stream_length_in_seconds(oggFile); float totalSeconds = stb_vorbis_stream_length_in_seconds(oggFile);
if (totalSeconds > 10) TraceLog(LOG_WARNING, "[%s] Ogg audio length is larger than 10 seconds (%f), that's a big file in memory, consider music streaming", fileName, totalSeconds); if (totalSeconds > 10) TraceLog(LOG_WARNING, "[%s] Ogg audio length is larger than 10 seconds (%f), that's a big file in memory, consider music streaming", fileName, totalSeconds);
wave.data = (short *)malloc(wave.sampleCount*wave.channels*sizeof(short)); wave.data = (short *)RL_MALLOC(wave.sampleCount*wave.channels*sizeof(short));
// NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!) // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!)
int numSamplesOgg = stb_vorbis_get_samples_short_interleaved(oggFile, info.channels, (short *)wave.data, wave.sampleCount*wave.channels); int numSamplesOgg = stb_vorbis_get_samples_short_interleaved(oggFile, info.channels, (short *)wave.data, wave.sampleCount*wave.channels);

View file

@ -56,7 +56,16 @@
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Defines and Macros // Defines and Macros
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
//... // Allow custom memory allocators
#ifndef RL_MALLOC
#define RL_MALLOC(sz) malloc(sz)
#endif
#ifndef RL_CALLOC
#define RL_CALLOC(n,sz) calloc(n,sz)
#endif
#ifndef RL_FREE
#define RL_FREE(p) free(p)
#endif
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Types and Structures Definition // Types and Structures Definition

View file

@ -99,6 +99,17 @@
// Shader and material limits // Shader and material limits
#define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct #define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct
#define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct #define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct
// Allow custom memory allocators
#ifndef RL_MALLOC
#define RL_MALLOC(sz) malloc(sz)
#endif
#ifndef RL_CALLOC
#define RL_CALLOC(n,sz) calloc(n,sz)
#endif
#ifndef RL_FREE
#define RL_FREE(p) free(p)
#endif
// NOTE: MSC C++ compiler does not support compound literals (C99 feature) // NOTE: MSC C++ compiler does not support compound literals (C99 feature)
// Plain structures in C++ (without constructors) can be initialized from { } initializers. // Plain structures in C++ (without constructors) can be initialized from { } initializers.

View file

@ -1492,7 +1492,7 @@ void rlglInit(int width, int height)
glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); glGetIntegerv(GL_NUM_EXTENSIONS, &numExt);
#if defined(_MSC_VER) #if defined(_MSC_VER)
const char **extList = malloc(sizeof(const char *)*numExt); const char **extList = RL_MALLOC(sizeof(const char *)*numExt);
#else #else
const char *extList[numExt]; const char *extList[numExt];
#endif #endif
@ -1504,7 +1504,7 @@ void rlglInit(int width, int height)
// NOTE: We have to duplicate string because glGetString() returns a const string // NOTE: We have to duplicate string because glGetString() returns a const string
int len = strlen(extensions) + 1; int len = strlen(extensions) + 1;
char *extensionsDup = (char *)malloc(len); char *extensionsDup = (char *)RL_MALLOC(len);
strcpy(extensionsDup, extensions); strcpy(extensionsDup, extensions);
// NOTE: String could be splitted using strtok() function (string.h) // NOTE: String could be splitted using strtok() function (string.h)
@ -1520,7 +1520,7 @@ void rlglInit(int width, int height)
extList[numExt] = strtok(NULL, " "); extList[numExt] = strtok(NULL, " ");
} }
free(extensionsDup); // Duplicated string must be deallocated RL_FREE(extensionsDup); // Duplicated string must be deallocated
numExt -= 1; numExt -= 1;
#endif #endif
@ -1595,7 +1595,7 @@ void rlglInit(int width, int height)
} }
#if defined(_WIN32) && defined(_MSC_VER) #if defined(_WIN32) && defined(_MSC_VER)
free(extList); RL_FREE(extList);
#endif #endif
#if defined(GRAPHICS_API_OPENGL_ES2) #if defined(GRAPHICS_API_OPENGL_ES2)
@ -1640,7 +1640,7 @@ void rlglInit(int width, int height)
transformMatrix = MatrixIdentity(); transformMatrix = MatrixIdentity();
// Init draw calls tracking system // Init draw calls tracking system
draws = (DrawCall *)malloc(sizeof(DrawCall)*MAX_DRAWCALL_REGISTERED); draws = (DrawCall *)RL_MALLOC(sizeof(DrawCall)*MAX_DRAWCALL_REGISTERED);
for (int i = 0; i < MAX_DRAWCALL_REGISTERED; i++) for (int i = 0; i < MAX_DRAWCALL_REGISTERED; i++)
{ {
@ -1710,7 +1710,7 @@ void rlglClose(void)
TraceLog(LOG_INFO, "[TEX ID %i] Unloaded texture data (base white texture) from VRAM", defaultTextureId); TraceLog(LOG_INFO, "[TEX ID %i] Unloaded texture data (base white texture) from VRAM", defaultTextureId);
free(draws); RL_FREE(draws);
#endif #endif
} }
@ -2300,7 +2300,7 @@ void rlGenerateMipmaps(Texture2D *texture)
} }
texture->mipmaps = mipmapCount + 1; texture->mipmaps = mipmapCount + 1;
free(data); // Once mipmaps have been generated and data has been uploaded to GPU VRAM, we can discard RAM data RL_FREE(data); // Once mipmaps have been generated and data has been uploaded to GPU VRAM, we can discard RAM data
TraceLog(LOG_WARNING, "[TEX ID %i] Mipmaps [%i] generated manually on CPU side", texture->id, texture->mipmaps); TraceLog(LOG_WARNING, "[TEX ID %i] Mipmaps [%i] generated manually on CPU side", texture->id, texture->mipmaps);
} }
@ -2735,18 +2735,18 @@ void rlDrawMesh(Mesh mesh, Material material, Matrix transform)
// Unload mesh data from CPU and GPU // Unload mesh data from CPU and GPU
void rlUnloadMesh(Mesh *mesh) void rlUnloadMesh(Mesh *mesh)
{ {
free(mesh->vertices); RL_FREE(mesh->vertices);
free(mesh->texcoords); RL_FREE(mesh->texcoords);
free(mesh->normals); RL_FREE(mesh->normals);
free(mesh->colors); RL_FREE(mesh->colors);
free(mesh->tangents); RL_FREE(mesh->tangents);
free(mesh->texcoords2); RL_FREE(mesh->texcoords2);
free(mesh->indices); RL_FREE(mesh->indices);
free(mesh->animVertices); RL_FREE(mesh->animVertices);
free(mesh->animNormals); RL_FREE(mesh->animNormals);
free(mesh->boneWeights); RL_FREE(mesh->boneWeights);
free(mesh->boneIds); RL_FREE(mesh->boneIds);
rlDeleteBuffers(mesh->vboId[0]); // vertex rlDeleteBuffers(mesh->vboId[0]); // vertex
rlDeleteBuffers(mesh->vboId[1]); // texcoords rlDeleteBuffers(mesh->vboId[1]); // texcoords
@ -2762,14 +2762,14 @@ void rlUnloadMesh(Mesh *mesh)
// Read screen pixel data (color buffer) // Read screen pixel data (color buffer)
unsigned char *rlReadScreenPixels(int width, int height) unsigned char *rlReadScreenPixels(int width, int height)
{ {
unsigned char *screenData = (unsigned char *)calloc(width*height*4, sizeof(unsigned char)); unsigned char *screenData = (unsigned char *)RL_CALLOC(width*height*4, sizeof(unsigned char));
// NOTE 1: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer // NOTE 1: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer
// NOTE 2: We are getting alpha channel! Be careful, it can be transparent if not cleared properly! // NOTE 2: We are getting alpha channel! Be careful, it can be transparent if not cleared properly!
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData);
// Flip image vertically! // Flip image vertically!
unsigned char *imgData = (unsigned char *)malloc(width*height*sizeof(unsigned char)*4); unsigned char *imgData = (unsigned char *)RL_MALLOC(width*height*sizeof(unsigned char)*4);
for (int y = height - 1; y >= 0; y--) for (int y = height - 1; y >= 0; y--)
{ {
@ -2783,7 +2783,7 @@ unsigned char *rlReadScreenPixels(int width, int height)
} }
} }
free(screenData); RL_FREE(screenData);
return imgData; // NOTE: image data should be freed return imgData; // NOTE: image data should be freed
} }
@ -2815,7 +2815,7 @@ void *rlReadTexturePixels(Texture2D texture)
if ((glInternalFormat != -1) && (texture.format < COMPRESSED_DXT1_RGB)) if ((glInternalFormat != -1) && (texture.format < COMPRESSED_DXT1_RGB))
{ {
pixels = (unsigned char *)malloc(size); pixels = (unsigned char *)RL_MALLOC(size);
glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels); glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels);
} }
else TraceLog(LOG_WARNING, "Texture data retrieval not suported for pixel format"); else TraceLog(LOG_WARNING, "Texture data retrieval not suported for pixel format");
@ -2841,7 +2841,7 @@ void *rlReadTexturePixels(Texture2D texture)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.id, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.id, 0);
// Allocate enough memory to read back our texture data // Allocate enough memory to read back our texture data
pixels = (unsigned char *)malloc(GetPixelDataSize(texture.width, texture.height, texture.format)); pixels = (unsigned char *)RL_MALLOC(GetPixelDataSize(texture.width, texture.height, texture.format));
// Get OpenGL internal formats and data type from our texture format // Get OpenGL internal formats and data type from our texture format
unsigned int glInternalFormat, glFormat, glType; unsigned int glInternalFormat, glFormat, glType;
@ -2911,7 +2911,7 @@ char *LoadText(const char *fileName)
if (size > 0) if (size > 0)
{ {
text = (char *)malloc(sizeof(char)*(size + 1)); text = (char *)RL_MALLOC(sizeof(char)*(size + 1));
int count = fread(text, sizeof(char), size, textFile); int count = fread(text, sizeof(char), size, textFile);
text[count] = '\0'; text[count] = '\0';
} }
@ -2938,8 +2938,8 @@ Shader LoadShader(const char *vsFileName, const char *fsFileName)
shader = LoadShaderCode(vShaderStr, fShaderStr); shader = LoadShaderCode(vShaderStr, fShaderStr);
if (vShaderStr != NULL) free(vShaderStr); if (vShaderStr != NULL) RL_FREE(vShaderStr);
if (fShaderStr != NULL) free(fShaderStr); if (fShaderStr != NULL) RL_FREE(fShaderStr);
return shader; return shader;
} }
@ -3758,7 +3758,7 @@ static unsigned int CompileShader(const char *shaderStr, int type)
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
#if defined(_MSC_VER) #if defined(_MSC_VER)
char *log = malloc(maxLength); char *log = RL_MALLOC(maxLength);
#else #else
char log[maxLength]; char log[maxLength];
#endif #endif
@ -3767,7 +3767,7 @@ static unsigned int CompileShader(const char *shaderStr, int type)
TraceLog(LOG_INFO, "%s", log); TraceLog(LOG_INFO, "%s", log);
#if defined(_MSC_VER) #if defined(_MSC_VER)
free(log); RL_FREE(log);
#endif #endif
} }
else TraceLog(LOG_INFO, "[SHDR ID %i] Shader compiled successfully", shader); else TraceLog(LOG_INFO, "[SHDR ID %i] Shader compiled successfully", shader);
@ -3814,7 +3814,7 @@ static unsigned int LoadShaderProgram(unsigned int vShaderId, unsigned int fShad
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
#if defined(_MSC_VER) #if defined(_MSC_VER)
char *log = malloc(maxLength); char *log = RL_MALLOC(maxLength);
#else #else
char log[maxLength]; char log[maxLength];
#endif #endif
@ -3823,7 +3823,7 @@ static unsigned int LoadShaderProgram(unsigned int vShaderId, unsigned int fShad
TraceLog(LOG_INFO, "%s", log); TraceLog(LOG_INFO, "%s", log);
#if defined(_MSC_VER) #if defined(_MSC_VER)
free(log); RL_FREE(log);
#endif #endif
glDeleteProgram(program); glDeleteProgram(program);
@ -3984,13 +3984,13 @@ static void LoadBuffersDefault(void)
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
for (int i = 0; i < MAX_BATCH_BUFFERING; i++) for (int i = 0; i < MAX_BATCH_BUFFERING; i++)
{ {
vertexData[i].vertices = (float *)malloc(sizeof(float)*3*4*MAX_BATCH_ELEMENTS); // 3 float by vertex, 4 vertex by quad vertexData[i].vertices = (float *)RL_MALLOC(sizeof(float)*3*4*MAX_BATCH_ELEMENTS); // 3 float by vertex, 4 vertex by quad
vertexData[i].texcoords = (float *)malloc(sizeof(float)*2*4*MAX_BATCH_ELEMENTS); // 2 float by texcoord, 4 texcoord by quad vertexData[i].texcoords = (float *)RL_MALLOC(sizeof(float)*2*4*MAX_BATCH_ELEMENTS); // 2 float by texcoord, 4 texcoord by quad
vertexData[i].colors = (unsigned char *)malloc(sizeof(unsigned char)*4*4*MAX_BATCH_ELEMENTS); // 4 float by color, 4 colors by quad vertexData[i].colors = (unsigned char *)RL_MALLOC(sizeof(unsigned char)*4*4*MAX_BATCH_ELEMENTS); // 4 float by color, 4 colors by quad
#if defined(GRAPHICS_API_OPENGL_33) #if defined(GRAPHICS_API_OPENGL_33)
vertexData[i].indices = (unsigned int *)malloc(sizeof(unsigned int)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices) vertexData[i].indices = (unsigned int *)RL_MALLOC(sizeof(unsigned int)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices)
#elif defined(GRAPHICS_API_OPENGL_ES2) #elif defined(GRAPHICS_API_OPENGL_ES2)
vertexData[i].indices = (unsigned short *)malloc(sizeof(unsigned short)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices) vertexData[i].indices = (unsigned short *)RL_MALLOC(sizeof(unsigned short)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices)
#endif #endif
for (int j = 0; j < (3*4*MAX_BATCH_ELEMENTS); j++) vertexData[i].vertices[j] = 0.0f; for (int j = 0; j < (3*4*MAX_BATCH_ELEMENTS); j++) vertexData[i].vertices[j] = 0.0f;
@ -4266,10 +4266,10 @@ static void UnloadBuffersDefault(void)
if (vaoSupported) glDeleteVertexArrays(1, &vertexData[i].vaoId); if (vaoSupported) glDeleteVertexArrays(1, &vertexData[i].vaoId);
// Free vertex arrays memory from CPU (RAM) // Free vertex arrays memory from CPU (RAM)
free(vertexData[i].vertices); RL_FREE(vertexData[i].vertices);
free(vertexData[i].texcoords); RL_FREE(vertexData[i].texcoords);
free(vertexData[i].colors); RL_FREE(vertexData[i].colors);
free(vertexData[i].indices); RL_FREE(vertexData[i].indices);
} }
} }
@ -4444,7 +4444,7 @@ static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight)
// Generate mipmaps // Generate mipmaps
// NOTE: Every mipmap data is stored after data // NOTE: Every mipmap data is stored after data
Color *image = (Color *)malloc(width*height*sizeof(Color)); Color *image = (Color *)RL_MALLOC(width*height*sizeof(Color));
Color *mipmap = NULL; Color *mipmap = NULL;
int offset = 0; int offset = 0;
int j = 0; int j = 0;
@ -4481,13 +4481,13 @@ static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight)
j++; j++;
} }
free(image); RL_FREE(image);
image = mipmap; image = mipmap;
mipmap = NULL; mipmap = NULL;
} }
free(mipmap); // free mipmap data RL_FREE(mipmap); // free mipmap data
return mipmapCount; return mipmapCount;
} }
@ -4501,7 +4501,7 @@ static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight)
int width = srcWidth/2; int width = srcWidth/2;
int height = srcHeight/2; int height = srcHeight/2;
Color *mipmap = (Color *)malloc(width*height*sizeof(Color)); Color *mipmap = (Color *)RL_MALLOC(width*height*sizeof(Color));
// Scaling algorithm works perfectly (box-filter) // Scaling algorithm works perfectly (box-filter)
for (int y = 0; y < height; y++) for (int y = 0; y < height; y++)

View file

@ -174,7 +174,7 @@ extern void LoadDefaultFont(void)
int imWidth = 128; int imWidth = 128;
int imHeight = 128; int imHeight = 128;
Color *imagePixels = (Color *)malloc(imWidth*imHeight*sizeof(Color)); Color *imagePixels = (Color *)RL_MALLOC(imWidth*imHeight*sizeof(Color));
for (int i = 0; i < imWidth*imHeight; i++) imagePixels[i] = BLANK; // Initialize array for (int i = 0; i < imWidth*imHeight; i++) imagePixels[i] = BLANK; // Initialize array
@ -196,7 +196,7 @@ extern void LoadDefaultFont(void)
Image image = LoadImageEx(imagePixels, imWidth, imHeight); Image image = LoadImageEx(imagePixels, imWidth, imHeight);
ImageFormat(&image, UNCOMPRESSED_GRAY_ALPHA); ImageFormat(&image, UNCOMPRESSED_GRAY_ALPHA);
free(imagePixels); RL_FREE(imagePixels);
defaultFont.texture = LoadTextureFromImage(image); defaultFont.texture = LoadTextureFromImage(image);
UnloadImage(image); UnloadImage(image);
@ -206,7 +206,7 @@ extern void LoadDefaultFont(void)
// Allocate space for our characters info data // Allocate space for our characters info data
// NOTE: This memory should be freed at end! --> CloseWindow() // NOTE: This memory should be freed at end! --> CloseWindow()
defaultFont.chars = (CharInfo *)malloc(defaultFont.charsCount*sizeof(CharInfo)); defaultFont.chars = (CharInfo *)RL_MALLOC(defaultFont.charsCount*sizeof(CharInfo));
int currentLine = 0; int currentLine = 0;
int currentPosX = charsDivisor; int currentPosX = charsDivisor;
@ -249,7 +249,7 @@ extern void LoadDefaultFont(void)
extern void UnloadDefaultFont(void) extern void UnloadDefaultFont(void)
{ {
UnloadTexture(defaultFont.texture); UnloadTexture(defaultFont.texture);
free(defaultFont.chars); RL_FREE(defaultFont.chars);
} }
#endif // SUPPORT_DEFAULT_FONT #endif // SUPPORT_DEFAULT_FONT
@ -407,7 +407,7 @@ Font LoadFontFromImage(Image image, Color key, int firstChar)
// Create a new image with the processed color data (key color replaced by BLANK) // Create a new image with the processed color data (key color replaced by BLANK)
Image fontClear = LoadImageEx(pixels, image.width, image.height); Image fontClear = LoadImageEx(pixels, image.width, image.height);
free(pixels); // Free pixels array memory RL_FREE(pixels); // Free pixels array memory
// Create spritefont with all data parsed from image // Create spritefont with all data parsed from image
Font spriteFont = { 0 }; Font spriteFont = { 0 };
@ -419,7 +419,7 @@ Font LoadFontFromImage(Image image, Color key, int firstChar)
// We got tempCharValues and tempCharsRecs populated with chars data // We got tempCharValues and tempCharsRecs populated with chars data
// Now we move temp data to sized charValues and charRecs arrays // Now we move temp data to sized charValues and charRecs arrays
spriteFont.chars = (CharInfo *)malloc(spriteFont.charsCount*sizeof(CharInfo)); spriteFont.chars = (CharInfo *)RL_MALLOC(spriteFont.charsCount*sizeof(CharInfo));
for (int i = 0; i < spriteFont.charsCount; i++) for (int i = 0; i < spriteFont.charsCount; i++)
{ {
@ -466,7 +466,7 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c
long size = ftell(fontFile); // Get file size long size = ftell(fontFile); // Get file size
fseek(fontFile, 0, SEEK_SET); // Reset file pointer fseek(fontFile, 0, SEEK_SET); // Reset file pointer
unsigned char *fontBuffer = (unsigned char *)malloc(size); unsigned char *fontBuffer = (unsigned char *)RL_MALLOC(size);
fread(fontBuffer, size, 1, fontFile); fread(fontBuffer, size, 1, fontFile);
fclose(fontFile); fclose(fontFile);
@ -491,12 +491,12 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c
int genFontChars = false; int genFontChars = false;
if (fontChars == NULL) if (fontChars == NULL)
{ {
fontChars = (int *)malloc(charsCount*sizeof(int)); fontChars = (int *)RL_MALLOC(charsCount*sizeof(int));
for (int i = 0; i < charsCount; i++) fontChars[i] = i + 32; for (int i = 0; i < charsCount; i++) fontChars[i] = i + 32;
genFontChars = true; genFontChars = true;
} }
chars = (CharInfo *)malloc(charsCount*sizeof(CharInfo)); chars = (CharInfo *)RL_MALLOC(charsCount*sizeof(CharInfo));
// NOTE: Using simple packaging, one char after another // NOTE: Using simple packaging, one char after another
for (int i = 0; i < charsCount; i++) for (int i = 0; i < charsCount; i++)
@ -540,8 +540,8 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c
chars[i].advanceX *= scaleFactor; chars[i].advanceX *= scaleFactor;
} }
free(fontBuffer); RL_FREE(fontBuffer);
if (genFontChars) free(fontChars); if (genFontChars) RL_FREE(fontChars);
} }
else TraceLog(LOG_WARNING, "[%s] TTF file could not be opened", fileName); else TraceLog(LOG_WARNING, "[%s] TTF file could not be opened", fileName);
#else #else
@ -572,7 +572,7 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi
atlas.width = imageSize; // Atlas bitmap width atlas.width = imageSize; // Atlas bitmap width
atlas.height = imageSize; // Atlas bitmap height atlas.height = imageSize; // Atlas bitmap height
atlas.data = (unsigned char *)calloc(1, atlas.width*atlas.height); // Create a bitmap to store characters (8 bpp) atlas.data = (unsigned char *)RL_CALLOC(1, atlas.width*atlas.height); // Create a bitmap to store characters (8 bpp)
atlas.format = UNCOMPRESSED_GRAYSCALE; atlas.format = UNCOMPRESSED_GRAYSCALE;
atlas.mipmaps = 1; atlas.mipmaps = 1;
@ -619,11 +619,11 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi
{ {
TraceLog(LOG_DEBUG, "Using Skyline packing algorythm!"); TraceLog(LOG_DEBUG, "Using Skyline packing algorythm!");
stbrp_context *context = (stbrp_context *)malloc(sizeof(*context)); stbrp_context *context = (stbrp_context *)RL_MALLOC(sizeof(*context));
stbrp_node *nodes = (stbrp_node *)malloc(charsCount*sizeof(*nodes)); stbrp_node *nodes = (stbrp_node *)RL_MALLOC(charsCount*sizeof(*nodes));
stbrp_init_target(context, atlas.width, atlas.height, nodes, charsCount); stbrp_init_target(context, atlas.width, atlas.height, nodes, charsCount);
stbrp_rect *rects = (stbrp_rect *)malloc(charsCount*sizeof(stbrp_rect)); stbrp_rect *rects = (stbrp_rect *)RL_MALLOC(charsCount*sizeof(stbrp_rect));
// Fill rectangles for packaging // Fill rectangles for packaging
for (int i = 0; i < charsCount; i++) for (int i = 0; i < charsCount; i++)
@ -655,16 +655,16 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi
else TraceLog(LOG_WARNING, "Character could not be packed: %i", i); else TraceLog(LOG_WARNING, "Character could not be packed: %i", i);
} }
free(rects); RL_FREE(rects);
free(nodes); RL_FREE(nodes);
free(context); RL_FREE(context);
} }
// TODO: Crop image if required for smaller size // TODO: Crop image if required for smaller size
// Convert image data from GRAYSCALE to GRAY_ALPHA // Convert image data from GRAYSCALE to GRAY_ALPHA
// WARNING: ImageAlphaMask(&atlas, atlas) does not work in this case, requires manual operation // WARNING: ImageAlphaMask(&atlas, atlas) does not work in this case, requires manual operation
unsigned char *dataGrayAlpha = (unsigned char *)malloc(imageSize*imageSize*sizeof(unsigned char)*2); // Two channels unsigned char *dataGrayAlpha = (unsigned char *)RL_MALLOC(imageSize*imageSize*sizeof(unsigned char)*2); // Two channels
for (int i = 0, k = 0; i < atlas.width*atlas.height; i++, k += 2) for (int i = 0, k = 0; i < atlas.width*atlas.height; i++, k += 2)
{ {
@ -672,7 +672,7 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi
dataGrayAlpha[k + 1] = ((unsigned char *)atlas.data)[i]; dataGrayAlpha[k + 1] = ((unsigned char *)atlas.data)[i];
} }
free(atlas.data); RL_FREE(atlas.data);
atlas.data = dataGrayAlpha; atlas.data = dataGrayAlpha;
atlas.format = UNCOMPRESSED_GRAY_ALPHA; atlas.format = UNCOMPRESSED_GRAY_ALPHA;
@ -688,10 +688,10 @@ void UnloadFont(Font font)
{ {
for (int i = 0; i < font.charsCount; i++) for (int i = 0; i < font.charsCount; i++)
{ {
free(font.chars[i].data); RL_FREE(font.chars[i].data);
} }
UnloadTexture(font.texture); UnloadTexture(font.texture);
free(font.chars); RL_FREE(font.chars);
TraceLog(LOG_DEBUG, "Unloaded sprite font data"); TraceLog(LOG_DEBUG, "Unloaded sprite font data");
} }
@ -1214,7 +1214,7 @@ const char *TextReplace(char *text, const char *replace, const char *by)
for (count = 0; (temp = strstr(insertPoint, replace)); count++) insertPoint = temp + replaceLen; for (count = 0; (temp = strstr(insertPoint, replace)); count++) insertPoint = temp + replaceLen;
// Allocate returning string and point temp to it // Allocate returning string and point temp to it
temp = result = malloc(strlen(text) + (byLen - replaceLen)*count + 1); temp = result = RL_MALLOC(strlen(text) + (byLen - replaceLen)*count + 1);
if (!result) return NULL; // Memory could not be allocated if (!result) return NULL; // Memory could not be allocated
@ -1245,7 +1245,7 @@ const char *TextInsert(const char *text, const char *insert, int position)
int textLen = strlen(text); int textLen = strlen(text);
int insertLen = strlen(insert); int insertLen = strlen(insert);
char *result = (char *)malloc(textLen + insertLen + 1); char *result = (char *)RL_MALLOC(textLen + insertLen + 1);
for (int i = 0; i < position; i++) result[i] = text[i]; for (int i = 0; i < position; i++) result[i] = text[i];
for (int i = position; i < insertLen + position; i++) result[i] = insert[i]; for (int i = position; i < insertLen + position; i++) result[i] = insert[i];
@ -1477,7 +1477,7 @@ static Font LoadBMFont(const char *fileName)
} }
// NOTE: We need some extra space to avoid memory corruption on next allocations! // NOTE: We need some extra space to avoid memory corruption on next allocations!
texPath = malloc(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4); texPath = RL_MALLOC(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4);
// NOTE: strcat() and strncat() required a '\0' terminated string to work! // NOTE: strcat() and strncat() required a '\0' terminated string to work!
*texPath = '\0'; *texPath = '\0';
@ -1501,13 +1501,13 @@ static Font LoadBMFont(const char *fileName)
else font.texture = LoadTextureFromImage(imFont); else font.texture = LoadTextureFromImage(imFont);
UnloadImage(imFont); UnloadImage(imFont);
free(texPath); RL_FREE(texPath);
// Fill font characters info data // Fill font characters info data
font.baseSize = fontSize; font.baseSize = fontSize;
font.charsCount = charsCount; font.charsCount = charsCount;
font.chars = (CharInfo *)malloc(charsCount*sizeof(CharInfo)); font.chars = (CharInfo *)RL_MALLOC(charsCount*sizeof(CharInfo));
int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX; int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX;

View file

@ -112,9 +112,14 @@
defined(SUPPORT_FILEFORMAT_GIF) || \ defined(SUPPORT_FILEFORMAT_GIF) || \
defined(SUPPORT_FILEFORMAT_PIC) || \ defined(SUPPORT_FILEFORMAT_PIC) || \
defined(SUPPORT_FILEFORMAT_HDR)) defined(SUPPORT_FILEFORMAT_HDR))
#define STBI_MALLOC RL_MALLOC
#define STBI_FREE RL_FREE
#define STBI_REALLOC(p,newsz) realloc(p,newsz)
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include "external/stb_image.h" // Required for: stbi_load_from_file() #include "external/stb_image.h" // Required for: stbi_load_from_file()
// NOTE: Used to read image data (multiple formats support) // NOTE: Used to read image data (multiple formats support)
#endif #endif
#if defined(SUPPORT_IMAGE_EXPORT) #if defined(SUPPORT_IMAGE_EXPORT)
@ -305,7 +310,7 @@ Image LoadImageEx(Color *pixels, int width, int height)
int k = 0; int k = 0;
image.data = (unsigned char *)malloc(image.width*image.height*4*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(image.width*image.height*4*sizeof(unsigned char));
for (int i = 0; i < image.width*image.height*4; i += 4) for (int i = 0; i < image.width*image.height*4; i += 4)
{ {
@ -353,7 +358,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int
unsigned int size = GetPixelDataSize(width, height, format); unsigned int size = GetPixelDataSize(width, height, format);
image.data = malloc(size); // Allocate required memory in bytes image.data = RL_MALLOC(size); // Allocate required memory in bytes
// NOTE: fread() returns num read elements instead of bytes, // NOTE: fread() returns num read elements instead of bytes,
// to get bytes we need to read (1 byte size, elements) instead of (x byte size, 1 element) // to get bytes we need to read (1 byte size, elements) instead of (x byte size, 1 element)
@ -364,7 +369,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int
{ {
TraceLog(LOG_WARNING, "[%s] RAW image data can not be read, wrong requested format or size", fileName); TraceLog(LOG_WARNING, "[%s] RAW image data can not be read, wrong requested format or size", fileName);
free(image.data); RL_FREE(image.data);
} }
else else
{ {
@ -425,7 +430,7 @@ RenderTexture2D LoadRenderTexture(int width, int height)
// Unload image from CPU memory (RAM) // Unload image from CPU memory (RAM)
void UnloadImage(Image image) void UnloadImage(Image image)
{ {
free(image.data); RL_FREE(image.data);
} }
// Unload texture from GPU memory (VRAM) // Unload texture from GPU memory (VRAM)
@ -448,7 +453,7 @@ void UnloadRenderTexture(RenderTexture2D target)
// Get pixel data from image in the form of Color struct array // Get pixel data from image in the form of Color struct array
Color *GetImageData(Image image) Color *GetImageData(Image image)
{ {
Color *pixels = (Color *)malloc(image.width*image.height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(image.width*image.height*sizeof(Color));
if (image.format >= COMPRESSED_DXT1_RGB) TraceLog(LOG_WARNING, "Pixel data retrieval not supported for compressed image formats"); if (image.format >= COMPRESSED_DXT1_RGB) TraceLog(LOG_WARNING, "Pixel data retrieval not supported for compressed image formats");
else else
@ -563,7 +568,7 @@ Color *GetImageData(Image image)
// Get pixel data from image as Vector4 array (float normalized) // Get pixel data from image as Vector4 array (float normalized)
Vector4 *GetImageDataNormalized(Image image) Vector4 *GetImageDataNormalized(Image image)
{ {
Vector4 *pixels = (Vector4 *)malloc(image.width*image.height*sizeof(Vector4)); Vector4 *pixels = (Vector4 *)RL_MALLOC(image.width*image.height*sizeof(Vector4));
if (image.format >= COMPRESSED_DXT1_RGB) TraceLog(LOG_WARNING, "Pixel data retrieval not supported for compressed image formats"); if (image.format >= COMPRESSED_DXT1_RGB) TraceLog(LOG_WARNING, "Pixel data retrieval not supported for compressed image formats");
else else
@ -797,7 +802,7 @@ void ExportImage(Image image, const char *fileName)
fclose(rawFile); fclose(rawFile);
} }
free(imgData); RL_FREE(imgData);
#endif #endif
if (success != 0) TraceLog(LOG_INFO, "Image exported successfully: %s", fileName); if (success != 0) TraceLog(LOG_INFO, "Image exported successfully: %s", fileName);
@ -863,7 +868,7 @@ Image ImageCopy(Image image)
if (height < 1) height = 1; if (height < 1) height = 1;
} }
newImage.data = malloc(size); newImage.data = RL_MALLOC(size);
if (newImage.data != NULL) if (newImage.data != NULL)
{ {
@ -896,7 +901,7 @@ void ImageToPOT(Image *image, Color fillColor)
Color *pixelsPOT = NULL; Color *pixelsPOT = NULL;
// Generate POT array from NPOT data // Generate POT array from NPOT data
pixelsPOT = (Color *)malloc(potWidth*potHeight*sizeof(Color)); pixelsPOT = (Color *)RL_MALLOC(potWidth*potHeight*sizeof(Color));
for (int j = 0; j < potHeight; j++) for (int j = 0; j < potHeight; j++)
{ {
@ -909,15 +914,15 @@ void ImageToPOT(Image *image, Color fillColor)
TraceLog(LOG_WARNING, "Image converted to POT: (%ix%i) -> (%ix%i)", image->width, image->height, potWidth, potHeight); TraceLog(LOG_WARNING, "Image converted to POT: (%ix%i) -> (%ix%i)", image->width, image->height, potWidth, potHeight);
free(pixels); // Free pixels data RL_FREE(pixels); // Free pixels data
free(image->data); // Free old image data RL_FREE(image->data); // Free old image data
int format = image->format; // Store image data format to reconvert later int format = image->format; // Store image data format to reconvert later
// NOTE: Image size changes, new width and height // NOTE: Image size changes, new width and height
*image = LoadImageEx(pixelsPOT, potWidth, potHeight); *image = LoadImageEx(pixelsPOT, potWidth, potHeight);
free(pixelsPOT); // Free POT pixels data RL_FREE(pixelsPOT); // Free POT pixels data
ImageFormat(image, format); // Reconvert image to previous format ImageFormat(image, format); // Reconvert image to previous format
} }
@ -932,7 +937,7 @@ void ImageFormat(Image *image, int newFormat)
{ {
Vector4 *pixels = GetImageDataNormalized(*image); // Supports 8 to 32 bit per channel Vector4 *pixels = GetImageDataNormalized(*image); // Supports 8 to 32 bit per channel
free(image->data); // WARNING! We loose mipmaps data --> Regenerated at the end... RL_FREE(image->data); // WARNING! We loose mipmaps data --> Regenerated at the end...
image->data = NULL; image->data = NULL;
image->format = newFormat; image->format = newFormat;
@ -942,7 +947,7 @@ void ImageFormat(Image *image, int newFormat)
{ {
case UNCOMPRESSED_GRAYSCALE: case UNCOMPRESSED_GRAYSCALE:
{ {
image->data = (unsigned char *)malloc(image->width*image->height*sizeof(unsigned char)); image->data = (unsigned char *)RL_MALLOC(image->width*image->height*sizeof(unsigned char));
for (int i = 0; i < image->width*image->height; i++) for (int i = 0; i < image->width*image->height; i++)
{ {
@ -952,7 +957,7 @@ void ImageFormat(Image *image, int newFormat)
} break; } break;
case UNCOMPRESSED_GRAY_ALPHA: case UNCOMPRESSED_GRAY_ALPHA:
{ {
image->data = (unsigned char *)malloc(image->width*image->height*2*sizeof(unsigned char)); image->data = (unsigned char *)RL_MALLOC(image->width*image->height*2*sizeof(unsigned char));
for (int i = 0; i < image->width*image->height*2; i += 2, k++) for (int i = 0; i < image->width*image->height*2; i += 2, k++)
{ {
@ -963,7 +968,7 @@ void ImageFormat(Image *image, int newFormat)
} break; } break;
case UNCOMPRESSED_R5G6B5: case UNCOMPRESSED_R5G6B5:
{ {
image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
unsigned char r = 0; unsigned char r = 0;
unsigned char g = 0; unsigned char g = 0;
@ -981,7 +986,7 @@ void ImageFormat(Image *image, int newFormat)
} break; } break;
case UNCOMPRESSED_R8G8B8: case UNCOMPRESSED_R8G8B8:
{ {
image->data = (unsigned char *)malloc(image->width*image->height*3*sizeof(unsigned char)); image->data = (unsigned char *)RL_MALLOC(image->width*image->height*3*sizeof(unsigned char));
for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++) for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++)
{ {
@ -994,7 +999,7 @@ void ImageFormat(Image *image, int newFormat)
{ {
#define ALPHA_THRESHOLD 50 #define ALPHA_THRESHOLD 50
image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
unsigned char r = 0; unsigned char r = 0;
unsigned char g = 0; unsigned char g = 0;
@ -1014,7 +1019,7 @@ void ImageFormat(Image *image, int newFormat)
} break; } break;
case UNCOMPRESSED_R4G4B4A4: case UNCOMPRESSED_R4G4B4A4:
{ {
image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
unsigned char r = 0; unsigned char r = 0;
unsigned char g = 0; unsigned char g = 0;
@ -1034,7 +1039,7 @@ void ImageFormat(Image *image, int newFormat)
} break; } break;
case UNCOMPRESSED_R8G8B8A8: case UNCOMPRESSED_R8G8B8A8:
{ {
image->data = (unsigned char *)malloc(image->width*image->height*4*sizeof(unsigned char)); image->data = (unsigned char *)RL_MALLOC(image->width*image->height*4*sizeof(unsigned char));
for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++) for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++)
{ {
@ -1048,7 +1053,7 @@ void ImageFormat(Image *image, int newFormat)
{ {
// WARNING: Image is converted to GRAYSCALE eqeuivalent 32bit // WARNING: Image is converted to GRAYSCALE eqeuivalent 32bit
image->data = (float *)malloc(image->width*image->height*sizeof(float)); image->data = (float *)RL_MALLOC(image->width*image->height*sizeof(float));
for (int i = 0; i < image->width*image->height; i++) for (int i = 0; i < image->width*image->height; i++)
{ {
@ -1057,7 +1062,7 @@ void ImageFormat(Image *image, int newFormat)
} break; } break;
case UNCOMPRESSED_R32G32B32: case UNCOMPRESSED_R32G32B32:
{ {
image->data = (float *)malloc(image->width*image->height*3*sizeof(float)); image->data = (float *)RL_MALLOC(image->width*image->height*3*sizeof(float));
for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++) for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++)
{ {
@ -1068,7 +1073,7 @@ void ImageFormat(Image *image, int newFormat)
} break; } break;
case UNCOMPRESSED_R32G32B32A32: case UNCOMPRESSED_R32G32B32A32:
{ {
image->data = (float *)malloc(image->width*image->height*4*sizeof(float)); image->data = (float *)RL_MALLOC(image->width*image->height*4*sizeof(float));
for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++) for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++)
{ {
@ -1081,7 +1086,7 @@ void ImageFormat(Image *image, int newFormat)
default: break; default: break;
} }
free(pixels); RL_FREE(pixels);
pixels = NULL; pixels = NULL;
// In case original image had mipmaps, generate mipmaps for formated image // In case original image had mipmaps, generate mipmaps for formated image
@ -1286,7 +1291,7 @@ void ImageCrop(Image *image, Rectangle crop)
{ {
// Start the cropping process // Start the cropping process
Color *pixels = GetImageData(*image); // Get data as Color pixels array Color *pixels = GetImageData(*image); // Get data as Color pixels array
Color *cropPixels = (Color *)malloc((int)crop.width*(int)crop.height*sizeof(Color)); Color *cropPixels = (Color *)RL_MALLOC((int)crop.width*(int)crop.height*sizeof(Color));
for (int j = (int)crop.y; j < (int)(crop.y + crop.height); j++) for (int j = (int)crop.y; j < (int)(crop.y + crop.height); j++)
{ {
@ -1296,7 +1301,7 @@ void ImageCrop(Image *image, Rectangle crop)
} }
} }
free(pixels); RL_FREE(pixels);
int format = image->format; int format = image->format;
@ -1304,7 +1309,7 @@ void ImageCrop(Image *image, Rectangle crop)
*image = LoadImageEx(cropPixels, (int)crop.width, (int)crop.height); *image = LoadImageEx(cropPixels, (int)crop.width, (int)crop.height);
free(cropPixels); RL_FREE(cropPixels);
// Reformat 32bit RGBA image to original format // Reformat 32bit RGBA image to original format
ImageFormat(image, format); ImageFormat(image, format);
@ -1341,7 +1346,7 @@ void ImageAlphaCrop(Image *image, float threshold)
Rectangle crop = { xMin, yMin, (xMax + 1) - xMin, (yMax + 1) - yMin }; Rectangle crop = { xMin, yMin, (xMax + 1) - xMin, (yMax + 1) - yMin };
free(pixels); RL_FREE(pixels);
// Check for not empty image brefore cropping // Check for not empty image brefore cropping
if (!((xMax < xMin) || (yMax < yMin))) ImageCrop(image, crop); if (!((xMax < xMin) || (yMax < yMin))) ImageCrop(image, crop);
@ -1355,7 +1360,7 @@ void ImageResize(Image *image, int newWidth, int newHeight)
{ {
// Get data as Color pixels array to work with it // Get data as Color pixels array to work with it
Color *pixels = GetImageData(*image); Color *pixels = GetImageData(*image);
Color *output = (Color *)malloc(newWidth*newHeight*sizeof(Color)); Color *output = (Color *)RL_MALLOC(newWidth*newHeight*sizeof(Color));
// NOTE: Color data is casted to (unsigned char *), there shouldn't been any problem... // NOTE: Color data is casted to (unsigned char *), there shouldn't been any problem...
stbir_resize_uint8((unsigned char *)pixels, image->width, image->height, 0, (unsigned char *)output, newWidth, newHeight, 0, 4); stbir_resize_uint8((unsigned char *)pixels, image->width, image->height, 0, (unsigned char *)output, newWidth, newHeight, 0, 4);
@ -1367,15 +1372,15 @@ void ImageResize(Image *image, int newWidth, int newHeight)
*image = LoadImageEx(output, newWidth, newHeight); *image = LoadImageEx(output, newWidth, newHeight);
ImageFormat(image, format); // Reformat 32bit RGBA image to original format ImageFormat(image, format); // Reformat 32bit RGBA image to original format
free(output); RL_FREE(output);
free(pixels); RL_FREE(pixels);
} }
// Resize and image to new size using Nearest-Neighbor scaling algorithm // Resize and image to new size using Nearest-Neighbor scaling algorithm
void ImageResizeNN(Image *image,int newWidth,int newHeight) void ImageResizeNN(Image *image,int newWidth,int newHeight)
{ {
Color *pixels = GetImageData(*image); Color *pixels = GetImageData(*image);
Color *output = (Color *)malloc(newWidth*newHeight*sizeof(Color)); Color *output = (Color *)RL_MALLOC(newWidth*newHeight*sizeof(Color));
// EDIT: added +1 to account for an early rounding problem // EDIT: added +1 to account for an early rounding problem
int xRatio = (int)((image->width << 16)/newWidth) + 1; int xRatio = (int)((image->width << 16)/newWidth) + 1;
@ -1400,8 +1405,8 @@ void ImageResizeNN(Image *image,int newWidth,int newHeight)
*image = LoadImageEx(output, newWidth, newHeight); *image = LoadImageEx(output, newWidth, newHeight);
ImageFormat(image, format); // Reformat 32bit RGBA image to original format ImageFormat(image, format); // Reformat 32bit RGBA image to original format
free(output); RL_FREE(output);
free(pixels); RL_FREE(pixels);
} }
// Resize canvas and fill with color // Resize canvas and fill with color
@ -1555,7 +1560,7 @@ void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp)
{ {
Color *pixels = GetImageData(*image); Color *pixels = GetImageData(*image);
free(image->data); // free old image data RL_FREE(image->data); // free old image data
if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8)) if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8))
{ {
@ -1573,7 +1578,7 @@ void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp)
} }
// NOTE: We will store the dithered data as unsigned short (16bpp) // NOTE: We will store the dithered data as unsigned short (16bpp)
image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
Color oldPixel = WHITE; Color oldPixel = WHITE;
Color newPixel = WHITE; Color newPixel = WHITE;
@ -1641,7 +1646,7 @@ void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp)
} }
} }
free(pixels); RL_FREE(pixels);
} }
} }
@ -1652,7 +1657,7 @@ Color *ImageExtractPalette(Image image, int maxPaletteSize, int *extractCount)
#define COLOR_EQUAL(col1, col2) ((col1.r == col2.r)&&(col1.g == col2.g)&&(col1.b == col2.b)&&(col1.a == col2.a)) #define COLOR_EQUAL(col1, col2) ((col1.r == col2.r)&&(col1.g == col2.g)&&(col1.b == col2.b)&&(col1.a == col2.a))
Color *pixels = GetImageData(image); Color *pixels = GetImageData(image);
Color *palette = (Color *)malloc(maxPaletteSize*sizeof(Color)); Color *palette = (Color *)RL_MALLOC(maxPaletteSize*sizeof(Color));
int palCount = 0; int palCount = 0;
for (int i = 0; i < maxPaletteSize; i++) palette[i] = BLANK; // Set all colors to BLANK for (int i = 0; i < maxPaletteSize; i++) palette[i] = BLANK; // Set all colors to BLANK
@ -1689,7 +1694,7 @@ Color *ImageExtractPalette(Image image, int maxPaletteSize, int *extractCount)
} }
} }
free(pixels); RL_FREE(pixels);
*extractCount = palCount; *extractCount = palCount;
@ -1799,8 +1804,8 @@ void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec)
*dst = LoadImageEx(dstPixels, (int)dst->width, (int)dst->height); *dst = LoadImageEx(dstPixels, (int)dst->width, (int)dst->height);
ImageFormat(dst, dst->format); ImageFormat(dst, dst->format);
free(srcPixels); RL_FREE(srcPixels);
free(dstPixels); RL_FREE(dstPixels);
} }
// Create an image from text (default font) // Create an image from text (default font)
@ -1933,7 +1938,7 @@ void ImageDrawTextEx(Image *dst, Vector2 position, Font font, const char *text,
void ImageFlipVertical(Image *image) void ImageFlipVertical(Image *image)
{ {
Color *srcPixels = GetImageData(*image); Color *srcPixels = GetImageData(*image);
Color *dstPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); Color *dstPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color));
for (int y = 0; y < image->height; y++) for (int y = 0; y < image->height; y++)
{ {
@ -1947,8 +1952,8 @@ void ImageFlipVertical(Image *image)
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(srcPixels); RL_FREE(srcPixels);
free(dstPixels); RL_FREE(dstPixels);
image->data = processed.data; image->data = processed.data;
} }
@ -1957,7 +1962,7 @@ void ImageFlipVertical(Image *image)
void ImageFlipHorizontal(Image *image) void ImageFlipHorizontal(Image *image)
{ {
Color *srcPixels = GetImageData(*image); Color *srcPixels = GetImageData(*image);
Color *dstPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); Color *dstPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color));
for (int y = 0; y < image->height; y++) for (int y = 0; y < image->height; y++)
{ {
@ -1971,8 +1976,8 @@ void ImageFlipHorizontal(Image *image)
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(srcPixels); RL_FREE(srcPixels);
free(dstPixels); RL_FREE(dstPixels);
image->data = processed.data; image->data = processed.data;
} }
@ -1981,7 +1986,7 @@ void ImageFlipHorizontal(Image *image)
void ImageRotateCW(Image *image) void ImageRotateCW(Image *image)
{ {
Color *srcPixels = GetImageData(*image); Color *srcPixels = GetImageData(*image);
Color *rotPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); Color *rotPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color));
for (int y = 0; y < image->height; y++) for (int y = 0; y < image->height; y++)
{ {
@ -1995,8 +2000,8 @@ void ImageRotateCW(Image *image)
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(srcPixels); RL_FREE(srcPixels);
free(rotPixels); RL_FREE(rotPixels);
image->data = processed.data; image->data = processed.data;
image->width = processed.width; image->width = processed.width;
@ -2007,7 +2012,7 @@ void ImageRotateCW(Image *image)
void ImageRotateCCW(Image *image) void ImageRotateCCW(Image *image)
{ {
Color *srcPixels = GetImageData(*image); Color *srcPixels = GetImageData(*image);
Color *rotPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); Color *rotPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color));
for (int y = 0; y < image->height; y++) for (int y = 0; y < image->height; y++)
{ {
@ -2021,8 +2026,8 @@ void ImageRotateCCW(Image *image)
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(srcPixels); RL_FREE(srcPixels);
free(rotPixels); RL_FREE(rotPixels);
image->data = processed.data; image->data = processed.data;
image->width = processed.width; image->width = processed.width;
@ -2059,7 +2064,7 @@ void ImageColorTint(Image *image, Color color)
Image processed = LoadImageEx(pixels, image->width, image->height); Image processed = LoadImageEx(pixels, image->width, image->height);
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(pixels); RL_FREE(pixels);
image->data = processed.data; image->data = processed.data;
} }
@ -2082,7 +2087,7 @@ void ImageColorInvert(Image *image)
Image processed = LoadImageEx(pixels, image->width, image->height); Image processed = LoadImageEx(pixels, image->width, image->height);
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(pixels); RL_FREE(pixels);
image->data = processed.data; image->data = processed.data;
} }
@ -2142,7 +2147,7 @@ void ImageColorContrast(Image *image, float contrast)
Image processed = LoadImageEx(pixels, image->width, image->height); Image processed = LoadImageEx(pixels, image->width, image->height);
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(pixels); RL_FREE(pixels);
image->data = processed.data; image->data = processed.data;
} }
@ -2182,7 +2187,7 @@ void ImageColorBrightness(Image *image, int brightness)
Image processed = LoadImageEx(pixels, image->width, image->height); Image processed = LoadImageEx(pixels, image->width, image->height);
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(pixels); RL_FREE(pixels);
image->data = processed.data; image->data = processed.data;
} }
@ -2212,7 +2217,7 @@ void ImageColorReplace(Image *image, Color color, Color replace)
Image processed = LoadImageEx(pixels, image->width, image->height); Image processed = LoadImageEx(pixels, image->width, image->height);
ImageFormat(&processed, image->format); ImageFormat(&processed, image->format);
UnloadImage(*image); UnloadImage(*image);
free(pixels); RL_FREE(pixels);
image->data = processed.data; image->data = processed.data;
} }
@ -2221,13 +2226,13 @@ void ImageColorReplace(Image *image, Color color, Color replace)
// Generate image: plain color // Generate image: plain color
Image GenImageColor(int width, int height, Color color) Image GenImageColor(int width, int height, Color color)
{ {
Color *pixels = (Color *)calloc(width*height, sizeof(Color)); Color *pixels = (Color *)RL_CALLOC(width*height, sizeof(Color));
for (int i = 0; i < width*height; i++) pixels[i] = color; for (int i = 0; i < width*height; i++) pixels[i] = color;
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2236,7 +2241,7 @@ Image GenImageColor(int width, int height, Color color)
// Generate image: vertical gradient // Generate image: vertical gradient
Image GenImageGradientV(int width, int height, Color top, Color bottom) Image GenImageGradientV(int width, int height, Color top, Color bottom)
{ {
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
for (int j = 0; j < height; j++) for (int j = 0; j < height; j++)
{ {
@ -2251,7 +2256,7 @@ Image GenImageGradientV(int width, int height, Color top, Color bottom)
} }
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2259,7 +2264,7 @@ Image GenImageGradientV(int width, int height, Color top, Color bottom)
// Generate image: horizontal gradient // Generate image: horizontal gradient
Image GenImageGradientH(int width, int height, Color left, Color right) Image GenImageGradientH(int width, int height, Color left, Color right)
{ {
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
for (int i = 0; i < width; i++) for (int i = 0; i < width; i++)
{ {
@ -2274,7 +2279,7 @@ Image GenImageGradientH(int width, int height, Color left, Color right)
} }
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2282,7 +2287,7 @@ Image GenImageGradientH(int width, int height, Color left, Color right)
// Generate image: radial gradient // Generate image: radial gradient
Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer) Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer)
{ {
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
float radius = (width < height)? (float)width/2.0f : (float)height/2.0f; float radius = (width < height)? (float)width/2.0f : (float)height/2.0f;
float centerX = (float)width/2.0f; float centerX = (float)width/2.0f;
@ -2306,7 +2311,7 @@ Image GenImageGradientRadial(int width, int height, float density, Color inner,
} }
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2314,7 +2319,7 @@ Image GenImageGradientRadial(int width, int height, float density, Color inner,
// Generate image: checked // Generate image: checked
Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2) Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2)
{ {
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
for (int y = 0; y < height; y++) for (int y = 0; y < height; y++)
{ {
@ -2326,7 +2331,7 @@ Image GenImageChecked(int width, int height, int checksX, int checksY, Color col
} }
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2334,7 +2339,7 @@ Image GenImageChecked(int width, int height, int checksX, int checksY, Color col
// Generate image: white noise // Generate image: white noise
Image GenImageWhiteNoise(int width, int height, float factor) Image GenImageWhiteNoise(int width, int height, float factor)
{ {
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
for (int i = 0; i < width*height; i++) for (int i = 0; i < width*height; i++)
{ {
@ -2343,7 +2348,7 @@ Image GenImageWhiteNoise(int width, int height, float factor)
} }
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2351,7 +2356,7 @@ Image GenImageWhiteNoise(int width, int height, float factor)
// Generate image: perlin noise // Generate image: perlin noise
Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale) Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale)
{ {
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
for (int y = 0; y < height; y++) for (int y = 0; y < height; y++)
{ {
@ -2374,7 +2379,7 @@ Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float
} }
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2382,13 +2387,13 @@ Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float
// Generate image: cellular algorithm. Bigger tileSize means bigger cells // Generate image: cellular algorithm. Bigger tileSize means bigger cells
Image GenImageCellular(int width, int height, int tileSize) Image GenImageCellular(int width, int height, int tileSize)
{ {
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
int seedsPerRow = width/tileSize; int seedsPerRow = width/tileSize;
int seedsPerCol = height/tileSize; int seedsPerCol = height/tileSize;
int seedsCount = seedsPerRow * seedsPerCol; int seedsCount = seedsPerRow * seedsPerCol;
Vector2 *seeds = (Vector2 *)malloc(seedsCount*sizeof(Vector2)); Vector2 *seeds = (Vector2 *)RL_MALLOC(seedsCount*sizeof(Vector2));
for (int i = 0; i < seedsCount; i++) for (int i = 0; i < seedsCount; i++)
{ {
@ -2431,10 +2436,10 @@ Image GenImageCellular(int width, int height, int tileSize)
} }
} }
free(seeds); RL_FREE(seeds);
Image image = LoadImageEx(pixels, width, height); Image image = LoadImageEx(pixels, width, height);
free(pixels); RL_FREE(pixels);
return image; return image;
} }
@ -2921,7 +2926,7 @@ static Image LoadDDS(const char *fileName)
{ {
if (ddsHeader.ddspf.flags == 0x40) // no alpha channel if (ddsHeader.ddspf.flags == 0x40) // no alpha channel
{ {
image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); image.data = (unsigned short *)RL_MALLOC(image.width*image.height*sizeof(unsigned short));
fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile);
image.format = UNCOMPRESSED_R5G6B5; image.format = UNCOMPRESSED_R5G6B5;
@ -2930,7 +2935,7 @@ static Image LoadDDS(const char *fileName)
{ {
if (ddsHeader.ddspf.aBitMask == 0x8000) // 1bit alpha if (ddsHeader.ddspf.aBitMask == 0x8000) // 1bit alpha
{ {
image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); image.data = (unsigned short *)RL_MALLOC(image.width*image.height*sizeof(unsigned short));
fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile);
unsigned char alpha = 0; unsigned char alpha = 0;
@ -2947,7 +2952,7 @@ static Image LoadDDS(const char *fileName)
} }
else if (ddsHeader.ddspf.aBitMask == 0xf000) // 4bit alpha else if (ddsHeader.ddspf.aBitMask == 0xf000) // 4bit alpha
{ {
image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); image.data = (unsigned short *)RL_MALLOC(image.width*image.height*sizeof(unsigned short));
fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile);
unsigned char alpha = 0; unsigned char alpha = 0;
@ -2967,14 +2972,14 @@ static Image LoadDDS(const char *fileName)
if (ddsHeader.ddspf.flags == 0x40 && ddsHeader.ddspf.rgbBitCount == 24) // DDS_RGB, no compressed if (ddsHeader.ddspf.flags == 0x40 && ddsHeader.ddspf.rgbBitCount == 24) // DDS_RGB, no compressed
{ {
// NOTE: not sure if this case exists... // NOTE: not sure if this case exists...
image.data = (unsigned char *)malloc(image.width*image.height*3*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(image.width*image.height*3*sizeof(unsigned char));
fread(image.data, image.width*image.height*3, 1, ddsFile); fread(image.data, image.width*image.height*3, 1, ddsFile);
image.format = UNCOMPRESSED_R8G8B8; image.format = UNCOMPRESSED_R8G8B8;
} }
else if (ddsHeader.ddspf.flags == 0x41 && ddsHeader.ddspf.rgbBitCount == 32) // DDS_RGBA, no compressed else if (ddsHeader.ddspf.flags == 0x41 && ddsHeader.ddspf.rgbBitCount == 32) // DDS_RGBA, no compressed
{ {
image.data = (unsigned char *)malloc(image.width*image.height*4*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(image.width*image.height*4*sizeof(unsigned char));
fread(image.data, image.width*image.height*4, 1, ddsFile); fread(image.data, image.width*image.height*4, 1, ddsFile);
unsigned char blue = 0; unsigned char blue = 0;
@ -3001,7 +3006,7 @@ static Image LoadDDS(const char *fileName)
TraceLog(LOG_DEBUG, "Pitch or linear size: %i", ddsHeader.pitchOrLinearSize); TraceLog(LOG_DEBUG, "Pitch or linear size: %i", ddsHeader.pitchOrLinearSize);
image.data = (unsigned char *)malloc(size*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char));
fread(image.data, size, 1, ddsFile); fread(image.data, size, 1, ddsFile);
@ -3098,7 +3103,7 @@ static Image LoadPKM(const char *fileName)
int size = image.width*image.height*bpp/8; // Total data size in bytes int size = image.width*image.height*bpp/8; // Total data size in bytes
image.data = (unsigned char *)malloc(size*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char));
fread(image.data, size, 1, pkmFile); fread(image.data, size, 1, pkmFile);
@ -3192,7 +3197,7 @@ static Image LoadKTX(const char *fileName)
int dataSize; int dataSize;
fread(&dataSize, sizeof(unsigned int), 1, ktxFile); fread(&dataSize, sizeof(unsigned int), 1, ktxFile);
image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(dataSize*sizeof(unsigned char));
fread(image.data, dataSize, 1, ktxFile); fread(image.data, dataSize, 1, ktxFile);
@ -3441,7 +3446,7 @@ static Image LoadPVR(const char *fileName)
} }
int dataSize = image.width*image.height*bpp/8; // Total data size in bytes int dataSize = image.width*image.height*bpp/8; // Total data size in bytes
image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(dataSize*sizeof(unsigned char));
// Read data from file // Read data from file
fread(image.data, dataSize, 1, pvrFile); fread(image.data, dataSize, 1, pvrFile);
@ -3518,7 +3523,7 @@ static Image LoadASTC(const char *fileName)
{ {
int dataSize = image.width*image.height*bpp/8; // Data size in bytes int dataSize = image.width*image.height*bpp/8; // Data size in bytes
image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); image.data = (unsigned char *)RL_MALLOC(dataSize*sizeof(unsigned char));
fread(image.data, dataSize, 1, astcFile); fread(image.data, dataSize, 1, astcFile);
if (bpp == 8) image.format = COMPRESSED_ASTC_4x4_RGBA; if (bpp == 8) image.format = COMPRESSED_ASTC_4x4_RGBA;

View file

@ -45,10 +45,10 @@
#include <android/asset_manager.h> // Required for: Android assets manager: AAsset, AAssetManager_open(), ... #include <android/asset_manager.h> // Required for: Android assets manager: AAsset, AAssetManager_open(), ...
#endif #endif
#include <stdlib.h> // Required for: malloc(), free() #include <stdlib.h> // Required for: exit()
#include <stdio.h> // Required for: fopen(), fclose(), fputc(), fwrite(), printf(), fprintf(), funopen() #include <stdio.h> // Required for: printf(), sprintf()
#include <stdarg.h> // Required for: va_list, va_start(), vfprintf(), va_end() #include <stdarg.h> // Required for: va_list, va_start(), vfprintf(), va_end()
#include <string.h> // Required for: strlen(), strrchr(), strcmp() #include <string.h> // Required for: strcpy(), strcat()
#define MAX_TRACELOG_BUFFER_SIZE 128 // Max length of one trace-log message #define MAX_TRACELOG_BUFFER_SIZE 128 // Max length of one trace-log message