Fix loading shader fragments by path relative to list file

This commit is contained in:
Kienan Stewart 2020-02-06 23:20:58 -05:00
parent 865fa558e9
commit df48698ab7
1 changed files with 26 additions and 2 deletions

View File

@ -2,9 +2,11 @@
#define _SHADERLOADER_H_
#include <fstream>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <unistd.h>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
@ -149,6 +151,9 @@ int loadShadersFromFile(const char* file_path, struct ShaderRegistry *registry)
char *name;
char *type;
char *path;
char *file_path_copy = (char*) calloc(strlen(file_path), sizeof(char));
strncpy(file_path_copy, file_path, strlen(file_path));
char *base = dirname((char*) file_path_copy);
while((size = getline(&line, &size, fp)) != -1) {
if(size == 0) {
// Skipping, line length 0
@ -168,10 +173,21 @@ int loadShadersFromFile(const char* file_path, struct ShaderRegistry *registry)
// Invalid line, not enough elements.
// @TODO Inform the user.
free(line_copy);
name = type = path = NULL;
name = type = path = NULL;
continue;
}
// Strip trailing new lines from the path.
path[strcspn(path, "\n")] = 0;
// Convert any paths as relative to the basename of the file_path they
// were loaded from.
int real_path_size = strlen(base) + 1 + strlen(path) + 1;
char *shader_path = (char*) calloc(real_path_size, sizeof(char));
strncat(shader_path, base, strlen(base));
strcat(shader_path + strlen(base), "/");
strncat(shader_path + strlen(base) + 1, path, strlen(path));
// Validate type
enum ShaderType shader_type;
if(strcmp("fragment", type) == 0) {
@ -188,18 +204,26 @@ int loadShadersFromFile(const char* file_path, struct ShaderRegistry *registry)
// Invalid line, unknown type.
// @TODO Inform the user.
free(line_copy);
free(shader_path);
name = type = path = NULL;
continue;
}
GLuint shader_id = compile_shader(path, shader_type);
GLuint shader_id = compile_shader(shader_path, shader_type);
if(shader_id == 0) {
// Error in compilation of the shader
// @TODO Inform the user.
free(line_copy);
free(shader_path);
name = type = path = NULL;
continue;
}
// Add to registry
// Cleanup
free(line_copy);
free(shader_path);
}
return 0;
}