aboutsummaryrefslogtreecommitdiff
path: root/src/model_loader/ObjModelLoader.cpp
blob: 7c4ee5c84edde150bbbe5466cb54f4021aca1b4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include "../../include/model_loader/ObjModelLoader.hpp"
#include "../../include/File.hpp"
#include "../../include/DataView.hpp"
#include "../../include/Image.hpp"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <libgen.h>
#include <string>

namespace amalgine {
    static StringView get_line(char *str, size_t size) {
        for(size_t i = 0; i < size; ++i) {
            char c = str[i];
            if(c == '\n' || c == '\r')
                return { str, i };
        }
        return { str, size };
    }

    static bool is_whitespace(char c) {
        switch(c) {
            case ' ':
            case '\t':
            case '\n':
            case '\r':
            case '\v':
                return true;
            default:
                return false;
        }
    }

    static bool contains_non_whitespace(const char *str, size_t size) {
        for(size_t i = 0; i < size; ++i)  {
            if(!is_whitespace(str[i]))
                return true;
        }
        return false;
    }

    // Return the number of columns, limited by @output_size
    static int split_columns(const StringView &str, char split_char, StringView *output, int output_size) {
        char *data = str.data;
        ssize_t size = str.size;

        int column = 0;
        while(size > 0) {
            char *found_ptr = (char*)memchr(data, split_char, size);
            if(!found_ptr)
                found_ptr = data + size;

            size_t column_size = static_cast<size_t>(found_ptr - data);
            if(column_size > 0 && contains_non_whitespace(data, column_size)) {
                output[column++] = { data, column_size };
                if(column == output_size)
                    break;
            }

            data = found_ptr + 1;
            size -= (column_size + 1);
        }

        return column;
    }

    static size_t find_or_end(const StringView &str, char c) {
        char *found_ptr = (char*)memchr(str.data, c, str.size);
        if(!found_ptr)
            found_ptr = str.data + str.size;
        return static_cast<size_t>(found_ptr - str.data);
    }

    struct FaceData {
        int vertex_index;
        int texcoord_index;
        int normal_index;
    };

    // TODO: Optimize? dont use sscanf 3 times
    static bool split_faces(StringView *input, FaceData *face_data) {
        input->data[input->size] = '\0';

        face_data->vertex_index = 0;
        face_data->texcoord_index = 0;
        face_data->normal_index = 0;
        if(sscanf(input->data, "%d/%d/%d", &face_data->vertex_index, &face_data->texcoord_index, &face_data->normal_index) == 3)
            return true;

        face_data->texcoord_index = 0;
        if(sscanf(input->data, "%d//%d", &face_data->vertex_index, &face_data->normal_index) == 2)
            return true;

        return sscanf(input->data, "%d/%d", &face_data->vertex_index, &face_data->texcoord_index) == 2;
    }

    struct Material {
        Image *image;
    };

    static Result<Material> load_material_from_file(const char *filepath);

    bool ObjModelLoader::load_from_file(const char *filepath, std::vector<Triangle3D> &triangles, std::vector<vec2f> &texture_coords, Image **image) {
        triangles.clear();
        texture_coords.clear();
        *image = nullptr;

        size_t file_size;
        char *file_data = file_get_content(filepath, &file_size);
        if(!file_data)
            return false;

        std::string dir_path = filepath;
        dirname(&dir_path[0]);
        const int dir_path_size = strlen(dir_path.c_str());
        dir_path.resize(dir_path_size);

        const int max_columns = 8;
        StringView columns[max_columns];

        std::vector<Vertex3D> vertices;
        std::vector<vec2f> temp_texture_coords;

        char *data = file_data;
        ssize_t size = file_size;
        while(size > 0) {
            StringView line_data = get_line(data, size);

            if(line_data.size > 2 && memcmp(line_data.data, "v ", 2) == 0) {
                //printf("line: |%.*s|\n", line_data.size, line_data.data);
                StringView column_data = { line_data.data + 2, line_data.size - 2 };

                int num_columns = split_columns(column_data, ' ', columns, max_columns);
                if(num_columns >= 3) {
                    columns[0].data[columns[0].size] = '\0';
                    columns[1].data[columns[1].size] = '\0';
                    columns[2].data[columns[2].size] = '\0';
                    vertices.push_back({ atof(columns[0].data), atof(columns[1].data), atof(columns[2].data) });
                }
            } else if(line_data.size > 2 && memcmp(line_data.data, "f ", 2) == 0) {
                //printf("line: |%.*s|\n", line_data.size, line_data.data);
                StringView column_data = { line_data.data + 2, line_data.size - 2 };

                int num_columns = split_columns(column_data, ' ', columns, max_columns);
                if(num_columns == 3 || num_columns == 4) {
                    bool valid = true;
                    // TODO: Handle these when they are not set in the below loop
                    int vertex_indices[4];
                    int texture_coord_indices[4];
                    int normal_indices[4]; // TODO: Use this

                    for(int i = 0; i < num_columns; ++i) {
                        FaceData face_data;
                        if(!split_faces(&columns[i], &face_data)) {
                            valid = false;
                            abort();
                            break;
                        }

                        vertex_indices[i] = face_data.vertex_index;
                        texture_coord_indices[i] = face_data.texcoord_index;
                        normal_indices[i] = face_data.normal_index;

                        if(vertex_indices[i] < 1 || vertex_indices[i] > vertices.size()) {
                            valid = false;
                            abort();
                            break;
                        }

                        if(texture_coord_indices[i] != 0 && (texture_coord_indices[i] < 1 || texture_coord_indices[i] > temp_texture_coords.size())) {
                            valid = false;
                            abort();
                            break;
                        }

                        --vertex_indices[i];
                        --texture_coord_indices[i];
                        --normal_indices[i];
                    }

                    if(valid) {
                        if(num_columns == 3) { // Triangle
                            triangles.push_back({ vertices[vertex_indices[0]], vertices[vertex_indices[1]], vertices[vertex_indices[2]] });

                            if(texture_coord_indices[0] >= 0) {
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[0]]);
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[1]]);
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[2]]);
                            }
                        } else if(num_columns == 4) { // Quad, convert to triangle. TODO: Support rendering quads instead of converting to triangles
                            triangles.push_back({ vertices[vertex_indices[0]], vertices[vertex_indices[1]], vertices[vertex_indices[2]] });
                            triangles.push_back({ vertices[vertex_indices[2]], vertices[vertex_indices[3]], vertices[vertex_indices[0]] });

                            if(texture_coord_indices[0] >= 0) {
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[0]]);
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[1]]);
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[2]]);

                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[2]]);
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[3]]);
                                texture_coords.push_back(temp_texture_coords[texture_coord_indices[0]]);
                            }
                        }
                    }
                }
            } else if(line_data.size > 3 && memcmp(line_data.data, "vt ", 3) == 0) {
                StringView column_data = { line_data.data + 3, line_data.size - 3 };
                int num_columns = split_columns(column_data, ' ', columns, max_columns);
                if(num_columns == 2) {
                    columns[0].data[columns[0].size] = '\0';
                    columns[1].data[columns[1].size] = '\0';
                    temp_texture_coords.push_back({ atof(columns[0].data), 1.0f - atof(columns[1].data) });
                }
            } else if(line_data.size > 7 && memcmp(line_data.data, "mtllib ", 7) == 0) {
                StringView column_data = { line_data.data + 7, line_data.size - 7 };
                int num_columns = split_columns(column_data, ' ', columns, max_columns);
                if(num_columns == 1) {
                    std::string material_path = dir_path + '/';
                    material_path.append(columns[0].data, columns[0].size);
                    printf("mtl file: %s\n", material_path.c_str());

                    assert(!*image);
                    Result<Material> material = load_material_from_file(material_path.c_str());
                    if(!material) {
                        fprintf(stderr, "Warning: %s\n", material.getErrorMsg().c_str());
                    } else {
                        *image = material->image;
                    }
                }
            }

            data += (line_data.size + 1);
            size -= (line_data.size + 1);
        }

        printf("num tex coords: %d\n", texture_coords.size());

        cleanup:
        free(file_data);
        return true;
    }

    Result<Material> load_material_from_file(const char *filepath) {
        size_t file_size;
        char *file_data = file_get_content(filepath, &file_size);
        if(!file_data)
            return Result<Material>::Err("Failed to load material: " + std::string(filepath));

        std::string dir_path = filepath;
        dirname(&dir_path[0]);
        const int dir_path_size = strlen(dir_path.c_str());
        dir_path.resize(dir_path_size);

        Image *image = nullptr;
        
        char *data = file_data;
        ssize_t size = file_size;
        while(size > 0) {
            StringView line_data = get_line(data, size);

            if(line_data.size > 7 && memcmp(line_data.data, "map_Kd ", 7) == 0) {
                StringView texture_file = { line_data.data + 7, line_data.size - 7 };
                line_data.data[line_data.size] = '\0';

                std::string texture_path;
                texture_path.resize(dir_path_size + 1 + texture_file.size);
                memcpy(&texture_path[0], dir_path.data(), dir_path_size);
                texture_path[dir_path_size] = '/';
                memcpy(&texture_path[dir_path_size + 1], texture_file.data, texture_file.size);
                printf("texture file: |%.*s|\n", texture_path.size(), texture_path.data());

                Result<Image*> image_result = Image::loadFromFile(texture_path.c_str());
                if(!image_result)
                    return Result<Material>::Err(image_result.getErrorMsg(), image_result.getErrorCode());

                image = image_result.unwrap();
                break;
            }

            data += (line_data.size + 1);
            size -= (line_data.size + 1);
        }

        free(file_data);
        return Result<Material>::Ok({ image });
    }
}