Subversion Repositories gelsvn

Rev

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