GLState.hh 19.5 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
2
3
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
Jan Möbius's avatar
Jan Möbius committed
4
 *      Copyright (C) 2001-2010 by Computer Graphics Group, RWTH Aachen      *
Jan Möbius's avatar
Jan Möbius committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 *                           www.openflipper.org                             *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenFlipper.                                        *
 *                                                                           *
 *  OpenFlipper is free software: you can redistribute it and/or modify      *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenFlipper is distributed in the hope that it will be useful,           *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenFlipper. If not,                                  *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/
Jan Möbius's avatar
 
Jan Möbius committed
34

Jan Möbius's avatar
Jan Möbius committed
35
36
/*===========================================================================*\
 *                                                                           *
Jan Möbius's avatar
Jan Möbius committed
37
 *   $Revision$                                                       *
Jan Möbius's avatar
Jan Möbius committed
38
39
40
41
 *   $Author$                                                      *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/
Jan Möbius's avatar
 
Jan Möbius committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61


//=============================================================================
//
//  CLASS GLState
//
//=============================================================================


#ifndef ACG_GLSTATE_HH
#define ACG_GLSTATE_HH


//== INCLUDES =================================================================


#include "gl.hh"
#include "../Math/GLMatrixT.hh"
#include "../Math/VectorT.hh"
#include "../Config/ACGDefines.hh"
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
62
#include "ColorStack.hh"
Jan Möbius's avatar
 
Jan Möbius committed
63
#include <stack>
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
64
#include <vector>
Jan Möbius's avatar
 
Jan Möbius committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

#ifdef WIN32
	#pragma warning(push)
	#pragma warning(disable:4251)
#endif

//== NAMESPACES ===============================================================


namespace ACG {


//== CLASS DEFINITION =========================================================


/** \class GLState GLState.hh <ACG/Scenegraph/GLState.hh>

    This class stores all relevant OpenGL states and can therefore
    provide some nice and efficient functions like projecting,
    unprojecting, eye point or viewing direction.

    \note This class needs an OpenGL context. This is currently
    given in a QGLContext.
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    
    \section pMatrix The projection matrix
    
    The GLState class stores its own projection matrix which is of type
    GLMatrixT. Creating a viewing frustum of a perspective projection
    will result in the following projection matrix:
    
    \image html pmatrix.png
    
    Where n is the orthogonal distance from the viewing plane (near plane)
    to the eye position, f is the orthogonal distance from the back clipping plane
    (far plane) to the eye position, l, r, t, b are scalars indicating the left, right,
    top and bottom coordinates of the viewing plane (so in fact we have a rectangle between
    the points (b,l) and (t,r)) and phi is the opening angle (field of view), also
    see figure 1.
    
    \image html projection.png "Figure 1. A schematic illustration of a viewing frustum"
    
    Some useful values that can directly be computed out of the projection matrix:
    
    \image html pfovy.png "Computing the fovy out of the projection matrix"
    
    \image html paspect.png "Computing the aspect out of the projection matrix"
Jan Möbius's avatar
 
Jan Möbius committed
111
112
113
114
115
116
117
**/

class ACGDLLEXPORT GLState
{
public:

  /// Default constructor
118
  GLState(bool _updateGL = true);
Jan Möbius's avatar
 
Jan Möbius committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

  /// destructor
  ~GLState() {}


  void makeCurrent() {  }

  /// initialize all state variables (called by constructor)
  void initialize();

  /// should GL matrices be updated after each matrix operation
  bool updateGL() const { return updateGL_; }
  /// should GL matrices be updated after each matrix operation
  void set_updateGL(bool _b) { updateGL_ = _b; }

  /// time passed since last redraw in milliseconds
  unsigned int msSinceLastRedraw () const { return msSinceLastRedraw_; }

  /// set time passed since last redraw in milliseconds
  void set_msSinceLastRedraw (unsigned int _ms) { msSinceLastRedraw_ = _ms; }

  /// set the whole stored gl state
  void setState ();

  /// clear buffers viewport rectangle
  void clearBuffers ();

  //---  set GL projection matrix ---------------------------------------------


  /// reset projection matrix (load identity)
  void reset_projection();

  /// set projection
  void set_projection(const GLMatrixd& _m) {
    GLMatrixd inv_m(_m);  inv_m.invert();  set_projection(_m, inv_m);
  }
  /// set projection and provide inverse projection matrix
  void set_projection(const GLMatrixd& _m, const GLMatrixd& _inv_m);

  /// orthographic projection
  void ortho( double _left, double _right,
	      double _bottom, double _top,
	      double _near_plane, double _far_plane );

  /// perspective projection
  void frustum( double _left, double _right,
		double _bottom, double _top,
		double _near_plane, double _far_plane );

  /// perspective projection
  void perspective( double _fovY, double _aspect,
		    double _near_plane, double _far_plane );

  /// set viewport (lower left corner, width, height, glcontext width, height)
  void viewport( int _left, int _bottom, int _width, int _height,
	         int _glwidth = 0, int _glheight = 0);





  //---  set GL modelview matrix ----------------------------------------------


  /// reset modelview matrix (load identity)
  void reset_modelview();

  /// set modelview
  void set_modelview(const GLMatrixd& _m) {
    GLMatrixd inv_m(_m);  inv_m.invert();  set_modelview(_m, inv_m);
  }
  /// set modelview and provide inverse modelview matrix
  void set_modelview(const GLMatrixd& _m, const GLMatrixd& _inv_m);

  /// set camera by lookAt
  void lookAt( const Vec3d& _eye, const Vec3d& _center, const Vec3d& _up );

  /// translate by (_x, _y, _z)
  void translate( double _x, double _y, double _z,
		  MultiplyFrom _mult_from = MULT_FROM_RIGHT );

  /// rotate around axis (_x, _y, _z) by _angle
  void rotate( double _angle, double _x, double _y, double _z,
	       MultiplyFrom _mult_from = MULT_FROM_RIGHT );

  /// scale by (_s, _s, _s)
  void scale( double _s )
  { scale(_s, _s, _s); }

  /// scale by (_s, _s, _s)
  void scale( double _s,
	      MultiplyFrom /* _mult_from = MULT_FROM_RIGHT  */ )
  { scale(_s, _s, _s); }

  /// scale by (_sx, _sy, _sz)
  void scale( double _sx, double _sy, double _sz,
	      MultiplyFrom _mult_from = MULT_FROM_RIGHT );

  /// multiply by a given transformation matrix
  void mult_matrix( const GLMatrixd& _m, const GLMatrixd& _inv_m,
		    MultiplyFrom _mult_from = MULT_FROM_RIGHT );


  /// push projection matrix
  void push_projection_matrix();
  /// pop projection matrix
  void pop_projection_matrix();

  /// push modelview matrix
  void push_modelview_matrix();
  /// pop modelview matrix
  void pop_modelview_matrix();


  //---  get GL states and matrices -------------------------------------------


  /// get projection matrix
  const GLMatrixd& projection() const {
    return projection_;
  }

  /// get modelview matrix
  const GLMatrixd& modelview() const {
    return modelview_;
  }

247
248
249
250
251
  /// get viewport matrix
  const GLMatrixd& viewport() const {
    return window2viewport_;
  }

Jan Möbius's avatar
 
Jan Möbius committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
  /// get forward projection matrix
  const GLMatrixd& forward_projection() const {
    return forward_projection_;
  }

  /// get inverse projection matrix
  const GLMatrixd& inverse_projection() const {
    return inverse_projection_;
  }

  /// get inverse modelview matrix
  const GLMatrixd& inverse_modelview() const {
    return inverse_modelview_;
  }

  /// get viewport
  void get_viewport( int& _left, int& _bottom,
		     int& _width, int& _height ) const {
    _left = left_; _bottom = bottom_; _width = width_; _height = height_;
  }

  /// get viewport width
  int viewport_width() const { return width_; }
  /// get viewport height
  int viewport_height() const { return height_; }

  /// get gl context width
  int context_width() const { return glwidth_; }

  /// get gl context height
  int context_height() const { return glheight_; }

  /// get near clipping distance
  double near_plane() const { return near_plane_; }

  /// get far clipping distance
  double far_plane() const { return far_plane_; }

  /// get field of view in y direction
291
  double fovy() const;
Jan Möbius's avatar
 
Jan Möbius committed
292
293

  /// get aspect ratio
294
  double aspect() const;
Jan Möbius's avatar
 
Jan Möbius committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

  /// get eye point
  Vec3d eye() const;

  /// get viewing ray
  Vec3d viewing_direction() const {
    return viewing_direction(width_>>1, height_>>1);
  }

  /// get viewing ray through pixel (_x,_y)
  Vec3d viewing_direction(int _x, int _y) const;

  /// get up-vector w.r.t. camera coordinates
  Vec3d up() const;

  /// get right-vector w.r.t. camera coordinates
  Vec3d right() const;

  /** get viewing ray (_orgin & _direction) through pixel (_x,_y).
      _direction will be nornalized.
  */
  void viewing_ray(int _x, int _y, Vec3d& _origin, Vec3d& _direction) const;
317
318
319
  
  /// get and set glDepthFunc() parameter
  GLenum& depthFunc() { return depth_func_; }
Jan Möbius's avatar
 
Jan Möbius committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393


  //--- project and unproject points ------------------------------------------

  /// project point in world coordinates to window coordinates
  Vec3d project(const Vec3d& _point) const;

  /// unproject point in window coordinates _winPoint to world coordinates
  Vec3d unproject(const Vec3d& _winPoint) const;




  //--- color & material ------------------------------------------------------

  /// default value for clear color
  static const Vec4f default_clear_color;
  /// default value for base color
  static const Vec4f default_base_color;
  /// default value for ambient color
  static const Vec4f default_ambient_color;
  /// default value for diffuse color
  static const Vec4f default_diffuse_color;
  /// default value for speculat color
  static const Vec4f default_specular_color;
  /// default value for shininess
  static const float default_shininess;


  /// set background color
  void set_clear_color(const Vec4f& _col);
  /// get background color
  const Vec4f& clear_color() const { return clear_color_; }

  /// set base color (used when lighting is off)
  void set_base_color(const Vec4f& _col);
  /// get base color (used when lighting is off)
  const Vec4f& base_color() const { return base_color_; }

  /// set ambient color
  void set_ambient_color(const Vec4f& _col);
  /// get ambient color
  const Vec4f& ambient_color() const { return ambient_color_; }

  /// set diffuse color
  void set_diffuse_color(const Vec4f& _col);
  /// get diffuse color
  const Vec4f& diffuse_color() const { return diffuse_color_; }

  /// set specular color
  void set_specular_color(const Vec4f& _col);
  /// get specular color
  const Vec4f& specular_color() const { return specular_color_; }

  /// set specular shininess (must be in [0, 128])
  void set_shininess(float _shininess);
  /// get specular shininess (must be in [0, 128])
  float shininess() const { return shininess_; }




  //--- thickness -------------------------------------------------------------

  /// set point size
  void set_point_size(float _f);
  /// get point size
  float point_size() const { return point_size_; }

  /// set line width
  void set_line_width(float _f);
  /// get line width
  float line_width() const { return line_width_; }

394
395
396
397
  //===========================================================================
  /** @name Render pass controls
   * @{ */
  //===========================================================================
Jan Möbius's avatar
 
Jan Möbius committed
398

399
400
401
402
403
public:
  /// get current render pass counter
  unsigned int render_pass() const { return render_pass_; }

  /// reset render pass counter
404
  void reset_render_pass() { render_pass_ = 1; }
405
406
407
408

  /// increment render pass counter
  void next_render_pass() { ++render_pass_; }

409
410
411
412
413
414
  /// get maximum number of render passes
  unsigned int max_render_passes() const { return max_render_passes_; }

  /// set maximum number of render passes
  void set_max_render_passes(const unsigned int _max) { max_render_passes_ = _max; }

415
private:
416
417
  /// holds the current render pass number (1-indexed)
  /// this has to be set externally
418
  unsigned int render_pass_;
Jan Möbius's avatar
 
Jan Möbius committed
419

420
421
422
423
424
425
  /// holds the maximum render pass number
  /// this has to be set externally
  unsigned int max_render_passes_;

  /** @} */

Jan Möbius's avatar
 
Jan Möbius committed
426
427
  //--- misc ------------------------------------------------------------------

428
public:
Jan Möbius's avatar
 
Jan Möbius committed
429
430
431
432
433
434
435
436
437
  /// set whether transparent or solid objects should be drawn
  void set_blending(bool _b) { blending_ = _b; }
  /// get whether transparenet or solid objects should be drawn
  bool blending() { return blending_; }

  /// set whether transparent or solid objects should be drawn
  void set_twosided_lighting(bool _b);
  /// get whether transparenet or solid objects should be drawn
  bool twosided_lighting() { return twosided_lighting_; }
438

439
  //--- Multi Sampling --------------------------------------------------------
440

441
442
  /// Enable or disable multisampling
  void set_multisampling( bool _b );
443

444
  /// Get current multisampling state
445
  bool multisampling() { return multisampling_; };
446

447
448
  /// Disable multisampling globally
  void allow_multisampling( bool _b ) { allow_multisampling_ = _b; };
449

450
  /// Check if Multisampling is globally disabled
451
452
453
454
  bool multisampling_allowed(){ return allow_multisampling_; };
  
  /// Get max number of available texture units
  int max_texture_units() const { return num_texture_units_; }
455
456
457
458
459
460
461
462
463
464
465
466
467
468
  
  //--- Mipmapping ------------------------------------------------------------
  
  /** \brief Allow mipmapping globally
  *
  * Note: This actually does not change the opengl state
  * since mipmapping is turned on/off via texture parameters
  * To change the behaviour see in TextureNode
  */
  
  void allow_mipmapping(bool _b) { mipmapping_ = _b; }
  
  /// Get current global mipmapping state
  bool mipmapping_allowed() const { return mipmapping_; }
Jan Möbius's avatar
 
Jan Möbius committed
469

Jan Möbius's avatar
Dennis:    
Jan Möbius committed
470
  //--- picking ---------------------------------------------------------------
Jan Möbius's avatar
 
Jan Möbius committed
471

472
473
474
475
476
477
478
479
480
  /** Follows the OpenGL selection buffer implementation (OpenGL Red Book Chapter 13)
    * http://www.glprogramming.com/red/chapter13.html
    *
    * Color picking is another method to realize picking. This functions replace the original OpenGL
    * functions, to allow the handling of selection buffer picking and color based picking with
    * the same code.
    */

  /// initialize name/color picking stack (like glInitNames())
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
481
482
483
  void pick_init (bool _color);

  /// sets the maximum used name index at current stack position (only used in color picking)
484
  /// A restriction inside the color picking implementation forces to set the maximum used
485
  /// number for the following pick_set_name calls between the two pick_push_name/pick_pop_name calls.
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
486
487
  bool pick_set_maximum (unsigned int _idx);

488
  /// sets the current name/color (like glLoadName(_idx))
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
489
490
  void pick_set_name (unsigned int _idx);

491
492
493
  /// returns the color that will be used for index _idx during color picking if this index will be set
  /// with pick_set_name. This can be used to generate color arrays instead of using direct gl calls
  /// for each primitive
494
495
  Vec4uc pick_get_name_color (unsigned int _idx);

496
  /// creates a new name the stack (like glPushName())
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
497
498
  void pick_push_name (unsigned int _idx);

499
  /// pops the current name from the stack (like glPopName())
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
500
501
502
  void pick_pop_name ();

  /// converts the given color to index values on the stack (only used in color picking)
503
  /// This can be compared to the results of the selection buffer results
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
504
  std::vector<unsigned int> pick_color_to_stack (Vec4uc _rgba) const;
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
505

506
  /// returns the number of still available colors during color picking
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
507
508
509
  unsigned int pick_free_indicies () const;

  /// Did an error occur during picking (only used in color picking)
510
  /// Mostly to small color depth or wrong handling of pick_set_maximum
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
511
512
513
  bool pick_error () const;

  /// returns the current color picking index (can be used for caching)
514
515
  /// Is this value equal to a value used in a previous picking, then the same colors will be used.
  /// In this case a previously calculated color array/display list can be reused.
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
516
  unsigned int pick_current_index () const;
Jan Möbius's avatar
 
Jan Möbius committed
517

Jan Möbius's avatar
Dennis:    
Jan Möbius committed
518
519
520
  /// Is color picking active?
  bool color_picking () const;

Jan Möbius's avatar
 
Jan Möbius committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550

private: //--------------------------------------------------------------------

  // update forward projection and backward projection matrices
  void update_matrices();


  // matrix stacks
  std::stack<GLMatrixd>  stack_projection_,
                         stack_modelview_,
                         stack_inverse_projection_,
                         stack_inverse_modelview_;

  // current matrices
  GLMatrixd  projection_,
             inverse_projection_,
             modelview_,
             inverse_modelview_,
             window2viewport_,
             inverse_window2viewport_,
             forward_projection_,
             backward_projection_;

  // viewport
  int left_, bottom_, width_, height_;

  // gl context
  int glwidth_, glheight_;

  // projection
551
  double near_plane_, far_plane_;
Jan Möbius's avatar
 
Jan Möbius committed
552
553
554
555
556
557
558
559
560
561
562
563
564

  // colors & materials
  Vec4f   clear_color_,
          base_color_,
          ambient_color_,
          diffuse_color_,
          specular_color_;

  float shininess_;

  // thickness
  float  point_size_, line_width_;

565
  // lighting
Jan Möbius's avatar
 
Jan Möbius committed
566
567
  bool twosided_lighting_;

568
569
570
  // Multisampling settings
  bool multisampling_;
  bool allow_multisampling_;
571
572
573
  
  int num_texture_units_;
  
574
575
576
  // Mipmapping settings
  bool mipmapping_;
  
Jan Möbius's avatar
 
Jan Möbius committed
577
578
579
580
581
582
583
584
585
  // helper: should GL matrices be updated
  bool updateGL_;

  // true -> draw tranparent Objects
  bool blending_;

  // time since last redraw
  unsigned int msSinceLastRedraw_;

Jan Möbius's avatar
Dennis:    
Jan Möbius committed
586
587
588
589
590
  // stack for color picking
  ColorStack colorStack_;

  // are we using color picking
  bool colorPicking_;
591
592
593
  
  // depth comparison function (GL_LESS by default)
  GLenum depth_func_;
Jan Möbius's avatar
Dennis:    
Jan Möbius committed
594

Jan Möbius's avatar
 
Jan Möbius committed
595
596
597
598
599
600
601
602
603
604
605
};

#ifdef WIN32
	#pragma warning(push)
#endif

//=============================================================================
} // namespace ACG
//=============================================================================
#endif // ACG_GLSTATE_HH defined
//=============================================================================