#include #include #include #include #include #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include #include FT_FREETYPE_H /* @lookup: * - understand kernals, how they work and how they affect post processing * - Check to see why it is necessary to do glBindTexture() * - understand the difference between binding textures, and activating a texture unit * - I do not understand how floating point numbers work, so I should probably look into that. * - The normal matrix calculation in the fragment shader for the object affected by light has been mainly copied. * I have tried to understand the formula, and whilst it made some sense, it is not fully clear to me, and I cannot picture it yet. * Revisit the derivation for the normal matrix some time in the future. * - Lookup the derivation of the formula for reflecting a vector about a normal. I am doing that for specular lighting, but the learnopengl tutorial * just uses a glsl reflect formula, and at the time of writing it is also very late so I am not in the mood or position to look into it at present. * - One of the things I have observed with specular lights is that the circle/specular highlight follows the camera (me) when I move. I would like to figure * out a way by which this does not happen and it remains fixed on the object, at the angle at which it hits. All of this will be made complicated by the fact * that ofcourse everything is actually happening from the cameras' perspective. I would still love to figure this out. */ /* * @note: * Model loading is busted and is missing a lot of things, not that it matters for now, * but it will be useful for the future */ typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef float r32; typedef double r64; typedef u8 b8; #include "math.h" // =========== Shader Loading ============= #define GL2D_UScale(x) (Vec2{(x), (x)}) enum Texture_Filtering { TF_NEAREST, TF_LINEAR }; struct GlTexturedQuad { u32 vao; u32 vbo; u32 texture_id; }; struct GlShader { u32 id; s32 model_loc; s32 view_loc; s32 proj_loc; }; void gl_shader_load_locations(GlShader *shader) { glUseProgram(shader->id); shader->model_loc = glGetUniformLocation(shader->id, "Model"); shader->view_loc = glGetUniformLocation(shader->id, "View"); shader->proj_loc = glGetUniformLocation(shader->id, "Projection"); return; } unsigned int gl_create_vertex_shader(char* vertex_shader_source) { unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL); glCompileShader(vertex_shader); int success; char info_log[512]; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex_shader, 512, NULL, info_log); printf("================================\n"); printf("vertex shader compilation failed:\n%s\n", info_log); } return vertex_shader; } unsigned int gl_create_fragment_shader(char* fragment_shader_source) { unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL); glCompileShader(fragment_shader); int success; char info_log[512]; glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment_shader, 512, NULL, info_log); printf("================================\n"); printf("fragment shader compilation failed:\n%s\n", info_log); } return fragment_shader; } unsigned int gl_create_shader_program(unsigned int vertex_shader, unsigned int fragment_shader) { unsigned int shader_program = glCreateProgram(); glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); glLinkProgram(shader_program); int success; char info_log[512]; glGetProgramiv(shader_program, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader_program, 512, NULL, info_log); printf("================================\n"); printf("shader program linking failed:\n%s\n", info_log); } glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); return shader_program; } unsigned int gl_shader_program(char* vertex_shader_source, char* fragment_shader_source) { unsigned int vertex_shader = gl_create_vertex_shader(vertex_shader_source); unsigned int fragment_shader = gl_create_fragment_shader(fragment_shader_source); unsigned int shader_program = gl_create_shader_program(vertex_shader, fragment_shader); return shader_program; } u32 gl_shader_program_from_path(char* vs_path, char* fs_path) { // @todo: add failure handling here // what to do if we fail to read the shaders size_t read_count; char* vs = (char*)SDL_LoadFile(vs_path, &read_count); char* fs = (char*)SDL_LoadFile(fs_path, &read_count); u32 shader_program = gl_shader_program(vs, fs); return shader_program; } s32 gl_load_texture(u32 texture_id, char *path, enum Texture_Filtering filter) { s32 width, height, nrChannels; stbi_set_flip_vertically_on_load(1); unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); stbi_set_flip_vertically_on_load(0); if (data) { GLenum format; if (nrChannels == 1) format = GL_RED; else if (nrChannels == 3) format = GL_RGB; else if (nrChannels == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); u32 min_filter; u32 max_filter; if (filter == TF_LINEAR) { min_filter = GL_LINEAR_MIPMAP_LINEAR; max_filter = GL_LINEAR; } else if (filter == TF_NEAREST) { min_filter = GL_NEAREST_MIPMAP_LINEAR; max_filter = GL_NEAREST; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, max_filter); stbi_image_free(data); } else { // @todo: logging printf("failed to load image texture at path: %s", path); stbi_image_free(data); return -1; } return 0; } GlTexturedQuad gl2d_setup_textured_quad(char* texture_path, enum Texture_Filtering filter) { // rendering is clock-wise r32 quad_vertices[] = { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-left 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-left }; u32 vao, vbo, tex_id; glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), &quad_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(r32), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(r32), (void*)(3*sizeof(r32))); glBindVertexArray(0); glGenTextures(1, &tex_id); glActiveTexture(GL_TEXTURE0); gl_load_texture(tex_id, texture_path, filter); GlTexturedQuad tex_quad; tex_quad.vao = vao; tex_quad.vbo = vbo; tex_quad.texture_id = tex_id; return tex_quad; } void gl2d_draw_tex_quad(GlShader shader, GlTexturedQuad tex_quad, Vec3 position, Vec2 scale, r32 angle) { glUseProgram(shader.id); s32 tex_id_loc = glGetUniformLocation(shader.id, "Texture"); glUniform1i(tex_id_loc, 0); // 1. Rotation Mat4 model = init_value4m(1.0f); if (angle) { Mat4 rotation = rotation_matrix4m(angle, Vec3{0.0f, 0.0f, 1.0f}); model = multiply4m(rotation, model); } // 2. Scale if (scale.x != 1.0f || scale.y != 1.0f) { Mat4 scaling = scaling_matrix4m(scale.x, scale.y, 1.0f); model = multiply4m(scaling, model); } // 3. Translation Mat4 translation = translation_matrix4m(position.x, position.y, position.z); model = multiply4m(translation, model); // sending model to the shader glUniformMatrix4fv(shader.model_loc, 1, GL_TRUE, model.buffer); glBindVertexArray(tex_quad.vao); glBindTexture(GL_TEXTURE_2D, tex_quad.texture_id); glDrawArrays(GL_TRIANGLES, 0, 6); } // =============== CAMERA STUFF ================= // @note: Be sure to update and refactor the camera Mat4 camera_create4m(Vec3 camera_pos, Vec3 camera_look, Vec3 camera_up) { // @note: We do this because this allows the camera to have the axis it looks at // inwards be the +z axis. // If we did not do this, then the inward axis the camera looks at would be negative. // I am still learning from learnopengl.com but I imagine that this was done for conveniences' sake. Vec3 camera_forward_dir = normalize3v(subtract3v(camera_pos, camera_look)); Vec3 camera_right_dir = normalize3v(cross_multiply3v(camera_up, camera_forward_dir)); Vec3 camera_up_dir = normalize3v(cross_multiply3v(camera_forward_dir, camera_right_dir)); Mat4 res = lookat4m(camera_up_dir, camera_forward_dir, camera_right_dir, camera_pos); return res; } Vec3 camera_look_around(r32 angle_pitch, r32 angle_yaw) { Vec3 camera_look = {0.0}; camera_look.x = cosf(angle_yaw) * cosf(angle_pitch); camera_look.y = sinf(angle_pitch); camera_look.z = sinf(angle_yaw) * cosf(angle_pitch); camera_look = normalize3v(camera_look); return camera_look; } struct TextChar { Vec2 size; Vec2 bearing; s64 advance; }; struct CameraOrtho { r32 left; r32 right; r32 bottom; r32 top; r32 near; r32 far; Vec2 resolution; Vec2 dimensions; Mat4 projection; }; CameraOrtho camera_orthographic(r32 height, Vec2 resolution, r32 near, r32 far) { CameraOrtho camera = { 0 }; r32 aspect_ratio = resolution.x / resolution.y; r32 width = height * aspect_ratio; r32 left = -width/2.0f; r32 right = width/2.0f; r32 bottom = -height/2.0f; r32 top = height/2.0f; camera.resolution = resolution; camera.dimensions = Vec2{width, height}; camera.left = left; camera.right = right; camera.bottom = bottom; camera.top = top; camera.near = near; camera.far = far; camera.projection = orthographic_projection4m(left, right, bottom, top, near, far); return camera; } Vec2 camera_from_screen(CameraOrtho camera, Vec2 position) { Vec2 camera_space = { 0 }; camera_space.x = camera.left + position.x * (camera.dimensions.x/camera.resolution.x); camera_space.y = camera.top - position.y * (camera.dimensions.y/camera.resolution.y); return camera_space; } int main(int argc, char* argv[]) { // Load freetype FT_Library ft_lib; FT_Face face; if (FT_Init_FreeType(&ft_lib)) { printf("Error: Could not init freetype library\n"); return -1; } FT_Error error = FT_New_Face(ft_lib, "assets/fonts/Roboto.ttf", 0, &face); if (error == FT_Err_Unknown_File_Format) { printf("Error: Font Loading Failed. The font format is unsupported.\n"); return -1; } else if (error) { printf("Error: Font Loading Failed. Unknown error code: %d\n", error); return -1; } int width = 1024; int height = 768; if (SDL_Init(SDL_INIT_VIDEO) != 0) { printf("Error initialising SDL2: %s\n", SDL_GetError()); return 0; }; // set opengl version and profile SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 ); // initialise window with opengl flag SDL_Window* window = SDL_CreateWindow("SDL Test", 50, 50, width, height, SDL_WINDOW_OPENGL); //SDL_SetRelativeMouseMode(SDL_TRUE); // create an opengl context SDL_GLContext context = SDL_GL_CreateContext(window); if (!context) { printf("OpenGL context creation failed: %s\n", SDL_GetError()); return -1; } // load glad if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { printf("Failed to initialize Glad\n"); return 1; } // vsync controls: 0 = OFF | 1 = ON (Default) SDL_GL_SetSwapInterval(0); // filesystem playground stuff size_t read_count; GlShader tex_quad_shader; tex_quad_shader.id = gl_shader_program_from_path("./source/shaders/textured_quad.vs.glsl", "./source/shaders/textured_quad.fs.glsl"); gl_shader_load_locations(&tex_quad_shader); u32 ui_text_sp = gl_shader_program_from_path("./source/shaders/ui_text_shader.vs.glsl", "./source/shaders/ui_text_shader.fs.glsl"); GlTexturedQuad tex_quad1 = gl2d_setup_textured_quad("./assets/smiling.png", TF_LINEAR); GlTexturedQuad tex_quad2 = gl2d_setup_textured_quad("./assets/container.jpg", TF_LINEAR); // ==================== // setup_text // debug only u32 chunk_size = 32; Mat4* text_transforms = (Mat4*)malloc(chunk_size*sizeof(Mat4)); s32* char_indexes = (s32*)malloc(chunk_size*sizeof(s32)); TextChar* all_text_chars = (TextChar*)malloc(128*sizeof(TextChar)); FT_Set_Pixel_Sizes(face, 256, 256); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); u32 texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D_ARRAY, texture); // generate texture glTexImage3D( GL_TEXTURE_2D_ARRAY, 0, GL_R8, 256, 256, 128, 0, GL_RED, GL_UNSIGNED_BYTE, 0 ); // generate characters for (unsigned char c = 0; c < 128; c++) { if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { printf("Error: Freetype failed to load glyph: %c", c); } else { glTexSubImage3D( GL_TEXTURE_2D_ARRAY, 0, 0, 0, // x, y offset int(c), face->glyph->bitmap.width, face->glyph->bitmap.rows, 1, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer ); // set texture options glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); TextChar tc = { Vec2{(r32)face->glyph->bitmap.width, (r32)face->glyph->bitmap.rows}, Vec2{(r32)face->glyph->bitmap_left, (r32)face->glyph->bitmap_top}, face->glyph->advance.x }; all_text_chars[c] = tc; } } glBindTexture(GL_TEXTURE_2D_ARRAY, 0); // @note: this data is used for GL_TRIANGLE_STRIP // as such the order for vertices for this is AntiCW -> CW -> AntiCW // that can be seen in this array as it goes from ACW -> CW r32 vertices[] = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f }; u32 vao, vbo; glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // ==================== END setup_text r32 FOV = 90.0; r32 time_curr; r32 time_prev = SDL_GetTicks64() / 100.0; // camera stuff Vec3 camera_pos = Vec3{ 0.0, 0.0, 10.0f}; Vec3 preset_up_dir = Vec3{ 0.0, 1.0, 0.0 }; r32 angle_yaw, angle_pitch, angle_roll; angle_pitch = (r32)To_Radian(0.0f); angle_yaw = (r32)-To_Radian(90.0f); Vec3 camera_look = camera_look_around(angle_pitch, angle_yaw); // @todo: remove this, I dont like this and think that this is unnecessary Vec3 camera_look_increment; r32 camera_speed = 2.5f; Mat4 view = camera_create4m(camera_pos, camera_look, preset_up_dir); Mat4 proj = perspective4m((r32)To_Radian(90.0), (r32)width / (r32)height, 0.1f, 1000.0f); Vec2 camera_res = {(r32)width, (r32)height}; r32 ortho_cam_height = 2.0f; // CameraOrtho ortho_cam = camera_orthographic(ortho_cam_height, Vec2{camera_res.x, camera_res.y}, 0.1f, 1000.0f); Mat4 ortho_proj = orthographic_projection4m(0.0f, (r32)width, 0.0f, (r32)height, 0.1f, 1000.0f); // objects Vec3 model_translations[] = { Vec3{ 0.0, 0.0, 0.0}, // 0: origin square Vec3{ -1.0, 0.0, -1.0}, // 1: plane Vec3{ -1.0, 0.0, -0.5}, // 2: window between squares Vec3{ 0.0, 0.0, 3.0}, // 3: window infront of origin square Vec3{ -2.5, 0.0, -0.5}, // 4: square to the left Vec3{ -1.0, 0.0, -1.5}, // 5: random square behind window between squares Vec3{ -1.0, 0.0, -8.0}, // 6: reflective plane Vec3{ -1.0, 2.0, -8.0}, // 7: refractive "window" }; s32 proj_loc; glUseProgram(ui_text_sp); proj_loc = glGetUniformLocation(ui_text_sp, "Projection"); // glUniformMatrix4fv(proj_loc, 1, GL_TRUE, ortho_cam.projection.buffer); glUniformMatrix4fv(proj_loc, 1, GL_TRUE, ortho_proj.buffer); //glUseProgram(tex_quad_shader.id); //glUniformMatrix4fv(tex_quad_shader.proj_loc, 1, GL_TRUE, ortho_cam.projection.buffer); glEnable(GL_DEPTH_TEST); //glEnable(GL_CULL_FACE); //glCullFace(GL_BACK); //glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); u8 game_running = true; u8 hold_lshift = false; u8 move_w = false; u8 move_a = false; u8 move_s = false; u8 move_d = false; while(game_running) { // frame delta time_curr = SDL_GetTicks64() / 100.0; r32 time_delta = time_curr - time_prev; r32 camera_speed_adjusted = time_delta * camera_speed; camera_look_increment = scaler_multiply3v(camera_look, camera_speed_adjusted); SDL_Event ev; while(SDL_PollEvent(&ev)) { // INPUT switch (ev.type) { case (SDL_QUIT): { game_running = false; } break; case (SDL_KEYDOWN): { if (ev.key.keysym.sym == SDLK_LSHIFT) { hold_lshift = true; } if (ev.key.keysym.sym == SDLK_w) { move_w = true; } if (ev.key.keysym.sym == SDLK_s) { move_s = true; } if (ev.key.keysym.sym == SDLK_a) { move_a = true; } if (ev.key.keysym.sym == SDLK_d) { move_d = true; } } break; case (SDL_KEYUP): { if (ev.key.keysym.sym == SDLK_LSHIFT) { hold_lshift = false; } if (ev.key.keysym.sym == SDLK_w) { move_w = false; } if (ev.key.keysym.sym == SDLK_s) { move_s = false; } if (ev.key.keysym.sym == SDLK_a) { move_a = false; } if (ev.key.keysym.sym == SDLK_d) { move_d = false; } } break; case (SDL_MOUSEMOTION): { #if 0 SDL_MouseMotionEvent mouse_event = ev.motion; r32 x_motion = (r32)mouse_event.xrel; r32 y_motion = (r32)mouse_event.yrel; if (x_motion != 0.0 || y_motion != 0.0) { angle_yaw = angle_yaw + To_Radian(x_motion * 0.1f); angle_pitch = clampf(angle_pitch + To_Radian(-y_motion * 0.1f), To_Radian(-89.0f), To_Radian(89.0f)); camera_look = camera_look_around(angle_pitch, angle_yaw); } #endif } break; default: { break; } } } // PROCESS if (move_w) { camera_pos = add3v(camera_pos, camera_look_increment); //model_translations[0].y += 0.25f; } if (move_s) { camera_pos = subtract3v(camera_pos, camera_look_increment); //model_translations[0].y -= 0.25f; } if (move_a) { Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look)); Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted); camera_pos = add3v(camera_pos, camera_right_scaled); //model_translations[0].x -= 0.25f; } if (move_d) { Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look)); Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted); camera_pos = subtract3v(camera_pos, camera_right_scaled); //model_translations[0].x += 0.25f; } view = camera_create4m(camera_pos, add3v(camera_pos, camera_look), preset_up_dir); // object shader program stuff time_prev = time_curr; //glUseProgram(tex_quad_shader.id); //glUniformMatrix4fv(tex_quad_shader.view_loc, 1, GL_TRUE, view.buffer); // OUTPUT glClearColor(1.0f, 0.6f, .6f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); { // render ui text glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(ui_text_sp); s32 text_color_loc = glGetUniformLocation(ui_text_sp, "TextColor"); glUniform3f(text_color_loc, 0.0f, 0.0f, 0.0f); glBindVertexArray(vao); glBindTexture(GL_TEXTURE_2D_ARRAY, texture); glBindBuffer(GL_ARRAY_BUFFER, vbo); glActiveTexture(GL_TEXTURE0); const char text_to_render[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pellentesque fringilla mauris vitae convallis. \nSuspendisse potenti. Morbi at eros nulla. Morbi pellentesque mollis diam, nec eleifend sapien commodo nec. \nAenean elementum, eros non mattis consectetur, odio nulla posuere orci, sed posuere nibh nisl suscipit orci. Donec lectus dolor, rhoncus at vulputate sit amet, pellentesque non velit. \nVivamus vitae lectus lacinia, feugiat elit non, malesuada diam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. \nNulla porttitor cursus nulla, sit amet pulvinar nibh tempus sed. Nulla quis luctus tellus. Suspendisse efficitur tellus vel augue tempor, sed gravida purus consectetur. \nSed congue rutrum elit nec aliquet.\n\n" "In hac habitasse platea dictumst. Nulla nec pellentesque purus, vitae interdum eros. Pellentesque pretium dui sed erat commodo finibus. \nInteger fringilla tincidunt orci, vel mattis dolor eleifend id. Sed condimentum lorem sit amet enim porttitor dictum nec ut arcu. \nMauris mauris ex, varius in sem eget, semper hendrerit enim. Curabitur vel vehicula metus, vel luctus nunc. \nPraesent et molestie diam, non faucibus ligula. Duis elementum nunc erat, eget dictum mi faucibus id.\n\n" "Nulla non vehicula erat, vitae tincidunt turpis. In tincidunt dolor vel augue tincidunt, vitae feugiat leo facilisis. Nullam auctor sodales sodales. \nDuis augue nibh, scelerisque id faucibus sit amet, ultricies eget lorem. Integer dapibus ultricies dolor sit amet mollis. \nQuisque eros sem, bibendum non convallis quis, vulputate ac erat. Nam laoreet justo id dui feugiat, condimentum elementum dolor pellentesque. \nVivamus imperdiet metus et mattis laoreet. Ut eget scelerisque neque. Praesent mollis, nisl quis volutpat eleifend, purus sem suscipit ex, \na molestie elit risus vel velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. \nProin vitae nibh ac leo tempor vehicula quis quis nulla. Donec sodales sapien et nulla varius vulputate. \nPhasellus ac eleifend dui.\n\n" "Nulla nec nibh ut mauris accumsan tristique. Nam iaculis pellentesque elit, sit amet tristique erat dignissim ac. \nDuis gravida dolor eget sem fringilla, ac consequat ipsum malesuada. In facilisis mattis nibh in bibendum. \nUt congue gravida bibendum. Phasellus egestas consectetur sem, ornare pellentesque mauris. Ut pretium eleifend dui ut feugiat. \nCurabitur ut faucibus nisi, ac laoreet tortor.\n\n" "Nulla interdum vehicula tempus. Curabitur bibendum nisl eget sem tristique, at aliquam magna rutrum. \nLorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempus posuere urna et auctor. \nVestibulum lectus risus, aliquet eget placerat nec, iaculis et augue. \nMauris vel nulla eu urna pretium vestibulum in vel elit. Donec sollicitudin dui felis, sed auctor nibh aliquam \nsit amet. Pellentesque eget elementum lacus, suscipit facilisis nisi. Integer tempus velit nulla. \nSed ullamcorper, eros et consequat pharetra, eros ipsum varius odio, vitae commodo lectus libero at libero. \nCurabitur sed elit tincidunt tellus tempor convallis et eu nunc. \nAliquam blandit auctor ipsum, eu mattis leo viverra vel. Integer feugiat dui neque, vitae vulputate lectus congue non. \nFusce molestie vel ligula nec sodales. Integer vestibulum molestie porttitor.\n\n"; u32 running_index = 0; r32 startx = 10.0f; r32 starty = 740.0f; r32 linex = startx; r32 zindex = 3.0f; r32 scale = 1.0f * 22.0f / 256.0f; r32 max_size = 0.0f; for (u32 i = 0; i < sizeof(text_to_render) - 1; i++) { char c = text_to_render[i]; TextChar rc = all_text_chars[c]; if (rc.size.y > max_size) { max_size = rc.size.y; } if (c == '\n') { linex = startx; starty = starty - (rc.size.y * 1.5 * scale); // line_height: 1.5; continue; } else if (c == ' ') { linex += (rc.advance >> 6) * scale; continue; } r32 xpos = linex + (scale * rc.bearing.x); r32 ypos = starty - (256.0f - rc.bearing.y) * scale; r32 w = scale * 256.0f; r32 h = scale * 256.0f; Mat4 tm = translation_matrix4m(xpos, ypos, -zindex); Mat4 sm = scaling_matrix4m(w, h, 0); Mat4 model_mat = multiply4m(tm, sm); text_transforms[running_index] = model_mat; char_indexes[running_index] = int(c); linex += (rc.advance >> 6) * scale; running_index++; if (running_index > chunk_size-1) { { r32 letter_transforms_loc = glGetUniformLocation(ui_text_sp, "LetterTransforms"); glUniformMatrix4fv(letter_transforms_loc, chunk_size, GL_TRUE, &text_transforms[0].buffer[0]); r32 texture_map_loc = glGetUniformLocation(ui_text_sp, "TextureMap"); glUniform1iv(texture_map_loc, chunk_size, char_indexes); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, chunk_size); running_index = 0; memset(text_transforms, 0, chunk_size); memset(char_indexes, 0, chunk_size); } } } if (running_index > 0) { r32 letter_transforms_loc = glGetUniformLocation(ui_text_sp, "LetterTransforms"); glUniformMatrix4fv(letter_transforms_loc, chunk_size, GL_TRUE, &text_transforms[0].buffer[0]); r32 texture_map_loc = glGetUniformLocation(ui_text_sp, "TextureMap"); glUniform1iv(texture_map_loc, chunk_size, char_indexes); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, chunk_size); } glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D_ARRAY, 0); } SDL_GL_SwapWindow(window); } free(text_transforms); free(char_indexes); free(all_text_chars); // opengl free calls // it is up to the renderer to free everything here // of course I have not bothered to set that up so it does not matter // glDeleteVertexArrays(1, &tex_quad1.vao); // glDeleteVertexArrays(1, &tex_quad2.vao); // glDeleteBuffers(1, &tex_quad1.vao); // glDeleteBuffers(1, &tex_quad2.vao); FT_Done_Face(face); FT_Done_FreeType(ft_lib); // sdl free calls SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 0; }