Debian Codegraph @

libs/opengl/src/CFBORender.cpp

raw
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 <mrpt/core/get_env.h>
13 #include <mrpt/opengl/CFBORender.h>
14 #include <mrpt/opengl/OpenGLDepth2LinearLUTs.h>
15 #include <mrpt/opengl/opengl_api.h>
16 //
17 #include <mrpt/config.h>
18
19 #define FBO_USE_LUT
20 //#define FBO_PROFILER
21
22 #ifdef FBO_PROFILER
23 #include <mrpt/system/CTimeLogger.h>
24 #endif
25
26 #if MRPT_HAS_EGL
27 #include <EGL/egl.h>
28 #include <EGL/eglext.h>
29 #endif
30
31 #define HAVE_FBO (MRPT_HAS_OPENCV && MRPT_HAS_OPENGL_GLUT && MRPT_HAS_EGL)
32
33 using namespace std;
34 using namespace mrpt;
35 using namespace mrpt::opengl;
36 using mrpt::img::CImage;
37
38 const thread_local bool MRPT_FBORENDER_SHOW_DEVICES =
39 mrpt::get_env<bool>("MRPT_FBORENDER_SHOW_DEVICES");
40
41 const thread_local bool MRPT_FBORENDER_USE_LUT =
42 mrpt::get_env<bool>("MRPT_FBORENDER_USE_LUT", true);
43
44 CFBORender::CFBORender(const Parameters& p) : m_params(p)
45 {
46 #if HAVE_FBO
47
48 MRPT_START
49
50 if (p.create_EGL_context)
51 {
52 // clang-format off
53 std::vector<EGLint> configAttribs = {
54 EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
55 EGL_BLUE_SIZE, p.blueSize,
56 EGL_GREEN_SIZE, p.greenSize,
57 EGL_RED_SIZE, p.redSize,
58 EGL_DEPTH_SIZE, p.depthSize
59 };
60 // clang-format on
61 if (p.conformantOpenGLES2)
62 {
63 configAttribs.push_back(EGL_CONFORMANT);
64 configAttribs.push_back(EGL_OPENGL_ES2_BIT);
65 }
66 if (p.renderableOpenGLES2)
67 {
68 configAttribs.push_back(EGL_RENDERABLE_TYPE);
69 configAttribs.push_back(EGL_OPENGL_ES2_BIT);
70 }
71 configAttribs.push_back(EGL_NONE);
72
73 constexpr int pbufferWidth = 9;
74 constexpr int pbufferHeight = 9;
75
76 static const EGLint pbufferAttribs[] = {
77 EGL_WIDTH, pbufferWidth, EGL_HEIGHT, pbufferHeight, EGL_NONE,
78 };
79
80 static const int MAX_DEVICES = 32;
81 EGLDeviceEXT eglDevs[MAX_DEVICES];
82 EGLint numDevices = 0;
83
84 PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT =
85 (PFNEGLQUERYDEVICESEXTPROC)eglGetProcAddress("eglQueryDevicesEXT");
86 ASSERT_(eglQueryDevicesEXT);
87
88 eglQueryDevicesEXT(MAX_DEVICES, eglDevs, &numDevices);
89
90 if (MRPT_FBORENDER_SHOW_DEVICES)
91 {
92 printf("[mrpt EGL] Detected %d devices\n", numDevices);
93
94 PFNEGLQUERYDEVICESTRINGEXTPROC eglQueryDeviceStringEXT =
95 (PFNEGLQUERYDEVICESTRINGEXTPROC)eglGetProcAddress("eglQueryDeviceStringEXT");
96 ASSERT_(eglQueryDeviceStringEXT);
97
98 for (int i = 0; i < numDevices; i++)
99 {
100 const char* devExts = eglQueryDeviceStringEXT(eglDevs[i], EGL_EXTENSIONS);
101
102 printf("[mrpt EGL] Device #%i. Extensions: %s\n", i, devExts ? devExts : "(None)");
103 }
104 }
105
106 ASSERT_LT_(p.deviceIndexToUse, numDevices);
107
108 PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT =
109 (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
110 ASSERT_(eglGetPlatformDisplayEXT);
111
112 m_eglDpy = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, eglDevs[p.deviceIndexToUse], 0);
113
114 // 1. Initialize EGL
115 if (m_eglDpy == EGL_NO_DISPLAY)
116 {
117 THROW_EXCEPTION("Failed to get EGL display");
118 }
119
120 EGLint major, minor;
121
122 if (eglInitialize(m_eglDpy, &major, &minor) == EGL_FALSE)
123 {
124 THROW_EXCEPTION_FMT("Failed to initialize EGL display: %x\n", eglGetError());
125 }
126
127 // printf("[mrpt EGL] version: %i.%i\n", major, minor);
128
129 // 2. Select an appropriate configuration
130 EGLint numConfigs;
131
132 eglChooseConfig(m_eglDpy, configAttribs.data(), &m_eglCfg, 1, &numConfigs);
133 if (numConfigs != 1)
134 {
135 THROW_EXCEPTION_FMT("Failed to choose exactly 1 config, chose %d\n", numConfigs);
136 }
137
138 // 3. Create a surface
139 m_eglSurf = eglCreatePbufferSurface(m_eglDpy, m_eglCfg, pbufferAttribs);
140
141 // 4. Bind the API
142 if (!eglBindAPI(p.bindOpenGLES_API ? EGL_OPENGL_ES_API : EGL_OPENGL_API))
143 {
144 // error:
145 THROW_EXCEPTION("no opengl api in egl");
146 }
147
148 // 5. Create a context and make it current
149
150 // clang-format off
151 std::vector<EGLint> ctxAttribs = {
152 EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
153 EGL_CONTEXT_OPENGL_DEBUG, p.contextDebug ? EGL_TRUE: EGL_FALSE
154 };
155 // clang-format on
156 if (p.contextMajorVersion != 0 && p.contextMinorVersion != 0)
157 {
158 ctxAttribs.push_back(EGL_CONTEXT_MAJOR_VERSION);
159 ctxAttribs.push_back(p.contextMajorVersion);
160 ctxAttribs.push_back(EGL_CONTEXT_MINOR_VERSION);
161 ctxAttribs.push_back(p.contextMinorVersion);
162 }
163 ctxAttribs.push_back(EGL_NONE);
164
165 m_eglContext = eglCreateContext(m_eglDpy, m_eglCfg, EGL_NO_CONTEXT, ctxAttribs.data());
166
167 ASSERT_(m_eglContext != EGL_NO_CONTEXT);
168
169 if (eglMakeCurrent(m_eglDpy, m_eglSurf, m_eglSurf, m_eglContext) == EGL_FALSE)
170 {
171 EGLint err = eglGetError();
172 THROW_EXCEPTION_FMT("eglMakeCurrent failed: 0x%X", err);
173 }
174 }
175
176 // -------------------------------
177 // Create frame buffer object:
178 // -------------------------------
179 m_fb.create(p.width, p.height); // TODO: Multisample doesn't work...
180 const auto oldFB = m_fb.bind();
181
182 // -------------------------------
183 // Create texture:
184 // -------------------------------
185 glGenTextures(1, &m_texRGB);
186 CHECK_OPENGL_ERROR();
187
188 glBindTexture(GL_TEXTURE_2D, m_texRGB);
189 CHECK_OPENGL_ERROR();
190
191 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
192 CHECK_OPENGL_ERROR_IN_DEBUG();
193 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
194 CHECK_OPENGL_ERROR_IN_DEBUG();
195
196 glTexImage2D(
197 GL_TEXTURE_2D, 0, GL_RGB, m_fb.width(), m_fb.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
198 CHECK_OPENGL_ERROR_IN_DEBUG();
199
200 // bind this texture to the current framebuffer obj. as color_attachement_0
201 glFramebufferTexture2D(
202 GL_FRAMEBUFFER, // DRAW + READ FB
203 GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texRGB, 0);
204 CHECK_OPENGL_ERROR();
205
206 // unbind:
207 FrameBuffer::Bind(oldFB);
208
209 MRPT_END
210 #else
211 THROW_EXCEPTION("This class requires MRPT built with: OpenCV; OpenGL, and EGL.");
212 #endif
213 }
214
215 CFBORender::~CFBORender()
216 {
217 #if HAVE_FBO
218 // delete the current texture, the framebuffer object and the EGL context
219 glDeleteTextures(1, &m_texRGB);
220 m_fb.destroy();
221 // Terminate EGL when finished:
222 if (m_eglDpy) eglTerminate(m_eglDpy);
223 #endif
224 }
225
226 void CFBORender::internal_render_RGBD(
227 [[maybe_unused]] const Scene& scene,
228 [[maybe_unused]] const mrpt::optional_ref<mrpt::img::CImage>& optoutRGB,
229 [[maybe_unused]] const mrpt::optional_ref<mrpt::math::CMatrixFloat>& optoutDepth)
230 {
231 #if HAVE_FBO
232
233 MRPT_START
234
235 ASSERT_(optoutRGB.has_value() || optoutDepth.has_value());
236
237 #ifdef FBO_PROFILER
238 thread_local mrpt::system::CTimeLogger profiler(true, "FBO_RENDERER");
239
240 using namespace std::string_literals;
241 const std::string sSec = mrpt::format("%ux%u_", m_fb.width(), m_fb.height());
242
243 auto tleR = mrpt::system::CTimeLoggerEntry(profiler, sSec + ".prepAndRender"s);
244 #endif
245
246 const auto oldFBs = m_fb.bind();
247
248 // change viewport size (in pixels)
249 // glViewport(0, 0, m_fb.width(), m_fb.height());
250 // CHECK_OPENGL_ERROR_IN_DEBUG();
251
252 // bind the framebuffer, fbo, so operations will now occur on it
253 glBindTexture(GL_TEXTURE_2D, m_texRGB);
254 CHECK_OPENGL_ERROR_IN_DEBUG();
255
256 glEnable(GL_DEPTH_TEST);
257 CHECK_OPENGL_ERROR_IN_DEBUG();
258
259 // ---------------------------
260 // Render:
261 // ---------------------------
262 for (const auto& viewport : scene.viewports())
263 viewport->render(m_fb.width(), m_fb.height(), 0, 0, &m_renderFromCamera);
264
265 #ifdef FBO_PROFILER
266 tleR.stop();
267 #endif
268
269 // ---------------------------
270 // RGB
271 // ---------------------------
272 if (optoutRGB.has_value())
273 {
274 auto& outRGB = optoutRGB.value().get();
275 // resize the outRGB if it is necessary
276 if (outRGB.isEmpty() || outRGB.getWidth() != static_cast<size_t>(m_fb.width()) ||
277 outRGB.getHeight() != static_cast<size_t>(m_fb.height()) || outRGB.getChannelCount() != 3)
278 { // resize:
279 outRGB.resize(m_fb.width(), m_fb.height(), mrpt::img::CH_RGB);
280 }
281
282 // check the outRGB size
283 ASSERT_(!outRGB.isEmpty());
284 ASSERT_EQUAL_(outRGB.getWidth(), static_cast<size_t>(m_fb.width()));
285 ASSERT_EQUAL_(outRGB.getHeight(), static_cast<size_t>(m_fb.height()));
286 ASSERT_EQUAL_(outRGB.getChannelCount(), 3);
287
288 #ifdef FBO_PROFILER
289 auto tle1 = mrpt::system::CTimeLoggerEntry(profiler, sSec + ".glReadPixels_rgb"s);
290 #endif
291
292 // TODO NOTE: This should fail if the image has padding bytes. See
293 // glPixelStore() etc.
294 glReadPixels(0, 0, m_fb.width(), m_fb.height(), GL_BGR_EXT, GL_UNSIGNED_BYTE, outRGB(0, 0));
295 CHECK_OPENGL_ERROR();
296
297 #ifdef FBO_PROFILER
298 tle1.stop();
299 auto tle2 = mrpt::system::CTimeLoggerEntry(profiler, sSec + ".flip_rgb"s);
300 #endif
301
302 // Flip vertically:
303 outRGB.flipVertical();
304 }
305
306 // ---------------------------
307 // Depth
308 // ---------------------------
309 if (optoutDepth.has_value())
310 {
311 auto& outDepth = optoutDepth.value().get();
312
313 #ifdef FBO_PROFILER
314 auto tle1 = mrpt::system::CTimeLoggerEntry(profiler, sSec + ".glReadPixels_float"s);
315 #endif
316
317 outDepth.resize(m_fb.height(), m_fb.width());
318
319 glReadPixels(0, 0, m_fb.width(), m_fb.height(), GL_DEPTH_COMPONENT, GL_FLOAT, outDepth.data());
320 CHECK_OPENGL_ERROR();
321
322 #ifdef FBO_PROFILER
323 tle1.stop();
324 #endif
325
326 using depth_lut_t = OpenGLDepth2LinearLUTs<18>;
327
328 // Dont create LUT if we are not about to use it anyway:
329 if (!m_params.raw_depth)
330 {
331 // Transform from OpenGL clip depths into linear distances:
332 const auto mats = scene.getViewport()->getRenderMatrices();
333 const float zn = mats.getLastClipZNear();
334 const float zf = mats.getLastClipZFar();
335
336 const depth_lut_t::lut_t* lut = nullptr;
337
338 #if !defined(FBO_USE_LUT)
339 const bool do_use_lut = false;
340 #else
341 bool do_use_lut = MRPT_FBORENDER_USE_LUT;
342 // dont use LUT for really small image areas:
343 if (m_fb.height() * m_fb.width() < 10000)
344 {
345 do_use_lut = false;
346 }
347 #endif
348
349 if (do_use_lut)
350 {
351 #ifdef FBO_PROFILER
352 auto tle_lut = mrpt::system::CTimeLoggerEntry(profiler, sSec + ".get_lut"s);
353 #endif
354 lut = &depth_lut_t::Instance().lut_from_zn_zf(zn, zf);
355 }
356
357 #ifdef FBO_PROFILER
358 auto tle2 = mrpt::system::CTimeLoggerEntry(profiler, sSec + ".linear"s);
359 #endif
360
361 if (!do_use_lut)
362 {
363 // Depth buffer -> linear depth:
364 const auto linearDepth = [zn, zf](float depthSample) -> float
365 {
366 depthSample = 2.0 * depthSample - 1.0;
367 float zLinear = 2.0 * zn * zf / (zf + zn - depthSample * (zf - zn));
368 return zLinear;
369 };
370 for (auto& d : outDepth)
371 {
372 if (d == 1)
373 d = 0; // no "echo return"
374 else
375 d = linearDepth(d);
376 }
377 }
378 else
379 {
380 // map d in [-1.0f,+1.0f] ==> real depth values:
381 for (auto& d : outDepth)
382 {
383 d = (*lut)[(d + 1.0f) * (depth_lut_t::NUM_ENTRIES - 1) / 2];
384 }
385 }
386 #ifdef FBO_PROFILER
387 tle2.stop();
388 #endif
389 }
390
391 #ifdef FBO_PROFILER
392 auto tle3 = mrpt::system::CTimeLoggerEntry(profiler, sSec + ".flip"s);
393 #endif
394
395 // flip lines:
396 std::vector<float> bufLine(m_fb.width());
397 const auto bytesPerLine = sizeof(float) * m_fb.width();
398 for (unsigned int y = 0; y < m_fb.height() / 2; y++)
399 {
400 const int yFlipped = m_fb.height() - 1 - y;
401 ::memcpy(bufLine.data(), &outDepth(y, 0), bytesPerLine);
402 ::memcpy(&outDepth(y, 0), &outDepth(yFlipped, 0), bytesPerLine);
403 ::memcpy(&outDepth(yFlipped, 0), bufLine.data(), bytesPerLine);
404 }
405 #ifdef FBO_PROFILER
406 tle3.stop();
407 #endif
408 }
409
410 //'unbind' the frambuffer object, so subsequent drawing ops are not
411 // drawn into the FBO.
412 FrameBuffer::Bind(oldFBs);
413
414 MRPT_END
415 #endif
416 }
417
418 void CFBORender::render_RGB(const Scene& scene, CImage& outRGB)
419 {
420 internal_render_RGBD(scene, outRGB, std::nullopt);
421 }
422
423 void CFBORender::render_RGBD(
424 const Scene& scene, mrpt::img::CImage& outRGB, mrpt::math::CMatrixFloat& outDepth)
425 {
426 internal_render_RGBD(scene, outRGB, outDepth);
427 }
428 void CFBORender::render_depth(const Scene& scene, mrpt::math::CMatrixFloat& outDepth)
429 {
430 internal_render_RGBD(scene, std::nullopt, outDepth);
431 }