3 #include <gmath/gmath.h>
13 * - whistle hhgg music
14 * - colliding particles merge
15 * - select objects and center camera on them
16 * - tesselate only where necessary
27 Particle *next, *prev;
49 int num_verts, num_idx, num_quads;
51 unsigned int vbo_v, vbo_uv, ibo;
56 #define GRID_SIZE 2048
58 #define GRID_X(idx) (((idx) >> GRID_BITS) & (GRID_SIZE - 1))
59 #define GRID_Y(idx) ((idx) & (GRID_SIZE - 1))
60 #define GRID_DELTA ((float)FIELD_SIZE / (float)GRID_SIZE)
62 #define FIELD_SIZE 2048
63 #define MIN_CAM_DIST 1.0f
64 #define MAX_CAM_DIST 350.0f
66 #define MASS_TO_RADIUS(m) log((m) + 1.0)
68 #define CONTRIB_THRES 0.005
69 #define CONTRIB_RANGE(m) sqrt((m) / CONTRIB_THRES)
71 static int pos_to_grid(float x, float y);
72 static Vec2 grid_to_pos(int gx, int gy);
74 static void calc_contrib_bounds(const Vec2 &pos, float mass, Rect *rect);
75 static void add_influence(const Vec2 &pos, float mass, float radius, const Rect &cbox);
77 static Vec2 calc_field_grad(int gidx);
79 static void destroy_quadmesh(QuadMesh *m);
80 static void draw_quadmesh(const QuadMesh *m, unsigned int prim = GL_QUADS);
81 static void gen_quad_plane(QuadMesh *mesh, float width, float height, int usub, int vsub);
83 static void spawn_particle(const Vec2 &pos, const Vec2 &vel, float mass);
84 static void add_particle(Particle *p);
85 static void remove_particle(Particle *p);
86 static Particle *alloc_particle();
87 void free_particle(Particle *p);
89 static float grid[GRID_SIZE * GRID_SIZE];
90 static Particle *grid_part[GRID_SIZE * GRID_SIZE];
91 static Texture *grid_tex;
93 static Particle *plist;
95 static std::vector<Emitter*> emitters;
97 static Texture *gvis_tex; // texture tile for visualizing a grid
98 static unsigned int field_sdr;
99 static int tess_level = 64;
100 static float field_scale = 16.0f;
102 static QuadMesh field_mesh;
105 static unsigned int particle_sdr;
107 static float cam_theta;
108 static float cam_dist = 100.0f;
109 static Vec2 *targ_pos;
110 static Mat4 view_matrix, proj_matrix;
112 // emitter placement data (filled by event handlers, completed in update)
113 static bool emit_place_pending;
114 static Vec2 emit_place_pos;
117 bool GameScreen::init()
119 grid_tex = new Texture;
120 grid_tex->create(GRID_SIZE, GRID_SIZE, TEX_2D, GL_LUMINANCE32F_ARB);
121 grid_tex->set_anisotropy(glcaps.max_aniso);
123 gvis_tex = new Texture;
124 if(!gvis_tex->load("data/purple_grid.png")) {
127 gvis_tex->set_anisotropy(glcaps.max_aniso);
129 unsigned int vsdr, tcsdr, tesdr, psdr;
131 if(!(vsdr = load_vertex_shader("sdr/field.v.glsl")) ||
132 !(tcsdr = load_tessctl_shader("sdr/field.tc.glsl")) ||
133 !(tesdr = load_tesseval_shader("sdr/field.te.glsl")) ||
134 !(psdr = load_pixel_shader("sdr/field.p.glsl"))) {
138 if(!(field_sdr = create_program_link(vsdr, tcsdr, tesdr, psdr, 0))) {
141 set_uniform_int(field_sdr, "gvis_tex", 0);
142 set_uniform_int(field_sdr, "field_tex", 1);
143 set_uniform_float(field_sdr, "gvis_scale", FIELD_SIZE / 32.0f);
144 set_uniform_int(field_sdr, "tess_level", tess_level);
145 set_uniform_float(field_sdr, "field_scale", field_scale);
147 gen_quad_plane(&field_mesh, FIELD_SIZE, FIELD_SIZE, 32, 32);
150 gen_geosphere(pmesh, 1.0, 2);
152 if(!(particle_sdr = create_program_load("sdr/sph.v.glsl", "sdr/sph.p.glsl"))) {
157 emit_place_pos = Vec2(0, 0);
158 emit_place_pending = true;
160 assert(glGetError() == GL_NO_ERROR);
164 void GameScreen::destroy()
166 free_program(field_sdr);
169 destroy_quadmesh(&field_mesh);
173 static void simstep()
175 // move existing particles
178 // calculate the field gradient at the particle position
179 int gidx = pos_to_grid(p->pos.x, p->pos.y);
180 Vec2 grad = calc_field_grad(gidx);
182 p->vel += grad * SIM_DT;
183 p->pos += p->vel * SIM_DT;
185 // find the grid cell it's moving to
186 int gidx_next = pos_to_grid(p->pos.x, p->pos.y);
187 p->vis_height = 0.0f;//-grid[gidx_next] * field_scale;
189 if(gidx_next == gidx) {
194 Particle *destp = grid_part[gidx_next];
197 // another particle at the destination, merge them
198 destp->vel += p->vel;
199 destp->mass += p->mass;
200 destp->radius = MASS_TO_RADIUS(destp->mass);
204 Particle *next = p->next;
209 // destination is empty, go there
210 if(gidx != gidx_next) {
212 grid_part[gidx_next] = p;
219 // TODO destroy particles which left the simulation field
222 int num_emitters = emitters.size();
223 for(int i=0; i<num_emitters; i++) {
224 Emitter *em = emitters[i];
225 em->spawn_pending += em->rate * SIM_DT;
226 while(em->spawn_pending >= 1.0f && em->mass > 0.0f) {
227 Vec2 pvel; // XXX calc eject velocity
229 float angle = (float)rand() / (float)RAND_MAX * (M_PI * 2.0);
230 float emradius = MASS_TO_RADIUS(em->mass);
231 Vec2 ppos = em->pos + Vec2(cos(angle), sin(angle)) * emradius * 1.00001;
233 float pmass = em->chunk > em->mass ? em->mass : em->chunk;
234 spawn_particle(ppos, pvel, pmass);
237 em->spawn_pending -= 1.0f;
241 // remove dead emitters
242 std::vector<Emitter*>::iterator it = emitters.begin();
243 while(it != emitters.end()) {
246 if(em->mass <= 0.0f) {
247 printf("emitter depleted\n");
248 it = emitters.erase(it);
255 // calculate gravitational field - assume field within radius constant: m / r^2
256 // first clear the field, and then add contributions
257 memset(grid, 0, sizeof grid);
259 // contribution of emitters
260 for(int i=0; i<num_emitters; i++) {
261 Emitter *em = emitters[i];
263 calc_contrib_bounds(em->pos, em->mass, &cbox);
264 float emradius = MASS_TO_RADIUS(em->mass);
266 add_influence(em->pos, -em->mass, emradius, cbox);
269 // contribution of particles
273 calc_contrib_bounds(p->pos, p->mass, &cbox);
274 add_influence(p->pos, p->mass, p->radius, cbox);
279 assert(glGetError() == GL_NO_ERROR);
281 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, GRID_SIZE, GRID_SIZE, GL_LUMINANCE,
283 assert(glGetError() == GL_NO_ERROR);
288 if(emit_place_pending) {
289 emit_place_pending = false;
290 Emitter *em = new Emitter;
291 em->pos = emit_place_pos;
294 em->chunk = 0.01 * em->mass;
297 em->spawn_pending = 0;
298 emitters.push_back(em);
301 calc_contrib_bounds(em->pos, em->mass, &cbox);
302 printf("bounds: %d,%d %dx%d\n", cbox.x, cbox.y, cbox.width, cbox.height);
306 static float interval;
307 interval += frame_dt;
308 if(interval >= SIM_DT) {
311 assert(glGetError() == GL_NO_ERROR);
314 // update projection matrix
315 proj_matrix.perspective(deg_to_rad(60.0f), win_aspect, 0.5, 5000.0);
317 // update view matrix
320 targ.x = targ_pos->x;
321 targ.z = targ_pos->y;
324 float theta = -deg_to_rad(cam_theta);
325 Vec3 camdir = Vec3(sin(theta) * cam_dist, pow(cam_dist * 0.1, 2.0) + 0.5, cos(theta) * cam_dist);
326 Vec3 campos = targ + camdir;
328 view_matrix.inv_lookat(campos, targ, Vec3(0, 1, 0));
331 void GameScreen::draw()
335 glClearColor(0.01, 0.01, 0.01, 1);
336 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
338 glMatrixMode(GL_PROJECTION);
339 glLoadMatrixf(proj_matrix[0]);
340 glMatrixMode(GL_MODELVIEW);
341 glLoadMatrixf(view_matrix[0]);
343 glPushAttrib(GL_ENABLE_BIT);
344 glDisable(GL_CULL_FACE);
346 // draw gravitational field
347 glEnable(GL_TEXTURE_2D);
348 bind_texture(gvis_tex, 0);
349 bind_texture(grid_tex, 1);
351 glUseProgram(field_sdr);
352 glPatchParameteri(GL_PATCH_VERTICES, 4);
353 draw_quadmesh(&field_mesh, GL_PATCHES);
356 glUseProgram(particle_sdr);
360 int gidx = pos_to_grid(p->pos.x, p->pos.y);
363 glTranslatef(p->pos.x, p->vis_height, p->pos.y);
364 glScalef(p->radius, p->radius, p->radius);
376 assert(glGetError() == GL_NO_ERROR);
379 void GameScreen::reshape(int x, int y)
385 void GameScreen::keyboard(int key, bool pressed)
394 if(tess_level < glcaps.max_tess_level) {
396 printf("tessellation level: %d\n", tess_level);
397 set_uniform_int(field_sdr, "tess_level", tess_level);
405 printf("tessellation level: %d\n", tess_level);
406 set_uniform_int(field_sdr, "tess_level", tess_level);
413 printf("field scale: %f\n", field_scale);
414 set_uniform_float(field_sdr, "field_scale", field_scale);
419 if(field_scale < 0.0f) {
422 printf("field scale: %f\n", field_scale);
423 set_uniform_float(field_sdr, "field_scale", field_scale);
432 static int prev_x, prev_y;
434 void GameScreen::mbutton(int bn, bool pressed, int x, int y)
440 void GameScreen::mmotion(int x, int y)
447 if(game_bnstate(2)) {
448 cam_theta += dx * 0.5;
452 void GameScreen::mwheel(int dir, int x, int y)
454 cam_dist -= dir * cam_dist * 0.05f;
455 if(cam_dist <= MIN_CAM_DIST) cam_dist = MIN_CAM_DIST;
456 if(cam_dist > MAX_CAM_DIST) cam_dist = MAX_CAM_DIST;
460 static int pos_to_grid(float x, float y)
462 int gx = ((x / (float)FIELD_SIZE) + 0.5f) * (float)GRID_SIZE;
463 int gy = ((y / (float)FIELD_SIZE) + 0.5f) * (float)GRID_SIZE;
466 if(gx >= GRID_SIZE) gx = GRID_SIZE - 1;
468 if(gy >= GRID_SIZE) gy = GRID_SIZE - 1;
470 return (gx << GRID_BITS) | gy;
473 static Vec2 grid_to_pos(int gx, int gy)
475 float x = (((float)gx / (float)GRID_SIZE) - 0.5f) * (float)FIELD_SIZE;
476 float y = (((float)gy / (float)GRID_SIZE) - 0.5f) * (float)FIELD_SIZE;
481 static void calc_contrib_bounds(const Vec2 &pos, float mass, Rect *rect)
483 int gidx = pos_to_grid(pos.x, pos.y);
484 int gx = GRID_X(gidx);
485 int gy = GRID_Y(gidx);
486 int maxrange = (int)ceil(CONTRIB_RANGE(mass));
488 int sx = gx - maxrange;
489 int sy = gy - maxrange;
490 int ex = gx + maxrange;
491 int ey = gy + maxrange;
493 if(ex > GRID_SIZE) ex = GRID_SIZE;
494 if(ey > GRID_SIZE) ey = GRID_SIZE;
496 rect->x = sx < 0 ? 0 : sx;
497 rect->y = sy < 0 ? 0 : sy;
498 rect->width = ex - sx;
499 rect->height = ey - sy;
502 static void add_influence(const Vec2 &pos, float mass, float radius, const Rect &cbox)
504 float *gptr = grid + cbox.y * GRID_SIZE + cbox.x;
505 Vec2 startpos = grid_to_pos(cbox.x, cbox.y);
507 for(int y=0; y<cbox.height; y++) {
508 for(int x=0; x<cbox.width; x++) {
509 Vec2 cellpos = Vec2(startpos.x + (float)x * GRID_DELTA, startpos.y);
511 Vec2 dir = cellpos - pos;
512 float dsq = dot(dir, dir);
513 float radsq = radius * radius;
518 gptr[x] += mass / dsq;
521 startpos.y += GRID_DELTA;
526 static Vec2 calc_field_grad(int gidx)
528 int gx = GRID_X(gidx);
529 int gy = GRID_Y(gidx);
531 int nidx = ((gx + 1 >= GRID_SIZE ? gx : gx + 1) << GRID_BITS) | gy;
532 int pidx = ((gx > 0 ? gx - 1 : gx) << GRID_BITS) | gy;
533 float dfdx = grid[nidx] - grid[pidx];
535 nidx = (gx << GRID_BITS) | (gy + 1 >= GRID_SIZE ? gy : gy + 1);
536 pidx = (gx << GRID_BITS) | (gy > 0 ? gy - 1 : gy);
537 float dfdy = grid[nidx] - grid[pidx];
539 return Vec2(dfdx, dfdy);
543 // ---- quad mesh operations ----
545 static void destroy_quadmesh(QuadMesh *m)
547 glDeleteBuffers(1, &m->vbo_v);
548 glDeleteBuffers(1, &m->vbo_uv);
549 glDeleteBuffers(1, &m->ibo);
556 static void draw_quadmesh(const QuadMesh *m, unsigned int prim)
558 glEnableClientState(GL_VERTEX_ARRAY);
559 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
561 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_v);
562 glVertexPointer(3, GL_FLOAT, 0, 0);
564 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_uv);
565 glTexCoordPointer(2, GL_FLOAT, 0, 0);
567 glBindBuffer(GL_ARRAY_BUFFER, 0);
569 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo);
570 glDrawElements(prim, m->num_idx, GL_UNSIGNED_SHORT, 0);
571 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
573 glDisableClientState(GL_VERTEX_ARRAY);
574 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
577 static void gen_quad_plane(QuadMesh *m, float width, float height, int usub, int vsub)
583 if(usub < 1) usub = 1;
584 if(vsub < 1) vsub = 1;
586 int uverts = usub + 1;
587 int vverts = vsub + 1;
588 m->num_verts = uverts * vverts;
589 m->num_quads = usub * vsub;
590 m->num_idx = m->num_quads * 4;
592 vptr = m->v = new Vec3[m->num_verts];
593 uvptr = m->uv = new Vec2[m->num_verts];
594 iptr = m->idx = new uint16_t[m->num_idx];
596 float du = 1.0f / (float)usub;
597 float dv = 1.0f / (float)vsub;
600 for(int i=0; i<uverts; i++) {
601 float x = (u - 0.5f) * width;
603 for(int j=0; j<vverts; j++) {
604 float y = (v - 0.5f) * height;
606 *vptr++ = Vec3(x, 0, y);
607 *uvptr++ = Vec2(u, v);
609 if(i < usub && j < vsub) {
610 int idx = i * vverts + j;
613 *iptr++ = idx + vverts;
614 *iptr++ = idx + vverts + 1;
623 glGenBuffers(1, &m->vbo_v);
624 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_v);
625 glBufferData(GL_ARRAY_BUFFER, m->num_verts * 3 * sizeof(float), m->v, GL_STATIC_DRAW);
627 glGenBuffers(1, &m->vbo_uv);
628 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_uv);
629 glBufferData(GL_ARRAY_BUFFER, m->num_verts * 2 * sizeof(float), m->uv, GL_STATIC_DRAW);
631 glGenBuffers(1, &m->ibo);
632 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo);
633 glBufferData(GL_ELEMENT_ARRAY_BUFFER, m->num_idx * sizeof(uint16_t), m->idx, GL_STATIC_DRAW);
635 glBindBuffer(GL_ARRAY_BUFFER, 0);
636 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
639 static void spawn_particle(const Vec2 &pos, const Vec2 &vel, float mass)
641 int gidx = pos_to_grid(pos.x, pos.y);
643 if(grid_part[gidx]) {
644 // merge with existing
645 Particle *p = grid_part[gidx];
648 p->radius = MASS_TO_RADIUS(p->mass);
651 Particle *p = alloc_particle();
655 p->radius = MASS_TO_RADIUS(mass);
662 static void add_particle(Particle *p)
664 if(plist) plist->prev = p;
671 static void remove_particle(Particle *p)
673 assert(plist->prev == 0);
676 assert(p->prev == 0);
680 p->prev->next = p->next;
683 p->next->prev = p->prev;
685 p->prev = p->next = 0;
688 // particle allocator
689 #define MAX_PFREE_SIZE 256
690 static Particle *pfree_list;
691 static int pfree_size;
693 static Particle *alloc_particle()
696 Particle *p = pfree_list;
697 pfree_list = pfree_list->next;
705 void free_particle(Particle *p)
707 if(pfree_size < MAX_PFREE_SIZE) {
708 p->next = pfree_list;