23 #include <Eigen/Dense> 38 #if defined(OPENGLVIEWPORT_ENABLE_TIMEPROFILING) 51 COpenGLViewport::COpenGLViewport(
COpenGLScene* parent,
const string& name)
52 : m_parent(parent), m_name(name)
66 const double x,
const double y,
const double width,
const double height)
84 double& x,
double& y,
double& width,
double& height)
106 const int startCoord,
const double dSize,
const int iLength)
109 return static_cast<int>(dSize);
114 return static_cast<int>(-iLength * dSize - startCoord + 1);
116 return static_cast<int>(-dSize - startCoord + 1);
119 return static_cast<int>(iLength * dSize);
123 return frac > 1 ?
static_cast<int>(frac)
124 : (frac < 0 ? static_cast<int>(dSize + frac)
125 :
static_cast<int>(dSize * frac));
131 #if MRPT_HAS_OPENGL_GLUT 132 #if defined(OPENGLVIEWPORT_ENABLE_TIMEPROFILING) 134 glv_timlog,
"COpenGLViewport::render imageview");
142 glDisable(GL_DEPTH_TEST);
144 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
149 const double img_ratio = double(img_w) / img_h;
150 const double vw_ratio = double(_.viewport_width) / _.viewport_height;
151 const double ratio = vw_ratio / img_ratio;
153 _.mv_matrix.setIdentity();
154 _.p_matrix.setIdentity();
157 _.p_matrix(1, 1) /= img_ratio;
158 else if (img_ratio > 0)
159 _.p_matrix(0, 0) /= img_ratio;
161 if (ratio > 0) _.p_matrix(0, 0) /= ratio;
163 auto &p00 = _.p_matrix(0, 0), &p11 = _.p_matrix(1, 1);
164 if (p00 > 0 && p11 > 0)
166 const double s = (p00 > p11) ? p00 : p11;
171 _.pmv_matrix.asEigen() = _.p_matrix.asEigen() * _.mv_matrix.asEigen();
189 #if MRPT_HAS_OPENGL_GLUT 192 std::vector<shader_id_t> lstShaderIDs = {
197 for (
const auto&
id : lstShaderIDs)
212 #if MRPT_HAS_OPENGL_GLUT 226 "Cloned viewport '%s' not found in parent COpenGLScene",
229 objectsToRender = &view->m_objects;
245 if (!myCamera) myCamera = &viewForGetCamera->
m_camera;
265 at = pose + viewDirection;
270 _.pointing.
x = at.
x();
271 _.pointing.y = at.
y();
272 _.pointing.z = at.z();
281 const double dis = std::max<double>(0.005, myCamera->
m_eyeDistance);
282 _.eye.x = _.pointing.x + dis * cos(_.azimuth) * cos(_.elev);
283 _.eye.y = _.pointing.y + dis * sin(_.azimuth) * cos(_.elev);
284 _.eye.z = _.pointing.z + dis * sin(_.elev);
290 _.up.x = -cos(_.azimuth) * sin(_.elev);
291 _.up.y = -sin(_.azimuth) * sin(_.elev);
292 _.up.z = cos(_.elev);
311 GL_POLYGON_SMOOTH_HINT,
313 CHECK_OPENGL_ERROR();
316 _.mv_matrix.setIdentity();
318 glEnable(GL_DEPTH_TEST);
319 glDepthFunc(GL_LEQUAL);
322 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
325 #if defined(GL_PROGRAM_POINT_SIZE) // it seems it's undefined in OSX (?) 326 glEnable(GL_PROGRAM_POINT_SIZE);
327 CHECK_OPENGL_ERROR();
344 #if MRPT_HAS_OPENGL_GLUT 351 _.p_matrix.setIdentity();
352 _.pmv_matrix.setIdentity();
354 glDisable(GL_DEPTH_TEST);
356 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
385 #if MRPT_HAS_OPENGL_GLUT 410 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
421 label.
x >= 1 ? label.
x : (label.
x < 0 ? w + label.
x : label.
x * w);
423 label.
y >= 1 ? label.
y : (label.
y < 0 ? h + label.
y : label.
y * h);
428 o->setString(label.
text);
429 o->setColor(label.
color);
432 o->setLocation(-1.0f + 2 * x / w, -1.0f + 2 * y / h, 0);
438 o->setString(label.
text);
443 -1.0f + 2 * (x + 1) / w, -1.0f + 2 * (y - 1) / h, 0.1);
459 [[maybe_unused]]
const int render_width,
460 [[maybe_unused]]
const int render_height,
461 [[maybe_unused]]
const int render_offset_x,
462 [[maybe_unused]]
const int render_offset_y)
const 464 #if MRPT_HAS_OPENGL_GLUT 474 glViewport(vx, vy, vw, vh);
475 CHECK_OPENGL_ERROR();
482 glScissor(vx, vy, vw, vh);
483 CHECK_OPENGL_ERROR();
485 glEnable(GL_SCISSOR_TEST);
486 CHECK_OPENGL_ERROR();
495 glGetFloatv(GL_COLOR_CLEAR_VALUE, prevCol);
496 CHECK_OPENGL_ERROR();
500 CHECK_OPENGL_ERROR();
504 GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
505 CHECK_OPENGL_ERROR();
510 glClearColor(prevCol[0], prevCol[1], prevCol[2], prevCol[3]);
511 CHECK_OPENGL_ERROR();
516 glClear(GL_DEPTH_BUFFER_BIT);
517 CHECK_OPENGL_ERROR();
519 glDisable(GL_SCISSOR_TEST);
520 CHECK_OPENGL_ERROR();
548 "The MRPT has been compiled with MRPT_HAS_OPENGL_GLUT=0! OpenGL " 549 "functions are not implemented");
569 for (
const auto& m_object :
m_objects)
out << *m_object;
647 if (m_object->m_name == str)
650 m_object->GetRuntimeClass() ==
664 for (
auto& obj :
m_objects) obj->initializeTextures();
672 string s(m_object->GetRuntimeClass()->className);
673 if (m_object->m_name.size())
674 s +=
string(
" (") + m_object->m_name + string(
")");
677 if (m_object->GetRuntimeClass() ==
680 std::vector<std::string> auxLst;
685 for (
const auto& i : auxLst) lst.emplace_back(
string(
" ") + i);
702 (*it)->GetRuntimeClass() ==
704 dynamic_cast<CSetOfObjects*>(it->get())->
removeObject(obj);
708 const float clip_min,
const float clip_max)
717 float& clip_min,
float& clip_max)
const 732 const double ASPECT =
764 if (ASPECT != 0) Ay /= ASPECT;
767 const double point_lx =
769 const double point_ly =
773 m_state.
eye.
x + point_lx * cam_x_3d.
x + point_ly * cam_up_3d.
x,
774 m_state.
eye.
y + point_lx * cam_x_3d.
y + point_ly * cam_up_3d.
y,
775 m_state.
eye.
z + point_lx * cam_x_3d.
z + point_ly * cam_up_3d.
z);
777 out_ray.
pBase = ray_origin;
793 const double FOVx = 2.0 * atan(ASPECT * tan(FOVy * 0.5));
797 const double len_horz = 2.0 * (-0.5 + x_coord / vw) * tan(0.5 * FOVx);
798 const double len_vert = -2.0 * (-0.5 + y_coord / vh) * tan(0.5 * FOVy);
803 l.x * cam_x_3d.
x + l.y * cam_up_3d.
x + l.z * pointing_dir.
x,
804 l.x * cam_x_3d.
y + l.y * cam_up_3d.
y + l.z * pointing_dir.
y,
805 l.x * cam_x_3d.
z + l.y * cam_up_3d.
z + l.z * pointing_dir.
z);
819 M(0, 0) = cam_x_3d.
x;
820 M(1, 0) = cam_x_3d.
y;
821 M(2, 0) = cam_x_3d.
z;
824 M(0, 1) = cam_up_3d.
x;
825 M(1, 1) = cam_up_3d.
y;
826 M(2, 1) = cam_up_3d.
z;
829 M(0, 2) = pointing_dir.
x;
830 M(1, 2) = pointing_dir.
y;
831 M(2, 2) = pointing_dir.
z;
897 std::numeric_limits<double>::max(), std::numeric_limits<double>::max(),
898 std::numeric_limits<double>::max());
900 -std::numeric_limits<double>::max(),
901 -std::numeric_limits<double>::max(),
902 -std::numeric_limits<double>::max());
907 std::numeric_limits<double>::max(),
908 std::numeric_limits<double>::max(),
909 std::numeric_limits<double>::max());
911 -std::numeric_limits<double>::max(),
912 -std::numeric_limits<double>::max(),
913 -std::numeric_limits<double>::max());
914 m_object->getBoundingBox(child_bbmin, child_bbmax);
float m_projectiveFOVdeg
Field-of-View in degs, only when projectiveModel=true (default=30 deg).
void serializeFrom(mrpt::serialization::CArchive &in, uint8_t serial_version) override
Pure virtual method for reading (deserializing) from an abstract archive.
static int startFromRatio(const double frac, const int dSize)
float m_clip_min
The min/max clip depth distances (default: 0.1 - 10000)
opengl::CListOpenGLObjects m_objects
The list of objects that comprise the 3D scene.
void serializeTo(mrpt::serialization::CArchive &out) const override
Pure virtual method for writing (serializing) to an abstract archive.
void keep_min(T &var, const K test_val)
If the second argument is below the first one, set the first argument to this lower value...
static Ptr Create(Args &&... args)
A compile-time fixed-size numeric matrix container.
CRenderizable::Ptr getByName(const std::string &str)
Returns the first object with a given name, or nullptr if not found.
void get3DRayForPixelCoord(const double x_coord, const double y_coord, mrpt::math::TLine3D &out_ray, mrpt::poses::CPose3D *out_cameraPose=nullptr) const
Compute the 3D ray corresponding to a given pixel; this can be used to allow the user to pick and sel...
mrpt::opengl::CText::Ptr gl_text
bool m_isTransparent
Whether to clear color buffer.
static constexpr shader_id_t TEXTURED_TRIANGLES
mrpt::opengl::CTexturedPlane::Ptr m_imageview_plane
The image to display, after calling setImageView()
A set of object, which are referenced to the coordinates framework established in this object...
#define THROW_EXCEPTION(msg)
uint32_t m_borderWidth
Default=0, the border around the viewport.
A safe way to call enter() and leave() of a mrpt::system::CTimeLogger upon construction and destructi...
void setCloneView(const std::string &clonedViewport)
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.
mrpt::opengl::CText::Ptr gl_text_shadow
void setViewportClipDistances(const float clip_min, const float clip_max)
Set the min/max clip depth distances of the rendering frustum (default: 0.1 - 10000) ...
#define IMPLEMENTS_SERIALIZABLE(class_name, base, NameSpace)
To be added to all CSerializable-classes implementation files.
std::deque< CRenderizable::Ptr > CListOpenGLObjects
A list of smart pointers to renderizable objects.
void set6DOFMode(bool v)
Set 6DOFMode, if enabled camera is set according to its pose (default=false).
void processRenderQueue(const RenderQueue &rq, std::map< shader_id_t, mrpt::opengl::Program::Ptr > &shaders, const mrpt::opengl::TLightParameters &lights)
After enqueForRendering(), actually executes the rendering tasks, grouped shader by shader...
void setImageView(const mrpt::img::CImage &img)
Set this viewport into "image view"-mode, where an image is efficiently drawn (fitting the viewport a...
bool m_custom_backgb_color
void renderImageMode() const
Render in image mode.
std::shared_ptr< CRenderizable > Ptr
static constexpr shader_id_t TEXT
TPoint3D pBase
Base point.
A viewport within a COpenGLScene, containing a set of OpenGL objects to render.
void getViewportClipDistances(float &clip_min, float &clip_max) const
Get the current min/max clip depth distances of the rendering frustum (default: 0.1 - 10000)
mrpt::safe_ptr< COpenGLScene > m_parent
The scene that contains this viewport.
TRenderMatrices m_state
Info updated with each "render()" and used in "get3DRayForPixelCoord".
mrpt::img::TColor m_borderColor
void loadDefaultShaders() const
Load all MPRT predefined shader programs into m_shaders.
void crossProduct3D(const T &v0, const U &v1, V &vOut)
Computes the cross product of two 3D vectors, returning a vector normal to both.
std::string vfont_name
Vectorized font name ("sans","mono","serif")
#define MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(__V)
For use in CSerializable implementations.
bool m_isClonedCamera
Set by setCloneCamera.
#define ASSERT_(f)
Defines an assertion mechanism.
void internal_enableImageView()
This base provides a set of functions for maths stuff.
bool m_isImageView
Set by setImageView.
std::map< size_t, DataPerText > messages
void getBoundingBox(mrpt::math::TPoint3D &bb_min, mrpt::math::TPoint3D &bb_max) const
Evaluates the bounding box of this object (including possible children) in the coordinate frame of th...
std::array< double, 3 > director
Director vector.
void enqueForRendering(const mrpt::opengl::CListOpenGLObjects &objs, const mrpt::opengl::TRenderMatrices &state, RenderQueue &rq)
Processes, recursively, all objects in the list, classifying them by shader programs into a list suit...
static int sizeFromRatio(const int startCoord, const double dSize, const int iLength)
constexpr double DEG2RAD(const double x)
Degrees to radians.
static constexpr shader_id_t WIREFRAME
void render(const int render_width, const int render_height, const int render_offset_x=0, const int render_offset_y=0) const
Render the objects in this viewport (called from COpenGLScene)
~COpenGLViewport() override
Destructor: clears all objects.
void unloadShaders()
Unload shader programs in m_shaders.
void removeObject(const CRenderizable::Ptr &obj)
Removes the given object from the scene (it also deletes the object to free its memory).
TPoint3D_< double > TPoint3D
Lightweight 3D point.
double x() const
Common members of all points & poses classes.
void setNormalMode()
Resets the viewport to a normal 3D viewport.
mrpt::math::CMatrixFloat44 mv_matrix
Model-view matrix.
bool m_OpenGL_enablePolygonNicest
Rendering state related to the projection and model-view matrices.
void getCurrentCameraPose(mrpt::poses::CPose3D &out_cameraPose) const
Compute the current 3D camera pose.
Classes for 2D/3D geometry representation, both of single values and probability density distribution...
double azimuth
Camera elev & azimuth, in radians.
TLightParameters m_lights
static constexpr shader_id_t TRIANGLES
void renderTextMessages() const
Renders all messages in the underlying class CTextMessageCapable.
void keep_max(T &var, const K test_val)
If the second argument is above the first one, set the first argument to this higher value...
TListTextMessages m_2D_texts
#define CLASS_ID_NAMESPACE(class_name, namespaceName)
std::map< shader_id_t, mrpt::opengl::Program::Ptr > m_shaders
Default shader program.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
bool m_projectiveModel
If set to true (default), camera model is projective, otherwise, it's orthogonal. ...
Virtual base class for "archives": classes abstracting I/O streams.
void clear()
Delete all internal obejcts.
size_t viewport_width
In pixels.
mrpt::math::TPoint3D eye
The camera is here.
An event sent by an mrpt::opengl::COpenGLViewport just after clearing the viewport and setting the GL...
A versatile "profiler" that logs the time spent within each pair of calls to enter(X)-leave(X), among other stats.
void regenerateGLobjects() const
(re)generate all CText objects in the gl_text fields
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
mrpt::vision::TStereoCalibResults out
uint8_t serializeGetVersion() const override
Must return the current versioning number of the object.
#define ASSERTDEB_(f)
Defines an assertion mechanism - only when compiled in debug.
void initializeTextures()
Initializes all textures in the scene (See opengl::CTexturedPlane::initializeTextures) ...
Program::Ptr LoadDefaultShader(const shader_id_t id)
Loads a set of OpenGL Vertex+Fragment shaders from the default library available in mrpt::opengl...
An event sent by an mrpt::opengl::COpenGLViewport after calling the scene OpenGL drawing primitives a...
#define ASSERT_ABOVE_(__A, __B)
void publishEvent(const mrptEvent &e) const
Called when you want this object to emit an event to all the observers currently subscribed to this o...
bool hasSubscribers() const
Can be called by a derived class before preparing an event for publishing with publishEvent to determ...
mrpt::opengl::CSetOfLines::Ptr m_borderLines
The namespace for 3D scene representation and rendering.
This class allows the user to create, load, save, and render 3D scenes using OpenGL primitives...
std::string m_clonedViewport
Only if m_isCloned=true.
CRenderizable & setPose(const mrpt::poses::CPose3D &o)
Set the 3D pose from a mrpt::poses::CPose3D object (return a ref to this)
mrpt::img::TColorf m_background_color
used only if m_custom_backgb_color
void renderNormalSceneMode() const
Render a normal scene with 3D objects.
double FOV
Vertical FOV in degrees.
mrpt::math::CMatrixFloat44 p_matrix
Projection matrix, computed by renderNormalScene() from all the parameters above. ...
void getRotationMatrix(mrpt::math::CMatrixDouble33 &ROT) const
Get the 3x3 rotation matrix.
A camera: if added to a scene, the viewpoint defined by this camera will be used instead of the camer...
void renderViewportBorder() const
Render the viewport border, if enabled.
#define THROW_EXCEPTION_FMT(_FORMAT_STRING,...)
void setViewportPosition(const double x, const double y, const double width, const double height)
Change the viewport position and dimension on the rendering window.
void dumpListOfObjects(std::vector< std::string > &lst)
Retrieves a list of all objects in text form.
mrpt::math::TPose3D getPose() const
Returns the 3D pose of the object as TPose3D.
void getViewportPosition(double &x, double &y, double &width, double &height)
Get the current viewport position and dimension on the rendering window.
void insert(const CRenderizable::Ptr &newObject)
Insert a new object into the list.
T::Ptr getByClass(size_t ith=0) const
Returns the i'th object of a given class (or of a descendant class), or nullptr (an empty smart point...
double m_view_x
The viewport position [0,1].
Lighting parameters, mostly for triangle shaders.
mrpt::img::TColorf shadow_color
static Ptr Create(Args &&... args)
void setCurrentCameraFromPose(mrpt::poses::CPose3D &p)
Changes the point of view of the camera, from a given pose.
static constexpr shader_id_t POINTS
opengl::CCamera m_camera
The camera associated to the viewport.
std::string m_name
The viewport's name.
A class for storing images as grayscale or RGB bitmaps.
float vfont_scale
Size of characters [pixels].
bool is_projective
true: projective, false: ortho
std::map< shader_id_t, std::multimap< float, RenderQueueElement > > RenderQueue
A queue for rendering, sorted by shader program to minimize changes of OpenGL shader programs while r...
bool m_isCloned
Set by setCloneView.
3D line, represented by a base point and a director vector.