| 1 |
/* +------------------------------------------------------------------------+ |
| 2 |
| Mobile Robot Programming Toolkit (MRPT) | |
| 3 |
| https://www.mrpt.org/ | |
| 4 |
| | |
| 5 |
| Copyright (c) 2005-2026, Individual contributors, see AUTHORS file | |
| 6 |
| See: https://www.mrpt.org/Authors - All rights reserved. | |
| 7 |
| Released under BSD License. See: https://www.mrpt.org/License | |
| 8 |
+------------------------------------------------------------------------+ */ |
| 9 |
|
| 10 |
#include "opengl-precomp.h" // Precompiled header |
| 11 |
// |
| 12 |
#include <Eigen/Dense> // First! to avoid conflicts with X.h |
| 13 |
// |
| 14 |
#include <mrpt/core/get_env.h> |
| 15 |
#include <mrpt/math/TLine3D.h> |
| 16 |
#include <mrpt/math/geometry.h> // crossProduct3D() |
| 17 |
#include <mrpt/opengl/CSetOfObjects.h> |
| 18 |
#include <mrpt/opengl/CTexturedPlane.h> |
| 19 |
#include <mrpt/opengl/DefaultShaders.h> |
| 20 |
#include <mrpt/opengl/Scene.h> |
| 21 |
#include <mrpt/opengl/Viewport.h> |
| 22 |
#include <mrpt/opengl/opengl_api.h> |
| 23 |
#include <mrpt/serialization/CArchive.h> |
| 24 |
#include <mrpt/serialization/metaprogramming_serialization.h> |
| 25 |
#include <mrpt/serialization/stl_serialization.h> |
| 26 |
#include <mrpt/system/CTimeLogger.h> |
| 27 |
|
| 28 |
using namespace mrpt; |
| 29 |
using namespace mrpt::poses; |
| 30 |
using namespace mrpt::opengl; |
| 31 |
using namespace mrpt::math; |
| 32 |
using namespace mrpt::serialization::metaprogramming; |
| 33 |
using namespace std; |
| 34 |
|
| 35 |
IMPLEMENTS_SERIALIZABLE(Viewport, CSerializable, mrpt::opengl) |
| 36 |
|
| 37 |
const bool MRPT_OPENGL_DEBUG_SHOW_SHADOW_MAP = |
| 38 |
mrpt::get_env<bool>("MRPT_OPENGL_DEBUG_SHOW_SHADOW_MAP", false); |
| 39 |
|
| 40 |
// #define OPENGLVIEWPORT_ENABLE_TIMEPROFILING |
| 41 |
|
| 42 |
#if defined(OPENGLVIEWPORT_ENABLE_TIMEPROFILING) |
| 43 |
mrpt::system::CTimeLogger glv_timlog; |
| 44 |
#endif |
| 45 |
|
| 46 |
/*-------------------------------------------------------------- |
| 47 |
|
| 48 |
IMPLEMENTATION OF Viewport |
| 49 |
|
| 50 |
---------------------------------------------------------------*/ |
| 51 |
|
| 52 |
/*-------------------------------------------------------------- |
| 53 |
Constructor |
| 54 |
---------------------------------------------------------------*/ |
| 55 |
Viewport::Viewport(Scene* parent, const string& name) : m_parent(parent), m_name(name) {} |
| 56 |
|
| 57 |
Viewport::~Viewport() { clear(); } |
| 58 |
|
| 59 |
void Viewport::setCloneView(const string& clonedViewport) |
| 60 |
{ |
| 61 |
clear(); |
| 62 |
m_isCloned = true; |
| 63 |
m_clonedViewport = clonedViewport; |
| 64 |
} |
| 65 |
|
| 66 |
void Viewport::setViewportPosition( |
| 67 |
const double x, const double y, const double width, const double height) |
| 68 |
{ |
| 69 |
MRPT_START |
| 70 |
|
| 71 |
m_view_x = x; |
| 72 |
m_view_y = y; |
| 73 |
m_view_width = width; |
| 74 |
m_view_height = height; |
| 75 |
|
| 76 |
MRPT_END |
| 77 |
} |
| 78 |
|
| 79 |
/*-------------------------------------------------------------- |
| 80 |
getViewportPosition |
| 81 |
---------------------------------------------------------------*/ |
| 82 |
void Viewport::getViewportPosition(double& x, double& y, double& width, double& height) |
| 83 |
{ |
| 84 |
x = m_view_x; |
| 85 |
y = m_view_y; |
| 86 |
width = m_view_width; |
| 87 |
height = m_view_height; |
| 88 |
} |
| 89 |
|
| 90 |
/*-------------------------------------------------------------- |
| 91 |
clear |
| 92 |
---------------------------------------------------------------*/ |
| 93 |
void Viewport::clear() { m_objects.clear(); } |
| 94 |
/*-------------------------------------------------------------- |
| 95 |
insert |
| 96 |
---------------------------------------------------------------*/ |
| 97 |
void Viewport::insert(const CRenderizable::Ptr& newObject) { m_objects.push_back(newObject); } |
| 98 |
|
| 99 |
// Maps [0,1] to [0,Len], wrap negative numbers, etc. |
| 100 |
namespace |
| 101 |
{ |
| 102 |
int sizeFromRatio(const int startCoord, const double dSize, const int iLength) |
| 103 |
{ |
| 104 |
if (dSize > 1) // >1 -> absolute pixels: |
| 105 |
return static_cast<int>(dSize); |
| 106 |
else if (dSize < 0) |
| 107 |
{ // Negative numbers: Specify the right side coordinates |
| 108 |
// instead of |
| 109 |
// the width: |
| 110 |
if (dSize >= -1) |
| 111 |
return static_cast<int>(-iLength * dSize - startCoord + 1); |
| 112 |
else |
| 113 |
return static_cast<int>(iLength + dSize - startCoord + 1); |
| 114 |
} |
| 115 |
// Otherwise: a fraction |
| 116 |
return static_cast<int>(iLength * dSize); |
| 117 |
} |
| 118 |
int startFromRatio(const double frac, const int dSize) |
| 119 |
{ |
| 120 |
const bool doWrap = (frac < 0); |
| 121 |
const auto fracAbs = std::abs(frac); |
| 122 |
|
| 123 |
const int L = fracAbs > 1 ? static_cast<int>(fracAbs) : static_cast<int>(dSize * fracAbs); |
| 124 |
|
| 125 |
int ret = doWrap ? dSize - L : L; |
| 126 |
|
| 127 |
return ret; |
| 128 |
} |
| 129 |
} // namespace |
| 130 |
|
| 131 |
// "Image mode" rendering: |
| 132 |
void Viewport::renderImageMode() const |
| 133 |
{ |
| 134 |
#if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL |
| 135 |
#if defined(OPENGLVIEWPORT_ENABLE_TIMEPROFILING) |
| 136 |
mrpt::system::CTimeLoggerEntry tle(glv_timlog, "Viewport::render imageview"); |
| 137 |
#endif |
| 138 |
|
| 139 |
// Do we have an actual image to render? |
| 140 |
if (!m_imageViewPlane || m_imageViewPlane->getTextureImage().isEmpty()) return; |
| 141 |
|
| 142 |
auto _ = m_threadedData.get().state; // make a copy |
| 143 |
|
| 144 |
glDisable(GL_DEPTH_TEST); |
| 145 |
glEnable(GL_BLEND); |
| 146 |
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); |
| 147 |
|
| 148 |
// Adjust the aspect ratio: |
| 149 |
const auto img_w = m_imageViewPlane->getTextureImage().getWidth(); |
| 150 |
const auto img_h = m_imageViewPlane->getTextureImage().getHeight(); |
| 151 |
const double img_ratio = double(img_w) / img_h; |
| 152 |
const double vw_ratio = double(_.viewport_width) / _.viewport_height; |
| 153 |
const double ratio = vw_ratio / img_ratio; |
| 154 |
|
| 155 |
_.matricesSetIdentity(); |
| 156 |
|
| 157 |
if (ratio > 1) |
| 158 |
_.p_matrix(1, 1) *= ratio; |
| 159 |
else if (ratio > 0) |
| 160 |
_.p_matrix(0, 0) /= ratio; |
| 161 |
|
| 162 |
auto &p00 = _.p_matrix(0, 0), &p11 = _.p_matrix(1, 1); |
| 163 |
if (p00 > 0 && p11 > 0) |
| 164 |
{ |
| 165 |
const double s = (p00 > p11) ? p00 : p11; |
| 166 |
p00 /= s; |
| 167 |
p11 /= s; |
| 168 |
} |
| 169 |
|
| 170 |
_.pmv_matrix.asEigen() = _.p_matrix.asEigen() * _.v_matrix.asEigen() * _.m_matrix.asEigen(); |
| 171 |
|
| 172 |
// Pass 1: Process all objects (recursively for sets of objects): |
| 173 |
CListOpenGLObjects lst; |
| 174 |
lst.push_back(m_imageViewPlane); |
| 175 |
mrpt::opengl::RenderQueue rq; |
| 176 |
mrpt::opengl::enqueueForRendering(lst, _, rq, true /*skip cull*/, false /* isShadowMap*/); |
| 177 |
|
| 178 |
// pass 2: render, sorted by shader program: |
| 179 |
mrpt::opengl::processRenderQueue(rq, m_threadedData.get().shaders, m_light); |
| 180 |
|
| 181 |
#endif |
| 182 |
} |
| 183 |
|
| 184 |
void Viewport::unloadShaders() { m_threadedData.get().shaders.clear(); } |
| 185 |
|
| 186 |
void Viewport::loadDefaultShaders() const |
| 187 |
{ |
| 188 |
#if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL |
| 189 |
MRPT_START |
| 190 |
|
| 191 |
using ID = DefaultShaderID; // save space below |
| 192 |
|
| 193 |
std::vector<shader_id_t> lstShaderIDs = { |
| 194 |
ID::POINTS, |
| 195 |
ID::WIREFRAME, |
| 196 |
ID::TRIANGLES_NO_LIGHT, |
| 197 |
ID::TRIANGLES_LIGHT, |
| 198 |
ID::TEXTURED_TRIANGLES_NO_LIGHT, |
| 199 |
ID::TEXTURED_TRIANGLES_LIGHT, |
| 200 |
ID::TEXT, |
| 201 |
ID::TRIANGLES_SHADOW_1ST, |
| 202 |
ID::TRIANGLES_SHADOW_2ND, |
| 203 |
ID::TEXTURED_TRIANGLES_SHADOW_1ST, |
| 204 |
ID::TEXTURED_TRIANGLES_SHADOW_2ND, |
| 205 |
ID::SKYBOX, |
| 206 |
ID::DEBUG_TEXTURE_TO_SCREEN}; |
| 207 |
|
| 208 |
// ----------------------------------------------------------- |
| 209 |
// Load general list of shaders |
| 210 |
// (and use them for the "no shadows" case): |
| 211 |
// ----------------------------------------------------------- |
| 212 |
auto& shaders = m_threadedData.get().shaders; |
| 213 |
for (const auto& id : lstShaderIDs) |
| 214 |
{ |
| 215 |
shaders[id] = mrpt::opengl::LoadDefaultShader(id); |
| 216 |
|
| 217 |
ASSERT_(shaders[id]); |
| 218 |
ASSERT_(!shaders[id]->empty()); |
| 219 |
} |
| 220 |
|
| 221 |
// ----------------------------------------------------------- |
| 222 |
// Shaders for rendering with shadows: 1st and 2nd passes use |
| 223 |
// different shader programs. Apply a replacement table. |
| 224 |
// ----------------------------------------------------------- |
| 225 |
// clang-format off |
| 226 |
const std::map<shader_id_t, std::pair<shader_id_t, shader_id_t>> |
| 227 |
replacements = { |
| 228 |
{ID::TRIANGLES_LIGHT, {ID::TRIANGLES_SHADOW_1ST, ID::TRIANGLES_SHADOW_2ND}}, |
| 229 |
{ID::TEXTURED_TRIANGLES_LIGHT, {ID::TEXTURED_TRIANGLES_SHADOW_1ST, ID::TEXTURED_TRIANGLES_SHADOW_2ND}}, |
| 230 |
{ID::POINTS, {ID::NONE, ID::POINTS}}, |
| 231 |
{ID::WIREFRAME, {ID::NONE, ID::WIREFRAME}}, |
| 232 |
{ID::TEXT, {ID::NONE, ID::TEXT}}, |
| 233 |
{ID::TRIANGLES_NO_LIGHT, {ID::TRIANGLES_SHADOW_1ST, ID::TRIANGLES_NO_LIGHT}}, |
| 234 |
{ID::TEXTURED_TRIANGLES_NO_LIGHT, {ID::TRIANGLES_SHADOW_1ST, ID::TEXTURED_TRIANGLES_NO_LIGHT}}, |
| 235 |
{ID::SKYBOX, {ID::NONE, ID::SKYBOX}} |
| 236 |
}; |
| 237 |
//clang-format on |
| 238 |
|
| 239 |
// 1st pass. Replace shaders: we only need depth in the 1st stage. |
| 240 |
// 2nd pass. Replace shaders: we need to account for the shadow map. |
| 241 |
auto& shadowShaders1st = m_threadedData.get().shadersShadow1st; |
| 242 |
shadowShaders1st = shaders; |
| 243 |
auto& shadowShaders2nd = m_threadedData.get().shadersShadow2nd; |
| 244 |
shadowShaders2nd = shaders; |
| 245 |
|
| 246 |
for (const auto& kv : replacements) |
| 247 |
{ |
| 248 |
if (kv.second.first!=ID::NONE) |
| 249 |
shadowShaders1st[kv.first] = shaders.at(kv.second.first); |
| 250 |
|
| 251 |
if (kv.second.second!=ID::NONE) |
| 252 |
shadowShaders2nd[kv.first] = shaders.at(kv.second.second); |
| 253 |
} |
| 254 |
|
| 255 |
MRPT_END |
| 256 |
#endif |
| 257 |
} |
| 258 |
|
| 259 |
// for debugging only if MRPT_OPENGL_DEBUG_SHOW_SHADOW_MAP |
| 260 |
#if (MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL) |
| 261 |
// From: https://learnopengl.com/Advanced-Lighting/Shadows/Shadow-Mapping |
| 262 |
|
| 263 |
// debugRenderQuad() renders a 1x1 XY quad in NDC |
| 264 |
// ----------------------------------------- |
| 265 |
static unsigned int quadVAO = 0; |
| 266 |
static unsigned int quadVBO; |
| 267 |
namespace |
| 268 |
{ |
| 269 |
void debugRenderQuad() |
| 270 |
{ |
| 271 |
if (quadVAO == 0) |
| 272 |
{ |
| 273 |
// clang-format off |
| 274 |
float quadVertices[] = { |
| 275 |
// positions // texture Coords |
| 276 |
-1.0f, -0.5f, 0.0f, 0.0f, 1.0f, |
| 277 |
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f, |
| 278 |
-0.5f, -0.5f, 0.0f, 1.0f, 1.0f, |
| 279 |
-0.5f, -1.0f, 0.0f, 1.0f, 0.0f, |
| 280 |
}; |
| 281 |
// clang-format on |
| 282 |
|
| 283 |
// setup plane VAO |
| 284 |
glGenVertexArrays(1, &quadVAO); |
| 285 |
glGenBuffers(1, &quadVBO); |
| 286 |
glBindVertexArray(quadVAO); |
| 287 |
glBindBuffer(GL_ARRAY_BUFFER, quadVBO); |
| 288 |
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); |
| 289 |
glEnableVertexAttribArray(0); |
| 290 |
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); |
| 291 |
glEnableVertexAttribArray(1); |
| 292 |
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); |
| 293 |
} |
| 294 |
glBindVertexArray(quadVAO); |
| 295 |
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); |
| 296 |
glBindVertexArray(0); |
| 297 |
} |
| 298 |
} // namespace |
| 299 |
#endif |
| 300 |
|
| 301 |
/** Render a normal scene with 3D objects */ |
| 302 |
void Viewport::renderNormalSceneMode(const CCamera& useThisCamera, bool is1stShadowMapPass) const |
| 303 |
{ |
| 304 |
#if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL |
| 305 |
MRPT_START |
| 306 |
|
| 307 |
#ifdef MRPT_OPENGL_PROFILER |
| 308 |
mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "Viewport.renderNormalSceneMode"); |
| 309 |
#endif |
| 310 |
|
| 311 |
// Prepare camera (projection matrix): |
| 312 |
// Needed for both, regular, and 1st/2nd shadow passes: |
| 313 |
// Note: if we were in the 1st stage of shadow rendering, |
| 314 |
// the projection matrix is actually the light projection matrix, |
| 315 |
// but that's handled by the shaders themselves, not here. |
| 316 |
updateMatricesFromCamera(useThisCamera); |
| 317 |
|
| 318 |
const auto& _ = m_threadedData.get().state; |
| 319 |
|
| 320 |
// Get objects to render: |
| 321 |
const CListOpenGLObjects* objectsToRender = nullptr; |
| 322 |
|
| 323 |
if (m_isCloned) |
| 324 |
{ // Clone: render someone's else objects. |
| 325 |
ASSERT_(m_parent.get() != nullptr); |
| 326 |
|
| 327 |
const auto view = m_parent->getViewport(m_clonedViewport); |
| 328 |
if (!view) |
| 329 |
THROW_EXCEPTION_FMT( |
| 330 |
"Cloned viewport '%s' not found in parent Scene", m_clonedViewport.c_str()); |
| 331 |
|
| 332 |
objectsToRender = &view->m_objects; |
| 333 |
} |
| 334 |
else |
| 335 |
{ // Normal case: render our own objects: |
| 336 |
objectsToRender = &m_objects; |
| 337 |
} |
| 338 |
|
| 339 |
// Optional pre-Render user code: |
| 340 |
if (hasSubscribers()) |
| 341 |
{ |
| 342 |
mrptEventGLPreRender ev(this); |
| 343 |
this->publishEvent(ev); |
| 344 |
} |
| 345 |
|
| 346 |
// Global OpenGL settings: |
| 347 |
// --------------------------------- |
| 348 |
#if !defined(__EMSCRIPTEN__) |
| 349 |
glHint(GL_POLYGON_SMOOTH_HINT, m_OpenGL_enablePolygonNicest ? GL_NICEST : GL_FASTEST); |
| 350 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 351 |
|
| 352 |
glEnable(GL_LINE_SMOOTH); |
| 353 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 354 |
#endif |
| 355 |
|
| 356 |
// Regular depth model: |
| 357 |
// 0: far, 1: near |
| 358 |
// ------------------------------- |
| 359 |
glEnable(GL_DEPTH_TEST); |
| 360 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 361 |
|
| 362 |
glDepthFunc(GL_LESS); |
| 363 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 364 |
|
| 365 |
glEnable(GL_BLEND); |
| 366 |
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); |
| 367 |
|
| 368 |
// Enable point sizes>1 |
| 369 |
#if !defined(__EMSCRIPTEN__) && defined(GL_PROGRAM_POINT_SIZE) // OSX undef? |
| 370 |
glEnable(GL_PROGRAM_POINT_SIZE); |
| 371 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 372 |
#endif |
| 373 |
|
| 374 |
// Enables Multisampling |
| 375 |
glEnable(GL_MULTISAMPLE); |
| 376 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 377 |
|
| 378 |
// Pass 1: Process all objects (recursively for sets of objects): |
| 379 |
mrpt::opengl::RenderQueue rq; |
| 380 |
mrpt::opengl::RenderQueueStats rqStats; |
| 381 |
mrpt::opengl::enqueueForRendering( |
| 382 |
*objectsToRender, _, rq, false /*skip cull checks*/, |
| 383 |
is1stShadowMapPass /* is shadow map pass */, &rqStats); |
| 384 |
|
| 385 |
// pass 2: render, sorted by shader program: |
| 386 |
auto& shaders = m_shadowsEnabled ? (is1stShadowMapPass ? m_threadedData.get().shadersShadow1st |
| 387 |
: m_threadedData.get().shadersShadow2nd) |
| 388 |
: m_threadedData.get().shaders; |
| 389 |
|
| 390 |
// shadow map, if enabled: |
| 391 |
std::optional<unsigned int> depthMapTextureId; |
| 392 |
if (m_shadowsEnabled && m_ShadowMapFBO.initialized()) |
| 393 |
depthMapTextureId = m_ShadowMapFBO.depthMapTextureId(); |
| 394 |
|
| 395 |
// go render: |
| 396 |
mrpt::opengl::processRenderQueue(rq, shaders, m_light, depthMapTextureId); |
| 397 |
|
| 398 |
#ifdef MRPT_OPENGL_PROFILER |
| 399 |
opengl_profiler().registerUserMeasure("render.totalObjects", rqStats.numObjTotal); |
| 400 |
opengl_profiler().registerUserMeasure("render.numObjRendered", rqStats.numObjRendered); |
| 401 |
opengl_profiler().registerUserMeasure( |
| 402 |
"render.ObjRenderedPercent", |
| 403 |
rqStats.numObjTotal != 0 ? 100.0 * rqStats.numObjRendered / rqStats.numObjTotal : 0); |
| 404 |
#endif |
| 405 |
|
| 406 |
MRPT_END |
| 407 |
|
| 408 |
#endif |
| 409 |
} |
| 410 |
|
| 411 |
void Viewport::renderViewportBorder() const |
| 412 |
{ |
| 413 |
#if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL |
| 414 |
MRPT_START |
| 415 |
if (m_borderWidth < 1) return; |
| 416 |
|
| 417 |
auto _ = m_threadedData.get().state; |
| 418 |
|
| 419 |
_.matricesSetIdentity(); |
| 420 |
|
| 421 |
glDisable(GL_DEPTH_TEST); |
| 422 |
glEnable(GL_BLEND); |
| 423 |
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); |
| 424 |
|
| 425 |
// |
| 426 |
if (!m_borderLines) |
| 427 |
{ |
| 428 |
m_borderLines = mrpt::opengl::CSetOfLines::Create(); |
| 429 |
m_borderLines->appendLine(-1, -1, 0, -1, 1, 0); |
| 430 |
m_borderLines->appendLine(-1, 1, 0, 1, 1, 0); |
| 431 |
m_borderLines->appendLine(1, 1, 0, 1, -1, 0); |
| 432 |
m_borderLines->appendLine(1, -1, 0, -1, -1, 0); |
| 433 |
} |
| 434 |
m_borderLines->setLineWidth(m_borderWidth); |
| 435 |
m_borderLines->setColor_u8(m_borderColor); |
| 436 |
|
| 437 |
CListOpenGLObjects lst; |
| 438 |
lst.push_back(m_borderLines); |
| 439 |
|
| 440 |
// Pass 1: Process all objects (recursively for sets of objects): |
| 441 |
mrpt::opengl::RenderQueue rq; |
| 442 |
mrpt::opengl::enqueueForRendering(lst, _, rq, true /*skip cull*/, false /* isShadowMap*/); |
| 443 |
|
| 444 |
// pass 2: render, sorted by shader program: |
| 445 |
mrpt::opengl::processRenderQueue(rq, m_threadedData.get().shaders, m_light); |
| 446 |
MRPT_END |
| 447 |
#endif |
| 448 |
} |
| 449 |
|
| 450 |
void Viewport::renderTextMessages() const |
| 451 |
{ |
| 452 |
#if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL |
| 453 |
MRPT_START |
| 454 |
|
| 455 |
// Ensure GL objects are up-to-date: |
| 456 |
m_2D_texts.regenerateGLobjects(); |
| 457 |
|
| 458 |
// Prepare shaders upon first invocation: |
| 459 |
if (m_threadedData.get().shaders.empty()) loadDefaultShaders(); |
| 460 |
|
| 461 |
// Prepare camera (projection matrix): |
| 462 |
TRenderMatrices _ = m_threadedData.get().state; // make a copy |
| 463 |
|
| 464 |
// Compute the projection matrix (p_matrix): |
| 465 |
// was: glLoadIdentity(); glOrtho(0, w, 0, h, -1, 1); |
| 466 |
const auto w = _.viewport_width, h = _.viewport_height; |
| 467 |
_.is_projective = false; |
| 468 |
|
| 469 |
// Reset model-view 4x4 matrix to the identity transformation: |
| 470 |
_.matricesSetIdentity(); |
| 471 |
//_.computeOrthoProjectionMatrix(0, w, 0, h, m_clip_min, m_clip_max); |
| 472 |
|
| 473 |
glEnable(GL_BLEND); |
| 474 |
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); |
| 475 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 476 |
|
| 477 |
// Text messages should always be visible on top the rest: |
| 478 |
glDisable(GL_DEPTH_TEST); |
| 479 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 480 |
|
| 481 |
// Collect all 2D text objects, and update their properties: |
| 482 |
CListOpenGLObjects objs; |
| 483 |
|
| 484 |
std::shared_lock<std::shared_mutex> lckRead2DTexts(m_2D_texts.mtx.data); |
| 485 |
for (auto& kv : m_2D_texts.messages) |
| 486 |
{ |
| 487 |
const DataPerText& label = kv.second; |
| 488 |
|
| 489 |
// If (x,y) \in [0,1[, it's interpreted as a ratio, otherwise, as an |
| 490 |
// actual coordinate in pixels |
| 491 |
float x = label.x >= 1 ? label.x : (label.x < 0 ? w + label.x : label.x * w); |
| 492 |
float y = label.y >= 1 ? label.y : (label.y < 0 ? h + label.y : label.y * h); |
| 493 |
|
| 494 |
if (CText::Ptr& o = label.gl_text_shadow; o) |
| 495 |
{ |
| 496 |
o->setFont(label.vfont_name, label.vfont_scale * 2); |
| 497 |
o->setString(label.text); |
| 498 |
o->setColor(label.shadow_color); |
| 499 |
// Change coordinates: mrpt text (0,0)-(1,1) to OpenGL |
| 500 |
// (-1,-1)-(+1,+1): |
| 501 |
o->setLocation(-1.0f + 2 * (x + 1) / w, -1.0f + 2 * (y - 1) / h, 0.1); |
| 502 |
objs.push_back(o); |
| 503 |
} |
| 504 |
if (CText::Ptr& o = label.gl_text; o) |
| 505 |
{ |
| 506 |
o->setFont(label.vfont_name, label.vfont_scale * 2); |
| 507 |
o->setString(label.text); |
| 508 |
o->setColor(label.color); |
| 509 |
// Change coordinates: mrpt text (0,0)-(1,1) to OpenGL |
| 510 |
// (-1,-1)-(+1,+1): |
| 511 |
o->setLocation(-1.0f + 2 * x / w, -1.0f + 2 * y / h, 0); |
| 512 |
objs.push_back(o); |
| 513 |
} |
| 514 |
} |
| 515 |
lckRead2DTexts.unlock(); |
| 516 |
|
| 517 |
// Pass 1: Process all objects (recursively for sets of objects): |
| 518 |
mrpt::opengl::RenderQueue rq; |
| 519 |
mrpt::opengl::enqueueForRendering(objs, _, rq, true /*skip cull*/, false /* isShadowMap*/); |
| 520 |
|
| 521 |
// pass 2: render, sorted by shader program: |
| 522 |
mrpt::opengl::processRenderQueue(rq, m_threadedData.get().shaders, m_light); |
| 523 |
MRPT_END |
| 524 |
#endif |
| 525 |
} |
| 526 |
|
| 527 |
void Viewport::render( |
| 528 |
[[maybe_unused]] const int render_width, |
| 529 |
[[maybe_unused]] const int render_height, |
| 530 |
[[maybe_unused]] const int render_offset_x, |
| 531 |
[[maybe_unused]] const int render_offset_y, |
| 532 |
[[maybe_unused]] const CCamera* forceThisCamera) const |
| 533 |
{ |
| 534 |
#if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL |
| 535 |
MRPT_START |
| 536 |
|
| 537 |
#ifdef MRPT_OPENGL_PROFILER |
| 538 |
mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "Viewport.render"); |
| 539 |
#endif |
| 540 |
|
| 541 |
if (!m_isViewportVisible) return; |
| 542 |
|
| 543 |
// Prepare shaders upon first invocation: |
| 544 |
if (m_threadedData.get().shaders.empty()) loadDefaultShaders(); |
| 545 |
|
| 546 |
auto& _ = m_threadedData.get().state; |
| 547 |
|
| 548 |
auto* activeCameraPtr = internalResolveActiveCamera(forceThisCamera); |
| 549 |
|
| 550 |
// make a copy so the camera remains const over the rendering: |
| 551 |
const CCamera activeCamera = *activeCameraPtr; |
| 552 |
|
| 553 |
// Get former viewport |
| 554 |
GLint oldViewport[4]; |
| 555 |
glGetIntegerv(GL_VIEWPORT, oldViewport); |
| 556 |
|
| 557 |
const GLint vx = render_offset_x + startFromRatio(m_view_x, render_width); |
| 558 |
const GLint vy = render_offset_y + startFromRatio(m_view_y, render_height); |
| 559 |
const GLint vw = sizeFromRatio(vx, m_view_width, render_width); |
| 560 |
const GLint vh = sizeFromRatio(vy, m_view_height, render_height); |
| 561 |
|
| 562 |
// Let the matrix generation stuff what's the viewport size (for real |
| 563 |
// rendering, not shadow 1st pass shadow map) |
| 564 |
_.viewport_width = vw; |
| 565 |
_.viewport_height = vh; |
| 566 |
|
| 567 |
// If we are rendering with shadows, run a camera-view depth map first |
| 568 |
// (Shadows 1st pass) |
| 569 |
// ---------------------------------------------------------------------- |
| 570 |
if (m_shadowsEnabled && !isImageViewMode()) |
| 571 |
{ |
| 572 |
if (!m_ShadowMapFBO.initialized()) |
| 573 |
{ |
| 574 |
m_ShadowMapFBO.createDepthMap(m_ShadowMapSizeX, m_ShadowMapSizeY); |
| 575 |
} |
| 576 |
|
| 577 |
glEnable(GL_DEPTH_TEST); |
| 578 |
|
| 579 |
// Render scene to depth map, as seen from the light point of view: |
| 580 |
glViewport(0, 0, m_ShadowMapSizeX, m_ShadowMapSizeY); |
| 581 |
|
| 582 |
const auto oldFBs = m_ShadowMapFBO.bind(); |
| 583 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 584 |
|
| 585 |
glClear(GL_DEPTH_BUFFER_BIT); |
| 586 |
|
| 587 |
renderNormalSceneMode(activeCamera, true /* is1stShadowMapPass */); |
| 588 |
|
| 589 |
m_ShadowMapFBO.Bind(oldFBs); |
| 590 |
|
| 591 |
// The 2nd pass is done inside renderNormalSceneMode() |
| 592 |
|
| 593 |
// TODO: Any way to refactor the whole pipeline to avoid recursive |
| 594 |
// rendering twice? |
| 595 |
} |
| 596 |
|
| 597 |
// Change viewport: |
| 598 |
// ------------------------------------------- |
| 599 |
glViewport(vx, vy, vw, vh); |
| 600 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 601 |
|
| 602 |
// Clear depth&/color buffers: |
| 603 |
// ------------------------------------------- |
| 604 |
|
| 605 |
glScissor(vx, vy, vw, vh); |
| 606 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 607 |
|
| 608 |
glEnable(GL_SCISSOR_TEST); |
| 609 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 610 |
|
| 611 |
if (!m_isTransparent) |
| 612 |
{ // Clear color & depth buffers: |
| 613 |
// Save: |
| 614 |
GLfloat prevBkCol[4]; |
| 615 |
glGetFloatv(GL_COLOR_CLEAR_VALUE, prevBkCol); |
| 616 |
|
| 617 |
glClearColor( |
| 618 |
m_background_color.R, m_background_color.G, m_background_color.B, m_background_color.A); |
| 619 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 620 |
|
| 621 |
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); |
| 622 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 623 |
|
| 624 |
glClearColor(prevBkCol[0], prevBkCol[1], prevBkCol[2], prevBkCol[3]); |
| 625 |
} |
| 626 |
else |
| 627 |
{ // Clear depth buffer only: |
| 628 |
glClear(GL_DEPTH_BUFFER_BIT); |
| 629 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 630 |
} |
| 631 |
glDisable(GL_SCISSOR_TEST); |
| 632 |
CHECK_OPENGL_ERROR_IN_DEBUG(); |
| 633 |
|
| 634 |
// If we are in "image mode", rendering is much simpler: just set |
| 635 |
// ortho projection and render the image quad: |
| 636 |
if (isImageViewMode()) |
| 637 |
renderImageMode(); |
| 638 |
else |
| 639 |
renderNormalSceneMode(activeCamera); |
| 640 |
|
| 641 |
// Draw text messages, if any: |
| 642 |
renderTextMessages(); |
| 643 |
|
| 644 |
// Finally, draw the border: |
| 645 |
renderViewportBorder(); |
| 646 |
|
| 647 |
// Optional post-Render user code: |
| 648 |
if (hasSubscribers()) |
| 649 |
{ |
| 650 |
mrptEventGLPostRender ev(this); |
| 651 |
this->publishEvent(ev); |
| 652 |
} |
| 653 |
|
| 654 |
// Debug: |
| 655 |
if (MRPT_OPENGL_DEBUG_SHOW_SHADOW_MAP && m_shadowsEnabled) |
| 656 |
{ |
| 657 |
// render Depth map to quad for visual debugging |
| 658 |
auto& sh = shaders().at(DefaultShaderID::DEBUG_TEXTURE_TO_SCREEN); |
| 659 |
sh->use(); |
| 660 |
sh->setInt("textureId", 0 /* Use GL_TEXTURE0 */); |
| 661 |
glActiveTexture(GL_TEXTURE0); |
| 662 |
glBindTexture(GL_TEXTURE_2D, m_ShadowMapFBO.depthMapTextureId()); |
| 663 |
debugRenderQuad(); |
| 664 |
} |
| 665 |
|
| 666 |
// Restore viewport: |
| 667 |
glViewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]); |
| 668 |
|
| 669 |
MRPT_END |
| 670 |
#else |
| 671 |
THROW_EXCEPTION( |
| 672 |
"MRPT has been compiled with MRPT_HAS_OPENGL_GLUT=0! OpenGL " |
| 673 |
"functions are not implemented"); |
| 674 |
#endif |
| 675 |
} |
| 676 |
|
| 677 |
uint8_t Viewport::serializeGetVersion() const { return 10; } |
| 678 |
void Viewport::serializeTo(mrpt::serialization::CArchive& out) const |
| 679 |
{ |
| 680 |
// Save data: |
| 681 |
out << m_camera << m_isCloned << m_isClonedCamera << m_clonedViewport << m_name << m_isTransparent |
| 682 |
<< m_borderWidth << m_view_x << m_view_y << m_view_width << m_view_height; |
| 683 |
|
| 684 |
// Added in v1: |
| 685 |
out << m_background_color.R << m_background_color.G << m_background_color.B |
| 686 |
<< m_background_color.A; |
| 687 |
|
| 688 |
// Save objects: |
| 689 |
uint32_t n; |
| 690 |
n = (uint32_t)m_objects.size(); |
| 691 |
out << n; |
| 692 |
for (const auto& m_object : m_objects) out << *m_object; |
| 693 |
|
| 694 |
// Added in v2: Global OpenGL settings: |
| 695 |
out << m_OpenGL_enablePolygonNicest; |
| 696 |
|
| 697 |
// Added in v3: Lights |
| 698 |
out << m_light; |
| 699 |
|
| 700 |
// Added in v4: text messages: |
| 701 |
std::shared_lock<std::shared_mutex> lckRead2DTexts(m_2D_texts.mtx.data); |
| 702 |
|
| 703 |
out.WriteAs<uint32_t>(m_2D_texts.messages.size()); |
| 704 |
for (auto& kv : m_2D_texts.messages) |
| 705 |
{ |
| 706 |
out << kv.first; // id |
| 707 |
out << kv.second.x << kv.second.y << kv.second.text; |
| 708 |
|
| 709 |
const auto& fp = kv.second; |
| 710 |
|
| 711 |
out << fp.vfont_name << fp.vfont_scale << fp.color << fp.draw_shadow << fp.shadow_color |
| 712 |
<< fp.vfont_spacing << fp.vfont_kerning; |
| 713 |
out.WriteAs<uint8_t>(static_cast<uint8_t>(fp.vfont_style)); |
| 714 |
} |
| 715 |
lckRead2DTexts.unlock(); |
| 716 |
|
| 717 |
// Added in v5: image mode |
| 718 |
out.WriteAs<bool>(m_imageViewPlane); |
| 719 |
if (m_imageViewPlane) out << *m_imageViewPlane; |
| 720 |
|
| 721 |
// Added in v6: |
| 722 |
out << m_clonedCameraViewport; |
| 723 |
|
| 724 |
// Added in v8: |
| 725 |
out << m_shadowsEnabled << m_ShadowMapSizeX << m_ShadowMapSizeY; |
| 726 |
|
| 727 |
// Added in v9: |
| 728 |
out << m_clip_max << m_clip_min << m_lightShadowClipMin << m_lightShadowClipMax; |
| 729 |
|
| 730 |
// v10: |
| 731 |
out << m_isViewportVisible; |
| 732 |
} |
| 733 |
|
| 734 |
void Viewport::serializeFrom(mrpt::serialization::CArchive& in, uint8_t version) |
| 735 |
{ |
| 736 |
switch (version) |
| 737 |
{ |
| 738 |
case 0: |
| 739 |
case 1: |
| 740 |
case 2: |
| 741 |
case 3: |
| 742 |
case 4: |
| 743 |
case 5: |
| 744 |
case 6: |
| 745 |
case 7: |
| 746 |
case 8: |
| 747 |
case 9: |
| 748 |
case 10: |
| 749 |
{ |
| 750 |
// Load data: |
| 751 |
in >> m_camera >> m_isCloned >> m_isClonedCamera >> m_clonedViewport >> m_name >> |
| 752 |
m_isTransparent >> m_borderWidth >> m_view_x >> m_view_y >> m_view_width >> m_view_height; |
| 753 |
|
| 754 |
// in v1: |
| 755 |
if (version >= 1) |
| 756 |
{ |
| 757 |
if (version < 7) |
| 758 |
{ |
| 759 |
// field removed in v7: |
| 760 |
bool was_m_custom_backgb_color; |
| 761 |
in >> was_m_custom_backgb_color; |
| 762 |
} |
| 763 |
|
| 764 |
in >> m_background_color.R >> m_background_color.G >> m_background_color.B >> |
| 765 |
m_background_color.A; |
| 766 |
} |
| 767 |
|
| 768 |
// Load objects: |
| 769 |
uint32_t n; |
| 770 |
in >> n; |
| 771 |
clear(); |
| 772 |
m_objects.resize(n); |
| 773 |
|
| 774 |
for_each(m_objects.begin(), m_objects.end(), ObjectReadFromStream(&in)); |
| 775 |
|
| 776 |
// Added in v2: Global OpenGL settings: |
| 777 |
if (version >= 2) |
| 778 |
{ |
| 779 |
in >> m_OpenGL_enablePolygonNicest; |
| 780 |
} |
| 781 |
else |
| 782 |
{ |
| 783 |
// Defaults |
| 784 |
} |
| 785 |
|
| 786 |
// Added in v3: Lights |
| 787 |
if (version >= 3) |
| 788 |
in >> m_light; |
| 789 |
else |
| 790 |
{ |
| 791 |
// Default: |
| 792 |
m_light = TLightParameters(); |
| 793 |
} |
| 794 |
|
| 795 |
// v4: text: |
| 796 |
m_2D_texts.messages.clear(); |
| 797 |
uint32_t nTexts = 0; |
| 798 |
if (version >= 4) nTexts = in.ReadAs<uint32_t>(); |
| 799 |
|
| 800 |
for (uint32_t i = 0; i < nTexts; i++) |
| 801 |
{ |
| 802 |
const auto id = in.ReadAs<uint32_t>(); |
| 803 |
double x, y; |
| 804 |
std::string text; |
| 805 |
in >> x >> y >> text; |
| 806 |
|
| 807 |
TFontParams fp; |
| 808 |
|
| 809 |
in >> fp.vfont_name >> fp.vfont_scale >> fp.color >> fp.draw_shadow >> fp.shadow_color >> |
| 810 |
fp.vfont_spacing >> fp.vfont_kerning; |
| 811 |
fp.vfont_style = static_cast<TOpenGLFontStyle>(in.ReadAs<uint8_t>()); |
| 812 |
|
| 813 |
this->addTextMessage(x, y, text, id, fp); |
| 814 |
} |
| 815 |
|
| 816 |
// Added in v5: image mode |
| 817 |
if (in.ReadAs<bool>()) |
| 818 |
{ |
| 819 |
in >> m_imageViewPlane; |
| 820 |
} |
| 821 |
else |
| 822 |
{ |
| 823 |
m_imageViewPlane.reset(); |
| 824 |
} |
| 825 |
|
| 826 |
if (version >= 6) |
| 827 |
in >> m_clonedCameraViewport; |
| 828 |
else |
| 829 |
m_clonedCameraViewport.clear(); |
| 830 |
|
| 831 |
if (version >= 8) |
| 832 |
{ |
| 833 |
in >> m_shadowsEnabled >> m_ShadowMapSizeX >> m_ShadowMapSizeY; |
| 834 |
} |
| 835 |
else |
| 836 |
{ |
| 837 |
m_shadowsEnabled = false; |
| 838 |
} |
| 839 |
|
| 840 |
if (version >= 9) |
| 841 |
{ |
| 842 |
in >> m_clip_max >> m_clip_min >> m_lightShadowClipMin >> m_lightShadowClipMax; |
| 843 |
} |
| 844 |
|
| 845 |
if (version >= 10) |
| 846 |
{ |
| 847 |
in >> m_isViewportVisible; |
| 848 |
} |
| 849 |
} |
| 850 |
break; |
| 851 |
default: |
| 852 |
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version); |
| 853 |
}; |
| 854 |
} |
| 855 |
|
| 856 |
/*--------------------------------------------------------------- |
| 857 |
getByName |
| 858 |
---------------------------------------------------------------*/ |
| 859 |
CRenderizable::Ptr Viewport::getByName(const string& str) |
| 860 |
{ |
| 861 |
for (auto& m_object : m_objects) |
| 862 |
{ |
| 863 |
if (m_object->getName() == str) |
| 864 |
return m_object; |
| 865 |
else if (m_object->GetRuntimeClass() == CLASS_ID_NAMESPACE(CSetOfObjects, opengl)) |
| 866 |
{ |
| 867 |
if (CRenderizable::Ptr ret = |
| 868 |
std::dynamic_pointer_cast<CSetOfObjects>(m_object)->getByName(str); |
| 869 |
ret) |
| 870 |
return ret; |
| 871 |
} |
| 872 |
} |
| 873 |
return {}; |
| 874 |
} |
| 875 |
|
| 876 |
void Viewport::initializeTextures() |
| 877 |
{ |
| 878 |
for (auto& obj : m_objects) obj->initializeTextures(); |
| 879 |
} |
| 880 |
|
| 881 |
void Viewport::dumpListOfObjects(std::vector<std::string>& lst) const |
| 882 |
{ |
| 883 |
for (auto& obj : m_objects) |
| 884 |
{ |
| 885 |
// Single obj: |
| 886 |
string s(obj->GetRuntimeClass()->className); |
| 887 |
if (!obj->getName().empty()) s += string(" (") + obj->getName() + string(")"); |
| 888 |
lst.emplace_back(s); |
| 889 |
|
| 890 |
if (obj->GetRuntimeClass() == CLASS_ID_NAMESPACE(CSetOfObjects, mrpt::opengl)) |
| 891 |
{ |
| 892 |
std::vector<std::string> auxLst; |
| 893 |
|
| 894 |
dynamic_cast<CSetOfObjects*>(obj.get())->dumpListOfObjects(auxLst); |
| 895 |
|
| 896 |
for (const auto& i : auxLst) lst.emplace_back(string(" ") + i); |
| 897 |
} |
| 898 |
} |
| 899 |
} |
| 900 |
|
| 901 |
mrpt::containers::yaml Viewport::asYAML() const |
| 902 |
{ |
| 903 |
mrpt::containers::yaml d = mrpt::containers::yaml::Sequence(); |
| 904 |
|
| 905 |
d.asSequence().resize(m_objects.size()); |
| 906 |
|
| 907 |
for (uint32_t i = 0; i < m_objects.size(); i++) |
| 908 |
{ |
| 909 |
const auto obj = m_objects.at(i); |
| 910 |
mrpt::containers::yaml de = mrpt::containers::yaml::Map(); |
| 911 |
|
| 912 |
// class-specific properties: |
| 913 |
obj->toYAMLMap(de); |
| 914 |
|
| 915 |
de["index"] = i; // type for "i" must be a stdint type |
| 916 |
if (!obj) |
| 917 |
{ |
| 918 |
de["class"] = "nullptr"; |
| 919 |
continue; |
| 920 |
} |
| 921 |
de["class"] = obj->GetRuntimeClass()->className; |
| 922 |
|
| 923 |
// Single obj: |
| 924 |
if (obj->GetRuntimeClass() == CLASS_ID_NAMESPACE(CSetOfObjects, mrpt::opengl)) |
| 925 |
{ |
| 926 |
de["obj_children"] = dynamic_cast<CSetOfObjects*>(obj.get())->asYAML(); |
| 927 |
} |
| 928 |
d.asSequence().at(i) = std::move(de); |
| 929 |
} |
| 930 |
return d; |
| 931 |
} |
| 932 |
|
| 933 |
/*-------------------------------------------------------------- |
| 934 |
removeObject |
| 935 |
---------------------------------------------------------------*/ |
| 936 |
void Viewport::removeObject(const CRenderizable::Ptr& obj) |
| 937 |
{ |
| 938 |
for (auto it = m_objects.begin(); it != m_objects.end(); ++it) |
| 939 |
if (*it == obj) |
| 940 |
{ |
| 941 |
m_objects.erase(it); |
| 942 |
return; |
| 943 |
} |
| 944 |
else if ((*it)->GetRuntimeClass() == CLASS_ID_NAMESPACE(CSetOfObjects, opengl)) |
| 945 |
dynamic_cast<CSetOfObjects*>(it->get())->removeObject(obj); |
| 946 |
} |
| 947 |
|
| 948 |
void Viewport::setViewportClipDistances(const float clip_min, const float clip_max) |
| 949 |
{ |
| 950 |
ASSERT_GT_(clip_max, clip_min); |
| 951 |
|
| 952 |
m_clip_min = clip_min; |
| 953 |
m_clip_max = clip_max; |
| 954 |
} |
| 955 |
|
| 956 |
void Viewport::getViewportClipDistances(float& clip_min, float& clip_max) const |
| 957 |
{ |
| 958 |
clip_min = m_clip_min; |
| 959 |
clip_max = m_clip_max; |
| 960 |
} |
| 961 |
|
| 962 |
void Viewport::setLightShadowClipDistances(const float clip_min, const float clip_max) |
| 963 |
{ |
| 964 |
ASSERT_GT_(clip_max, clip_min); |
| 965 |
|
| 966 |
m_lightShadowClipMin = clip_min; |
| 967 |
m_lightShadowClipMax = clip_max; |
| 968 |
} |
| 969 |
|
| 970 |
void Viewport::getLightShadowClipDistances(float& clip_min, float& clip_max) const |
| 971 |
{ |
| 972 |
clip_min = m_lightShadowClipMin; |
| 973 |
clip_max = m_lightShadowClipMax; |
| 974 |
} |
| 975 |
|
| 976 |
/*-------------------------------------------------------------- |
| 977 |
get3DRayForPixelCoord |
| 978 |
---------------------------------------------------------------*/ |
| 979 |
void Viewport::get3DRayForPixelCoord( |
| 980 |
const double x_coord, |
| 981 |
const double y_coord, |
| 982 |
mrpt::math::TLine3D& out_ray, |
| 983 |
mrpt::poses::CPose3D* out_cameraPose) const |
| 984 |
{ |
| 985 |
auto& _ = m_threadedData.get().state; |
| 986 |
|
| 987 |
if (!_.initialized) |
| 988 |
{ |
| 989 |
updateMatricesFromCamera(*internalResolveActiveCamera()); |
| 990 |
ASSERT_(_.initialized); |
| 991 |
} |
| 992 |
|
| 993 |
ASSERTDEB_(_.viewport_height > 0 && _.viewport_width > 0); |
| 994 |
|
| 995 |
const double ASPECT = _.viewport_width / double(_.viewport_height); |
| 996 |
|
| 997 |
// unitary vector between (eye) -> (pointing): |
| 998 |
const TPoint3D pointing_dir = { |
| 999 |
-cos(_.azimuth) * cos(_.elev), -sin(_.azimuth) * cos(_.elev), -sin(_.elev)}; |
| 1000 |
|
| 1001 |
// The camera X vector (in 3D) can be computed from the camera azimuth |
| 1002 |
// angle: |
| 1003 |
const TPoint3D cam_x_3d = {-sin(_.azimuth), cos(_.azimuth), 0}; |
| 1004 |
|
| 1005 |
// The camera real UP vector (in 3D) is the cross product: |
| 1006 |
// X3d x pointing_dir: |
| 1007 |
const auto cam_up_3d = mrpt::math::crossProduct3D(cam_x_3d, pointing_dir); |
| 1008 |
|
| 1009 |
if (!_.is_projective) |
| 1010 |
{ |
| 1011 |
// Ortho projection: |
| 1012 |
// ------------------------------- |
| 1013 |
double Ax = _.eyeDistance * 0.25; |
| 1014 |
double Ay = Ax; |
| 1015 |
|
| 1016 |
if (ASPECT > 1) |
| 1017 |
Ax *= ASPECT; |
| 1018 |
else |
| 1019 |
{ |
| 1020 |
if (ASPECT != 0) Ay /= ASPECT; |
| 1021 |
} |
| 1022 |
|
| 1023 |
const double point_lx = (-0.5 + x_coord / _.viewport_width) * 2 * Ax; |
| 1024 |
const double point_ly = -(-0.5 + y_coord / _.viewport_height) * 2 * Ay; |
| 1025 |
|
| 1026 |
const TPoint3D ray_origin( |
| 1027 |
_.eye.x + point_lx * cam_x_3d.x + point_ly * cam_up_3d.x, |
| 1028 |
_.eye.y + point_lx * cam_x_3d.y + point_ly * cam_up_3d.y, |
| 1029 |
_.eye.z + point_lx * cam_x_3d.z + point_ly * cam_up_3d.z); |
| 1030 |
|
| 1031 |
out_ray.pBase = ray_origin; |
| 1032 |
out_ray.director[0] = pointing_dir.x; |
| 1033 |
out_ray.director[1] = pointing_dir.y; |
| 1034 |
out_ray.director[2] = pointing_dir.z; |
| 1035 |
} |
| 1036 |
else |
| 1037 |
{ |
| 1038 |
// Perspective camera |
| 1039 |
// ------------------------------- |
| 1040 |
|
| 1041 |
// JL: This can be derived from: |
| 1042 |
// http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml |
| 1043 |
// where one arrives to: |
| 1044 |
// tan(FOVx/2) = ASPECT_RATIO * tan(FOVy/2) |
| 1045 |
// |
| 1046 |
const double FOVy = DEG2RAD(_.FOV); |
| 1047 |
const double FOVx = 2.0 * atan(ASPECT * tan(FOVy * 0.5)); |
| 1048 |
|
| 1049 |
const auto vw = _.viewport_width; |
| 1050 |
const auto vh = _.viewport_height; |
| 1051 |
const double len_horz = 2.0 * (-0.5 + x_coord / vw) * tan(0.5 * FOVx); |
| 1052 |
const double len_vert = -2.0 * (-0.5 + y_coord / vh) * tan(0.5 * FOVy); |
| 1053 |
// Point in camera local reference frame |
| 1054 |
const auto l = mrpt::math::TPoint3D(len_horz, len_vert, 1.0); |
| 1055 |
|
| 1056 |
const mrpt::math::TPoint3D ray_director( |
| 1057 |
l.x * cam_x_3d.x + l.y * cam_up_3d.x + l.z * pointing_dir.x, |
| 1058 |
l.x * cam_x_3d.y + l.y * cam_up_3d.y + l.z * pointing_dir.y, |
| 1059 |
l.x * cam_x_3d.z + l.y * cam_up_3d.z + l.z * pointing_dir.z); |
| 1060 |
|
| 1061 |
// Set out ray: |
| 1062 |
out_ray.pBase = _.eye; |
| 1063 |
out_ray.director[0] = ray_director.x; |
| 1064 |
out_ray.director[1] = ray_director.y; |
| 1065 |
out_ray.director[2] = ray_director.z; |
| 1066 |
|
| 1067 |
} // end projective |
| 1068 |
|
| 1069 |
// Camera pose: |
| 1070 |
if (out_cameraPose) |
| 1071 |
{ |
| 1072 |
mrpt::math::CMatrixDouble44 M(UNINITIALIZED_MATRIX); |
| 1073 |
M(0, 0) = cam_x_3d.x; |
| 1074 |
M(1, 0) = cam_x_3d.y; |
| 1075 |
M(2, 0) = cam_x_3d.z; |
| 1076 |
M(3, 0) = 0; |
| 1077 |
|
| 1078 |
M(0, 1) = cam_up_3d.x; |
| 1079 |
M(1, 1) = cam_up_3d.y; |
| 1080 |
M(2, 1) = cam_up_3d.z; |
| 1081 |
M(3, 1) = 0; |
| 1082 |
|
| 1083 |
M(0, 2) = pointing_dir.x; |
| 1084 |
M(1, 2) = pointing_dir.y; |
| 1085 |
M(2, 2) = pointing_dir.z; |
| 1086 |
M(3, 2) = 0; |
| 1087 |
|
| 1088 |
M(0, 3) = _.eye.x; |
| 1089 |
M(1, 3) = _.eye.y; |
| 1090 |
M(2, 3) = _.eye.z; |
| 1091 |
M(3, 3) = 1; |
| 1092 |
|
| 1093 |
*out_cameraPose = CPose3D(M); |
| 1094 |
} |
| 1095 |
} |
| 1096 |
|
| 1097 |
void Viewport::setCurrentCameraFromPose(mrpt::poses::CPose3D& p) |
| 1098 |
{ |
| 1099 |
m_camera.set6DOFMode(true); |
| 1100 |
m_camera.setPose(p); |
| 1101 |
} |
| 1102 |
|
| 1103 |
void Viewport::getCurrentCameraPose(mrpt::poses::CPose3D& out_cameraPose) const |
| 1104 |
{ |
| 1105 |
mrpt::math::TLine3D dum; |
| 1106 |
get3DRayForPixelCoord(0, 0, dum, &out_cameraPose); |
| 1107 |
} |
| 1108 |
|
| 1109 |
/** Resets the viewport to a normal 3D viewport \sa setCloneView, setImageView |
| 1110 |
*/ |
| 1111 |
void Viewport::setNormalMode() |
| 1112 |
{ |
| 1113 |
// If this was an image-mode viewport, remove the quad object to disable it. |
| 1114 |
m_imageViewPlane.reset(); |
| 1115 |
|
| 1116 |
m_isCloned = false; |
| 1117 |
m_isClonedCamera = false; |
| 1118 |
} |
| 1119 |
|
| 1120 |
void Viewport::setImageView(const mrpt::img::CImage& img, bool transparentBackground) |
| 1121 |
{ |
| 1122 |
internal_enableImageView(transparentBackground); |
| 1123 |
m_imageViewPlane->assignImage(img); |
| 1124 |
} |
| 1125 |
void Viewport::setImageView(mrpt::img::CImage&& img, bool transparentBackground) |
| 1126 |
{ |
| 1127 |
internal_enableImageView(transparentBackground); |
| 1128 |
m_imageViewPlane->assignImage(img); |
| 1129 |
} |
| 1130 |
|
| 1131 |
void Viewport::internal_enableImageView(bool transparentBackground) |
| 1132 |
{ |
| 1133 |
// If this is the first time, we have to create the quad object: |
| 1134 |
if (!m_imageViewPlane) |
| 1135 |
{ |
| 1136 |
m_imageViewPlane = mrpt::opengl::CTexturedPlane::Create(); |
| 1137 |
// Flip vertically: |
| 1138 |
m_imageViewPlane->setPlaneCorners(-1, 1, 1, -1); |
| 1139 |
} |
| 1140 |
setTransparent(transparentBackground); |
| 1141 |
} |
| 1142 |
|
| 1143 |
/** Evaluates the bounding box of this object (including possible children) in |
| 1144 |
* the coordinate frame of the object parent. */ |
| 1145 |
auto Viewport::getBoundingBox() const -> mrpt::math::TBoundingBox |
| 1146 |
{ |
| 1147 |
mrpt::math::TBoundingBox bb; |
| 1148 |
bool first = true; |
| 1149 |
|
| 1150 |
for (const auto& o : m_objects) |
| 1151 |
{ |
| 1152 |
if (first) |
| 1153 |
{ |
| 1154 |
bb = o->getBoundingBox(); |
| 1155 |
first = false; |
| 1156 |
} |
| 1157 |
else |
| 1158 |
bb = bb.unionWith(o->getBoundingBox()); |
| 1159 |
} |
| 1160 |
|
| 1161 |
return bb; |
| 1162 |
} |
| 1163 |
|
| 1164 |
void Viewport::setCloneCamera(bool enable) |
| 1165 |
{ |
| 1166 |
m_isClonedCamera = enable; |
| 1167 |
if (!enable) |
| 1168 |
{ |
| 1169 |
m_clonedCameraViewport.clear(); |
| 1170 |
} |
| 1171 |
else |
| 1172 |
{ |
| 1173 |
ASSERTMSG_( |
| 1174 |
!m_clonedViewport.empty(), |
| 1175 |
"Error: cannot setCloneCamera(true) on a viewport before calling " |
| 1176 |
"setCloneView()"); |
| 1177 |
|
| 1178 |
m_clonedCameraViewport = m_clonedViewport; |
| 1179 |
} |
| 1180 |
} |
| 1181 |
|
| 1182 |
const CCamera* Viewport::internalResolveActiveCamera(const CCamera* forceThisCamera) const |
| 1183 |
{ |
| 1184 |
// Prepare camera (projection matrix): |
| 1185 |
Viewport* viewForGetCamera = nullptr; |
| 1186 |
|
| 1187 |
if (!m_clonedCameraViewport.empty()) |
| 1188 |
{ |
| 1189 |
const auto view = m_parent->getViewport(m_clonedCameraViewport); |
| 1190 |
if (!view) |
| 1191 |
THROW_EXCEPTION_FMT( |
| 1192 |
"Cloned viewport '%s' not found in parent Scene", m_clonedViewport.c_str()); |
| 1193 |
|
| 1194 |
viewForGetCamera = m_isClonedCamera ? view.get() : const_cast<Viewport*>(this); |
| 1195 |
} |
| 1196 |
else |
| 1197 |
{ // Normal case: render our own objects: |
| 1198 |
viewForGetCamera = const_cast<Viewport*>(this); |
| 1199 |
} |
| 1200 |
|
| 1201 |
// Get camera: |
| 1202 |
// 1st: if there is a CCamera in the scene (nullptr if no camera found): |
| 1203 |
const auto camPtr = viewForGetCamera->getByClass<CCamera>(); |
| 1204 |
const auto* myCamera = camPtr ? camPtr.get() : nullptr; |
| 1205 |
|
| 1206 |
// 2nd: the internal camera of all viewports: |
| 1207 |
if (!myCamera) myCamera = &viewForGetCamera->m_camera; |
| 1208 |
|
| 1209 |
// forced cam? |
| 1210 |
if (forceThisCamera) myCamera = forceThisCamera; |
| 1211 |
|
| 1212 |
return myCamera; |
| 1213 |
} |
| 1214 |
|
| 1215 |
void Viewport::updateMatricesFromCamera(const CCamera& myCamera) const |
| 1216 |
{ |
| 1217 |
auto& _ = m_threadedData.get().state; |
| 1218 |
|
| 1219 |
if (myCamera.isNoProjection()) |
| 1220 |
{ |
| 1221 |
// No translation nor rotation nor perspective: |
| 1222 |
_.computeNoProjectionMatrix(m_clip_min, m_clip_max); |
| 1223 |
} |
| 1224 |
else |
| 1225 |
{ |
| 1226 |
// Projective or orthogonal camera models: |
| 1227 |
ASSERT_(myCamera.getZoomDistance() > 0); |
| 1228 |
|
| 1229 |
_.is_projective = myCamera.isProjective(); |
| 1230 |
|
| 1231 |
_.FOV = myCamera.getProjectiveFOVdeg(); |
| 1232 |
_.pinhole_model = myCamera.getPinholeModel(); |
| 1233 |
_.eyeDistance = myCamera.getZoomDistance(); |
| 1234 |
_.azimuth = DEG2RAD(myCamera.getAzimuthDegrees()); |
| 1235 |
_.elev = DEG2RAD(myCamera.getElevationDegrees()); |
| 1236 |
_.roll = DEG2RAD(myCamera.getRollDegrees()); |
| 1237 |
|
| 1238 |
if (myCamera.is6DOFMode()) |
| 1239 |
{ |
| 1240 |
// In 6DOFMode eye is set viewing towards the direction of the |
| 1241 |
// positive Z axis |
| 1242 |
// Up is set as -Y axis |
| 1243 |
const auto pose = mrpt::poses::CPose3D(myCamera.getPose()); |
| 1244 |
const auto viewDirection = mrpt::poses::CPose3D::FromTranslation(0, 0, 1); |
| 1245 |
const auto at = pose + viewDirection; |
| 1246 |
|
| 1247 |
_.eye = pose.translation(); |
| 1248 |
_.pointing = at.translation(); |
| 1249 |
// "UP" = -Y axis |
| 1250 |
pose.getRotationMatrix().extractColumn(1, _.up); |
| 1251 |
_.up *= -1.0; |
| 1252 |
} |
| 1253 |
else |
| 1254 |
{ |
| 1255 |
// Normal mode: use "camera orbit" parameters to compute pointing-to |
| 1256 |
// point: |
| 1257 |
_.pointing = myCamera.getPointingAt(); |
| 1258 |
|
| 1259 |
const auto c2m_u = mrpt::math::TVector3D( |
| 1260 |
cos(_.azimuth) * cos(_.elev), // |
| 1261 |
sin(_.azimuth) * cos(_.elev), // |
| 1262 |
sin(_.elev) // |
| 1263 |
); |
| 1264 |
|
| 1265 |
const double dis = std::max<double>(0.001, myCamera.getZoomDistance()); |
| 1266 |
_.eye = _.pointing + c2m_u * dis; |
| 1267 |
|
| 1268 |
_.up.x = -cos(_.azimuth) * sin(_.elev); |
| 1269 |
_.up.y = -sin(_.azimuth) * sin(_.elev); |
| 1270 |
_.up.z = cos(_.elev); |
| 1271 |
|
| 1272 |
// roll? |
| 1273 |
if (_.roll != .0) |
| 1274 |
{ |
| 1275 |
// _.up & c2m_u are both unit vectors and orthogonal to each other. |
| 1276 |
const auto w = mrpt::math::crossProduct3D(c2m_u, _.up); |
| 1277 |
_.up = _.up * cos(_.roll) + w * sin(_.roll); |
| 1278 |
} |
| 1279 |
} |
| 1280 |
|
| 1281 |
// Compute the projection matrix (p_matrix): |
| 1282 |
_.computeProjectionMatrix(m_clip_min, m_clip_max); |
| 1283 |
|
| 1284 |
// Apply eye center and lookAt to p_matrix: |
| 1285 |
_.computeViewMatrix(); |
| 1286 |
} |
| 1287 |
|
| 1288 |
// Reset model4x4 matrix to the identity transformation: |
| 1289 |
_.m_matrix.setIdentity(); |
| 1290 |
|
| 1291 |
// Compute the directional light projection matrix (light_pv) |
| 1292 |
_.computeLightProjectionMatrix(m_lightShadowClipMin, m_lightShadowClipMax, m_light); |
| 1293 |
|
| 1294 |
_.initialized = true; |
| 1295 |
} |
| 1296 |
|
| 1297 |
void Viewport::enableShadowCasting( |
| 1298 |
bool enabled, unsigned int SHADOW_MAP_SIZE_X, unsigned int SHADOW_MAP_SIZE_Y) |
| 1299 |
{ |
| 1300 |
m_shadowsEnabled = enabled; |
| 1301 |
if (SHADOW_MAP_SIZE_X) m_ShadowMapSizeX = SHADOW_MAP_SIZE_X; |
| 1302 |
if (SHADOW_MAP_SIZE_Y) m_ShadowMapSizeY = SHADOW_MAP_SIZE_Y; |
| 1303 |
} |