f0f3a957576d17da6fdf5b60c521174e060eaeec
[clouds.git] / clouds.cpp
1 #include "GL/glew.h"
2 #include "debug.hpp"
3 #include "program.hpp"
4 #include "simulation.hpp"
5 #include <GLUT/glut.h>
6 #include <array>
7 #include <chrono>
8 #include <cmath>
9 #include <cstdio>
10 #include <cstdlib>
11 #include <glm/ext.hpp>
12 #include <glm/glm.hpp>
13 #include <sys/stat.h>
14 #include <vector>
15
16 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
17
18 enum Mode { render, debugContDist, debugColor, debugProbExt, debugProbAct };
19 Mode curMode = render;
20
21 using namespace std;
22 using namespace glm;
23
24 const float metaballR = 1.f / 16.f;
25 inline float metaballField(float r) {
26   if (r > 1)
27     return 0;
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;
31 }
32
33 const float normalizationFactor = (748.f / 405.f) * M_PI;
34
35 void checkError() {
36   if (GLenum e = glGetError()) {
37     fprintf(stderr, "%s\n", gluErrorString(e));
38     abort();
39   }
40 }
41
42 GLuint bbProg, sunProg;
43 GLuint bbVao;
44
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?
48
49 #define NQ 64
50 GLuint bbTexIds[NQ];
51
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);
57
58   for (int d = 0; d < NQ; d++) {
59     float data[32 * 32];
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;
65         data[i + j * 32] =
66             1 - fmin(1, (3 * density * (metaballField(r) / normalizationFactor)));
67       }
68     }
69
70     mkdir("bbtex", 0777);
71     char path[32];
72     snprintf(path, 32, "bbtex/%i.tga", d);
73     saveGrayscale(data, 32, 32, path);
74
75     glBindTexture(GL_TEXTURE_2D, bbTexIds[d]);
76
77     glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 32, 32, 0, GL_RED, GL_FLOAT, data);
78     glGenerateMipmap(GL_TEXTURE_2D); // required, otherwise texture is blank
79
80     fprintf(stderr, "\r%i out of %i densities calculated%s", d + 1, NQ,
81             d == NQ - 1 ? "\n" : "");
82   }
83 }
84
85 struct Metaball {
86   vec3 pos;
87   ivec3 coords;
88   /** Density */
89   float d;
90   vec4 col;
91 };
92
93 array<Metaball, CLOUD_DIM_X * CLOUD_DIM_Y * CLOUD_DIM_Z> metaballs;
94
95 const float cloudScale = metaballR;
96 const float metaballScale = metaballR * 1.5f;
97 Clouds cs;
98
99 void calculateMetaballs() {
100   stepClouds(&cs);
101   /* for (int i = 0; i < 256; i++) { */
102   /*   float x = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
103   /*   float y = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
104   /*   float z = ((float)rand()/(float)(RAND_MAX) - 0.5) * 2; */
105   /*   float r = (float)rand()/(float)(RAND_MAX) * 1; */
106   /*   Metaball m = {{x,y,z}, r}; */
107   /*   metaballs.push_back(m); */
108   /* } */
109   for (int i = 0; i < CLOUD_DIM_X; i++) {
110     for (int j = 0; j < CLOUD_DIM_Y; j++) {
111       for (int k = 0; k < CLOUD_DIM_Z; k++) {
112         Metaball m = {vec3(i, j, k) * vec3(cloudScale), {i, j, k}};
113         /* m.pos = (m.pos * vec3(2)) - (cloudScale / 2); */
114         m.pos -= vec3(CLOUD_DIM_X, CLOUD_DIM_Y, CLOUD_DIM_Z) * cloudScale / 2.f;
115         m.d = cs.q[i][j][k];
116         /* m.d = 0; */
117         metaballs[i * CLOUD_DIM_Y * CLOUD_DIM_Z + j * CLOUD_DIM_Z + k] = m;
118       }
119     }
120   }
121   /* for (int z = 0; z < CLOUD_DIM_Z; z++) */
122   /*   metaballs[32 * CLOUD_DIM_Y * CLOUD_DIM_Z + 32 * CLOUD_DIM_Z + z].d = 1;
123    */
124 }
125
126 vec3 sunPos = {0, 5, 0}, sunDir = {0, -1, 0};
127 size_t envColorIdx = 0;
128 // First color is sun color, second is sky color
129 std::array<std::array<vec4, 2>, 3> envColors{
130     {{vec4(1, 1, 1, 1), vec4(0.9, 1, 1, 1)},
131      {vec4(0.939, 0.632, 0.815, 1), vec4(0.9, 1, 1, 1)},
132      {vec4(0.999, 0.999, 0.519, 1), vec4(0.981, 0.667, 0.118, 1)}}};
133 vec3 camPos = {0, 0, -3}, viewPos = {0, 0, 0};
134 mat4 proj; // projection matrix
135 mat4 view; // view matrix
136 float znear = 0.001, zfar = 1000;
137 // for performance with glReadPixels these should be powers of 2!
138 float width = 1200, height = 800;
139
140 void setProjectionAndViewUniforms(GLuint progId) {
141   GLuint projLoc = glGetUniformLocation(progId, "projection");
142   glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
143
144   GLuint viewLoc = glGetUniformLocation(progId, "view");
145   glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
146 }
147
148 /** Orientates the transformation matrix to face the camera in the view matrix
149  */
150 mat4 faceView(mat4 m) {
151   m[0][0] = view[0][0];
152   m[0][1] = view[1][0];
153   m[0][2] = view[2][0];
154   m[1][0] = view[0][1];
155   m[1][1] = view[1][1];
156   m[1][2] = view[2][1];
157   m[2][0] = view[0][2];
158   m[2][1] = view[1][2];
159   m[2][2] = view[2][2];
160   return m;
161 }
162
163 #define PBO
164
165 /* const int shadeWidth = 256, shadeHeight = 256; */
166 const int shadeWidth = 256, shadeHeight = 256;
167
168 #ifdef PBO
169 const int numPbos = 64;
170 GLuint pboBufs[numPbos];
171 GLbyte sink[shadeWidth * shadeHeight * 4];
172
173 void inline mapPixelRead(int pboBuf, int metaball) {
174       glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[pboBuf]);
175       GLubyte *src = (GLubyte *)glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, 4 * sizeof(GLubyte),
176           GL_MAP_READ_BIT);
177       vec4 pixel = vec4(src[0], src[1], src[2], src[3]) / vec4(255.f);
178       glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
179
180       glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
181
182       // Multiply the pixel value by the sunlight color.
183       pixel *= envColors[envColorIdx][0];
184
185       // Store the color for the previous set of pixels
186       metaballs[metaball].col = pixel;
187 }
188
189 #endif
190
191 void shadeClouds() {
192
193   glDisable(GL_DEPTH_TEST);
194   // shaderOutput * 0 + buffer * shader alpha
195   glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
196   glEnable(GL_BLEND);
197
198   // sort by ascending distance from the sun
199   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
200     return distance(sunPos, a.pos) < distance(sunPos, b.pos);
201   });
202
203   glActiveTexture(GL_TEXTURE0);
204   glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
205
206   GLuint modelLoc = glGetUniformLocation(bbProg, "model");
207   glUniform1i(glGetUniformLocation(bbProg, "debug"), 0);
208
209   glViewport(0, 0, shadeWidth, shadeHeight);
210
211 #ifdef PBO
212   int pboIdx = 0;
213 #endif
214
215   auto begin_time = std::chrono::system_clock::now();
216   size_t i = 0;
217   for (auto &k : metaballs) {
218     /* fprintf(stderr, "\rShading metaball %lu/%lu...", i, metaballs.size()); */
219     // place the billboard at the center of k
220     mat4 model = translate(mat4(1), k.pos);
221
222     // rotate the billboard so that its normal is oriented to the sun
223     model = faceView(model);
224
225     model = scale(model, vec3(metaballScale));
226
227     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
228
229     // Set the billboard color as RGBA = (1.0, 1.0, 1.0, 1.0).
230     vec4 color = {1, 1, 1, 1};
231     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
232                  glm::value_ptr(color));
233
234     // Map the billboard texture with GL_MODULATE.
235     // i.e. multiply rather than add
236     // but glTexEnv is for the old fixed function pipeline --
237     // need to just tell our fragment shader then to modulate
238     int dIdx = k.d * NQ;
239     glBindTexture(GL_TEXTURE_2D, bbTexIds[dIdx]);
240     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 1);
241
242     // Render the billboard.
243     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
244
245     // Read the pixel value corresponding to the center of metaball k.
246     // 1. First get position in opengl screen space: from [-1,1]
247     // 2. Normalize to [0,1]
248     // 3. Multiply by (width * height)
249     ivec2 screenPos =
250         ((vec2(proj * view * model * vec4(0, 0, 0, 1)) + vec2(1)) / vec2(2)) *
251         vec2(shadeWidth, shadeHeight);
252
253 #ifndef PBO
254     vec4 pixel;
255     // TODO: This is a huge bottleneck
256     glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_FLOAT, &pixel);
257
258     // Multiply the pixel value by the sunlight color.
259     pixel *= envColors[envColorIdx][0];
260
261     // Store the color into an array C[k] as the color of the billboard.
262     k.col = pixel;
263 #else
264
265     glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[pboIdx]);
266     glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,
267                  NULL);
268     // TODO: use this
269     /* glReadPixels(0, 0, shadeWidth, shadeHeight, GL_RGBA, GL_UNSIGNED_BYTE, */
270     /*              NULL); */
271
272     int nextPbo = (pboIdx + 1) % numPbos;
273     if (i >= numPbos - 1) {
274       // start mapping the read values back
275       mapPixelRead(nextPbo, i - numPbos + 1);
276     }
277     pboIdx = nextPbo;
278 #endif
279     
280     i++;
281   }
282   /* fprintf(stderr, "\n"); */
283
284 #ifdef PBO
285   // sink remaining reads
286   for (int i = 0; i < numPbos; i++) {
287     mapPixelRead(i, metaballs.size() - numPbos + i);
288   }
289 #endif
290
291   auto elapsed = std::chrono::system_clock::now() - begin_time;
292   double elapsed_seconds =
293       std::chrono::duration_cast<std::chrono::duration<double>>(elapsed)
294           .count();
295   fprintf(stderr, "Time taken to shade: %fs\n", elapsed_seconds);
296
297   saveFBO();
298   checkError();
299   glViewport(0, 0, width, height);
300 }
301
302 void renderObject() {
303   glDisable(GL_BLEND);
304   // render the sun
305   glUseProgram(sunProg);
306   mat4 model = translate(mat4(1), sunPos);
307   model = lookAt(sunPos, sunPos + sunDir, {0, 1, 0}) * model;
308   model = translate(scale(translate(model, -sunPos), vec3(0.3)), sunPos);
309   glUniformMatrix4fv(glGetUniformLocation(sunProg, "model"), 1, GL_FALSE,
310                      glm::value_ptr(model));
311   glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
312 }
313
314 void renderClouds() {
315   glUseProgram(bbProg);
316
317   // Sort metaballs in descending order from the viewpoint
318   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
319     return distance(camPos, a.pos) > distance(camPos, b.pos);
320   });
321
322   glUniform1i(glGetUniformLocation(bbProg, "debug"), curMode != render);
323
324   glDisable(GL_DEPTH_TEST);
325   glEnable(GL_BLEND);
326   // shaderOutput * 1 + buffer * shader alpha
327   glBlendFunc(GL_ONE, GL_SRC_ALPHA);
328
329   /* glBlendColor(1.f,1.f,1.f,1.f); */
330   /* glBlendFuncSeparate(GL_ONE, GL_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_SRC_ALPHA);
331    */
332
333   glActiveTexture(GL_TEXTURE0);
334   glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
335
336   for (int i = 0; i < metaballs.size(); i++) {
337     Metaball k = metaballs[i];
338
339     GLuint modelLoc = glGetUniformLocation(bbProg, "model");
340
341     // Place the billboard at the center of the corresponding metaball n.
342     mat4 model = translate(mat4(1), k.pos);
343     // Rotate the billboard so that its normal is oriented to the viewpoint.
344     model = faceView(model);
345
346     model = scale(model, vec3(metaballScale));
347
348     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
349
350     // Set the billboard color as C[n].
351     k.col.w = 1;
352     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
353                  glm::value_ptr(k.col));
354
355     // Map the billboard texture.
356     int dIdx = k.d * (NQ - 1);
357     glBindTexture(GL_TEXTURE_2D, bbTexIds[dIdx]);
358
359     // Don't modulate it -- blend it
360     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 0);
361
362     glUniform1f(glGetUniformLocation(bbProg, "debugColor"),
363                 curMode == debugColor);
364     if (curMode != render) {
365       float debugVal = 0;
366       if (curMode == debugContDist)
367         debugVal = k.d;
368       else if (curMode == debugProbAct)
369         debugVal = cs.p_act[k.coords.x][k.coords.y][k.coords.z] / P_ACT;
370       else if (curMode == debugProbExt)
371         debugVal = cs.p_ext[k.coords.x][k.coords.y][k.coords.z] / P_EXT;
372       glUniform1f(glGetUniformLocation(bbProg, "debugVal"), debugVal);
373       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
374       model = scale(model, vec3(0.1));
375       glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
376     }
377
378     // Render the billboard with the blending function.
379     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
380   }
381 }
382
383 bool curBeenShaded = false;
384
385 void display() {
386   if (!curBeenShaded && (curMode == render || curMode == debugColor)) {
387     // TODO: find a way to make sure there's no clipping
388     view = glm::lookAt(sunPos + sunDir * vec3(100.f), sunPos, {0, 0, 1});
389     // TODO: calculate bounds so everything is covered
390     proj = glm::ortho(2.5f, -2.5f, -2.5f, 2.5f, znear, 10000.f);
391     glUseProgram(bbProg);
392     setProjectionAndViewUniforms(bbProg);
393
394     glClearColor(1, 1, 1, 1);
395     glClear(GL_COLOR_BUFFER_BIT);
396     shadeClouds();
397     curBeenShaded = true;
398   }
399
400   view = glm::lookAt(camPos, viewPos, {0, 1, 0});
401   const float aspect = width / height;
402   proj = glm::perspective(45.f, aspect, znear, zfar);
403   glUseProgram(sunProg);
404   setProjectionAndViewUniforms(sunProg);
405   glUseProgram(bbProg);
406   setProjectionAndViewUniforms(bbProg);
407
408   vec4 skyColor = envColors[envColorIdx][1];
409   glClearColor(skyColor.r, skyColor.g, skyColor.b,
410                skyColor.a); // background color
411   glClear(GL_COLOR_BUFFER_BIT);
412   renderObject(); // render things that aren't clouds
413   renderClouds();
414
415   glutSwapBuffers();
416 }
417
418 bool needsRedisplay = false;
419 void timer(int _) {
420   if (needsRedisplay) {
421     glutPostRedisplay();
422   }
423   needsRedisplay = false;
424   glutTimerFunc(16, timer, 0);
425 }
426
427 void keyboard(unsigned char key, int x, int y) {
428   if (key == ' ') {
429     calculateMetaballs();
430     needsRedisplay = true;
431     curBeenShaded = false;
432   }
433   if (key == '0') {
434     curMode = render;
435     needsRedisplay = true;
436   }
437   if (key == '1') {
438     curMode = debugContDist;
439     needsRedisplay = true;
440   }
441   if (key == '2') {
442     curMode = debugColor;
443     needsRedisplay = true;
444   }
445   if (key == '3') {
446     curMode = debugProbAct;
447     needsRedisplay = true;
448   }
449   if (key == '4') {
450     curMode = debugProbExt;
451     needsRedisplay = true;
452   }
453   if (key == 's') {
454     envColorIdx = (envColorIdx + 1) % envColors.size();
455     needsRedisplay = true;
456     curBeenShaded = false;
457   }
458 }
459
460 int prevMouseX, prevMouseY;
461 bool firstMouse = true;
462 void motion(int x, int y) {
463   if (firstMouse) {
464     prevMouseX = x;
465     prevMouseY = y;
466     firstMouse = false;
467   }
468   float dx = x - prevMouseX, dy = y - prevMouseY;
469   prevMouseX = x;
470   prevMouseY = y;
471   const vec3 origin(0, 0, 0);
472   const float sensitivity = 0.003f;
473   auto camMat = translate(mat4(1), origin + camPos);
474   auto rotation = rotate(rotate(mat4(1), -dx * sensitivity, {0, 1, 0}),
475                          -dy * sensitivity, {1, 0, 0});
476   auto rotAroundOrig = camMat * rotation * translate(mat4(1), origin - camPos);
477   camPos = rotAroundOrig * glm::vec4(camPos, 0);
478   needsRedisplay = true;
479 }
480
481 void passiveMotion(int x, int y) {
482   prevMouseX = x;
483   prevMouseY = y;
484 }
485
486 void reshape(int w, int h) {
487   width = w;
488   height = h;
489 }
490
491 int main(int argc, char **argv) {
492   glutInit(&argc, argv);
493   glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA |
494                       GLUT_3_2_CORE_PROFILE);
495   glutInitWindowSize(width, height);
496   glutCreateWindow("Clouds");
497   glutDisplayFunc(display);
498   glutReshapeFunc(reshape);
499   glutKeyboardFunc(keyboard);
500   glutMotionFunc(motion);
501   glutPassiveMotionFunc(passiveMotion);
502   glutTimerFunc(16, timer, 0);
503
504   glewInit();
505
506   Program prog("billboardvert.glsl", "billboardfrag.glsl");
507   bbProg = prog.progId;
508   Program sProg("sunvert.glsl", "sunfrag.glsl");
509   sunProg = sProg.progId;
510
511   glGenVertexArrays(1, &bbVao);
512   glUseProgram(sunProg);
513   glBindVertexArray(bbVao);
514   glUseProgram(bbProg);
515   glBindVertexArray(bbVao);
516   GLuint vbos[2];
517   glGenBuffers(2, vbos);
518
519   vector<vec3> poss = {{-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}};
520   vector<GLuint> indices = {2, 1, 0, 3, 2, 0};
521
522   GLuint posLoc = glGetAttribLocation(bbProg, "vPosition");
523   glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
524   glBufferData(GL_ARRAY_BUFFER, poss.size() * sizeof(glm::vec3), &poss[0],
525                GL_STATIC_DRAW);
526   glEnableVertexAttribArray(posLoc);
527   glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
528
529   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]);
530   glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint),
531                &indices[0], GL_STATIC_DRAW);
532
533   prog.validate();
534
535   precalculateBillboardTextures();
536
537   initClouds(&cs);
538   calculateMetaballs();
539
540 #ifdef PBO
541   // setup PBOs for buffering readPixels
542   glGenBuffers(numPbos, pboBufs);
543   for (int i = 0; i < numPbos; i++) {
544     glBindBuffer(GL_PIXEL_PACK_BUFFER, pboBufs[i]);
545     glBufferData(GL_PIXEL_PACK_BUFFER, shadeWidth * shadeHeight * 4, NULL,
546                  GL_DYNAMIC_READ);
547   }
548   glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
549 #endif
550
551   glutMainLoop();
552
553   return 0;
554 }