4 #include "simulation.hpp"
11 #include <glm/ext.hpp>
12 #include <glm/glm.hpp>
16 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
18 enum Mode { render, debugContDist, debugColor, debugProbExt, debugProbAct };
19 Mode curMode = render;
24 const float metaballR = 1.f / 16.f;
25 inline float metaballField(float r) {
28 const float a = r / (1);
29 return (-4.f / 9.f * powf(a, 6)) + (17.f / 9.f * powf(a, 4)) -
30 (22.f / 9.f * powf(a, 2)) + 1;
33 const float normalizationFactor = (748.f / 405.f) * M_PI;
36 if (GLenum e = glGetError()) {
37 fprintf(stderr, "%s\n", gluErrorString(e));
42 GLuint bbProg, sunProg;
45 // Here we need to generate n_q textures for different densities of metaballs
46 // These textures then go on the billboards
47 // The texture stores attenuation ratio?
52 // Stores attenuation ratio inside r channel
53 // Should be highest value at center
54 void precalculateBillboardTextures() {
55 fprintf(stderr, "Calculating billboard textures...\n");
56 glGenTextures(NQ, bbTexIds);
58 for (int d = 0; d < NQ; d++) {
60 for (int j = 0; j < 32; j++) {
61 for (int i = 0; i < 32; i++) {
62 // TODO: properly calculate this instead of whatever this is
63 float r = distance(vec2(i, j), vec2(16, 16)) / 16;
64 float density = (float)d / NQ;
67 fmin(1, (3 * density * (metaballField(r) / normalizationFactor)));
73 snprintf(path, 32, "bbtex/%i.tga", d);
74 saveGrayscale(data, 32, 32, path);
76 glBindTexture(GL_TEXTURE_2D, bbTexIds[d]);
78 glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 32, 32, 0, GL_RED, GL_FLOAT, data);
79 glGenerateMipmap(GL_TEXTURE_2D); // required, otherwise texture is blank
81 fprintf(stderr, "\r%i out of %i densities calculated%s", d + 1, NQ,
82 d == NQ - 1 ? "\n" : "");
94 array<Metaball, CLOUD_DIM_X * CLOUD_DIM_Y * CLOUD_DIM_Z> metaballs;
96 const float cloudScale = metaballR;
97 const float metaballScale = metaballR * 1.5f;
100 void calculateMetaballs() {
102 /* for (int i = 0; i < 256; i++) { */
103 /* float x = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
104 /* float y = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
105 /* float z = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
106 /* float r = (float)rand()/(float)(RAND_MAX) * 1; */
107 /* Metaball m = {{x,y,z}, r}; */
108 /* metaballs.push_back(m); */
110 for (int i = 0; i < CLOUD_DIM_X; i++) {
111 for (int j = 0; j < CLOUD_DIM_Y; j++) {
112 for (int k = 0; k < CLOUD_DIM_Z; k++) {
113 Metaball m = {vec3(i, j, k) * vec3(cloudScale), {i, j, k}};
114 /* m.pos = (m.pos * vec3(2)) - (cloudScale / 2); */
115 m.pos -= vec3(CLOUD_DIM_X, CLOUD_DIM_Y, CLOUD_DIM_Z) * cloudScale / 2.f;
118 metaballs[i * CLOUD_DIM_Y * CLOUD_DIM_Z + j * CLOUD_DIM_Z + k] = m;
122 /* for (int z = 0; z < CLOUD_DIM_Z; z++) */
123 /* metaballs[32 * CLOUD_DIM_Y * CLOUD_DIM_Z + 32 * CLOUD_DIM_Z + z].d = 1;
127 vec3 sunPos = {0, 5, 0}, sunDir = {0, -1, 0};
128 size_t envColorIdx = 0;
129 // First color is sun color, second is sky color
130 std::array<std::array<vec4, 2>, 3> envColors{
131 {{vec4(1, 1, 1, 1), vec4(0.9, 1, 1, 1)},
132 {vec4(0.939, 0.632, 0.815, 1), vec4(0.9, 1, 1, 1)},
133 {vec4(0.999, 0.999, 0.519, 1), vec4(0.981, 0.667, 0.118, 1)}}};
134 vec3 camPos = {0, 0, -3}, viewPos = {0, 0, 0};
135 mat4 proj; // projection matrix
136 mat4 view; // view matrix
137 float znear = 0.001, zfar = 1000;
138 // for performance with glReadPixels these should be powers of 2!
139 float width = 1200, height = 800;
141 void setProjectionAndViewUniforms(GLuint progId) {
142 GLuint projLoc = glGetUniformLocation(progId, "projection");
143 glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
145 GLuint viewLoc = glGetUniformLocation(progId, "view");
146 glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
149 /** Orientates the transformation matrix to face the camera in the view matrix
151 mat4 faceView(mat4 m) {
152 m[0][0] = view[0][0];
153 m[0][1] = view[1][0];
154 m[0][2] = view[2][0];
155 m[1][0] = view[0][1];
156 m[1][1] = view[1][1];
157 m[1][2] = view[2][1];
158 m[2][0] = view[0][2];
159 m[2][1] = view[1][2];
160 m[2][2] = view[2][2];
166 /* const int shadeWidth = 256, shadeHeight = 256; */
167 const int shadeWidth = 256, shadeHeight = 256;
170 const int numPbos = 512;
171 GLuint pboBufs[numPbos];
172 GLbyte sink[shadeWidth * shadeHeight * 4];
174 void inline mapPixelRead(int pboBuf, int metaball) {
175 glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[pboBuf]);
177 (GLubyte *)glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0,
178 4 * sizeof(GLubyte), GL_MAP_READ_BIT);
179 vec4 pixel = vec4(src[0], src[1], src[2], src[3]) / vec4(255.f);
180 glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
182 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
184 // Multiply the pixel value by the sunlight color.
185 pixel *= envColors[envColorIdx][0];
187 // Store the color for the previous set of pixels
188 metaballs[metaball].col = pixel;
195 glDisable(GL_DEPTH_TEST);
196 // shaderOutput * 0 + buffer * shader alpha
197 glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
200 // sort by ascending distance from the sun
201 sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
202 return distance(sunPos, a.pos) < distance(sunPos, b.pos);
205 glActiveTexture(GL_TEXTURE0);
206 glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
208 GLuint modelLoc = glGetUniformLocation(bbProg, "model");
209 glUniform1i(glGetUniformLocation(bbProg, "debug"), 0);
211 glViewport(0, 0, shadeWidth, shadeHeight);
217 auto begin_time = std::chrono::system_clock::now();
219 for (auto &k : metaballs) {
220 /* fprintf(stderr, "\rShading metaball %lu/%lu...", i, metaballs.size()); */
221 // place the billboard at the center of k
222 mat4 model = translate(mat4(1), k.pos);
224 // rotate the billboard so that its normal is oriented to the sun
225 model = faceView(model);
227 model = scale(model, vec3(metaballScale));
229 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
231 // Set the billboard color as RGBA = (1.0, 1.0, 1.0, 1.0).
232 vec4 color = {1, 1, 1, 1};
233 glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
234 glm::value_ptr(color));
236 // Map the billboard texture with GL_MODULATE.
237 // i.e. multiply rather than add
238 // but glTexEnv is for the old fixed function pipeline --
239 // need to just tell our fragment shader then to modulate
241 glBindTexture(GL_TEXTURE_2D, bbTexIds[dIdx]);
242 glUniform1i(glGetUniformLocation(bbProg, "modulate"), 1);
244 // Render the billboard.
245 glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
247 // Read the pixel value corresponding to the center of metaball k.
248 // 1. First get position in opengl screen space: from [-1,1]
249 // 2. Normalize to [0,1]
250 // 3. Multiply by (width * height)
252 ((vec2(proj * view * model * vec4(0, 0, 0, 1)) + vec2(1)) / vec2(2)) *
253 vec2(shadeWidth, shadeHeight);
257 // TODO: This is a huge bottleneck
258 glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_FLOAT, &pixel);
260 // Multiply the pixel value by the sunlight color.
261 pixel *= envColors[envColorIdx][0];
263 // Store the color into an array C[k] as the color of the billboard.
267 glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[pboIdx]);
268 // It would be nice if this worked. But it doesn't
269 // macOS driver does this synchronously
270 /* glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,
273 glReadPixels(screenPos.x, screenPos.y, 64, 64, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
275 int nextPbo = (pboIdx + 1) % numPbos;
276 if (i >= numPbos - 1) {
277 // start mapping the read values back
278 mapPixelRead(nextPbo, i - numPbos + 1);
285 /* fprintf(stderr, "\n"); */
288 // sink remaining reads
289 for (int i = 0; i < numPbos; i++) {
290 mapPixelRead(i, metaballs.size() - numPbos + i);
294 auto elapsed = std::chrono::system_clock::now() - begin_time;
295 double elapsed_seconds =
296 std::chrono::duration_cast<std::chrono::duration<double>>(elapsed)
298 fprintf(stderr, "Time taken to shade: %fs\n", elapsed_seconds);
302 glViewport(0, 0, width, height);
305 void renderObject() {
308 glUseProgram(sunProg);
309 mat4 model = translate(mat4(1), sunPos);
310 model = lookAt(sunPos, sunPos + sunDir, {0, 1, 0}) * model;
311 model = translate(scale(translate(model, -sunPos), vec3(0.3)), sunPos);
312 glUniformMatrix4fv(glGetUniformLocation(sunProg, "model"), 1, GL_FALSE,
313 glm::value_ptr(model));
314 glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
317 void renderClouds() {
318 glUseProgram(bbProg);
320 // Sort metaballs in descending order from the viewpoint
321 sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
322 return distance(camPos, a.pos) > distance(camPos, b.pos);
325 glUniform1i(glGetUniformLocation(bbProg, "debug"), curMode != render);
327 glDisable(GL_DEPTH_TEST);
329 // shaderOutput * 1 + buffer * shader alpha
330 glBlendFunc(GL_ONE, GL_SRC_ALPHA);
332 /* glBlendColor(1.f,1.f,1.f,1.f); */
333 /* glBlendFuncSeparate(GL_ONE, GL_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_SRC_ALPHA);
336 glActiveTexture(GL_TEXTURE0);
337 glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
339 for (int i = 0; i < metaballs.size(); i++) {
340 Metaball k = metaballs[i];
342 GLuint modelLoc = glGetUniformLocation(bbProg, "model");
344 // Place the billboard at the center of the corresponding metaball n.
345 mat4 model = translate(mat4(1), k.pos);
346 // Rotate the billboard so that its normal is oriented to the viewpoint.
347 model = faceView(model);
349 model = scale(model, vec3(metaballScale));
351 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
353 // Set the billboard color as C[n].
355 glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
356 glm::value_ptr(k.col));
358 // Map the billboard texture.
359 int dIdx = k.d * (NQ - 1);
360 glBindTexture(GL_TEXTURE_2D, bbTexIds[dIdx]);
362 // Don't modulate it -- blend it
363 glUniform1i(glGetUniformLocation(bbProg, "modulate"), 0);
365 glUniform1f(glGetUniformLocation(bbProg, "debugColor"),
366 curMode == debugColor);
367 if (curMode != render) {
369 if (curMode == debugContDist)
371 else if (curMode == debugProbAct)
372 debugVal = cs.p_act[k.coords.x][k.coords.y][k.coords.z] / P_ACT;
373 else if (curMode == debugProbExt)
374 debugVal = cs.p_ext[k.coords.x][k.coords.y][k.coords.z] / P_EXT;
375 glUniform1f(glGetUniformLocation(bbProg, "debugVal"), debugVal);
376 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
377 model = scale(model, vec3(0.1));
378 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
381 // Render the billboard with the blending function.
382 glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
386 bool curBeenShaded = false;
389 if (!curBeenShaded && (curMode == render || curMode == debugColor)) {
390 // TODO: find a way to make sure there's no clipping
391 view = glm::lookAt(sunPos + sunDir * vec3(100.f), sunPos, {0, 0, 1});
392 // TODO: calculate bounds so everything is covered
393 proj = glm::ortho(2.5f, -2.5f, -2.5f, 2.5f, znear, 10000.f);
394 glUseProgram(bbProg);
395 setProjectionAndViewUniforms(bbProg);
397 glClearColor(1, 1, 1, 1);
398 glClear(GL_COLOR_BUFFER_BIT);
400 curBeenShaded = true;
403 view = glm::lookAt(camPos, viewPos, {0, 1, 0});
404 const float aspect = width / height;
405 proj = glm::perspective(45.f, aspect, znear, zfar);
406 glUseProgram(sunProg);
407 setProjectionAndViewUniforms(sunProg);
408 glUseProgram(bbProg);
409 setProjectionAndViewUniforms(bbProg);
411 vec4 skyColor = envColors[envColorIdx][1];
412 glClearColor(skyColor.r, skyColor.g, skyColor.b,
413 skyColor.a); // background color
414 glClear(GL_COLOR_BUFFER_BIT);
415 renderObject(); // render things that aren't clouds
421 bool needsRedisplay = false;
423 if (needsRedisplay) {
426 needsRedisplay = false;
427 glutTimerFunc(16, timer, 0);
430 void keyboard(unsigned char key, int x, int y) {
432 calculateMetaballs();
433 needsRedisplay = true;
434 curBeenShaded = false;
438 needsRedisplay = true;
441 curMode = debugContDist;
442 needsRedisplay = true;
445 curMode = debugColor;
446 needsRedisplay = true;
449 curMode = debugProbAct;
450 needsRedisplay = true;
453 curMode = debugProbExt;
454 needsRedisplay = true;
457 envColorIdx = (envColorIdx + 1) % envColors.size();
458 needsRedisplay = true;
459 curBeenShaded = false;
463 int prevMouseX, prevMouseY;
464 bool firstMouse = true;
465 void motion(int x, int y) {
471 float dx = x - prevMouseX, dy = y - prevMouseY;
474 const vec3 origin(0, 0, 0);
475 const float sensitivity = 0.003f;
476 auto camMat = translate(mat4(1), origin + camPos);
477 auto rotation = rotate(rotate(mat4(1), -dx * sensitivity, {0, 1, 0}),
478 -dy * sensitivity, {1, 0, 0});
479 auto rotAroundOrig = camMat * rotation * translate(mat4(1), origin - camPos);
480 camPos = rotAroundOrig * glm::vec4(camPos, 0);
481 needsRedisplay = true;
484 void passiveMotion(int x, int y) {
489 void reshape(int w, int h) {
494 int main(int argc, char **argv) {
495 glutInit(&argc, argv);
496 glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA |
497 GLUT_3_2_CORE_PROFILE);
498 glutInitWindowSize(width, height);
499 glutCreateWindow("Clouds");
500 glutDisplayFunc(display);
501 glutReshapeFunc(reshape);
502 glutKeyboardFunc(keyboard);
503 glutMotionFunc(motion);
504 glutPassiveMotionFunc(passiveMotion);
505 glutTimerFunc(16, timer, 0);
509 Program prog("billboardvert.glsl", "billboardfrag.glsl");
510 bbProg = prog.progId;
511 Program sProg("sunvert.glsl", "sunfrag.glsl");
512 sunProg = sProg.progId;
514 glGenVertexArrays(1, &bbVao);
515 glUseProgram(sunProg);
516 glBindVertexArray(bbVao);
517 glUseProgram(bbProg);
518 glBindVertexArray(bbVao);
520 glGenBuffers(2, vbos);
522 vector<vec3> poss = {{-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}};
523 vector<GLuint> indices = {2, 1, 0, 3, 2, 0};
525 GLuint posLoc = glGetAttribLocation(bbProg, "vPosition");
526 glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
527 glBufferData(GL_ARRAY_BUFFER, poss.size() * sizeof(glm::vec3), &poss[0],
529 glEnableVertexAttribArray(posLoc);
530 glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
532 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]);
533 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint),
534 &indices[0], GL_STATIC_DRAW);
538 precalculateBillboardTextures();
541 calculateMetaballs();
544 // setup PBOs for buffering readPixels
545 glGenBuffers(numPbos, pboBufs);
546 for (int i = 0; i < numPbos; i++) {
547 glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[i]);
548 glBufferData(GL_PIXEL_PACK_BUFFER, 64 * 64 * 4, NULL,
551 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);