Subversion Repositories gelsvn

Rev

Rev 596 | Rev 638 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
305 jab 1
#include <iostream>
2
#include <vector>
3
#include <algorithm>
4
#include <cmath>
5
 
596 jab 6
#include <GLGraphics/gel_glut.h>
7
#include <GLGraphics/GLViewController.h>
305 jab 8
 
596 jab 9
#include <CGLA/Vec2f.h>
10
#include <CGLA/Vec3i.h>
11
#include <CGLA/Vec3f.h>
12
#include <CGLA/Vec3d.h>
13
#include <CGLA/Mat4x4f.h>
309 jab 14
 
596 jab 15
#include <HMesh/Manifold.h>
305 jab 16
 
596 jab 17
#include <Geometry/TriMesh.h>
18
#include <Geometry/obj_load.h>
19
#include <Geometry/Ray.h>
20
#include <Geometry/BSPTree.h>
21
#include <Geometry/build_bbtree.h>
22
#include <Geometry/AABox.h>
23
#include <Geometry/OBox.h>
24
 
25
#include <Util/Timer.h>
26
 
305 jab 27
#include "Camera.h"
28
 
313 jrf 29
#define USE_BSP
309 jab 30
 
305 jab 31
using namespace std;
32
using namespace CGLA;
33
using namespace Geometry;
309 jab 34
using namespace HMesh;
305 jab 35
using namespace GLGraphics;
36
 
309 jab 37
/*
38
 * TODO: 
39
 * - BBOX remove HMesh dependency - that is crazy.
40
 * - BBox visit child nodes in order of how far away the intersection point on
41
 *        the bbox is. Closest nodes visited first. Cull nodes farther than
42
 *        an actual intersection point.
43
 * - BBox Smooth interpolation of triangle normals. Straightforward.
44
 */
45
 
46
 
305 jab 47
namespace
48
{
310 jrf 49
  const int MAX_OBJECTS = 4;   // Maximum number of triangles in a BSP tree node
305 jab 50
  const int MAX_LEVEL = 20;    // Maximum number of BSP tree subdivisions
51
 
52
  const unsigned int TEX_SIZE = 512;
53
 
54
  bool raytrace = false;
55
  bool done = false;
56
  bool shadow = false;
57
 
58
  unsigned int winx = TEX_SIZE;     // Screen width
59
  unsigned int winy = TEX_SIZE;     // Screen height
60
 
61
  unsigned int PIXEL_SUBDIVS = 1;
62
 
63
  int mouse_state = GLUT_UP;
64
  int mouse_button = 0;
65
  int spin_timer = 20;
66
 
310 jrf 67
  GLViewController *vctrl;
305 jab 68
 
69
  TriMesh mesh;
322 jab 70
  vector<const TriMesh*> mesh_vector(1, &mesh);
305 jab 71
  vector<Mat4x4f> transforms(1, identity_Mat4x4f());
72
 
73
  double light_pow = 1.0;
74
  Vec3f light_dir = normalize(Vec3f(1.0, 1.0, 1.0));
75
  Vec3d background(0.8, 0.9, 1.0);
76
 
77
  BSPTree tree;
78
  Camera* cam;
79
 
80
  Vec3f image[TEX_SIZE][TEX_SIZE];
81
  unsigned int image_tex;
82
 
83
  // Function to generate a random number between 0 and 1.
417 jrf 84
  // gel_rand() returns a random number ranging from 0 to GEL_RAND_MAX.
305 jab 85
  inline double my_random()
86
  {
417 jrf 87
    return gel_rand()/static_cast<double>(GEL_RAND_MAX);
305 jab 88
  }
309 jab 89
 
310 jrf 90
  AABBTree bb_tree;		
305 jab 91
}
92
 
93
void spin(int x);
94
 
95
//////////////////////////////////////////////////////////////
96
//      I N I T I A L I Z A T I O N               
97
//////////////////////////////////////////////////////////////
98
 
99
void init_texture(unsigned int& tex)
100
{
322 jab 101
  glGenTextures(1, reinterpret_cast<GLuint*>(&tex));
305 jab 102
 
103
  glBindTexture(GL_TEXTURE_2D, tex);
104
 
105
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
106
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
107
 
108
  // load the texture image
109
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 
418 jrf 110
	             TEX_SIZE, TEX_SIZE,
111
	             0, GL_RGB, GL_FLOAT, image[0][0].get());
305 jab 112
}
113
 
114
void initRaytracer()
115
{
116
  Vec3f c;
117
  float r;
118
  mesh.get_bsphere(c, r);
119
  r *= 1.5;
120
 
121
  // Initialize track ball
310 jrf 122
  vctrl = new GLViewController(winx, winy, c, r);
305 jab 123
 
124
  // Initialize corresponding camera
418 jrf 125
  cam = new Camera(c - Vec3f(r), c, Vec3f(0.0f, 1.0f, 0.0f), 1.0f);
305 jab 126
 
312 jrf 127
#ifdef USE_BSP
309 jab 128
   cout << "Constructing BSP tree..." << endl;
129
   tree.init(mesh_vector, transforms, MAX_OBJECTS, MAX_LEVEL);
130
   tree.build();
131
#else
132
	// AABB TREE
133
	Manifold m;
134
	vector<int> faces(mesh.geometry.no_faces(), 3);
135
	cout << "Creating manifold" << endl;
136
	build_manifold(m, 
418 jrf 137
				         mesh.geometry.no_vertices(), 
138
				         &mesh.geometry.vertex(0), 
139
				         faces.size(), &faces[0], 
140
				         reinterpret_cast<const int*>(&mesh.geometry.face(0)));
309 jab 141
	cout << "Building tree" << endl;
142
	build_AABBTree(m, bb_tree);
143
#endif
305 jab 144
}
145
 
146
void initGL()
147
{
148
  glShadeModel(GL_SMOOTH); 
309 jab 149
  glDisable(GL_CULL_FACE);
305 jab 150
  glFrontFace(GL_CCW);
151
 
152
  glClearColor(1.0, 1.0, 1.0, 1.0);
153
  glColor3f(0.0, 0.0, 0.0);
154
}
155
 
156
 
157
//////////////////////////////////////////////////////////////
158
//      S H A D E   F U N C T I O N S
159
//////////////////////////////////////////////////////////////
160
 
161
double shadow_shade(Ray& r)
162
{
163
  r.compute_position();
164
  Ray shadow(r.hit_pos, light_dir);
165
  double s = tree.intersect(shadow) ? 0.0 : 1.0;
166
 
167
  r.compute_normal();
168
  return s*light_pow*dot(r.hit_normal, light_dir);
169
}
170
 
171
double lambertian_shade(Ray& r)
172
{
312 jrf 173
#ifdef USE_BSP
418 jrf 174
	r.compute_normal();
309 jab 175
#endif
305 jab 176
  return light_pow*dot(r.hit_normal, light_dir);
177
}
178
 
179
double (*shade_ray[2])(Ray&) = { lambertian_shade,
418 jrf 180
				                         shadow_shade      };
305 jab 181
 
182
//////////////////////////////////////////////////////////////
183
//      D R A W   F U N C T I O N S
184
//////////////////////////////////////////////////////////////
185
 
186
/*
187
void enable_textures(TriMesh& tm)
188
{
189
  for(unsigned int i=0;i<tm.materials.size(); ++i)
190
  {
191
    Material& mat = tm.materials[i];
192
    if(mat.tex_name != "")
193
    {
194
      string name = mat.tex_path + mat.tex_name;
195
 
196
      GLuint tex_id;
197
      if(load_image_into_texture(name, tex_id))
198
	mat.tex_id = tex_id;
199
    }
200
  }
201
}
202
*/
203
 
204
void set_perspective_proj()
205
{
206
  glMatrixMode(GL_PROJECTION);	 
207
  glLoadIdentity();            
208
 
209
  gluPerspective(64.0, 1.0, 0.1, 1000.0);
210
 
211
  glMatrixMode(GL_MODELVIEW);
212
}
213
 
214
void set_ortho_proj()
215
{
216
  glMatrixMode(GL_PROJECTION);	 
217
  glLoadIdentity();             
218
 
219
  glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
220
 
221
  glMatrixMode(GL_MODELVIEW);  
222
}
223
 
224
void draw_texture(unsigned int tex)
225
{
226
  static GLfloat verts[] = { 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
227
 
228
  glColor4f(1.0, 1.0, 1.0, 1.0);
229
 
230
  glBindTexture(GL_TEXTURE_2D, tex);
231
  glEnable(GL_TEXTURE_2D);
232
 
233
  glEnableClientState(GL_VERTEX_ARRAY);
234
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
235
 
236
  glVertexPointer(2, GL_FLOAT, 0, verts);
237
  glTexCoordPointer(2, GL_FLOAT, 0, verts);
238
 
239
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
240
 
241
  glDisableClientState(GL_VERTEX_ARRAY);
242
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
243
 
244
  glDisable(GL_TEXTURE_2D);
245
}
246
 
247
void drawOBJ()
248
{
249
  static bool washere = false;
250
  static unsigned int disp_list;
251
 
252
  if(!washere)
253
  {
254
    disp_list = glGenLists(1);
255
    glNewList(disp_list, GL_COMPILE);
256
 
257
    glBegin(GL_TRIANGLES);
418 jrf 258
    for(int i = 0; i < mesh.geometry.no_faces(); ++i)
259
    {
260
      Vec3i n_face = mesh.normals.face(i);
261
      Vec3i g_face = mesh.geometry.face(i);
262
      for(int j=0;j<3;j++)
305 jab 263
      {
418 jrf 264
        double shade = 0.5;
305 jab 265
 
418 jrf 266
        if(n_face != Geometry::NULL_FACE)
267
        {
268
          Vec3f norm = normalize(mesh.normals.vertex(n_face[j]));
269
          glNormal3fv(norm.get());
270
          shade = light_pow*dot(norm, light_dir);
271
        }
305 jab 272
 
418 jrf 273
        glColor3d(shade, shade, shade);
274
        Vec3f vert = mesh.geometry.vertex(g_face[j]);	  
275
        glVertex3fv(vert.get());
305 jab 276
      }
418 jrf 277
    }
305 jab 278
    glEnd();
279
 
280
    glEndList();
281
    washere = true;
282
  }
283
  glCallList(disp_list);
284
}
285
 
286
 
287
//////////////////////////////////////////////////////////////
288
//      G L U T   C A L L B A C K   F U N C T I O N S                 
289
//////////////////////////////////////////////////////////////
290
 
291
void display()
292
{
293
  static bool first = true;
294
 
295
  if(first)
296
  {
297
    first = false;
298
    glutTimerFunc(spin_timer, spin, 0);
299
  }
300
 
301
  Vec3f eye, focus, up;
309 jab 302
	vctrl->get_view_param(eye, focus, up);
303
	cam->set(eye, focus, up, cam->get_focal_dist());
304
 
305 jab 305
  if(raytrace)
306
  {
307
    raytrace = false;
308
 
309
    cout << "Raytracing";
310
    float win_to_vp = 1.0f/static_cast<float>(TEX_SIZE);
311
    float lowerleft = 0.5 + win_to_vp*0.5;
312
    float step = win_to_vp/static_cast<float>(PIXEL_SUBDIVS);
313
 
314
    vector<Vec2f> jitter(PIXEL_SUBDIVS*PIXEL_SUBDIVS); 
315
    for(unsigned int i = 0; i < PIXEL_SUBDIVS; ++i)
316
      for(unsigned int j = 0; j < PIXEL_SUBDIVS; ++j)
317
      {
418 jrf 318
	      jitter[i*PIXEL_SUBDIVS + j][0] = (my_random() + (j%PIXEL_SUBDIVS))*step; 
319
	      jitter[i*PIXEL_SUBDIVS + j][1] = (my_random() + (i%PIXEL_SUBDIVS))*step; 
305 jab 320
      }
321
 
418 jrf 322
    Util::Timer tim;
323
    tim.start();
305 jab 324
    for(unsigned int i = 0; i < TEX_SIZE; ++i)
325
    {
418 jrf 326
	    for(unsigned int j = 0; j < TEX_SIZE; ++j)
327
	    {
328
		    Vec3d sum(0.0f);
329
		    Vec2f vp_pos(j*win_to_vp - lowerleft, i*win_to_vp - lowerleft);
330
 
331
		    for(unsigned int ky = 0; ky < PIXEL_SUBDIVS; ++ky)
332
		      for(unsigned int kx = 0; kx < PIXEL_SUBDIVS; ++kx)
333
		      {
334
			      Ray r = cam->get_ray(vp_pos + jitter[ky*PIXEL_SUBDIVS + kx]);
305 jab 335
 
312 jrf 336
#ifdef USE_BSP
418 jrf 337
			      if(tree.intersect(r))
338
			        sum += Vec3d(shade_ray[shadow](r));
339
			      else
340
			        sum += background;
309 jab 341
#else
418 jrf 342
			      float t = FLT_MAX;
343
			      bb_tree.intersect(r);
344
			      if(r.has_hit)
345
			        sum += Vec3d(shade_ray[0](r));
346
			      else 
347
			        sum += background;
309 jab 348
#endif		
418 jrf 349
		      }
350
	      image[i][j] = Vec3f(sum/static_cast<double>(PIXEL_SUBDIVS*PIXEL_SUBDIVS));
351
      }
352
      if(((i + 1) % 50) == 0) cerr << ".";
353
    }
354
	  cout << " - " << tim.get_secs() << " secs " << endl;
305 jab 355
    cout << endl;
356
 
357
    init_texture(image_tex);
358
 
359
    done = true;
360
  }
361
 
362
  if(done)
363
  {
364
    set_ortho_proj();
365
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
366
    glLoadIdentity();
367
 
368
    draw_texture(image_tex);
369
  }
370
  else
371
  {
372
    glEnable(GL_DEPTH_TEST);
373
 
374
    cam->glSetPerspective(winx, winy);
375
 
376
    glClearColor(background[0], background[1], background[2], 1.0);
377
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
378
    glLoadIdentity();
379
 
418 jrf 380
	  cam->glSetCamera();
305 jab 381
 
382
    glColor3f(0.5, 0.5, 0.5);
383
    drawOBJ();
384
 
385
    glDisable(GL_DEPTH_TEST);
386
  }
387
 
388
  glutSwapBuffers();  
389
}
390
 
391
void reshape(int w, int h)
392
{
393
  winx = w; winy = h;
394
 
309 jab 395
  vctrl->reshape(winx, winy);
305 jab 396
 
397
  glViewport(0, 0, winx, winy);
398
}
399
 
400
void keyboard(unsigned char key, int x, int y)
401
{
402
  switch(key)
403
  {
404
  case '+':
405
    ++PIXEL_SUBDIVS;
406
    cout << "Rays per pixel: " << PIXEL_SUBDIVS*PIXEL_SUBDIVS << endl;
407
    break;
408
  case '-':
409
    if(PIXEL_SUBDIVS > 1)
410
      --PIXEL_SUBDIVS;
411
    cout << "Rays per pixel: " << PIXEL_SUBDIVS*PIXEL_SUBDIVS << endl;
412
    break;
413
  case 'r':
414
    if(done) done = false;
415
    else raytrace = true;
416
    break;
417
  case 's':
418
    shadow = !shadow;
419
    cout << "Shadow " << (shadow ? "on." : "off.") << endl;
420
    break;
421
  case 27:
309 jab 422
    delete vctrl;
305 jab 423
    delete cam;
424
    exit(0);
425
  }
426
}
427
 
428
void mouse(int btn, int state, int x, int y)
429
{
430
  if(state == GLUT_DOWN) 
431
  {
432
    if(btn == GLUT_LEFT_BUTTON) 
309 jab 433
      vctrl->grab_ball(ROTATE_ACTION, Vec2i(x, y));
305 jab 434
    else if(btn == GLUT_MIDDLE_BUTTON) 
309 jab 435
      vctrl->grab_ball(ZOOM_ACTION, Vec2i(x, y));
305 jab 436
    else if(btn == GLUT_RIGHT_BUTTON) 
309 jab 437
      vctrl->grab_ball(PAN_ACTION, Vec2i(x, y));
305 jab 438
  }
439
  else if(state == GLUT_UP)
309 jab 440
			vctrl->release_ball();
305 jab 441
 
442
  mouse_state = state;
443
  mouse_button = btn;
444
 
445
  glutPostRedisplay();
446
}
447
 
448
void move(int x, int y)
449
{
309 jab 450
    vctrl->roll_ball(Vec2i(x, y));
305 jab 451
 
452
  glutPostRedisplay();
453
}
454
 
455
void spin(int x)
456
{
309 jab 457
  vctrl->try_spin();
305 jab 458
  glutTimerFunc(spin_timer, spin, 0);  
459
  glutPostRedisplay();
460
}
461
 
462
 
463
//////////////////////////////////////////////////////////////
464
//                        M A I N
465
//////////////////////////////////////////////////////////////
466
 
467
int main(int argc, char** argv)
468
{
469
#ifdef __BORLANDC__
470
  _control87(MCW_EM, MCW_EM);  // Borland C++ will crash OpenGL if this
471
                               // magic line is not inserted
472
#endif
473
 
474
  glutInit(&argc, argv);
475
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
476
  glutInitWindowSize(winx, winy);
477
  glutCreateWindow("Press 'r' to raytrace");
478
  glutDisplayFunc(display);
479
  glutReshapeFunc(reshape);
480
  glutKeyboardFunc(keyboard);
481
  glutMouseFunc(mouse);
482
  glutMotionFunc(move);
483
 
484
  // LOAD OBJ
485
  string filename;
486
  if(argc > 1)
487
  {
488
    filename = argv[1];
489
    cout << "Loading " << filename << endl;
490
 
491
    obj_load(filename, mesh);
492
    //if(!mesh.has_normals())
493
    //{
494
      cout << "Computing normals" << endl;
495
      mesh.compute_normals();
496
    //}
497
 
498
    cout << "No. of triangles: " << mesh.geometry.no_faces() << endl;
499
  }
500
  else
501
  {
502
    obj_load("../../data/dolphins.obj", mesh);
503
 
418 jrf 504
  	cout << "Computing normals" << endl;
305 jab 505
    mesh.compute_normals();
506
 
418 jrf 507
    //cout << "Usage: raytrace any_object.obj";
305 jab 508
    //exit(0);
509
  }
510
 
511
  initRaytracer();
512
  initGL();    
513
 
514
  glutMainLoop();
515
 
516
  return 0;
517
}
518