Start simulation
[clouds.git] / clouds.cpp
1 #include "debug.hpp"
2 #include "simulation.h"
3 #include "program.hpp"
4 #include <GL/glew.h>
5 #include <GLUT/glut.h>
6 #include <cmath>
7 #include <cstdio>
8 #include <cstdlib>
9 #include <glm/ext.hpp>
10 #include <glm/glm.hpp>
11 #include <vector>
12
13 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
14
15 using namespace std;
16 using namespace glm;
17
18 // calculate continuous distribution
19 void calcContDist(Clouds *clds);
20
21 float w(int i, int j, int k) { return 1; }
22
23 const float metaballR = 1;
24 float metaballField(float r) {
25   if (r > metaballR)
26     return 0;
27   const float a = r / metaballR;
28   return (-4.f / 9.f * powf(a, 6)) + (17.f / 9.f * powf(a, 4)) -
29          (22.f / 9.f * powf(a, 2)) + 1;
30 }
31
32 /* const float normalizationFactor = 748.f / 405.f * M_PI * metaballR; */
33
34 void calcContDist(Clouds *clds, float t) {
35   const int i0 = 2, j0 = 2, k0 = 2, t0 = 2;
36   const float divisor =
37       1.f / ((2 * t0 + 1) * (2 * k0 + 1) * (2 * j0 + 1) * (2 * i0 + 1));
38   float sum = 0;
39   for (int i = 0; i < CLOUD_DIM; i++) {
40     for (int j = 0; j < CLOUD_DIM; j++) {
41       for (int k = 0; k < CLOUD_DIM; k++) {
42
43         // inner sums
44         /* for (int tp = -t0, tp < t0; tp++) { */
45         for (int ip = -i0; ip < i0; ip++) {
46           for (int jp = -j0; jp < j0; jp++) {
47             for (int kp = -k0; kp < k0; kp++) {
48
49               sum += w(ip, jp, kp) * (float)clds->cld[i + ip][j + jp][k + kp];
50             }
51           }
52         }
53         /* } */
54
55         clds->contDist[i][j][k] = sum / divisor;
56       }
57     }
58   }
59 }
60
61 void checkError() {
62   if (GLenum e = glGetError()) {
63     fprintf(stderr, "%s\n", gluErrorString(e));
64     abort();
65   }
66 }
67
68 vector<vec4> bbColors;
69
70 GLuint bbProg;
71 GLuint bbVao;
72
73 // Here we need to generate n_q textures for different densities of metaballs
74 // These textures then go on the billboards
75 // The texture stores attenuation ratio?
76
77 #define NQ 1
78 GLuint bbTexIds[NQ];
79
80 // Stores attenuation ratio inside r channel
81 // Should be highest value at center
82 void precalculateBillboardTextures() {
83   float data[32 * 32];
84   // TODO: properly calculate this instead of whatever this is
85   for (int j = 0; j < 32; j++)
86     for (int i = 0; i < 32; i++)
87       data[i + j * 32] = fmin(1.f, 0.5f + 1.f * (distance(vec2(i, j), vec2(16, 16)) / 16));
88
89   glGenTextures(NQ, bbTexIds);
90
91   for (int i = 0; i < NQ; i++) {
92     glBindTexture(GL_TEXTURE_2D, bbTexIds[i]);
93     checkError();
94
95     glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 32, 32, 0, GL_RED, GL_FLOAT, data);
96     glGenerateMipmap(GL_TEXTURE_2D); // required, otherwise texture is blank
97
98     checkError();
99   }
100 }
101
102 struct Metaball {
103   vec3 pos;
104   float r;
105 };
106 // TODO: why is the x axis flipped??
107 /* vector<Metaball> metaballs = {{{-0.5, 0.5, 0.5}, 0.25}, */
108 /*                               {{-0.3, 0.5, 0.3}, 0.25}}; */
109 vector<Metaball> metaballs = {{{0, 0, 0.5}, 1.f},
110                               {{0, 0.3, 0.3}, 0.7f}};
111
112 Clouds cs;
113
114 void calculateMetaballs() {
115   stepClouds(&cs);
116   metaballs.clear();
117   for (int i = 0; i < CLOUD_DIM; i++) {
118     for (int j = 0; j < CLOUD_DIM; j++) {
119       for (int k = 0; k < CLOUD_DIM; k++) {
120         if (cs.cld[i][j][k]) {
121           /* float x = (float)rand()/(float)(RAND_MAX); */
122           /* float y = (float)rand()/(float)(RAND_MAX); */
123           /* float z = (float)rand()/(float)(RAND_MAX); */
124           /* float r = (float)rand()/(float)(RAND_MAX); */
125           /* Metaball m = {{x,y, 0.3 + z * 0.5}, r}; */
126           /* metaballs.push_back(m); */
127           Metaball m = {{i / (float)CLOUD_DIM, j / (float)CLOUD_DIM, k / (float)CLOUD_DIM},
128                         1.f / (float)CLOUD_DIM };
129           m.pos = (m.pos * vec3(2)) - vec3(1);
130           metaballs.push_back(m);
131         }
132       }
133     }
134   }
135   fprintf(stderr, "num metaballs: %lu\n", metaballs.size());
136 }
137
138 vec3 sunPos = {0, 2, 2}, viewPos = {0, 0, 0}, lookPos = {0, 0, 1};
139 mat4 proj; // projection matrix
140 mat4 view; // view matrix
141 float znear = 0.001, zfar = 1000;
142 float width = 600, height = 400;
143 float aspect = width / height;
144
145 void setProjectionAndViewUniforms(GLuint progId) {
146   GLuint projLoc = glGetUniformLocation(progId, "projection");
147   glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
148
149   GLuint viewLoc = glGetUniformLocation(progId, "view");
150   glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
151 }
152
153 /** Orientates the transformation matrix to face the camera in the view matrix
154  */
155 void faceView(mat4 m) {
156   m[0][0] = view[0][0];
157   m[0][1] = view[1][0];
158   m[0][2] = view[2][0];
159   m[1][0] = view[0][1];
160   m[1][1] = view[1][1];
161   m[1][2] = view[2][1];
162   m[2][0] = view[0][2];
163   m[2][1] = view[1][2];
164   m[2][2] = view[2][2];
165 }
166
167 GLuint attenuationTex;
168
169 void shadeClouds() {
170
171   bbColors.clear();
172
173   glDisable(GL_DEPTH_TEST);
174   // shaderOutput * 0 + buffer * shader alpha
175   glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
176   glEnable(GL_BLEND);
177
178   // sort by ascending distance from the sun
179   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
180     return distance(sunPos, a.pos) < distance(sunPos, b.pos);
181   });
182
183   glActiveTexture(GL_TEXTURE0);
184   glBindTexture(GL_TEXTURE_2D, bbTexIds[0]);
185   glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
186
187   GLuint modelLoc = glGetUniformLocation(bbProg, "model");
188
189   for (auto k : metaballs) {
190     // place the billboard at the center of k
191     mat4 model = scale(translate(mat4(1), k.pos), vec3(k.r) * 2.f);
192
193     // rotate the billboard so that its normal is oriented to the sun
194     faceView(model);
195
196     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
197
198     // Set the billboard color as RGBA = (1.0, 1.0, 1.0, 1.0).
199     vec4 color = {1, 1, 1, 1};
200     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
201                  glm::value_ptr(color));
202
203     // Map the billboard texture with GL_MODULATE.
204     // i.e. multiply rather than add
205     // but glTexEnv is for the old fixed function pipeline --
206     // need to just tell our fragment shader then to modulate
207     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 1);
208
209     // Render the billboard.
210     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
211
212     // Read the pixel value corresponding to the center of metaball k.
213     // 1. First get position in opengl screen space: from [-1,1]
214     // 2. Normalize to [0,1]
215     // 3. Multiply by (width * height)
216     vec2 screenPos = ((vec2(proj * view * model * vec4(0,0,0,1)) + vec2(1)) / vec2(2))
217                       * vec2(width, height);
218     vec4 pixel;
219     glReadPixels(screenPos.x, screenPos.y, 1, 1, GL_RGBA, GL_FLOAT, value_ptr(pixel));
220     /* fprintf(stderr, "pixel:"); */
221     /* dump(pixel); */
222
223     // Multiply the pixel value by the sunlight color.
224     vec4 sunColor = {1, 1, 0.9, 1};
225     pixel *= sunColor;
226
227     // Store the color into an array C[k] as the color of the billboard.
228     bbColors.push_back(pixel);
229   }
230
231   saveFBO();
232   checkError();
233 }
234
235 void renderObject() {}
236
237 void renderClouds() {
238   // Sort metaballs in descending order from the viewpoint
239   sort(metaballs.begin(), metaballs.end(), [](Metaball &a, Metaball &b) {
240     return distance(viewPos, a.pos) > distance(viewPos, b.pos);
241   });
242
243   glDisable(GL_DEPTH_TEST);
244   glEnable(GL_BLEND);
245   // shaderOutput * 1 + buffer * shader alpha
246   glBlendFunc(GL_ONE, GL_SRC_ALPHA);
247   for (int i = 0; i < metaballs.size(); i++) {
248     Metaball k = metaballs[i];
249
250     GLuint modelLoc = glGetUniformLocation(bbProg, "model");
251
252     // Place the billboard at the center of the corresponding metaball n.
253     mat4 model = scale(translate(mat4(1), k.pos), vec3(k.r) * 2.f);
254     // Rotate the billboard so that its normal is oriented to the viewpoint.
255     faceView(model);
256
257     glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
258
259     // Set the billboard color as C[n].
260     /* fprintf(stderr, "bbColors[i]: "); */
261     /* dump(bbColors[i]); */
262     /* bbColors[i].x = 1 - bbColors[i].x; */
263     /* bbColors[i].y = 1 - bbColors[i].y; */
264     /* bbColors[i].z = 1 - bbColors[i].z; */
265     bbColors[i].w = 1;
266     glUniform4fv(glGetUniformLocation(bbProg, "color"), 1,
267                  glm::value_ptr(bbColors[i]));
268
269     // Map the billboard texture.
270     glActiveTexture(GL_TEXTURE0);
271     glBindTexture(GL_TEXTURE_2D, bbTexIds[0]);
272     glUniform1i(glGetUniformLocation(bbProg, "tex"), 0);
273
274     // Don't modulate it -- blend it
275     glUniform1i(glGetUniformLocation(bbProg, "modulate"), 0);
276
277     // Render the billboard with the blending function.
278     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
279   }
280 }
281
282 void display() {
283   view = glm::lookAt(sunPos, viewPos, {0, 1, 0});
284   proj = glm::ortho(1.f * aspect, -1.f * aspect, -1.f, 1.f, znear, zfar);
285   setProjectionAndViewUniforms(bbProg);
286
287   glClearColor(1, 1, 1, 1);
288   glClear(GL_COLOR_BUFFER_BIT);
289   shadeClouds();
290
291   view = glm::lookAt(viewPos, lookPos, {0, 1, 0});
292   proj = glm::perspective(60.f, aspect, znear, zfar);
293   setProjectionAndViewUniforms(bbProg);
294
295   glClearColor(0.73,1,1,1); // background color
296   glClear(GL_COLOR_BUFFER_BIT);
297   renderObject();               // render things that aren't clouds
298   renderClouds();
299
300   glutSwapBuffers();
301 }
302
303 void timer(int _) {
304   /* calculateMetaballs(); */
305   /* glutPostRedisplay(); */
306   /* glutTimerFunc(16, timer, 0); */
307 }
308
309 void keyboard(unsigned char key, int x, int y) {
310         if (key == ' ') {
311                 calculateMetaballs();
312                 glutPostRedisplay();
313         }
314 }
315
316 int main(int argc, char **argv) {
317   glutInit(&argc, argv);
318   glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB |
319                       GLUT_3_2_CORE_PROFILE);
320   glutInitWindowSize(width, height);
321   glutCreateWindow("Clouds");
322   glutDisplayFunc(display);
323
324   glewInit();
325
326   Program prog("billboardvert.glsl", "billboardfrag.glsl");
327
328   bbProg = prog.progId;
329   glUseProgram(bbProg);
330
331   glGenVertexArrays(1, &bbVao);
332   glBindVertexArray(bbVao);
333   GLuint vbos[2];
334   glGenBuffers(2, vbos);
335
336   vector<vec3> poss = {{-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}};
337   vector<GLuint> indices = {2, 1, 0, 3, 2, 0};
338
339   GLuint posLoc = glGetAttribLocation(bbProg, "vPosition");
340   glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
341   glBufferData(GL_ARRAY_BUFFER, poss.size() * sizeof(glm::vec3), &poss[0],
342                GL_STATIC_DRAW);
343   glEnableVertexAttribArray(posLoc);
344   glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
345
346   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbos[1]);
347   glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint),
348                &indices[0], GL_STATIC_DRAW);
349
350   prog.validate();
351
352   precalculateBillboardTextures();
353
354   initClouds(&cs);
355   calculateMetaballs();
356
357   glGenTextures(1, &attenuationTex);
358
359   glutKeyboardFunc(keyboard);
360   glutTimerFunc(16, timer, 0);
361
362   // set up billboard prog
363
364   glutMainLoop();
365
366   return 0;
367 }