3 #include <gmath/gmath.h>
13 * - whistle hhgg music
14 * - select objects and center camera on them
25 Particle *next, *prev;
47 int num_verts, num_idx, num_quads;
49 unsigned int vbo_v, vbo_uv, ibo;
54 #define GRID_SIZE 2048
56 #define GRID_X(idx) (((idx) >> GRID_BITS) & (GRID_SIZE - 1))
57 #define GRID_Y(idx) ((idx) & (GRID_SIZE - 1))
58 #define GRID_DELTA ((float)FIELD_SIZE / (float)GRID_SIZE)
60 #define FIELD_SIZE 2048
61 #define MIN_CAM_DIST 1.0f
62 #define MAX_CAM_DIST 350.0f
64 #define MASS_TO_RADIUS(m) log((m) + 1.0)
66 #define CONTRIB_THRES 0.005
67 #define CONTRIB_RANGE(m) sqrt((m) / CONTRIB_THRES)
69 /* gravitational strength */
70 #define GRAV_STR 16.0f
72 static int pos_to_grid_x_noclamp(float x);
73 static int pos_to_grid_y_noclamp(float y);
74 static int pos_to_grid(float x, float y);
75 static Vec2 grid_to_pos(int gx, int gy);
77 static void calc_contrib_bounds(const Vec2 &pos, float mass, Rect *rect);
78 static void add_influence(const Vec2 &pos, float mass, float radius, const Rect &cbox);
80 static Vec2 calc_field_grad(int gidx);
82 static void destroy_quadmesh(QuadMesh *m);
83 static void draw_quadmesh(const QuadMesh *m, unsigned int prim = GL_QUADS);
84 static void gen_quad_plane(QuadMesh *mesh, float width, float height, int usub, int vsub);
86 static void spawn_particle(const Vec2 &pos, const Vec2 &vel, float mass);
87 static void add_particle(Particle *p);
88 static void remove_particle(Particle *p);
89 static Particle *alloc_particle();
90 void free_particle(Particle *p);
94 static float grid[GRID_SIZE * GRID_SIZE];
95 static Particle *grid_part[GRID_SIZE * GRID_SIZE];
96 static Texture *grid_tex;
98 static Particle *plist;
100 static std::vector<Emitter*> emitters;
102 static Texture *gvis_tex; // texture tile for visualizing a grid
103 static unsigned int field_sdr;
104 static int tess_level = 64;
105 static float field_scale = 16.0f;
107 static QuadMesh field_mesh;
110 static unsigned int particle_sdr;
113 static float cam_theta;
114 static float cam_dist = 100.0f;
115 static Vec2 *targ_pos = &cam_pos;
116 static Mat4 view_matrix, proj_matrix;
118 static bool wireframe;
120 // emitter placement data (filled by event handlers, completed in update)
121 static bool emit_place_pending;
122 static Vec2 emit_place_pos;
125 bool GameScreen::init()
127 grid_tex = new Texture;
128 grid_tex->create(GRID_SIZE, GRID_SIZE, TEX_2D, GL_LUMINANCE32F_ARB);
129 grid_tex->set_anisotropy(glcaps.max_aniso);
131 gvis_tex = new Texture;
132 if(!gvis_tex->load("data/purple_grid.png")) {
135 gvis_tex->set_anisotropy(glcaps.max_aniso);
137 unsigned int vsdr, tcsdr, tesdr, psdr;
139 if(!(vsdr = load_vertex_shader("sdr/field.v.glsl")) ||
140 !(tcsdr = load_tessctl_shader("sdr/field.tc.glsl")) ||
141 !(tesdr = load_tesseval_shader("sdr/field.te.glsl")) ||
142 !(psdr = load_pixel_shader("sdr/field.p.glsl"))) {
146 if(!(field_sdr = create_program_link(vsdr, tcsdr, tesdr, psdr, 0))) {
149 set_uniform_int(field_sdr, "gvis_tex", 0);
150 set_uniform_int(field_sdr, "field_tex", 1);
151 set_uniform_float(field_sdr, "gvis_scale", FIELD_SIZE / 32.0f);
152 set_uniform_int(field_sdr, "tess_level", tess_level);
153 set_uniform_float(field_sdr, "field_scale", field_scale);
155 gen_quad_plane(&field_mesh, FIELD_SIZE, FIELD_SIZE, 32, 32);
158 gen_geosphere(pmesh, 1.0, 2);
160 if(!(particle_sdr = create_program_load("sdr/sph.v.glsl", "sdr/sph.p.glsl"))) {
165 emit_place_pos = Vec2(0, 0);
166 emit_place_pending = true;
168 assert(glGetError() == GL_NO_ERROR);
172 void GameScreen::destroy()
174 free_program(field_sdr);
177 destroy_quadmesh(&field_mesh);
181 static void simstep()
185 // move existing particles
188 // calculate the field gradient at the particle position
189 int gidx = pos_to_grid(p->pos.x, p->pos.y);
190 Vec2 grad = calc_field_grad(gidx) * GRAV_STR;
192 p->vel += grad * SIM_DT;
193 p->pos += p->vel * SIM_DT;
195 // if it moved outside of the simulation field, remove it
196 int gx = pos_to_grid_x_noclamp(p->pos.x);
197 int gy = pos_to_grid_y_noclamp(p->pos.y);
198 if(gx < 0 || gx >= GRID_SIZE || gy < 0 || gy >= GRID_SIZE) {
199 Particle *next = p->next;
207 // find the grid cell it's moving to
208 int gidx_next = pos_to_grid(p->pos.x, p->pos.y);
209 p->vis_height = 0.0f;//-grid[gidx_next] * field_scale;
211 if(gidx_next == gidx) {
216 Particle *destp = grid_part[gidx_next];
219 // another particle at the destination, merge them
220 destp->vel += p->vel;
221 destp->mass += p->mass;
222 destp->radius = MASS_TO_RADIUS(destp->mass);
226 Particle *next = p->next;
231 // destination is empty, go there
232 if(gidx != gidx_next) {
234 grid_part[gidx_next] = p;
241 // TODO destroy particles which left the simulation field
244 int num_emitters = emitters.size();
245 for(int i=0; i<num_emitters; i++) {
246 Emitter *em = emitters[i];
247 em->spawn_pending += em->rate * SIM_DT;
248 while(em->spawn_pending >= 1.0f && em->mass > 0.0f) {
249 Vec2 pvel; // XXX calc eject velocity
251 float angle = (float)rand() / (float)RAND_MAX * (M_PI * 2.0);
252 float emradius = MASS_TO_RADIUS(em->mass);
253 Vec2 ppos = em->pos + Vec2(cos(angle), sin(angle)) * emradius * 1.00001;
255 float pmass = em->chunk > em->mass ? em->mass : em->chunk;
256 spawn_particle(ppos, pvel, pmass);
259 em->spawn_pending -= 1.0f;
263 // remove dead emitters
264 std::vector<Emitter*>::iterator it = emitters.begin();
265 while(it != emitters.end()) {
268 if(em->mass <= 0.0f) {
269 printf("emitter depleted\n");
270 it = emitters.erase(it);
277 // calculate gravitational field - assume field within radius constant: m / r^2
278 // first clear the field, and then add contributions
279 memset(grid, 0, sizeof grid);
281 // contribution of emitters
282 for(int i=0; i<num_emitters; i++) {
283 Emitter *em = emitters[i];
285 calc_contrib_bounds(em->pos, em->mass, &cbox);
286 float emradius = MASS_TO_RADIUS(em->mass);
288 add_influence(em->pos, -em->mass, emradius, cbox);
291 // contribution of particles
295 calc_contrib_bounds(p->pos, p->mass, &cbox);
296 add_influence(p->pos, p->mass, p->radius, cbox);
301 assert(glGetError() == GL_NO_ERROR);
303 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, GRID_SIZE, GRID_SIZE, GL_LUMINANCE,
305 assert(glGetError() == GL_NO_ERROR);
310 if(emit_place_pending) {
311 emit_place_pending = false;
312 Emitter *em = new Emitter;
313 em->pos = emit_place_pos;
316 em->chunk = 0.001 * em->mass;
319 em->spawn_pending = 0;
320 emitters.push_back(em);
323 calc_contrib_bounds(em->pos, em->mass, &cbox);
324 printf("bounds: %d,%d %dx%d\n", cbox.x, cbox.y, cbox.width, cbox.height);
328 static float interval;
329 interval += frame_dt;
330 if(interval >= SIM_DT) {
333 assert(glGetError() == GL_NO_ERROR);
336 // update projection matrix
337 proj_matrix.perspective(deg_to_rad(60.0f), win_aspect, 0.5, 5000.0);
339 // update view matrix
342 targ.x = targ_pos->x;
343 targ.z = targ_pos->y;
346 float theta = -deg_to_rad(cam_theta);
347 Vec3 camdir = Vec3(sin(theta) * cam_dist, pow(cam_dist * 0.1, 2.0) + 0.5, cos(theta) * cam_dist);
348 Vec3 campos = targ + camdir;
350 view_matrix.inv_lookat(campos, targ, Vec3(0, 1, 0));
353 void GameScreen::draw()
357 glClearColor(0.01, 0.01, 0.01, 1);
358 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
360 glMatrixMode(GL_PROJECTION);
361 glLoadMatrixf(proj_matrix[0]);
362 glMatrixMode(GL_MODELVIEW);
363 glLoadMatrixf(view_matrix[0]);
365 // draw gravitational field
367 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
369 float amb[] = {0.5, 0.5, 0.5, 1.0};
370 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb);
372 float amb[] = {0.01, 0.01, 0.01, 1.0};
373 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb);
376 bind_texture(gvis_tex, 0);
377 bind_texture(grid_tex, 1);
379 glUseProgram(field_sdr);
380 glPatchParameteri(GL_PATCH_VERTICES, 4);
381 draw_quadmesh(&field_mesh, GL_PATCHES);
384 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
388 glUseProgram(particle_sdr);
392 int gidx = pos_to_grid(p->pos.x, p->pos.y);
395 glTranslatef(p->pos.x, p->vis_height, p->pos.y);
396 glScalef(p->radius, p->radius, p->radius);
406 assert(glGetError() == GL_NO_ERROR);
409 void GameScreen::reshape(int x, int y)
415 void GameScreen::keyboard(int key, bool pressed)
424 if(tess_level < glcaps.max_tess_level) {
426 printf("tessellation level: %d\n", tess_level);
427 set_uniform_int(field_sdr, "tess_level", tess_level);
435 printf("tessellation level: %d\n", tess_level);
436 set_uniform_int(field_sdr, "tess_level", tess_level);
443 printf("field scale: %f\n", field_scale);
444 set_uniform_float(field_sdr, "field_scale", field_scale);
449 if(field_scale < 0.0f) {
452 printf("field scale: %f\n", field_scale);
453 set_uniform_float(field_sdr, "field_scale", field_scale);
457 wireframe = !wireframe;
470 static int prev_x, prev_y;
472 void GameScreen::mbutton(int bn, bool pressed, int x, int y)
478 void GameScreen::mmotion(int x, int y)
485 if(game_bnstate(0)) {
486 float pan_speed = pow(cam_dist, 1.5) * 0.00035; // magic
487 Vec2 dir = rotate(Vec2(dx, dy) * pan_speed, deg_to_rad(cam_theta));
492 if(game_bnstate(2)) {
493 cam_theta += dx * 0.5;
497 void GameScreen::mwheel(int dir, int x, int y)
499 cam_dist -= dir * cam_dist * 0.05f;
500 if(cam_dist <= MIN_CAM_DIST) cam_dist = MIN_CAM_DIST;
501 if(cam_dist > MAX_CAM_DIST) cam_dist = MAX_CAM_DIST;
504 static int pos_to_grid_x_noclamp(float x)
506 return ((x / (float)FIELD_SIZE) + 0.5f) * (float)GRID_SIZE;
509 static int pos_to_grid_y_noclamp(float y)
511 return ((y / (float)FIELD_SIZE) + 0.5f) * (float)GRID_SIZE;
514 static int pos_to_grid(float x, float y)
516 int gx = pos_to_grid_x_noclamp(x);
517 int gy = pos_to_grid_y_noclamp(y);
520 if(gx >= GRID_SIZE) gx = GRID_SIZE - 1;
522 if(gy >= GRID_SIZE) gy = GRID_SIZE - 1;
524 return (gx << GRID_BITS) | gy;
527 static Vec2 grid_to_pos(int gx, int gy)
529 float x = (((float)gx / (float)GRID_SIZE) - 0.5f) * (float)FIELD_SIZE;
530 float y = (((float)gy / (float)GRID_SIZE) - 0.5f) * (float)FIELD_SIZE;
535 static void calc_contrib_bounds(const Vec2 &pos, float mass, Rect *rect)
537 int gidx = pos_to_grid(pos.x, pos.y);
538 int gx = GRID_X(gidx);
539 int gy = GRID_Y(gidx);
540 int maxrange = (int)ceil(CONTRIB_RANGE(mass));
542 int sx = gx - maxrange;
543 int sy = gy - maxrange;
544 int ex = gx + maxrange;
545 int ey = gy + maxrange;
547 if(ex > GRID_SIZE) ex = GRID_SIZE;
548 if(ey > GRID_SIZE) ey = GRID_SIZE;
550 rect->x = sx < 0 ? 0 : sx;
551 rect->y = sy < 0 ? 0 : sy;
552 rect->width = ex - sx;
553 rect->height = ey - sy;
556 static void add_influence(const Vec2 &pos, float mass, float radius, const Rect &cbox)
558 float *gptr = grid + cbox.y * GRID_SIZE + cbox.x;
559 Vec2 startpos = grid_to_pos(cbox.x, cbox.y);
561 for(int y=0; y<cbox.height; y++) {
562 for(int x=0; x<cbox.width; x++) {
563 Vec2 cellpos = Vec2(startpos.x + (float)x * GRID_DELTA, startpos.y);
565 Vec2 dir = cellpos - pos;
566 float dsq = dot(dir, dir);
567 float radsq = radius * radius;
572 gptr[x] += mass / dsq;
575 startpos.y += GRID_DELTA;
580 static Vec2 calc_field_grad(int gidx)
582 int gx = GRID_X(gidx);
583 int gy = GRID_Y(gidx);
585 int nidx = ((gx + 1 >= GRID_SIZE ? gx : gx + 1) << GRID_BITS) | gy;
586 int pidx = ((gx > 0 ? gx - 1 : gx) << GRID_BITS) | gy;
587 float dfdx = grid[nidx] - grid[pidx];
589 nidx = (gx << GRID_BITS) | (gy + 1 >= GRID_SIZE ? gy : gy + 1);
590 pidx = (gx << GRID_BITS) | (gy > 0 ? gy - 1 : gy);
591 float dfdy = grid[nidx] - grid[pidx];
593 return Vec2(dfdx, dfdy);
597 // ---- quad mesh operations ----
599 static void destroy_quadmesh(QuadMesh *m)
601 glDeleteBuffers(1, &m->vbo_v);
602 glDeleteBuffers(1, &m->vbo_uv);
603 glDeleteBuffers(1, &m->ibo);
610 static void draw_quadmesh(const QuadMesh *m, unsigned int prim)
612 glEnableClientState(GL_VERTEX_ARRAY);
613 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
615 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_v);
616 glVertexPointer(3, GL_FLOAT, 0, 0);
618 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_uv);
619 glTexCoordPointer(2, GL_FLOAT, 0, 0);
621 glBindBuffer(GL_ARRAY_BUFFER, 0);
623 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo);
624 glDrawElements(prim, m->num_idx, GL_UNSIGNED_SHORT, 0);
625 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
627 glDisableClientState(GL_VERTEX_ARRAY);
628 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
631 static void gen_quad_plane(QuadMesh *m, float width, float height, int usub, int vsub)
637 if(usub < 1) usub = 1;
638 if(vsub < 1) vsub = 1;
640 int uverts = usub + 1;
641 int vverts = vsub + 1;
642 m->num_verts = uverts * vverts;
643 m->num_quads = usub * vsub;
644 m->num_idx = m->num_quads * 4;
646 vptr = m->v = new Vec3[m->num_verts];
647 uvptr = m->uv = new Vec2[m->num_verts];
648 iptr = m->idx = new uint16_t[m->num_idx];
650 float du = 1.0f / (float)usub;
651 float dv = 1.0f / (float)vsub;
654 for(int i=0; i<uverts; i++) {
655 float x = (u - 0.5f) * width;
657 for(int j=0; j<vverts; j++) {
658 float y = (v - 0.5f) * height;
660 *vptr++ = Vec3(x, 0, y);
661 *uvptr++ = Vec2(u, v);
663 if(i < usub && j < vsub) {
664 int idx = i * vverts + j;
668 *iptr++ = idx + vverts + 1;
669 *iptr++ = idx + vverts;
677 glGenBuffers(1, &m->vbo_v);
678 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_v);
679 glBufferData(GL_ARRAY_BUFFER, m->num_verts * 3 * sizeof(float), m->v, GL_STATIC_DRAW);
681 glGenBuffers(1, &m->vbo_uv);
682 glBindBuffer(GL_ARRAY_BUFFER, m->vbo_uv);
683 glBufferData(GL_ARRAY_BUFFER, m->num_verts * 2 * sizeof(float), m->uv, GL_STATIC_DRAW);
685 glGenBuffers(1, &m->ibo);
686 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo);
687 glBufferData(GL_ELEMENT_ARRAY_BUFFER, m->num_idx * sizeof(uint16_t), m->idx, GL_STATIC_DRAW);
689 glBindBuffer(GL_ARRAY_BUFFER, 0);
690 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
693 static void spawn_particle(const Vec2 &pos, const Vec2 &vel, float mass)
695 int gidx = pos_to_grid(pos.x, pos.y);
697 if(grid_part[gidx]) {
698 // merge with existing
699 Particle *p = grid_part[gidx];
702 p->radius = MASS_TO_RADIUS(p->mass);
705 Particle *p = alloc_particle();
709 p->radius = MASS_TO_RADIUS(mass);
716 static void add_particle(Particle *p)
718 if(plist) plist->prev = p;
725 static void remove_particle(Particle *p)
727 assert(plist->prev == 0);
730 assert(p->prev == 0);
734 p->prev->next = p->next;
737 p->next->prev = p->prev;
739 p->prev = p->next = 0;
742 // particle allocator
743 #define MAX_PFREE_SIZE 256
744 static Particle *pfree_list;
745 static int pfree_size;
747 static Particle *alloc_particle()
750 Particle *p = pfree_list;
751 pfree_list = pfree_list->next;
759 void free_particle(Particle *p)
761 if(pfree_size < MAX_PFREE_SIZE) {
762 p->next = pfree_list;