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