Debian Codegraph @

src/Gui/SoFCOffscreenRenderer.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <FCConfig.h>
24
25 #include <iomanip>
26 #include <ios>
27 #include <sstream>
28 #include <Inventor/actions/SoGLRenderAction.h>
29 #include <Inventor/elements/SoGLCacheContextElement.h>
30 #include <Inventor/fields/SoSFImage.h>
31 #include <Inventor/nodes/SoNode.h>
32 #include <QBuffer>
33 #include <QDateTime>
34 #include <QFile>
35 #include <QImage>
36 #include <QImageWriter>
37
38 #if defined(FC_OS_WIN32)
39 # include <windows.h>
40 #endif
41
42 #if !defined(FC_OS_MACOSX)
43 # include <GL/gl.h>
44 # include <GL/glu.h>
45 # include <GL/glext.h>
46 #endif
47
48 #include <QOpenGLFramebufferObject>
49 #include <QOpenGLContext>
50 #include <QOffscreenSurface>
51
52 #include <App/Application.h>
53 #include <Base/FileInfo.h>
54 #include <Base/Exception.h>
55 #include <Base/Console.h>
56 #include <Base/Interpreter.h>
57
58 #include "SoFCOffscreenRenderer.h"
59 #include "BitmapFactory.h"
60
61
62 using namespace Gui;
63 using namespace std;
64
65
66 void writeJPEGComment(const std::string&, QByteArray&);
67
68 // ---------------------------------------------------------------
69
70 SoFCOffscreenRenderer* SoFCOffscreenRenderer::inst = nullptr;
71
72
73 SoFCOffscreenRenderer& SoFCOffscreenRenderer::instance()
74 {
75 if (!inst) {
76 inst = new SoFCOffscreenRenderer(SbViewportRegion());
77 }
78 return *inst;
79 }
80
81 SoFCOffscreenRenderer::SoFCOffscreenRenderer(const SbViewportRegion& viewportregion)
82 : SoOffscreenRenderer(viewportregion)
83 {}
84
85 SoFCOffscreenRenderer::SoFCOffscreenRenderer(SoGLRenderAction* action)
86 : SoOffscreenRenderer(action)
87 {}
88
89 SoFCOffscreenRenderer::~SoFCOffscreenRenderer() = default;
90
91 void SoFCOffscreenRenderer::writeToImage(QImage& img) const
92 {
93 const unsigned char* bytes = getBuffer();
94 SbVec2s size = getViewportRegion().getViewportSizePixels();
95 int numcomponents = (int)this->getComponents();
96
97 SoSFImage image;
98 image.setValue(size, numcomponents, bytes, SoSFImage::NO_COPY);
99 BitmapFactory().convert(image, img);
100 }
101
102 void SoFCOffscreenRenderer::writeToImageFile(
103 const char* filename,
104 const char* comment,
105 const SbMatrix& mat,
106 const QImage& image
107 )
108 {
109 if (image.isNull()) {
110 std::stringstream str;
111 str << "Cannot save null image.";
112 throw Base::ValueError(str.str());
113 }
114
115 Base::FileInfo file(filename);
116 if (file.hasExtension({"JPG", "JPEG"})) {
117 // writing comment in case of jpeg (Qt ignores setText() in case of jpeg)
118 std::string com;
119 if (strcmp(comment, "") == 0) {
120 com = "Screenshot created by FreeCAD";
121 }
122 else if (strcmp(comment, "$MIBA") == 0) {
123 com = createMIBA(mat);
124 }
125 else {
126 com = comment;
127 }
128
129 // write into memory
130 QByteArray ba;
131 QBuffer buffer(&ba);
132 buffer.open(QIODevice::WriteOnly);
133 image.save(&buffer, "JPG", 90);
134 writeJPEGComment(com, ba);
135
136 QFile file(QString::fromUtf8(filename));
137 if (file.open(QFile::WriteOnly)) {
138 file.write(ba);
139 file.close();
140 }
141 else {
142 std::stringstream str;
143 str << "Cannot open file '" << filename << "' for writing.";
144 throw Base::FileSystemError(str.str());
145 }
146 }
147 else {
148 // check for all QImage formats
149 bool supported = false;
150 QByteArray format;
151 QList<QByteArray> qtformats = QImageWriter::supportedImageFormats();
152 for (const auto& it : qtformats) {
153 if (file.hasExtension(it.data())) {
154 format = it;
155 supported = true;
156 break;
157 }
158 }
159
160 // Supported by Qt
161 if (supported) {
162 QImage img = image;
163 // set keywords for PNG format
164 if (file.hasExtension("PNG")) {
165 img.setText(QLatin1String("Title"), QString::fromUtf8(filename));
166 img.setText(QLatin1String("Author"), QLatin1String("FreeCAD (https://www.freecad.org)"));
167 if (strcmp(comment, "") == 0) {
168 img.setText(
169 QLatin1String("Description"),
170 QLatin1String("Screenshot created by FreeCAD")
171 );
172 }
173 else if (strcmp(comment, "$MIBA") == 0) {
174 img.setText(QLatin1String("Description"), QLatin1String(createMIBA(mat).c_str()));
175 }
176 else {
177 img.setText(QLatin1String("Description"), QString::fromUtf8(comment));
178 }
179 img.setText(QLatin1String("Creation Time"), QDateTime::currentDateTime().toString());
180 img.setText(
181 QLatin1String("Software"),
182 QString::fromStdString(App::Application::getExecutableName())
183 );
184 }
185
186 QFile f(QString::fromUtf8(filename));
187 if (f.open(QFile::WriteOnly)) {
188 if (img.save(&f, format.data())) {
189 f.close();
190 }
191 else {
192 f.close();
193 std::stringstream str;
194 str << "Cannot save image to file '" << filename << "'.";
195 throw Base::ValueError(str.str());
196 }
197 }
198 else {
199 std::stringstream str;
200 str << "Cannot open file '" << filename << "' for writing.";
201 Base::FileException e;
202 e.setMessage(str.str());
203 throw e;
204 }
205 }
206 //
207 // Use internal buffer instead of QImage
208 //
209 else if (isWriteSupported(file.extension().c_str())) {
210 // Any format which is supported by Coin only
211 if (!writeToFile(filename, file.extension().c_str())) {
212 throw Base::FileException("Error writing image file", filename);
213 }
214 }
215 else if (file.hasExtension({"EPS", "PS"})) {
216 // Any format which is supported by Coin only
217 #ifdef FC_OS_WIN32
218 FILE* fd = _wfopen(file.toStdWString().c_str(), L"w");
219 #else
220 FILE* fd = fopen(filename, "w");
221 #endif
222 bool ok = writeToPostScript(fd);
223 fclose(fd);
224 if (!ok) {
225 throw Base::FileException("Error writing image file", filename);
226 }
227 }
228 else if (file.hasExtension({"RGB", "SGI"})) {
229 // Any format which is supported by Coin only
230 #ifdef FC_OS_WIN32
231 FILE* fd = _wfopen(file.toStdWString().c_str(), L"w");
232 #else
233 FILE* fd = fopen(filename, "w");
234 #endif
235 bool ok = writeToRGB(fd);
236 fclose(fd);
237 if (!ok) {
238 throw Base::FileException("Error writing image file", filename);
239 }
240 }
241 }
242 }
243
244 QStringList SoFCOffscreenRenderer::getWriteImageFiletypeInfo()
245 {
246 QStringList formats;
247
248 // get all supported formats by Coin3D
249 int num = getNumWriteFiletypes();
250 for (int i = 0; i < num; i++) {
251
252 SbPList extlist;
253
254 SbString fullname, description;
255 getWriteFiletypeInfo(i, extlist, fullname, description);
256
257 for (int j = 0; j < extlist.getLength(); j++) {
258 QString ext = QLatin1String((const char*)extlist[j]);
259 if (formats.indexOf(ext.toUpper()) == -1) {
260 formats << ext.toUpper();
261 }
262 }
263 }
264
265 // add now all further QImage formats
266 QList<QByteArray> qtformats = QImageWriter::supportedImageFormats();
267 for (const auto& it : qtformats) {
268 // not supported? then append
269 if (!isWriteSupported(it.data()) && formats.indexOf(QLatin1String(it)) == -1) {
270 formats << QLatin1String(it);
271 }
272 }
273
274 // now add PostScript and SGI RGB
275 if (formats.indexOf(QLatin1String("EPS")) == -1) {
276 formats << QLatin1String("EPS");
277 }
278 else if (formats.indexOf(QLatin1String("SGI")) == -1) {
279 formats << QLatin1String("SGI");
280 }
281
282 formats.sort();
283
284 return formats;
285 }
286
287 std::string SoFCOffscreenRenderer::createMIBA(const SbMatrix& mat) const
288 {
289 std::stringstream com;
290 const std::map<std::string, std::string>& cfg = App::Application::Config();
291 std::map<std::string, std::string>::const_iterator it;
292 it = cfg.find("BuildVersionMajor");
293 std::string major = (it != cfg.end() ? it->second : "");
294 it = cfg.find("BuildVersionMinor");
295 std::string minor = (it != cfg.end() ? it->second : "");
296
297 com << setw(7) << setfill(' ') << fixed;
298 com << "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";
299 com << "<MIBA xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
300 "xsi:noNamespaceSchemaLocation=\"http://juergen-riegel.net/Miba/Miba2.xsd\" "
301 "Version=\"2\"> \n";
302 com << " <View>\n";
303 com << " <Matrix \n";
304 com << " a11=\"" << mat[0][0] << "\" a12=\"" << mat[1][0] << "\" a13=\"" << mat[2][0]
305 << "\" a14=\"" << mat[3][0] << "\"\n";
306 com << " a21=\"" << mat[0][1] << "\" a22=\"" << mat[1][1] << "\" a23=\"" << mat[2][1]
307 << "\" a24=\"" << mat[3][1] << "\"\n";
308 com << " a31=\"" << mat[0][2] << "\" a32=\"" << mat[1][2] << "\" a33=\"" << mat[2][2]
309 << "\" a34=\"" << mat[3][2] << "\"\n";
310 com << " a41=\"" << mat[0][3] << "\" a42=\"" << mat[1][3] << "\" a43=\"" << mat[2][3]
311 << "\" a44=\"" << mat[3][3] << "\"\n";
312 com << " />\n";
313 com << " </View>\n";
314 com << " <Source>\n";
315 com << " <Creator>Unknown</Creator>\n";
316 com << " <CreationDate>" << QDateTime::currentDateTime().toString().toLatin1().constData()
317 << "</CreationDate>\n";
318 com << " <CreatingSystem>" << App::Application::getExecutableName() << " " << major << "."
319 << minor << "</CreatingSystem>\n";
320 com << " <PartNumber>Unknown</PartNumber>\n";
321 com << " <Revision>1.0</Revision>\n";
322 com << " </Source>\n";
323 com << "</MIBA>\n";
324
325 return com.str();
326 }
327
328 void writeJPEGComment(const std::string& comment, QByteArray& ba)
329 {
330 const unsigned char M_SOF0 = 0xc0;
331 const unsigned char M_SOF1 = 0xc1;
332 const unsigned char M_SOF2 = 0xc2;
333 const unsigned char M_SOF3 = 0xc3;
334 const unsigned char M_SOF5 = 0xc5;
335 const unsigned char M_SOF6 = 0xc6;
336 const unsigned char M_SOF7 = 0xc7;
337 const unsigned char M_SOF9 = 0xc9;
338 const unsigned char M_SOF10 = 0xcA;
339 const unsigned char M_SOF11 = 0xcb;
340 const unsigned char M_SOF13 = 0xcd;
341 const unsigned char M_SOF14 = 0xce;
342 const unsigned char M_SOF15 = 0xcf;
343 const unsigned char M_SOI = 0xd8;
344 const unsigned char M_EOI = 0xd9;
345 const unsigned char M_COM = 0xfe;
346
347 class Byte
348 {
349 char c {};
350 unsigned char u {};
351
352 public:
353 void setc(char v)
354 {
355 c = v;
356 std::memcpy(&u, &c, sizeof(u));
357 }
358 void setu(unsigned char v)
359 {
360 u = v;
361 std::memcpy(&c, &u, sizeof(c));
362 }
363 char getc() const
364 {
365 return c;
366 }
367 unsigned char getu() const
368 {
369 return u;
370 }
371 };
372
373 if (comment.empty() || ba.length() < 2) {
374 return;
375 }
376
377 // first marker
378 Byte a, b;
379 a.setc(ba[0]);
380 b.setc(ba[1]);
381 if (a.getu() == 0xff && b.getu() == M_SOI) {
382 int index = 2;
383 int len = ba.length();
384 while (index < len) {
385 // next marker
386 a.setc(ba[index++]);
387 while (a.getu() != 0xff && index < len) {
388 a.setc(ba[index++]);
389 }
390 do {
391 b.setc(ba[index++]);
392 } while (b.getu() == 0xff && index < len);
393 switch (b.getu()) {
394 case M_SOF0:
395 case M_SOF1:
396 case M_SOF2:
397 case M_SOF3:
398 case M_SOF5:
399 case M_SOF6:
400 case M_SOF7:
401 case M_SOF9:
402 case M_SOF10:
403 case M_SOF11:
404 case M_SOF13:
405 case M_SOF14:
406 case M_SOF15:
407 case M_EOI: {
408 Byte a, b;
409 a.setu(0xff);
410 b.setu(M_COM);
411 index -= 2; // insert comment before marker
412 ba.insert(index++, a.getc());
413 ba.insert(index++, b.getc());
414 int val = comment.size() + 2;
415 ba.insert(index++, (val >> 8) & 0xff);
416 ba.insert(index++, val & 0xff);
417 ba.insert(index, comment.c_str());
418 index = len; // finished
419 } break;
420 case M_COM:
421 default: {
422 Byte a, b;
423 a.setc(ba[index++]);
424 b.setc(ba[index++]);
425 int off = ((unsigned int)a.getu() << 8) + (unsigned int)b.getu();
426 index += off;
427 index -= 2; // next marker
428 } break;
429 }
430 }
431 }
432 }
433
434 // ---------------------------------------------------------------
435
436 #define PRIVATE(p) p
437 #define PUBLIC(p) p
438
439 void SoQtOffscreenRenderer::init(const SbViewportRegion& vpr, SoGLRenderAction* glrenderaction)
440 {
441 this->backgroundcolor.setValue(0, 0, 0);
442
443 if (glrenderaction) {
444 this->renderaction = glrenderaction;
445 }
446 else {
447 this->renderaction = new SoGLRenderAction(vpr);
448 this->renderaction->setCacheContext(SoGLCacheContextElement::getUniqueCacheContext());
449 this->renderaction->setTransparencyType(SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND);
450 }
451
452 this->didallocation = glrenderaction ? false : true;
453 this->viewport = vpr; // clazy:exclude=rule-of-two-soft
454
455 this->framebuffer = nullptr;
456 this->numSamples = -1;
457 // this->texFormat = GL_RGBA32F_ARB;
458 this->texFormat = GL_RGB32F_ARB;
459 this->cache_context = 0;
460 }
461
462 /*!
463 Constructor. Argument is the \a viewportregion we should use when
464 rendering. An internal SoGLRenderAction will be constructed.
465 */
466 SoQtOffscreenRenderer::SoQtOffscreenRenderer(const SbViewportRegion& viewportregion)
467 {
468 init(viewportregion);
469 }
470
471 /*!
472 Constructor. Argument is the \a action we should apply to the
473 scene graph when rendering the scene. Information about the
474 viewport is extracted from the \a action.
475 */
476 SoQtOffscreenRenderer::SoQtOffscreenRenderer(SoGLRenderAction* action)
477 {
478 init(action->getViewportRegion(), action);
479 }
480
481 /*!
482 Destructor.
483 */
484 SoQtOffscreenRenderer::~SoQtOffscreenRenderer()
485 {
486 delete framebuffer;
487
488 if (this->didallocation) {
489 delete this->renderaction;
490 }
491 }
492
493 /*!
494 Sets the viewport region.
495
496 This will invalidate the current buffer, if any. The buffer will not
497 contain valid data until another call to
498 SoOffscreenRendererQt::render() happens.
499 */
500 void SoQtOffscreenRenderer::setViewportRegion(const SbViewportRegion& region)
501 {
502 PRIVATE(this)->viewport = region; // clazy:exclude=rule-of-two-soft
503 }
504
505 /*!
506 Returns the viewerport region.
507 */
508 const SbViewportRegion& SoQtOffscreenRenderer::getViewportRegion() const
509 {
510 return PRIVATE(this)->viewport;
511 }
512
513 /*!
514 Sets the background color. The buffer is cleared to this color
515 before rendering.
516 */
517 void SoQtOffscreenRenderer::setBackgroundColor(const SbColor4f& color)
518 {
519 PRIVATE(this)->backgroundcolor = color;
520 PRIVATE(this)->backgroundopaque = color;
521 if (color[3] < 1.0) {
522 PRIVATE(this)->backgroundopaque.setValue(1, 1, 1, 1);
523 }
524 }
525
526 /*!
527 Returns the background color.
528 */
529 const SbColor4f& SoQtOffscreenRenderer::getBackgroundColor() const
530 {
531 return PRIVATE(this)->backgroundcolor;
532 }
533
534 /*!
535 Sets the render action. Use this if you have special rendering needs.
536 */
537 void SoQtOffscreenRenderer::setGLRenderAction(SoGLRenderAction* action)
538 {
539 if (action == PRIVATE(this)->renderaction) {
540 return;
541 }
542
543 if (PRIVATE(this)->didallocation) {
544 delete PRIVATE(this)->renderaction;
545 }
546 PRIVATE(this)->renderaction = action;
547 PRIVATE(this)->didallocation = false;
548 }
549
550 /*!
551 Returns the rendering action currently used.
552 */
553 SoGLRenderAction* SoQtOffscreenRenderer::getGLRenderAction() const
554 {
555 return PRIVATE(this)->renderaction;
556 }
557
558 void SoQtOffscreenRenderer::setNumPasses(const int num)
559 {
560 PRIVATE(this)->numSamples = num;
561 }
562
563 int SoQtOffscreenRenderer::getNumPasses() const
564 {
565 return PRIVATE(this)->numSamples;
566 }
567
568 void SoQtOffscreenRenderer::setInternalTextureFormat(GLenum internalTextureFormat)
569 {
570 PRIVATE(this)->texFormat = internalTextureFormat;
571 }
572
573 GLenum SoQtOffscreenRenderer::internalTextureFormat() const
574 {
575 return PRIVATE(this)->texFormat;
576 }
577
578 // *************************************************************************
579
580 void SoQtOffscreenRenderer::pre_render_cb(void* /*userdata*/, SoGLRenderAction* action)
581 {
582 glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
583 action->setRenderingIsRemote(false);
584 }
585
586 void SoQtOffscreenRenderer::makeFrameBuffer(int width, int height, int samples)
587 {
588 if (framebuffer) {
589 delete framebuffer;
590 framebuffer = nullptr;
591 }
592
593 viewport.setWindowSize(width, height);
594
595 QOpenGLFramebufferObjectFormat fmt;
596 fmt.setSamples(samples);
597 fmt.setAttachment(QOpenGLFramebufferObject::Depth);
598 // With enabled alpha a transparent background is supported but
599 // at the same time breaks semi-transparent models. A workaround
600 // is to use a certain background color using GL_RGB as texture
601 // format and in the output image search for the above color and
602 // replaces it with the color requested by the user.
603 fmt.setInternalTextureFormat(this->texFormat);
604
605 framebuffer = new QOpenGLFramebufferObject(width, height, fmt);
606 cache_context = SoGLCacheContextElement::getUniqueCacheContext(); // unique per pixel buffer
607 // object, just to be sure
608 }
609
610 SbBool SoQtOffscreenRenderer::renderFromBase(SoBase* base)
611 {
612 const SbVec2s fullsize = this->viewport.getViewportSizePixels();
613
614 QSurfaceFormat format;
615 format.setSamples(PRIVATE(this)->numSamples);
616 QOpenGLContext context;
617 context.setFormat(format);
618 if (!context.create()) {
619 return false;
620 }
621 QOffscreenSurface offscreen;
622 offscreen.setFormat(format);
623 offscreen.create();
624 context.makeCurrent(&offscreen);
625
626 if (!framebuffer) {
627 makeFrameBuffer(fullsize[0], fullsize[1], PRIVATE(this)->numSamples);
628 }
629 else if (framebuffer->width() != fullsize[0] || framebuffer->height() != fullsize[1]) {
630 // get the size right!
631 makeFrameBuffer(fullsize[0], fullsize[1], PRIVATE(this)->numSamples);
632 }
633
634 framebuffer->bind(); // activate us!
635
636 // oldcontext is used to restore the previous context id, in case
637 // the render action is not allocated by us.
638 const uint32_t oldcontext = this->renderaction->getCacheContext();
639 this->renderaction->setCacheContext(cache_context);
640
641 glEnable(GL_DEPTH_TEST);
642 glClearColor(
643 this->backgroundopaque[0],
644 this->backgroundopaque[1],
645 this->backgroundopaque[2],
646 this->backgroundopaque[3]
647 );
648
649 // needed to clear viewport after glViewport() is called from
650 // SoGLRenderAction
651 this->renderaction->addPreRenderCallback(pre_render_cb, nullptr);
652 this->renderaction->setViewportRegion(this->viewport);
653
654 if (base->isOfType(SoNode::getClassTypeId())) {
655 this->renderaction->apply((SoNode*)base);
656 }
657 else if (base->isOfType(SoPath::getClassTypeId())) {
658 this->renderaction->apply((SoPath*)base);
659 }
660 else {
661 assert(false && "Cannot apply to anything else than an SoNode or an SoPath");
662 }
663
664 this->renderaction->removePreRenderCallback(pre_render_cb, nullptr);
665 framebuffer->release();
666
667 this->renderaction->setCacheContext(oldcontext); // restore old
668
669 glImage = framebuffer->toImage();
670 context.doneCurrent();
671
672 return true;
673 }
674
675 /*!
676 Render the scenegraph rooted at \a scene into our internal pixel
677 buffer.
678
679 Important note: make sure you pass in a \a scene node pointer which
680 has both a camera and at least one lightsource below it -- otherwise
681 you are likely to end up with just a blank or black image buffer.
682
683 This mistake is easily made if you use an SoQtOffscreenRenderer on a
684 scenegraph from one of the standard viewer components, as you will
685 often just leave the addition of a camera and a headlight
686 lightsource to the viewer to set up. This camera and lightsource are
687 then part of the viewer's private "super-graph" outside of the scope
688 of the scenegraph passed in by the application programmer. To make
689 sure the complete scenegraph (including the viewer's "private parts"
690 (*snicker*)) are passed to this method, you can get the scenegraph
691 root from the viewer's internal SoSceneManager instance instead of
692 from the viewer's own getSceneGraph() method, like this:
693
694 \code
695 SoQtOffscreenRenderer * myRenderer = new SoQtOffscreenRenderer(vpregion);
696 SoNode * root = myViewer->getSceneManager()->getSceneGraph();
697 SbBool ok = myRenderer->render(root);
698 // [then use image buffer in a texture, or write it to file, or whatever]
699 \endcode
700
701 If you do this and still get a blank buffer, another common problem
702 is to have a camera which is not actually pointing at the scene
703 geometry you want a snapshot of. If you suspect that could be the
704 cause of problems on your end, take a look at SoCamera::pointAt()
705 and SoCamera::viewAll() to see how you can make a camera node
706 guaranteed to be directed at the scene geometry.
707
708 Yet another common mistake when setting up the camera is to specify
709 values for the SoCamera::nearDistance and SoCamera::farDistance
710 fields which doesn't not enclose the full scene. This will result in
711 either just the background color, or that parts at the front or the
712 back of the scene will not be visible in the rendering.
713
714 \sa writeToImage()
715 */
716 SbBool SoQtOffscreenRenderer::render(SoNode* scene)
717 {
718 return PRIVATE(this)->renderFromBase(scene);
719 }
720
721 /*!
722 Render the \a scene path into our internal memory buffer.
723 */
724 SbBool SoQtOffscreenRenderer::render(SoPath* scene)
725 {
726 return PRIVATE(this)->renderFromBase(scene);
727 }
728
729 /*!
730 Writes the rendered image buffer directly into a QImage object.
731 */
732 void SoQtOffscreenRenderer::writeToImage(QImage& img) const
733 {
734 img = this->glImage;
735 if (PRIVATE(this)->backgroundcolor[3] < 1.0) {
736 QColor c1, c2;
737 c1.setRedF(PRIVATE(this)->backgroundcolor[0]);
738 c1.setGreenF(PRIVATE(this)->backgroundcolor[1]);
739 c1.setBlueF(PRIVATE(this)->backgroundcolor[2]);
740 c1.setAlphaF(PRIVATE(this)->backgroundcolor[3]);
741 c2.setRedF(PRIVATE(this)->backgroundopaque[0]);
742 c2.setGreenF(PRIVATE(this)->backgroundopaque[1]);
743 c2.setBlueF(PRIVATE(this)->backgroundopaque[2]);
744 c2.setAlphaF(PRIVATE(this)->backgroundopaque[3]);
745
746 QImage image(img.constBits(), img.width(), img.height(), QImage::Format_ARGB32);
747 img = image.copy();
748 QRgb rgba = c1.rgba();
749 QRgb rgb = c2.rgb();
750 QRgb* bits = (QRgb*)img.bits();
751 int height = img.height();
752 int width = img.width();
753 for (int y = 0; y < height; y++) {
754 for (int x = 0; x < width; x++) {
755 if (*bits == rgb) {
756 *bits = rgba;
757 }
758 bits++;
759 }
760 }
761 }
762 }
763
764 /*!
765 This method returns all image file formats supported by Coin3D (see getWriteFiletypeInfo()) with
766 all QImage file formats that are not directly supported by Coin3D, if so.
767 */
768 QStringList SoQtOffscreenRenderer::getWriteImageFiletypeInfo() const
769 {
770 QList<QByteArray> qtformats = QImageWriter::supportedImageFormats();
771
772 QStringList formats;
773 for (const auto& it : qtformats) {
774 formats << QLatin1String(it);
775 }
776 formats.sort();
777 return formats;
778 }
779
780 #undef PRIVATE
781 #undef PUBLIC