From bb353e8b085db0397d90be884924f79b879b2d9a Mon Sep 17 00:00:00 2001 From: Brendan Hansen Date: Tue, 20 Oct 2020 16:31:14 -0500 Subject: [PATCH] various changes --- include/utils.h | 22 ++++++++++++++++++++++ src/sim.cpp | 30 +++++++++++++++++++++++------- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/include/utils.h b/include/utils.h index 8c4ee7c..4b36e38 100644 --- a/include/utils.h +++ b/include/utils.h @@ -30,6 +30,28 @@ float randf(); float randf(float max); float randf(float min, float max); + +/* "defer" is a useful construct from many other programming languages. +It allows you to run a block of code at the end of a scope, but write the +block of code in the middle of the the block. For example, + +void foo() +{ +defer { printf("2\n"); }; + printf("1\n"); +} + +This would print, + +1 +2 + +This is very useful freeing mutex locks and closing files. + +The code below is the best way to do this in C++ using destructors. +This code generates no overhead, in such a way that there is no extra +function calls. + */ #ifndef defer struct defer_dummy {}; diff --git a/src/sim.cpp b/src/sim.cpp index 3af7c82..6a9e722 100644 --- a/src/sim.cpp +++ b/src/sim.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -198,10 +199,24 @@ update(f64 dt) { } -internal GLsizei circle_mesh; +internal GLuint body_buffer; +internal Body* body_data; + +internal GLuint circle_mesh; internal void draw() { + foreach(i, 0, 128) + { + body_data[i].pos = V2f{ randf(0, 800), randf(0, 800) }; + body_data[i].vel = V2f{ 0.0f, 0.0f }; + body_data[i].mass = randf(10.0f, 50.0f); + } + + glBindBuffer(GL_ARRAY_BUFFER, body_buffer); + glBufferSubData(GL_ARRAY_BUFFER, 0, 128 * sizeof(Body), body_data); + glBindBuffer(GL_ARRAY_BUFFER, -1); + glClearColor(0.1, 0.1, 0.1, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -238,6 +253,8 @@ loop() i32 main(i32 argc, char* argv[]) { + srand(time(NULL)); + init_glfw(); defer { deinit_glfw(); }; @@ -254,22 +271,21 @@ main(i32 argc, char* argv[]) GLuint ortho_mat_loc = glGetUniformLocation(program, "u_proj"); glUniformMatrix4fv(ortho_mat_loc, 1, false, (f32 *) ortho_mat); - auto bodies = alloc_bodies(128); + body_data = alloc_bodies(128); foreach(i, 0, 128) { - bodies[i].pos = V2f{ randf(0, 800), randf(0, 800) }; - bodies[i].vel = V2f{ 0.0f, 0.0f }; - bodies[i].mass = randf(10.0f, 50.0f); + body_data[i].pos = V2f{ randf(0, 800), randf(0, 800) }; + body_data[i].vel = V2f{ 0.0f, 0.0f }; + body_data[i].mass = randf(10.0f, 50.0f); } { glBindVertexArray(circle_mesh); defer { glBindVertexArray(-1); }; - GLuint body_buffer; glGenBuffers(1, &body_buffer); glBindBuffer(GL_ARRAY_BUFFER, body_buffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(Body) * 128, bodies, GL_STREAM_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(Body) * 128, body_data, GL_STREAM_DRAW); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glVertexAttribDivisor(1, 1); -- 2.25.1