A 3D game engine from scratch.
1// (c) 2020 Vlad-Stefan Harbuz <vlad@vladh.net>
2
3#include "logs.hpp"
4#include "memory.hpp"
5#include "stb.hpp"
6#include "files.hpp"
7
8
9unsigned char *
10files::load_image(
11 const char *path,
12 i32 *width,
13 i32 *height,
14 i32 *n_channels,
15 bool should_flip
16) {
17 stbi_set_flip_vertically_on_load(should_flip);
18 unsigned char *image_data = stbi_load(path, width, height, n_channels, 0);
19 if (!image_data) {
20 logs::fatal("Could not open file %s.", path);
21 }
22 return image_data;
23}
24
25
26unsigned char *
27files::load_image(
28 const char *path,
29 i32 *width,
30 i32 *height,
31 i32 *n_channels
32) {
33 return load_image(path, width, height, n_channels, true);
34}
35
36
37void
38files::free_image(unsigned char *image_data)
39{
40 stbi_image_free(image_data);
41}
42
43
44u32
45files::get_file_size(char const *path)
46{
47 FILE *f = fopen(path, "rb");
48 if (!f) {
49 logs::error("Could not open file %s.", path);
50 return 0;
51 }
52 fseek(f, 0, SEEK_END);
53 u32 size = ftell(f);
54 fclose(f);
55 return size;
56}
57
58
59char const *
60files::load_file(memory::Pool *memory_pool, const char *path)
61{
62 FILE *f = fopen(path, "rb");
63 if (!f) {
64 logs::error("Could not open file %s.", path);
65 return nullptr;
66 }
67 fseek(f, 0, SEEK_END);
68 u32 file_size = ftell(f);
69 fseek(f, 0, SEEK_SET);
70
71 char *string = (char*)memory::push(memory_pool, file_size + 1, path);
72 size_t result = fread(string, file_size, 1, f);
73 fclose(f);
74 if (result != 1) {
75 logs::error("Could not read from file %s.", path);
76 return nullptr;
77 }
78
79 string[file_size] = 0;
80 return string;
81}
82
83
84char const *
85files::load_file(char *string, const char *path)
86{
87 FILE *f = fopen(path, "rb");
88 if (!f) {
89 logs::error("Could not open file %s.", path);
90 return nullptr;
91 }
92 fseek(f, 0, SEEK_END);
93 u32 file_size = ftell(f);
94 fseek(f, 0, SEEK_SET);
95
96 size_t result = fread(string, file_size, 1, f);
97 fclose(f);
98 if (result != 1) {
99 logs::error("Could not read from file %s.", path);
100 return nullptr;
101 }
102
103 string[file_size] = 0;
104 return string;
105}