aboutsummaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: 22bfe1c0b64573fde2f4a9fcda635757d72d19f3 (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
#include "../include/RenderBackend/OpenGL/opengl.hpp"
#include "../include/RenderBackend/OpenGL/Shader.hpp"
#include "../include/RenderBackend/OpenGL/ShaderProgram.hpp"
#include "../include/RenderBackend/OpenGL/DeviceMemory.hpp"
#include "../include/RenderBackend/OpenGL/DeviceFrame.hpp"
#include "../include/RenderBackend/OpenGL/Texture2D.hpp"
#include "../include/Image.hpp"
#include "../include/Triangle.hpp"

#include "../include/model_loader/ObjModelLoader.hpp"

#include <cstdio>
#include <chrono>

// TODO: Creating buffers etc should be somehow created/drawn using the window object, since they are associated with the window
// opengl context

using namespace amalgine;
using namespace std;

static void glfwErrorHandler(int errorCode, const char *errorDescription);
static void initGlfw();
static void initGlew();
static GLFWwindow *createWindow();
static std::unique_ptr<Shader> load_shader_from_file(const char *filepath, Shader::Type shader_type);
static std::unique_ptr<ShaderProgram> build_shader_program_from_shaders(const std::vector<Shader*> &shaders);

struct Userdata {
    float cam_dist;
};

static std::vector<Triangle3D> generate_sand() {
    const int rows = 50;
    const int columns = 50;
    std::vector<Triangle3D> vertices(rows * columns * 2);
    int i = 0;
    float div = 0.3f;
    for(int y = 0; y < rows; ++y) {
        for(int x = 0; x < columns; ++x) {
            vertices[i++] = {
                Vertex3D{x * div + 0.0f, y * div + 0.0f, 0.0f},
                Vertex3D{x * div + 1.0f * div, y * div + 0.0f, 0.0f},
                Vertex3D{x * div + 0.0f, y * div + 1.0f * div, 0.0f}
            };
            vertices[i++] = {
                Vertex3D{x * div + 1.0f * div, y * div + 0.0f, 0.0f},
                Vertex3D{x * div + 1.0f * div, y * div + 1.0f * div, 0.0f},
                Vertex3D{x * div + 0.0f, y * div + 1.0f * div, 0.0f}
            };
        }
    }
    return vertices;
}

int main()
{
    initGlfw();
    glfwSetErrorCallback(glfwErrorHandler);
    GLFWwindow *window = createWindow();
    int window_width = 1;
    int window_height = 1;
    glfwGetWindowSize(window, &window_width, &window_height);
    
    DeviceFrame frame;
    
    std::vector<Triangle3D> cpu_sand = generate_sand();
    DeviceMemory *gpuSand = frame.alloc();
    gpuSand->copy({cpu_sand.data(), cpu_sand.size()}, DeviceMemory::StorageType::STATIC);

    std::unique_ptr<Shader> sand_vertex_shader = load_shader_from_file("shaders/sand_vertex.vert", Shader::Type::VERTEX);
    std::unique_ptr<Shader> sand_pixel_shader = load_shader_from_file("shaders/sand_fragment.frag", Shader::Type::PIXEL);
    std::unique_ptr<ShaderProgram> sand_shader_program = build_shader_program_from_shaders({ sand_vertex_shader.get(), sand_pixel_shader.get() });

    std::vector<Triangle3D> triangles;
    std::vector<vec2f> texture_coords;
    Image *image;
    ObjModelLoader::load_from_file("/home/dec05eba/Downloads/ELI4OS.obj", triangles, texture_coords, &image);
    DeviceMemory *gpuModel = frame.alloc();
    gpuModel->copy({triangles.data(), triangles.size()}, DeviceMemory::StorageType::STATIC);

    Texture2D model_texture(image);
    DeviceMemory *model_gpu_texture = frame.alloc();
    model_gpu_texture->copy({texture_coords.data(), texture_coords.size()}, DeviceMemory::StorageType::STATIC);

    std::unique_ptr<Shader> vertex_shader = load_shader_from_file("shaders/vertex.vert", Shader::Type::VERTEX);
    std::unique_ptr<Shader> pixel_shader = load_shader_from_file("shaders/fragment.frag", Shader::Type::PIXEL);
    std::unique_ptr<ShaderProgram> shader_program = build_shader_program_from_shaders({ vertex_shader.get(), pixel_shader.get() });

    glm::mat4 proj = glm::perspective(glm::radians(75.0f), (float)window_width / (float)window_height, 0.2f, 1000.0f);
    vec3f triangle_color = { 1.0f, 0.0f, 0.0f };

    Result<Uniform> sand_proj_uniform = sand_shader_program->get_uniform_by_name("proj");
    Result<Uniform> sand_view_uniform = sand_shader_program->get_uniform_by_name("view");
    Result<Uniform> sand_model_uniform = sand_shader_program->get_uniform_by_name("model");
    Result<Uniform> sand_time = sand_shader_program->get_uniform_by_name("time");
    Result<Uniform> sand_triangle_color_uniform = sand_shader_program->get_uniform_by_name("triangle_color");

    Result<Uniform> proj_uniform = shader_program->get_uniform_by_name("proj");
    Result<Uniform> view_uniform = shader_program->get_uniform_by_name("view");
    Result<Uniform> model_uniform = shader_program->get_uniform_by_name("model");
    Result<Uniform> tex_uniform = shader_program->get_uniform_by_name("tex");

    sand_proj_uniform->set(proj);
    sand_triangle_color_uniform->set(triangle_color);

    proj_uniform->set(proj);

    shader_program->set_input_data("texcoord_vert", *model_gpu_texture);
    tex_uniform->set(model_texture);

    Userdata userdata;
    userdata.cam_dist = 3.0f;
    glm::vec3 character_pos(0.0f, 0.0f, userdata.cam_dist);
    auto t_start = std::chrono::high_resolution_clock::now();

    glfwSetWindowUserPointer(window, &userdata);
    
    glfwSetScrollCallback(window, [](GLFWwindow *window, double xoffset, double yoffset){
        Userdata *userdata = (Userdata*)glfwGetWindowUserPointer(window);
        userdata->cam_dist += yoffset;
    });
    
    glEnable(GL_CULL_FACE);
    float time = 0.0f;
    while(!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
            glfwSetWindowShouldClose(window, GL_TRUE);

        auto t_now = std::chrono::high_resolution_clock::now();
        float time_delta = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();
        t_start = t_now;
        time += time_delta;

        float move_speed = time_delta * 3.0f;
        if(glfwGetKey(window, GLFW_KEY_W))
            character_pos.y -= move_speed;
        if(glfwGetKey(window, GLFW_KEY_S))
            character_pos.y += move_speed;
        if(glfwGetKey(window, GLFW_KEY_A))
            character_pos.x += move_speed;
        if(glfwGetKey(window, GLFW_KEY_D))
            character_pos.x -= move_speed;

        character_pos.z = userdata.cam_dist;

        glm::mat4 view = glm::lookAt(
            character_pos,
            character_pos - glm::vec3(0.0f, 3.0f, 3.0f),
            glm::vec3(0.0f, 0.0f, 1.0f)
        );
        sand_view_uniform->set(view);
        view_uniform->set(view);

        glm::mat4 model = glm::mat4(1.0f);
        model = glm::rotate(
            model,
            0.0f,
            glm::vec3(0.0f, 0.0f, 1.0f)
        );
        sand_model_uniform->set(model);
        model_uniform->set(model);

        //printf("now: %f\n", time);
        sand_time->set(time);

        // Set color for clearing
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        // Do the actual screen clearing, using the color set using glClearColor
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

        shader_program->set_input_data("position", *gpuModel);
        frame.draw(shader_program.get());

        sand_shader_program->set_input_data("position", *gpuSand);
        frame.draw(sand_shader_program.get());

        //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        glfwSwapBuffers(window);
    }

    delete image;
    //glfwTerminate();
    return 0;
}

void glfwErrorHandler(int errorCode, const char *errorDescription)
{
    printf("GLFW error code: %d, description: %s\n", errorCode, errorDescription);
}

void initGlfw()
{
    if(!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        exit(-1);
    }

    glfwWindowHint(GLFW_SAMPLES, 4); // anti aliasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
}

void initGlew() {
    glewExperimental = true;
    if(glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        glfwTerminate();
        exit(-1);
    }
}

GLFWwindow* createWindow() {
    GLFWwindow *window = glfwCreateWindow(1920, 1080, "Amalgine", nullptr, nullptr);
    if(!window)
    {
        fprintf(stderr, "Failed to open GLFW window\n");
        glfwTerminate();
        exit(10);
    }

    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_FALSE);
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1); // 1 = enable vsync
    initGlew();
    return window;
}

static int file_read_all(const char *filepath, std::string &result) {
    FILE *file = fopen(filepath, "rb");
    if(!file) {
        perror("file_read_all");
        return errno;
    }

    fseek(file, 0, SEEK_END);
    size_t file_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    result.resize(file_size);
    fread(&result[0], 1, result.size(), file);
    fclose(file);
    return 0;
}

std::unique_ptr<Shader> load_shader_from_file(const char *filepath, Shader::Type shader_type) {
    std::string file_content;
    if(file_read_all(filepath, file_content) != 0)
        exit(13);

    Result<std::unique_ptr<Shader>> vertex_shader_result = Shader::compile(shader_type, file_content.data(), file_content.size());
    if(!vertex_shader_result) {
        fprintf(stderr, "Failed to compile shader, error: %s\n", vertex_shader_result.getErrorMsg().c_str());
        exit(12);
    }
    return std::move(vertex_shader_result.unwrap());
}

std::unique_ptr<ShaderProgram> build_shader_program_from_shaders(const std::vector<Shader*> &shaders) {
    Result<std::unique_ptr<ShaderProgram>> shader_program_result = ShaderProgram::build(shaders);
    if(!shader_program_result) {
        fprintf(stderr, "Failed to link shaders, error: %s\n", shader_program_result.getErrorMsg().c_str());
        exit(13);
    }
    return std::move(shader_program_result.unwrap());
}