Main MRPT website > C++ reference
MRPT logo
COpenGLViewport.h
Go to the documentation of this file.
1 /* +---------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | http://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2014, Individual contributors, see AUTHORS file |
6  | See: http://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See details in http://www.mrpt.org/License |
8  +---------------------------------------------------------------------------+ */
9 #ifndef opengl_COpenGLViewport_H
10 #define opengl_COpenGLViewport_H
11 
14 #include <mrpt/utils/CImage.h>
15 #include <mrpt/opengl/CCamera.h>
17 #include <mrpt/opengl/CLight.h>
19 #include <mrpt/utils/CObservable.h>
20 #include <mrpt/utils/CStringList.h>
21 #include <mrpt/utils/mrptEvent.h>
22 
23 namespace mrpt
24 {
25  namespace utils { class CImage; }
26 
27  namespace opengl
28  {
29  using namespace mrpt::math;
30 
31  class COpenGLScene;
32  class CRenderizable;
33 
34  // This must be added to any CSerializable derived class:
36 
37  /** A viewport within a COpenGLScene, containing a set of OpenGL objects to render.
38  * This class has protected constuctor, thus it cannot be created by users. Use COpenGLScene::createViewport instead.
39  * A viewport has these "operation modes":
40  * - Normal (default): It renders the contained objects.
41  * - Cloned: It clones the objects from another viewport. See \a setCloneView()
42  * - Image mode: It renders an image (e.g. from a video stream) efficiently using a textued quad. See \a setImageView().
43  *
44  * In any case, the viewport can be resized to only fit a part of the entire parent viewport.
45  * There will be always at least one viewport in a COpenGLScene named "main".
46  *
47  * This class can be observed (see mrpt::utils::CObserver) for the following events (see mrpt::utils::mrptEvent):
48  * - mrpt::opengl::mrptEventGLPreRender
49  * - mrpt::opengl::mrptEventGLPostRender
50  *
51  * Two directional light sources at infinity are created by default, with directions (-1,-1,-1) and (1,2,1), respectively.
52  * All OpenGL properties of light sources are accesible via the methods: setNumberOfLights(), lightsClearAll(), addLight(), and getLight().
53  * Please, refer to mrpt::opengl::CLight and the standard OpenGL documentation for the meaning of all light properties.
54  *
55  * Refer to mrpt::opengl::COpenGLScene for further details.
56  * \ingroup mrpt_opengl_grp
57  */
59  public mrpt::utils::CSerializable,
60  public mrpt::utils::CObservable
61  {
63  friend class COpenGLScene;
64  public:
65  // -------------------------------------------------------------------
66  /** @name Set the viewport "modes"
67  @{ */
68 
69  /** Set this viewport as a clone of some other viewport, given its name - as a side effect, current list of internal OpenGL objects is cleared.
70  * By default, only the objects are cloned, not the camera. See
71  * \sa resetCloneView
72  */
73  void setCloneView( const std::string &clonedViewport );
74 
75  /** Set this viewport into "image view"-mode, where an image is efficiently drawn (fitting the viewport area) using an OpenGL textured quad.
76  * Call this method with the new image to update the displayed image (but recall to first lock the parent openglscene's critical section, then do the update, then release the lock, and then issue a window repaint).
77  * Internally, the texture is drawn using a mrpt::opengl::CTexturedPlane
78  * The viewport can be reverted to behave like a normal viewport by calling setNormalMode()
79  * \sa setImageView_fast
80  */
81  void setImageView(const mrpt::utils::CImage &img);
82 
83  /** Just like \a setImageView but moves the internal image memory instead of making a copy, so it's faster but empties the input image.
84  * \sa setImageView
85  */
86  void setImageView_fast(mrpt::utils::CImage &img);
87 
88  /** Reset the viewport to normal mode: rendering its own objects.
89  * \sa setCloneView, setNormalMode
90  */
91  inline void resetCloneView() { setNormalMode(); }
92 
93  /** If set to true, and setCloneView() has been called, this viewport will be rendered using the camera of the cloned viewport.
94  */
95  inline void setCloneCamera(bool enable) { m_isClonedCamera = enable; }
96 
97  /** Resets the viewport to a normal 3D viewport \sa setCloneView, setImageView */
98  void setNormalMode();
99 
100  /** @} */ // end of Set the "viewport mode"
101  // ------------------------------------------------------
102 
103 
104  /** @name OpenGL global settings that affect rendering all objects in the scene/viewport
105  @{ */
106 
107  /** Sets glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) is enabled, or GL_FASTEST otherwise. */
108  void enablePolygonNicest(bool enable=true) { m_OpenGL_enablePolygonNicest=enable; }
109  bool isPolygonNicestEnabled() const { return m_OpenGL_enablePolygonNicest; }
110 
111  /** Removes all lights (and disables the global "GL_LIGHTING") */
112  void lightsClearAll() { m_lights.clear(); }
113 
114  /** Append a new light to the scene. By default there are two lights. "GL_LIGHTING" is disabled if all lights are removed */
115  void addLight(const CLight &l) { m_lights.push_back(l); }
116 
117  /** Allocates a number of lights, which must be correctly defined via getLight(i), etc. */
118  void setNumberOfLights(const size_t N) { m_lights.resize(N); }
119 
120  CLight & getLight(const size_t i) { ASSERT_BELOW_(i,m_lights.size()) return m_lights[i]; }
121  const CLight & getLight(const size_t i) const { ASSERT_BELOW_(i,m_lights.size()) return m_lights[i]; }
122 
123  /** @} */ // end of OpenGL settings
124 
125  // -------------------------------------------------------------------
126  /** @name Change or read viewport properties (except "viewport modes")
127  @{ */
128 
129  /** Returns the name of the viewport */
130  inline std::string getName() { return m_name; }
131 
132  /** Change the viewport position and dimension on the rendering window.
133  * X & Y coordinates here can have two interpretations:
134  * - If in the range [0,1], they are factors with respect to the actual window sizes (i.e. width=1 means the entire width of the rendering window).
135  * - If >1, they are interpreted as pixels.
136  *
137  * width & height can be interpreted as:
138  * - If >1, they are the size of the viewport in that dimension, in pixels.
139  * - If in [0,1], they are the size of the viewport in that dimension, in a factor of the width/height.
140  * - If in [-1,0[, the size is computed such as the right/top border ends up in the given coordinate, interpreted as a factor (e.g. -1: up to the end of the viewport, -0.5: up to the middle of it).
141  * - If <-1 the size is computed such as the right/top border ends up in the given absolute coordinate (e.g. -200: up to the row/column 200px).
142  *
143  * \note (x,y) specify the lower left corner of the viewport rectangle.
144  * \sa getViewportPosition
145  */
146  void setViewportPosition(
147  const double x,
148  const double y,
149  const double width,
150  const double height );
151 
152  /** Get the current viewport position and dimension on the rendering window.
153  * X & Y coordinates here can have two interpretations:
154  * - If in the range [0,1], they are factors with respect to the actual window sizes (i.e. width=1 means the entire width of the rendering window).
155  * - If >1, they are interpreted as pixels.
156  * \note (x,y) specify the lower left corner of the viewport rectangle.
157  * \sa setViewportPosition
158  */
159  void getViewportPosition(
160  double &x,
161  double &y,
162  double &width,
163  double &height );
164 
165  /** Set the min/max clip depth distances of the rendering frustum (default: 0.1 - 10000)
166  * \sa getViewportClipDistances
167  */
168  void setViewportClipDistances(const double clip_min, const double clip_max);
169 
170  /** Get the current min/max clip depth distances of the rendering frustum (default: 0.1 - 10000)
171  * \sa setViewportClipDistances
172  */
173  void getViewportClipDistances(double &clip_min, double &clip_max) const;
174 
175  /** Set the border size ("frame") of the viewport (default=0).
176  */
177  inline void setBorderSize( unsigned int lineWidth ) { m_borderWidth = lineWidth; }
178 
179  /** Return whether the viewport will be rendered transparent over previous viewports.
180  */
181  inline bool isTransparent() { return m_isTransparent; }
182 
183  /** Set the transparency, that is, whether the viewport will be rendered transparent over previous viewports (default=false).
184  */
185  inline void setTransparent( bool trans ) { m_isTransparent=trans; }
186 
187  /** Set a background color different from that of the parent GUI window */
188  inline void setCustomBackgroundColor( const mrpt::utils::TColorf &color ) { m_custom_backgb_color = true; m_background_color = color; }
189 
190  inline mrpt::utils::TColorf getCustomBackgroundColor() const { return m_background_color; }
191 
192  /** Compute the 3D ray corresponding to a given pixel; this can be used to allow the user to pick and select 3D objects by clicking onto the 2D image.
193  * \param x_coord Horizontal coordinate with the usual meaning (0:left of the viewport, W-1: right border).
194  * \param y_coord Horizontal coordinate with the usual meaning (0:top of the viewport, H-1: right border).
195  * \param out_cameraPose If not NULL, will have the camera 3D pose as a mrpt::poses::CPose3D. See also
196  * \note (x,y) refer to VIEWPORT coordinates. Take into account this when viewports do not extend to the whole window size.
197  * \note x and y are double instead of integers to allow sub-pixel precision.
198  * \sa getCurrentCameraPose
199  */
200  void get3DRayForPixelCoord( const double x_coord, const double y_coord, mrpt::math::TLine3D &out_ray, mrpt::poses::CPose3D *out_cameraPose=NULL ) const;
201 
202  /** @} */ // end of Change or read viewport properties
203  // ------------------------------------------------------
204 
205 
206  // -------------------------------------------------------------------
207  /** @name Contained objects set/get/search
208  @{ */
209 
212 
213  inline const_iterator begin() const { return m_objects.begin(); }
214  inline const_iterator end() const { return m_objects.end(); }
215  inline iterator begin() { return m_objects.begin(); }
216  inline iterator end() { return m_objects.end(); }
217 
218  /** Delete all internal obejcts
219  * \sa insert */
220  void clear();
221 
222  /** Insert a new object into the list.
223  * The object MUST NOT be deleted, it will be deleted automatically by this object when not required anymore.
224  */
225  void insert( const CRenderizablePtr &newObject );
226 
227  /** Compute the current 3D camera pose.
228  * \sa get3DRayForPixelCoord
229  */
230  void getCurrentCameraPose( mrpt::poses::CPose3D &out_cameraPose ) const;
231 
232  /** Returns the first object with a given name, or NULL if not found.
233  */
234  CRenderizablePtr getByName( const std::string &str );
235 
236  /** Returns the i'th object of a given class (or of a descendant class), or NULL (an empty smart pointer) if not found.
237  * Example:
238  * \code
239  CSpherePtr obs = view.getByClass<CSphere>();
240  * \endcode
241  * By default (ith=0), the first observation is returned.
242  */
243  template <typename T>
244  typename T::SmartPtr getByClass( const size_t &ith = 0 ) const
245  {
246  MRPT_START
247  size_t foundCount = 0;
248  const mrpt::utils::TRuntimeClassId* class_ID = T::classinfo;
249  for (CListOpenGLObjects::const_iterator it = m_objects.begin();it!=m_objects.end();++it)
250  if ( (*it).present() && (*it)->GetRuntimeClass()->derivedFrom( class_ID ) )
251  if (foundCount++ == ith)
252  return typename T::SmartPtr(*it);
253 
254  // If not found directly, search recursively:
255  for (CListOpenGLObjects::const_iterator it=m_objects.begin();it!=m_objects.end();++it)
256  {
257  if ( (*it).present() && (*it)->GetRuntimeClass() == CLASS_ID_NAMESPACE(CSetOfObjects,mrpt::opengl))
258  {
259  typename T::SmartPtr o = CSetOfObjectsPtr(*it)->getByClass<T>(ith);
260  if (o.present()) return o;
261  }
262  }
263  return typename T::SmartPtr(); // Not found: return empty smart pointer
264  MRPT_END
265  }
266 
267  /** Removes the given object from the scene (it also deletes the object to free its memory).
268  */
269  void removeObject( const CRenderizablePtr & obj );
270 
271  /** Number of objects contained. */
272  inline size_t size() const { return m_objects.size(); }
273 
274  inline bool empty() const { return m_objects.empty(); }
275 
276  opengl::CCamera& getCamera() { return m_camera;} //!< Get a reference to the camera associated with this viewport.
277 
278  const opengl::CCamera & getCamera() const { return m_camera;} //!< Get a reference to the camera associated with this viewport.
279 
280  /** Evaluates the bounding box of this object (including possible children) in the coordinate frame of the object parent. */
281  void getBoundingBox(mrpt::math::TPoint3D &bb_min, mrpt::math::TPoint3D &bb_max) const;
282 
283  /** @} */ // end of Contained objects set/get/search
284  // ------------------------------------------------------
285 
286 
287  virtual ~COpenGLViewport(); //!< Destructor: clears all objects.
288 
289 
290  protected:
291  /** Constructor, invoked from COpenGLScene only.
292  */
293  COpenGLViewport( COpenGLScene *parent=NULL, const std::string &name=std::string("") );
294 
295  /** Initializes all textures in the scene (See opengl::CTexturedPlane::loadTextureInOpenGL)
296  */
297  void initializeAllTextures();
298 
299  /** Retrieves a list of all objects in text form.
300  */
301  void dumpListOfObjects( mrpt::utils::CStringList &lst );
302 
303  /** Render the objects in this viewport (called from COpenGLScene only) */
304  void render( const int render_width, const int render_height ) const;
305 
306  /** The camera associated to the viewport */
308  utils::safe_ptr<COpenGLScene> m_parent; //!< The scene that contains this viewport.
309  bool m_isCloned; //!< Set by setCloneView
310  bool m_isClonedCamera; //!< Set by setCloneCamera
311  std::string m_clonedViewport; //!< Only if m_isCloned=true
312  std::string m_name; //!< The viewport's name
313  bool m_isTransparent; //!< Whether to clear color buffer.
314  uint32_t m_borderWidth; //!< Default=0, the border around the viewport.
315  double m_view_x, m_view_y,m_view_width,m_view_height; //!< The viewport position [0,1]
316  double m_clip_min,m_clip_max; //!< The min/max clip depth distances (default: 0.1 - 10000)
318  mrpt::utils::TColorf m_background_color; //!< used only if m_custom_backgb_color
319  bool m_isImageView; //!< Set by setImageView
320  //CRenderizablePtr m_imageview_quad ; //!< A mrpt::opengl::CTexturedPlane used after setImageView() is called
321  mrpt::utils::CImagePtr m_imageview_img; //!< The image to display, after calling \a setImageView()
322 
324  {
325  TLastProjectiveMatrixInfo() : is_projective(true),eye(0,0,0),pointing(0,0,0),up(0,0,0), FOV(30), viewport_width(640), viewport_height(480), azimuth(0), elev(0), zoom(1)
326  {}
327  bool is_projective; // true: projective, false: ortho
328  TPoint3D eye; //!< The camera is here.
329  TPoint3D pointing; //!< The camera points to here
330  TPoint3D up; //!< Up vector of the camera.
331  float FOV; //!< FOV in degrees.
332  size_t viewport_width, viewport_height; //!< In pixels. This may be smaller than the total render window.
333  float azimuth, elev; //!< Camera elev & azimuth, in radians.
334  float zoom;
335  };
336  mutable TLastProjectiveMatrixInfo m_lastProjMat; //!< Info updated with each "render()" and used in "get3DRayForPixelCoord"
337 
338  /** The list of objects that comprise the 3D scene.
339  * Objects are automatically deleted when calling "clear" or in the destructor.
340  */
342 
343  void internal_setImageView_fast(const mrpt::utils::CImage &img, bool is_fast);
344 
345  // OpenGL global settings:
347 
348  std::vector<CLight> m_lights;
349  };
351  /**
352  * Inserts an openGL object into a viewport. Allows call chaining.
353  * \sa mrpt::opengl::COpenGLViewport::insert
354  */
355  inline COpenGLViewportPtr &operator<<(COpenGLViewportPtr &s,const CRenderizablePtr &r) {
356  s->insert(r);
357  return s;
358  }
359  /**
360  * Inserts any iterable set of openGL objects into a viewport. Allows call chaining.
361  * \sa mrpt::opengl::COpenGLViewport::insert
362  */
363  inline COpenGLViewportPtr &operator<<(COpenGLViewportPtr &s,const std::vector<CRenderizablePtr> &v) {
364  for (std::vector<CRenderizablePtr>::const_iterator it=v.begin();it!=v.end();++it) s->insert(*it);
365  return s;
366  }
367 
368 
369 
370  /** @name Events emitted by COpenGLViewport
371  @{ */
372 
373  /** An event sent by an mrpt::opengl::COpenGLViewport just after clearing the viewport and setting the GL_PROJECTION matrix, and before calling the scene OpenGL drawing primitives.
374  *
375  * While handling this event you can call OpenGL glBegin(),glEnd(),gl* functions or those in mrpt::opengl::gl_utils to draw stuff *in the back* of the normal
376  * objects contained in the COpenGLScene.
377  *
378  * After processing this event, COpenGLViewport will change the OpenGL matrix mode into "GL_MODELVIEW" and load an identity matrix to continue
379  * rendering the scene objects as usual. Any change done to the GL_PROJECTION will have effects, so do a glPushMatrix()/glPopMatrix() if that is not your intention.
380  *
381  *
382  * IMPORTANTE NOTICE: Event handlers in your observer class will most likely be invoked from an internal GUI thread of MRPT,
383  * so all your code in the handler must be thread safe.
384  */
386  {
387  protected:
388  virtual void do_nothing() { } //!< Just to allow this class to be polymorphic
389  public:
390  inline mrptEventGLPreRender(const COpenGLViewport* obj) : source_viewport(obj) { }
392  }; // End of class def.
393 
394  /** An event sent by an mrpt::opengl::COpenGLViewport after calling the scene OpenGL drawing primitives and before doing a glSwapBuffers
395  *
396  * While handling this event you can call OpenGL glBegin(),glEnd(),gl* functions or those in mrpt::opengl::gl_utils to draw stuff *on the top* of the normal
397  * objects contained in the COpenGLScene.
398  *
399  * IMPORTANTE NOTICE: Event handlers in your observer class will most likely be invoked from an internal GUI thread of MRPT,
400  * so all your code in the handler must be thread safe.
401  */
403  {
404  protected:
405  virtual void do_nothing() { } //!< Just to allow this class to be polymorphic
406  public:
407  inline mrptEventGLPostRender(const COpenGLViewport* obj) : source_viewport(obj) { }
409  }; // End of class def.
410 
411 
412  /** @} */
413 
414 
415 
416  } // end namespace
417 
418 } // End of namespace
419 
420 
421 #endif
opengl::CListOpenGLObjects m_objects
The list of objects that comprise the 3D scene.
void setBorderSize(unsigned int lineWidth)
Set the border size ("frame") of the viewport (default=0).
const COpenGLViewport *const source_viewport
const opengl::CCamera & getCamera() const
Get a reference to the camera associated with this viewport.
mrpt::utils::CImagePtr m_imageview_img
The image to display, after calling setImageView()
bool m_isTransparent
Whether to clear color buffer.
opengl::CCamera & getCamera()
Get a reference to the camera associated with this viewport.
A set of object, which are referenced to the coordinates framework established in this object...
Definition: CSetOfObjects.h:32
uint32_t m_borderWidth
Default=0, the border around the viewport.
The virtual base class which provides a unified interface for all persistent objects in MRPT...
Definition: CSerializable.h:35
mrptEventGLPostRender(const COpenGLViewport *obj)
A class for storing images as grayscale or RGB bitmaps.
Definition: CImage.h:97
The basic event type for the observer-observable pattern in MRPT.
Definition: mrptEvent.h:34
std::vector< CLight > m_lights
#define ASSERT_BELOW_(__A, __B)
Scalar * iterator
Definition: eigen_plugins.h:23
std::deque< CRenderizablePtr > CListOpenGLObjects
A list of objects pointers, automatically managing memory free at destructor, and managing copies cor...
Definition: CRenderizable.h:33
CLight & getLight(const size_t i)
STL namespace.
const Scalar * const_iterator
Definition: eigen_plugins.h:24
mrpt::utils::TColorf m_background_color
used only if m_custom_backgb_color
CListOpenGLObjects::iterator iterator
mrpt::utils::TColorf getCustomBackgroundColor() const
A viewport within a COpenGLScene, containing a set of OpenGL objects to render.
void setCloneCamera(bool enable)
If set to true, and setCloneView() has been called, this viewport will be rendered using the camera o...
Each of the possible lights of a 3D scene.
Definition: CLight.h:28
const COpenGLViewport *const source_viewport
bool m_isClonedCamera
Set by setCloneCamera.
A class for storing a list of text lines.
Definition: CStringList.h:32
This base provides a set of functions for maths stuff.
Definition: CArray.h:18
bool m_isImageView
Set by setImageView.
#define DEFINE_SERIALIZABLE_PRE_CUSTOM_BASE_LINKAGE(class_name, base_name, _LINKAGE_)
This declaration must be inserted in all CSerializable classes definition, before the class declarati...
#define MRPT_END
virtual void do_nothing()
Just to allow this class to be polymorphic.
TLastProjectiveMatrixInfo m_lastProjMat
Info updated with each "render()" and used in "get3DRayForPixelCoord".
const_iterator begin() const
mrptEventGLPreRender(const COpenGLViewport *obj)
#define CLASS_ID_NAMESPACE(class_name, namespaceName)
Access to runtime class ID for a defined class name.
Definition: CObject.h:92
const CLight & getLight(const size_t i) const
#define MRPT_START
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
#define DEFINE_SERIALIZABLE(class_name)
This declaration must be inserted in all CSerializable classes definition, within the class declarati...
An event sent by an mrpt::opengl::COpenGLViewport just after clearing the viewport and setting the GL...
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
Definition: CPose3D.h:69
float elev
Camera elev & azimuth, in radians.
An event sent by an mrpt::opengl::COpenGLViewport after calling the scene OpenGL drawing primitives a...
void enablePolygonNicest(bool enable=true)
Sets glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) is enabled, or GL_FASTEST otherwise.
size_t size() const
Number of objects contained.
CListOpenGLObjects::const_iterator const_iterator
The namespace for 3D scene representation and rendering.
This class allows the user to create, load, save, and render 3D scenes using OpenGL primitives...
Definition: COpenGLScene.h:49
void setTransparent(bool trans)
Set the transparency, that is, whether the viewport will be rendered transparent over previous viewpo...
A RGB color - floats in the range [0,1].
Definition: TColor.h:52
std::string m_clonedViewport
Only if m_isCloned=true.
void lightsClearAll()
Removes all lights (and disables the global "GL_LIGHTING")
std::string getName()
Returns the name of the viewport.
void addLight(const CLight &l)
Append a new light to the scene.
void setCustomBackgroundColor(const mrpt::utils::TColorf &color)
Set a background color different from that of the parent GUI window.
A structure that holds runtime class type information.
Definition: CObject.h:46
const_iterator end() const
Lightweight 3D point.
EIGEN_STRONG_INLINE void eye()
Make the matrix an identity matrix.
Definition: eigen_plugins.h:63
A camera: if added to a scene, the viewpoint defined by this camera will be used instead of the camer...
Definition: CCamera.h:31
virtual void do_nothing()
Just to allow this class to be polymorphic.
Inherit from this class for those objects capable of being observed by a CObserver class...
Definition: CObservable.h:33
bool isTransparent()
Return whether the viewport will be rendered transparent over previous viewports. ...
#define DEFINE_SERIALIZABLE_POST_CUSTOM_BASE_LINKAGE(class_name, base_name, _LINKAGE_)
utils::safe_ptr< COpenGLScene > m_parent
The scene that contains this viewport.
opengl::CCamera m_camera
The camera associated to the viewport.
A wrapper class for pointers that can be safely copied with "=" operator without problems.
Definition: safe_pointers.h:67
T::SmartPtr getByClass(const size_t &ith=0) const
Returns the i'th object of a given class (or of a descendant class), or NULL (an empty smart pointer)...
std::string m_name
The viewport's name.
bool m_isCloned
Set by setCloneView.
3D line, represented by a base point and a director vector.
void setNumberOfLights(const size_t N)
Allocates a number of lights, which must be correctly defined via getLight(i), etc.



Page generated by Doxygen 1.8.8 for MRPT 1.2.2 SVN:Unversioned directory at Tue Oct 14 02:14:08 UTC 2014