1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_View.hxx>
18 #include <Aspect_RenderingContext.hxx>
19 #include <Aspect_Window.hxx>
20 #include <Aspect_XRSession.hxx>
21 #include <Graphic3d_AspectFillArea3d.hxx>
22 #include <Graphic3d_Texture2Dmanual.hxx>
23 #include <Graphic3d_TextureEnv.hxx>
24 #include <Graphic3d_Mat4d.hxx>
25 #include <Image_AlienPixMap.hxx>
26 #include <OpenGl_ArbFBO.hxx>
27 #include <OpenGl_BackgroundArray.hxx>
28 #include <OpenGl_Context.hxx>
29 #include <OpenGl_DepthPeeling.hxx>
30 #include <OpenGl_FrameBuffer.hxx>
31 #include <OpenGl_GlCore11.hxx>
32 #include <OpenGl_GraduatedTrihedron.hxx>
33 #include <OpenGl_GraphicDriver.hxx>
34 #include <OpenGl_ShaderManager.hxx>
35 #include <OpenGl_ShadowMap.hxx>
36 #include <OpenGl_Texture.hxx>
37 #include <OpenGl_Window.hxx>
38 #include <OpenGl_Workspace.hxx>
39 #include <OSD_Parallel.hxx>
40 #include <Standard_CLocaleSentry.hxx>
42 #include "../Graphic3d/Graphic3d_Structure.pxx"
43 #include "../Textures/Textures_EnvLUT.pxx"
47 //! Format Frame Buffer format for logging messages.
48 static TCollection_AsciiString printFboFormat (const Handle(OpenGl_FrameBuffer)& theFbo)
50 return TCollection_AsciiString() + theFbo->GetInitVPSizeX() + "x" + theFbo->GetInitVPSizeY() + "@" + theFbo->NbSamples();
53 //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
54 static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
55 Standard_Integer theSizeX,
56 Standard_Integer theSizeY,
57 Standard_Integer theNbSamples)
59 return !theFboToCheck->IsValid()
60 && theFboToCheck->GetInitVPSizeX() == theSizeX
61 && theFboToCheck->GetInitVPSizeY() == theSizeY
62 && theFboToCheck->NbSamples() == theNbSamples;
65 //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
66 static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
67 const Handle(OpenGl_FrameBuffer)& theFboRef)
69 return checkWasFailedFbo (theFboToCheck, theFboRef->GetVPSizeX(), theFboRef->GetVPSizeY(), theFboRef->NbSamples());
72 //! Chooses compatible internal color format for OIT frame buffer.
73 static bool chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
74 const Standard_Integer theConfigIndex,
75 OpenGl_ColorFormats& theFormats)
78 switch (theConfigIndex)
80 case 0: // choose best applicable color format combination
82 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
83 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_R16F : GL_R32F);
86 case 1: // choose non-optimal applicable color format combination
88 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
89 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
93 return false; // color combination does not exist
97 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView)
99 // =======================================================================
100 // function : Constructor
102 // =======================================================================
103 OpenGl_View::OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
104 const Handle(OpenGl_GraphicDriver)& theDriver,
105 const Handle(OpenGl_Caps)& theCaps,
106 OpenGl_StateCounter* theCounter)
107 : Graphic3d_CView (theMgr),
108 myDriver (theDriver.operator->()),
110 myWasRedrawnGL (Standard_False),
111 myToShowGradTrihedron (false),
112 myZLayers (Structure_MAX_PRIORITY - Structure_MIN_PRIORITY + 1),
113 myStateCounter (theCounter),
114 myCurrLightSourceState (theCounter->Increment()),
115 myLightsRevision (0),
116 myLastLightSourceState (0, 0),
118 myFboColorFormat (GL_SRGB8_ALPHA8), // note that GL_SRGB8 is not required to be renderable, unlike GL_RGB8, GL_RGBA8, GL_SRGB8_ALPHA8
119 myFboDepthFormat (GL_DEPTH24_STENCIL8),
120 myToFlipOutput (Standard_False),
123 myHasFboBlit (Standard_True),
124 myToDisableOIT (Standard_False),
125 myToDisableOITMSAA (Standard_False),
126 myToDisableMSAA (Standard_False),
127 myTransientDrawToFront (Standard_True),
128 myBackBufferRestored (Standard_False),
129 myIsImmediateDrawn (Standard_False),
130 myTextureParams (new OpenGl_Aspects()),
131 myCubeMapParams (new OpenGl_Aspects()),
132 myPBREnvState (OpenGl_PBREnvState_NONEXISTENT),
133 myPBREnvRequest (Standard_False),
134 // ray-tracing fields initialization
135 myRaytraceInitStatus (OpenGl_RT_NONE),
136 myIsRaytraceDataValid (Standard_False),
137 myIsRaytraceWarnTextures (Standard_False),
138 myRaytraceBVHBuilder (new BVH_BinnedBuilder<Standard_ShortReal, 3, BVH_Constants_NbBinsBest> (BVH_Constants_LeafNodeSizeAverage,
139 BVH_Constants_MaxTreeDepth,
141 OSD_Parallel::NbLogicalProcessors() + 1)),
142 myRaytraceSceneRadius (0.0f),
143 myRaytraceSceneEpsilon (1.0e-6f),
144 myToUpdateEnvironmentMap (Standard_False),
145 myRaytraceLayerListState (0),
146 myPrevCameraApertureRadius(0.f),
147 myPrevCameraFocalPlaneDist(0.f)
149 for (int i = 0; i < Graphic3d_TypeOfBackground_NB; ++i)
151 myBackgrounds[i] = new OpenGl_BackgroundArray(Graphic3d_TypeOfBackground(i));
154 myWorkspace = new OpenGl_Workspace (this, NULL);
156 Handle(Graphic3d_CLight) aLight = new Graphic3d_CLight (Graphic3d_TypeOfLightSource_Ambient);
157 aLight->SetColor (Quantity_NOC_WHITE);
158 myLights = new Graphic3d_LightSet();
159 myNoShadingLight = new Graphic3d_LightSet();
160 myNoShadingLight->Add (aLight);
162 myMainSceneFbos[0] = new OpenGl_FrameBuffer();
163 myMainSceneFbos[1] = new OpenGl_FrameBuffer();
164 myMainSceneFbosOit[0] = new OpenGl_FrameBuffer();
165 myMainSceneFbosOit[1] = new OpenGl_FrameBuffer();
166 myImmediateSceneFbos[0] = new OpenGl_FrameBuffer();
167 myImmediateSceneFbos[1] = new OpenGl_FrameBuffer();
168 myImmediateSceneFbosOit[0] = new OpenGl_FrameBuffer();
169 myImmediateSceneFbosOit[1] = new OpenGl_FrameBuffer();
170 myXrSceneFbo = new OpenGl_FrameBuffer();
171 myOpenGlFBO = new OpenGl_FrameBuffer();
172 myOpenGlFBO2 = new OpenGl_FrameBuffer();
173 myRaytraceFBO1[0] = new OpenGl_FrameBuffer();
174 myRaytraceFBO1[1] = new OpenGl_FrameBuffer();
175 myRaytraceFBO2[0] = new OpenGl_FrameBuffer();
176 myRaytraceFBO2[1] = new OpenGl_FrameBuffer();
177 myDepthPeelingFbos = new OpenGl_DepthPeeling();
178 myShadowMaps = new OpenGl_ShadowMapArray();
181 // =======================================================================
182 // function : Destructor
184 // =======================================================================
185 OpenGl_View::~OpenGl_View()
187 ReleaseGlResources (NULL); // ensure ReleaseGlResources() was called within valid context
188 for (int i = 0; i < Graphic3d_TypeOfBackground_NB; ++i)
190 OpenGl_Element::Destroy(NULL, myBackgrounds[i]);
193 OpenGl_Element::Destroy (NULL, myTextureParams);
194 OpenGl_Element::Destroy (NULL, myCubeMapParams);
197 // =======================================================================
198 // function : releaseSrgbResources
200 // =======================================================================
201 void OpenGl_View::releaseSrgbResources (const Handle(OpenGl_Context)& theCtx)
203 myRenderParams.RebuildRayTracingShaders = true;
205 if (!myTextureEnv.IsNull())
207 if (!theCtx.IsNull())
209 for (OpenGl_TextureSet::Iterator aTextureIter (myTextureEnv); aTextureIter.More(); aTextureIter.Next())
211 theCtx->DelayedRelease (aTextureIter.ChangeValue());
212 aTextureIter.ChangeValue().Nullify();
215 myTextureEnv.Nullify();
218 if (myTextureParams != NULL)
220 myTextureParams->Release (theCtx.get());
223 if (myCubeMapParams != NULL)
225 myCubeMapParams->Release (theCtx.get());
228 for (int i = 0; i < Graphic3d_TypeOfBackground_NB; ++i)
230 if (myBackgrounds[i] != NULL)
232 myBackgrounds[i]->Release (theCtx.get());
236 myMainSceneFbos[0] ->Release (theCtx.get());
237 myMainSceneFbos[1] ->Release (theCtx.get());
238 myMainSceneFbosOit[0] ->Release (theCtx.get());
239 myMainSceneFbosOit[1] ->Release (theCtx.get());
240 myImmediateSceneFbos[0] ->Release (theCtx.get());
241 myImmediateSceneFbos[1] ->Release (theCtx.get());
242 myImmediateSceneFbosOit[0]->Release (theCtx.get());
243 myImmediateSceneFbosOit[1]->Release (theCtx.get());
244 myXrSceneFbo ->Release (theCtx.get());
245 myDepthPeelingFbos ->Release (theCtx.get());
246 myOpenGlFBO ->Release (theCtx.get());
247 myOpenGlFBO2 ->Release (theCtx.get());
248 myFullScreenQuad .Release (theCtx.get());
249 myFullScreenQuadFlip .Release (theCtx.get());
250 myShadowMaps->Release (theCtx.get());
252 // Technically we should also re-initialize all sRGB/RGB8 color textures.
253 // But for now consider this sRGB disabling/enabling to be done at application start-up
254 // and re-create dynamically only frame buffers.
257 // =======================================================================
258 // function : ReleaseGlResources
260 // =======================================================================
261 void OpenGl_View::ReleaseGlResources (const Handle(OpenGl_Context)& theCtx)
263 myGraduatedTrihedron.Release (theCtx.get());
264 myFrameStatsPrs.Release (theCtx.get());
266 releaseSrgbResources (theCtx);
268 releaseRaytraceResources (theCtx);
270 if (!myPBREnvironment.IsNull())
272 myPBREnvironment->Release (theCtx.get());
277 // =======================================================================
280 // =======================================================================
281 void OpenGl_View::Remove()
288 myDriver->RemoveView (this);
291 Graphic3d_CView::Remove();
294 // =======================================================================
295 // function : SetLocalOrigin
297 // =======================================================================
298 void OpenGl_View::SetLocalOrigin (const gp_XYZ& theOrigin)
300 myLocalOrigin = theOrigin;
301 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
304 aCtx->ShaderManager()->SetLocalOrigin (theOrigin);
308 // =======================================================================
309 // function : SetTextureEnv
311 // =======================================================================
312 void OpenGl_View::SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv)
314 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
315 if (!aCtx.IsNull() && !myTextureEnv.IsNull())
317 for (OpenGl_TextureSet::Iterator aTextureIter (myTextureEnv); aTextureIter.More(); aTextureIter.Next())
319 aCtx->DelayedRelease (aTextureIter.ChangeValue());
320 aTextureIter.ChangeValue().Nullify();
324 myToUpdateEnvironmentMap = Standard_True;
325 myTextureEnvData = theTextureEnv;
326 myTextureEnv.Nullify();
327 initTextureEnv (aCtx);
330 // =======================================================================
331 // function : initTextureEnv
333 // =======================================================================
334 void OpenGl_View::initTextureEnv (const Handle(OpenGl_Context)& theContext)
336 if (myTextureEnvData.IsNull()
337 || theContext.IsNull()
338 || !theContext->MakeCurrent())
343 Handle(OpenGl_Texture) aTextureEnv = new OpenGl_Texture (myTextureEnvData->GetId(), myTextureEnvData->GetParams());
344 if (Handle(Image_PixMap) anImage = myTextureEnvData->GetImage (theContext->SupportedTextureFormats()))
346 aTextureEnv->Init (theContext, *anImage, myTextureEnvData->Type(), true);
348 myTextureEnv = new OpenGl_TextureSet (aTextureEnv);
349 myTextureEnv->ChangeTextureSetBits() = Graphic3d_TextureSetBits_BaseColor;
352 // =======================================================================
353 // function : SetImmediateModeDrawToFront
355 // =======================================================================
356 Standard_Boolean OpenGl_View::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
358 const Standard_Boolean aPrevMode = myTransientDrawToFront;
359 myTransientDrawToFront = theDrawToFrontBuffer;
363 // =======================================================================
366 // =======================================================================
367 Handle(Aspect_Window) OpenGl_View::Window() const
369 return myWindow->PlatformWindow();
372 // =======================================================================
373 // function : SetWindow
375 // =======================================================================
376 void OpenGl_View::SetWindow (const Handle(Aspect_Window)& theWindow,
377 const Aspect_RenderingContext theContext)
379 myWindow = myDriver->CreateRenderWindow (theWindow, theContext);
380 Standard_ASSERT_RAISE (!myWindow.IsNull(),
381 "OpenGl_View::SetWindow, "
382 "Failed to create OpenGl window.");
384 myWorkspace = new OpenGl_Workspace (this, myWindow);
385 myWorldViewProjState.Reset();
386 myToUpdateEnvironmentMap = Standard_True;
387 myHasFboBlit = Standard_True;
390 // Environment texture resource does not support lazy initialization.
391 initTextureEnv (myWorkspace->GetGlContext());
394 // =======================================================================
395 // function : Resized
397 // =======================================================================
398 void OpenGl_View::Resized()
400 if (myWindow.IsNull())
406 // =======================================================================
407 // function : SetMinMaxValuesCallback
409 // =======================================================================
410 static void SetMinMaxValuesCallback (Graphic3d_CView* theView)
412 OpenGl_View* aView = dynamic_cast<OpenGl_View*>(theView);
416 Bnd_Box aBox = theView->MinMaxValues();
419 gp_Pnt aMin = aBox.CornerMin();
420 gp_Pnt aMax = aBox.CornerMax();
422 Graphic3d_Vec3 aMinVec ((Standard_ShortReal )aMin.X(), (Standard_ShortReal )aMin.Y(), (Standard_ShortReal )aMin.Z());
423 Graphic3d_Vec3 aMaxVec ((Standard_ShortReal )aMax.X(), (Standard_ShortReal )aMax.Y(), (Standard_ShortReal )aMax.Z());
424 aView->GraduatedTrihedronMinMaxValues (aMinVec, aMaxVec);
428 // =======================================================================
429 // function : GraduatedTrihedronDisplay
431 // =======================================================================
432 void OpenGl_View::GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData)
434 myGTrihedronData = theTrihedronData;
435 myGTrihedronData.SetCubicAxesCallback (SetMinMaxValuesCallback);
436 myGraduatedTrihedron.SetValues (myGTrihedronData);
437 myToShowGradTrihedron = true;
440 // =======================================================================
441 // function : GraduatedTrihedronErase
443 // =======================================================================
444 void OpenGl_View::GraduatedTrihedronErase()
446 myGraduatedTrihedron.Release (myWorkspace->GetGlContext().operator->());
447 myToShowGradTrihedron = false;
450 // =======================================================================
451 // function : GraduatedTrihedronMinMaxValues
453 // =======================================================================
454 void OpenGl_View::GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax)
456 myGraduatedTrihedron.SetMinMax (theMin, theMax);
459 // =======================================================================
460 // function : BufferDump
462 // =======================================================================
463 Standard_Boolean OpenGl_View::BufferDump (Image_PixMap& theImage, const Graphic3d_BufferType& theBufferType)
465 if (theBufferType != Graphic3d_BT_RGB_RayTraceHdrLeft)
467 return myWorkspace->BufferDump(myFBO, theImage, theBufferType);
470 if (!myRaytraceParameters.AdaptiveScreenSampling)
472 return myWorkspace->BufferDump(myAccumFrames % 2 ? myRaytraceFBO2[0] : myRaytraceFBO1[0], theImage, theBufferType);
475 #if defined(GL_ES_VERSION_2_0)
478 if (theImage.Format() != Image_Format_RGBF)
483 const GLuint aW = myRaytraceOutputTexture[0]->SizeX();
484 const GLuint aH = myRaytraceOutputTexture[0]->SizeY();
485 if (aW / 3 != theImage.SizeX() || aH / 2 != theImage.SizeY())
490 std::vector<GLfloat> aValues;
493 aValues.resize (aW * aH);
495 catch (const std::bad_alloc&)
500 glBindTexture (GL_TEXTURE_RECTANGLE, myRaytraceOutputTexture[0]->TextureId());
501 glGetTexImage (GL_TEXTURE_RECTANGLE, 0, OpenGl_TextureFormat::Create<GLfloat, 1>().Format(), GL_FLOAT, &aValues[0]);
502 glBindTexture (GL_TEXTURE_RECTANGLE, 0);
503 for (unsigned int aRow = 0; aRow < aH; aRow += 2)
505 for (unsigned int aCol = 0; aCol < aW; aCol += 3)
507 float* anImageValue = theImage.ChangeValue<float[3]> ((aH - aRow) / 2 - 1, aCol / 3);
508 float aInvNbSamples = 1.f / aValues[aRow * aW + aCol + aW];
509 anImageValue[0] = aValues[aRow * aW + aCol] * aInvNbSamples;
510 anImageValue[1] = aValues[aRow * aW + aCol + 1] * aInvNbSamples;
511 anImageValue[2] = aValues[aRow * aW + aCol + 1 + aW] * aInvNbSamples;
519 // =======================================================================
520 // function : GradientBackground
522 // =======================================================================
523 Aspect_GradientBackground OpenGl_View::GradientBackground() const
525 Quantity_Color aColor1, aColor2;
526 aColor1.SetValues (myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0).r(),
527 myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0).g(),
528 myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0).b(), Quantity_TOC_RGB);
529 aColor2.SetValues (myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1).r(),
530 myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1).g(),
531 myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1).b(), Quantity_TOC_RGB);
532 return Aspect_GradientBackground (aColor1, aColor2, myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientFillMethod());
535 // =======================================================================
536 // function : SetGradientBackground
538 // =======================================================================
539 void OpenGl_View::SetGradientBackground (const Aspect_GradientBackground& theBackground)
541 Quantity_Color aColor1, aColor2;
542 theBackground.Colors (aColor1, aColor2);
543 myBackgrounds[Graphic3d_TOB_GRADIENT]->SetGradientParameters (aColor1, aColor2, theBackground.BgGradientFillMethod());
545 myBackgroundType = Graphic3d_TOB_GRADIENT;
548 // =======================================================================
549 // function : SetBackgroundImage
551 // =======================================================================
552 void OpenGl_View::SetBackgroundImage (const Handle(Graphic3d_TextureMap)& theTextureMap,
553 Standard_Boolean theToUpdatePBREnv)
555 Handle(Graphic3d_TextureMap) aNewMap = theTextureMap;
556 if (theTextureMap.IsNull()
557 || !theTextureMap->IsDone())
559 if (!theTextureMap.IsNull())
561 Message::SendFail ("Error: unable to set image background");
566 Handle(Graphic3d_CubeMap) aCubeMap = Handle(Graphic3d_CubeMap)::DownCast (aNewMap);
567 if (theToUpdatePBREnv)
569 // update PBR environment
570 const TCollection_AsciiString anIdOld = !myCubeMapIBL.IsNull()
571 ? myCubeMapIBL->GetId()
572 : TCollection_AsciiString();
573 const TCollection_AsciiString anIdNew = !aCubeMap.IsNull()
575 : TCollection_AsciiString();
576 if (anIdNew != anIdOld)
578 myPBREnvRequest = true;
580 myCubeMapIBL = aCubeMap;
583 if (aNewMap.IsNull())
585 if (myBackgroundType == Graphic3d_TOB_TEXTURE
586 || myBackgroundType == Graphic3d_TOB_CUBEMAP)
588 myBackgroundType = Graphic3d_TOB_NONE;
593 Handle(Graphic3d_AspectFillArea3d) anAspect = new Graphic3d_AspectFillArea3d();
594 Handle(Graphic3d_TextureSet) aTextureSet = new Graphic3d_TextureSet (aNewMap);
595 anAspect->SetInteriorStyle (Aspect_IS_SOLID);
596 anAspect->SetFaceCulling (Graphic3d_TypeOfBackfacingModel_DoubleSided);
597 anAspect->SetShadingModel (Graphic3d_TypeOfShadingModel_Unlit);
598 anAspect->SetTextureSet (aTextureSet);
599 anAspect->SetTextureMapOn (true);
601 if (Handle(Graphic3d_Texture2D) aTextureMap = Handle(Graphic3d_Texture2D)::DownCast (aNewMap))
603 myTextureParams->SetAspect (anAspect);
604 myBackgroundType = Graphic3d_TOB_TEXTURE;
605 myBackgroundImage = aTextureMap;
609 if (!aCubeMap.IsNull())
611 aCubeMap->SetMipmapsGeneration (Standard_True);
612 if (const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext())
614 anAspect->SetShaderProgram (aCtx->ShaderManager()->GetBgCubeMapProgram());
617 myCubeMapParams->SetAspect (anAspect);
619 const OpenGl_Aspects* anAspectsBackup = myWorkspace->SetAspects (myCubeMapParams);
620 myWorkspace->ApplyAspects();
621 myWorkspace->SetAspects (anAspectsBackup);
622 myWorkspace->ApplyAspects();
624 myBackgroundType = Graphic3d_TOB_CUBEMAP;
625 myCubeMapBackground = aCubeMap;
629 throw Standard_ProgramError ("OpenGl_View::SetBackgroundImage() - invalid texture map set for background");
632 // =======================================================================
633 // function : SetImageBasedLighting
635 // =======================================================================
636 void OpenGl_View::SetImageBasedLighting (Standard_Boolean theToEnableIBL)
639 || myBackgroundType != Graphic3d_TOB_CUBEMAP)
641 if (!myCubeMapIBL.IsNull())
643 myPBREnvRequest = true;
644 myCubeMapIBL.Nullify();
649 const TCollection_AsciiString anIdOld = !myCubeMapIBL.IsNull()
650 ? myCubeMapIBL->GetId()
651 : TCollection_AsciiString();
652 const TCollection_AsciiString anIdNew = !myCubeMapBackground.IsNull()
653 ? myCubeMapBackground->GetId()
654 : TCollection_AsciiString();
655 if (anIdNew != anIdOld)
657 myPBREnvRequest = true;
659 myCubeMapIBL = myCubeMapBackground;
662 // =======================================================================
663 // function : BackgroundImageStyle
665 // =======================================================================
666 Aspect_FillMethod OpenGl_View::BackgroundImageStyle() const
668 return myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod();
671 // =======================================================================
672 // function : SetBackgroundImageStyle
674 // =======================================================================
675 void OpenGl_View::SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle)
677 myBackgrounds[Graphic3d_TOB_TEXTURE]->SetTextureFillMethod (theFillStyle);
680 // =======================================================================
681 // function : SpecIBLMapLevels
683 // =======================================================================
684 unsigned int OpenGl_View::SpecIBLMapLevels() const
686 return myPBREnvironment.IsNull() ? 0 : myPBREnvironment->SpecMapLevelsNumber();
689 //=======================================================================
690 //function : InsertLayerBefore
692 //=======================================================================
693 void OpenGl_View::InsertLayerBefore (const Graphic3d_ZLayerId theLayerId,
694 const Graphic3d_ZLayerSettings& theSettings,
695 const Graphic3d_ZLayerId theLayerAfter)
697 myZLayers.InsertLayerBefore (theLayerId, theSettings, theLayerAfter);
700 //=======================================================================
701 //function : InsertLayerAfter
703 //=======================================================================
704 void OpenGl_View::InsertLayerAfter (const Graphic3d_ZLayerId theLayerId,
705 const Graphic3d_ZLayerSettings& theSettings,
706 const Graphic3d_ZLayerId theLayerBefore)
708 myZLayers.InsertLayerAfter (theLayerId, theSettings, theLayerBefore);
711 //=======================================================================
712 //function : RemoveZLayer
714 //=======================================================================
715 void OpenGl_View::RemoveZLayer (const Graphic3d_ZLayerId theLayerId)
717 myZLayers.RemoveLayer (theLayerId);
720 //=======================================================================
721 //function : SetZLayerSettings
723 //=======================================================================
724 void OpenGl_View::SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
725 const Graphic3d_ZLayerSettings& theSettings)
727 myZLayers.SetLayerSettings (theLayerId, theSettings);
730 //=======================================================================
731 //function : ZLayerMax
733 //=======================================================================
734 Standard_Integer OpenGl_View::ZLayerMax() const
736 Standard_Integer aLayerMax = Graphic3d_ZLayerId_Default;
737 for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
739 aLayerMax = Max (aLayerMax, aLayerIter.Value()->LayerId());
744 //=======================================================================
747 //=======================================================================
748 const NCollection_List<Handle(Graphic3d_Layer)>& OpenGl_View::Layers() const
750 return myZLayers.Layers();
753 //=======================================================================
756 //=======================================================================
757 Handle(Graphic3d_Layer) OpenGl_View::Layer (const Graphic3d_ZLayerId theLayerId) const
759 Handle(Graphic3d_Layer) aLayer;
760 if (theLayerId != Graphic3d_ZLayerId_UNKNOWN)
762 myZLayers.LayerIDs().Find (theLayerId, aLayer);
767 //=======================================================================
768 //function : MinMaxValues
770 //=======================================================================
771 Bnd_Box OpenGl_View::MinMaxValues (const Standard_Boolean theToIncludeAuxiliary) const
778 Bnd_Box aBox = base_type::MinMaxValues (theToIncludeAuxiliary);
783 //=======================================================================
786 //=======================================================================
787 Handle(Standard_Transient) OpenGl_View::FBO() const
789 return Handle(Standard_Transient)(myFBO);
792 //=======================================================================
795 //=======================================================================
796 void OpenGl_View::SetFBO (const Handle(Standard_Transient)& theFbo)
798 myFBO = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
801 //=======================================================================
802 //function : FBOCreate
804 //=======================================================================
805 Handle(Standard_Transient) OpenGl_View::FBOCreate (const Standard_Integer theWidth,
806 const Standard_Integer theHeight)
808 return myWorkspace->FBOCreate (theWidth, theHeight);
811 //=======================================================================
812 //function : FBORelease
814 //=======================================================================
815 void OpenGl_View::FBORelease (Handle(Standard_Transient)& theFbo)
817 Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
818 if (aFrameBuffer.IsNull())
823 myWorkspace->FBORelease (aFrameBuffer);
827 //=======================================================================
828 //function : FBOGetDimensions
830 //=======================================================================
831 void OpenGl_View::FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
832 Standard_Integer& theWidth,
833 Standard_Integer& theHeight,
834 Standard_Integer& theWidthMax,
835 Standard_Integer& theHeightMax)
837 const Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
838 if (aFrameBuffer.IsNull())
843 theWidth = aFrameBuffer->GetVPSizeX(); // current viewport size
844 theHeight = aFrameBuffer->GetVPSizeY();
845 theWidthMax = aFrameBuffer->GetSizeX(); // texture size
846 theHeightMax = aFrameBuffer->GetSizeY();
849 //=======================================================================
850 //function : FBOChangeViewport
852 //=======================================================================
853 void OpenGl_View::FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
854 const Standard_Integer theWidth,
855 const Standard_Integer theHeight)
857 const Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
858 if (aFrameBuffer.IsNull())
863 aFrameBuffer->ChangeViewport (theWidth, theHeight);
866 //=======================================================================
867 //function : displayStructure
869 //=======================================================================
870 void OpenGl_View::displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
871 const Standard_Integer thePriority)
873 const OpenGl_Structure* aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
874 const Graphic3d_ZLayerId aZLayer = aStruct->ZLayer();
875 myZLayers.AddStructure (aStruct, aZLayer, thePriority);
878 //=======================================================================
879 //function : eraseStructure
881 //=======================================================================
882 void OpenGl_View::eraseStructure (const Handle(Graphic3d_CStructure)& theStructure)
884 const OpenGl_Structure* aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
885 myZLayers.RemoveStructure (aStruct);
888 //=======================================================================
889 //function : changeZLayer
891 //=======================================================================
892 void OpenGl_View::changeZLayer (const Handle(Graphic3d_CStructure)& theStructure,
893 const Graphic3d_ZLayerId theNewLayerId)
895 const Graphic3d_ZLayerId anOldLayer = theStructure->ZLayer();
896 const OpenGl_Structure* aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
897 myZLayers.ChangeLayer (aStruct, anOldLayer, theNewLayerId);
899 Update (theNewLayerId);
902 //=======================================================================
903 //function : changePriority
905 //=======================================================================
906 void OpenGl_View::changePriority (const Handle(Graphic3d_CStructure)& theStructure,
907 const Standard_Integer theNewPriority)
909 const Graphic3d_ZLayerId aLayerId = theStructure->ZLayer();
910 const OpenGl_Structure* aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
911 myZLayers.ChangePriority (aStruct, aLayerId, theNewPriority);
914 //=======================================================================
915 //function : DiagnosticInformation
917 //=======================================================================
918 void OpenGl_View::DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
919 Graphic3d_DiagnosticInfo theFlags) const
921 base_type::DiagnosticInformation (theDict, theFlags);
922 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
923 if (!myWorkspace->Activate()
929 aCtx->DiagnosticInformation (theDict, theFlags);
930 if ((theFlags & Graphic3d_DiagnosticInfo_FrameBuffer) != 0)
932 TCollection_AsciiString aResRatio (myRenderParams.ResolutionRatio());
933 theDict.ChangeFromIndex (theDict.Add ("ResolutionRatio", aResRatio)) = aResRatio;
937 //=======================================================================
938 //function : StatisticInformation
940 //=======================================================================
941 void OpenGl_View::StatisticInformation (TColStd_IndexedDataMapOfStringString& theDict) const
943 if (const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext())
945 const Handle(OpenGl_FrameStats)& aStats = aCtx->FrameStats();
946 const Graphic3d_RenderingParams& aRendParams = myWorkspace->View()->RenderingParams();
947 aStats->FormatStats (theDict, aRendParams.CollectedStats);
951 //=======================================================================
952 //function : StatisticInformation
954 //=======================================================================
955 TCollection_AsciiString OpenGl_View::StatisticInformation() const
957 if (const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext())
959 const Handle(OpenGl_FrameStats)& aStats = aCtx->FrameStats();
960 const Graphic3d_RenderingParams& aRendParams = myWorkspace->View()->RenderingParams();
961 return aStats->FormatStats (aRendParams.CollectedStats);
963 return TCollection_AsciiString();
966 //=======================================================================
967 //function : drawBackground
969 //=======================================================================
970 void OpenGl_View::drawBackground (const Handle(OpenGl_Workspace)& theWorkspace,
971 Graphic3d_Camera::Projection theProjection)
973 const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
974 const bool wasUsedZBuffer = theWorkspace->SetUseZBuffer (false);
977 aCtx->core11fwd->glDisable (GL_DEPTH_TEST);
980 #ifdef GL_DEPTH_CLAMP
981 const bool wasDepthClamped = aCtx->arbDepthClamp && glIsEnabled (GL_DEPTH_CLAMP);
982 if (aCtx->arbDepthClamp && !wasDepthClamped)
984 // make sure background is always drawn (workaround skybox rendering on some hardware)
985 aCtx->core11fwd->glEnable (GL_DEPTH_CLAMP);
989 if (myBackgroundType == Graphic3d_TOB_CUBEMAP)
991 myCubeMapParams->Aspect()->ShaderProgram()->PushVariableInt ("uZCoeff", myCubeMapBackground->ZIsInverted() ? -1 : 1);
992 myCubeMapParams->Aspect()->ShaderProgram()->PushVariableInt ("uYCoeff", myCubeMapBackground->IsTopDown() ? 1 : -1);
993 const OpenGl_Aspects* anOldAspectFace = theWorkspace->SetAspects (myCubeMapParams);
995 myBackgrounds[Graphic3d_TOB_CUBEMAP]->Render (theWorkspace, theProjection);
997 theWorkspace->SetAspects (anOldAspectFace);
999 else if (myBackgroundType == Graphic3d_TOB_GRADIENT
1000 || myBackgroundType == Graphic3d_TOB_TEXTURE)
1002 // Drawing background gradient if:
1003 // - gradient fill type is not Aspect_GradientFillMethod_None and
1004 // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
1005 if (myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined()
1006 && (!myTextureParams->Aspect()->ToMapTexture()
1007 || myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod() == Aspect_FM_CENTERED
1008 || myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod() == Aspect_FM_NONE))
1010 myBackgrounds[Graphic3d_TOB_GRADIENT]->Render(theWorkspace, theProjection);
1013 // Drawing background image if it is defined
1014 // (texture is defined and fill type is not Aspect_FM_NONE)
1015 if (myBackgrounds[Graphic3d_TOB_TEXTURE]->IsDefined()
1016 && myTextureParams->Aspect()->ToMapTexture())
1018 aCtx->core11fwd->glDisable (GL_BLEND);
1020 const OpenGl_Aspects* anOldAspectFace = theWorkspace->SetAspects (myTextureParams);
1021 myBackgrounds[Graphic3d_TOB_TEXTURE]->Render (theWorkspace, theProjection);
1022 theWorkspace->SetAspects (anOldAspectFace);
1028 theWorkspace->SetUseZBuffer (Standard_True);
1029 aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
1031 #ifdef GL_DEPTH_CLAMP
1032 if (aCtx->arbDepthClamp && !wasDepthClamped)
1034 aCtx->core11fwd->glDisable (GL_DEPTH_CLAMP);
1039 //=======================================================================
1040 //function : prepareFrameBuffers
1042 //=======================================================================
1043 bool OpenGl_View::prepareFrameBuffers (Graphic3d_Camera::Projection& theProj)
1045 theProj = myCamera->ProjectionType();
1046 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1048 Standard_Integer aSizeX = 0, aSizeY = 0;
1049 OpenGl_FrameBuffer* aFrameBuffer = myFBO.get();
1050 if (aFrameBuffer != NULL)
1052 aSizeX = aFrameBuffer->GetVPSizeX();
1053 aSizeY = aFrameBuffer->GetVPSizeY();
1055 else if (IsActiveXR())
1057 aSizeX = myXRSession->RecommendedViewport().x();
1058 aSizeY = myXRSession->RecommendedViewport().y();
1062 aSizeX = myWindow->Width();
1063 aSizeY = myWindow->Height();
1066 const Graphic3d_Vec2i aRendSize (Standard_Integer(myRenderParams.RenderResolutionScale * aSizeX + 0.5f),
1067 Standard_Integer(myRenderParams.RenderResolutionScale * aSizeY + 0.5f));
1070 || aRendSize.x() < 1
1071 || aRendSize.y() < 1)
1073 myBackBufferRestored = Standard_False;
1074 myIsImmediateDrawn = Standard_False;
1078 // determine multisampling parameters
1079 Standard_Integer aNbSamples = !myToDisableMSAA && aSizeX == aRendSize.x()
1080 ? Max (Min (myRenderParams.NbMsaaSamples, aCtx->MaxMsaaSamples()), 0)
1082 if (aNbSamples != 0)
1084 aNbSamples = OpenGl_Context::GetPowerOfTwo (aNbSamples, aCtx->MaxMsaaSamples());
1087 bool toUseOit = myRenderParams.TransparencyMethod != Graphic3d_RTM_BLEND_UNORDERED
1088 && checkOitCompatibility (aCtx, aNbSamples > 0);
1090 const bool toInitImmediateFbo = myTransientDrawToFront
1091 && (!aCtx->caps->useSystemBuffer || (toUseOit && HasImmediateStructures()));
1093 if ( aFrameBuffer == NULL
1094 && !aCtx->DefaultFrameBuffer().IsNull()
1095 && aCtx->DefaultFrameBuffer()->IsValid())
1097 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
1101 && (myTransientDrawToFront
1102 || theProj == Graphic3d_Camera::Projection_Stereo
1105 || aSizeX != aRendSize.x()))
1107 if (myMainSceneFbos[0]->GetVPSize() != aRendSize
1108 || myMainSceneFbos[0]->NbSamples() != aNbSamples)
1110 if (!myTransientDrawToFront)
1112 myImmediateSceneFbos[0]->Release (aCtx.operator->());
1113 myImmediateSceneFbos[1]->Release (aCtx.operator->());
1114 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
1115 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
1118 // prepare FBOs containing main scene
1119 // for further blitting and rendering immediate presentations on top
1120 if (aCtx->core20fwd != NULL)
1122 const bool wasFailedMain0 = checkWasFailedFbo (myMainSceneFbos[0], aRendSize.x(), aRendSize.y(), aNbSamples);
1123 if (!myMainSceneFbos[0]->Init (aCtx, aRendSize, myFboColorFormat, myFboDepthFormat, aNbSamples)
1126 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO "
1127 + printFboFormat (myMainSceneFbos[0]) + " initialization has failed";
1128 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1133 if (myMainSceneFbos[0]->IsValid() && (toInitImmediateFbo || myImmediateSceneFbos[0]->IsValid()))
1135 const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
1136 if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
1139 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO "
1140 + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
1141 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1147 myMainSceneFbos [0]->Release (aCtx.operator->());
1148 myMainSceneFbos [1]->Release (aCtx.operator->());
1149 myImmediateSceneFbos[0]->Release (aCtx.operator->());
1150 myImmediateSceneFbos[1]->Release (aCtx.operator->());
1151 myXrSceneFbo ->Release (aCtx.operator->());
1152 myMainSceneFbos [0]->ChangeViewport (0, 0);
1153 myMainSceneFbos [1]->ChangeViewport (0, 0);
1154 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
1155 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
1156 myXrSceneFbo ->ChangeViewport (0, 0);
1159 bool hasXRBlitFbo = false;
1160 if (theProj == Graphic3d_Camera::Projection_Stereo
1162 && myMainSceneFbos[0]->IsValid())
1165 || aSizeX != aRendSize.x())
1167 hasXRBlitFbo = myXrSceneFbo->InitLazy (aCtx, Graphic3d_Vec2i (aSizeX, aSizeY), myFboColorFormat, myFboDepthFormat, 0);
1170 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! VR FBO "
1171 + printFboFormat (myXrSceneFbo) + " initialization has failed";
1172 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1176 else if (theProj == Graphic3d_Camera::Projection_Stereo
1177 && myMainSceneFbos[0]->IsValid())
1179 const bool wasFailedMain1 = checkWasFailedFbo (myMainSceneFbos[1], myMainSceneFbos[0]);
1180 if (!myMainSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
1183 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO (second) "
1184 + printFboFormat (myMainSceneFbos[1]) + " initialization has failed";
1185 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1187 if (!myMainSceneFbos[1]->IsValid())
1189 // no enough memory?
1190 theProj = Graphic3d_Camera::Projection_Perspective;
1192 else if (!myTransientDrawToFront)
1196 else if (!aCtx->HasStereoBuffers()
1197 || myRenderParams.StereoMode != Graphic3d_StereoMode_QuadBuffer)
1199 const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
1200 const bool wasFailedImm1 = checkWasFailedFbo (myImmediateSceneFbos[1], myMainSceneFbos[0]);
1201 if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
1204 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
1205 + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
1206 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1208 if (!myImmediateSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
1211 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
1212 + printFboFormat (myImmediateSceneFbos[1]) + " initialization has failed";
1213 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1215 if (!myImmediateSceneFbos[0]->IsValid()
1216 || !myImmediateSceneFbos[1]->IsValid())
1218 theProj = Graphic3d_Camera::Projection_Perspective;
1224 myXrSceneFbo->Release (aCtx.get());
1225 myXrSceneFbo->ChangeViewport (0, 0);
1228 // process PBR environment
1229 if (myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_Pbr
1230 || myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_PbrFacet)
1232 if (!myPBREnvironment.IsNull()
1233 && myPBREnvironment->SizesAreDifferent (myRenderParams.PbrEnvPow2Size,
1234 myRenderParams.PbrEnvSpecMapNbLevels))
1236 myPBREnvironment->Release (aCtx.get());
1237 myPBREnvironment.Nullify();
1238 myPBREnvState = OpenGl_PBREnvState_NONEXISTENT;
1239 myPBREnvRequest = true;
1243 if (myPBREnvState == OpenGl_PBREnvState_NONEXISTENT
1246 myPBREnvironment = OpenGl_PBREnvironment::Create (aCtx, myRenderParams.PbrEnvPow2Size, myRenderParams.PbrEnvSpecMapNbLevels);
1247 myPBREnvState = myPBREnvironment.IsNull() ? OpenGl_PBREnvState_UNAVAILABLE : OpenGl_PBREnvState_CREATED;
1248 if (myPBREnvState == OpenGl_PBREnvState_CREATED)
1250 Handle(OpenGl_Texture) anEnvLUT;
1251 static const TCollection_AsciiString THE_SHARED_ENV_LUT_KEY("EnvLUT");
1252 if (!aCtx->GetResource (THE_SHARED_ENV_LUT_KEY, anEnvLUT))
1254 bool toConvertHalfFloat = false;
1255 #if defined(GL_ES_VERSION_2_0)
1256 // GL_RG32F is not texture-filterable format in OpenGL ES without OES_texture_float_linear extension.
1257 // GL_RG16F is texture-filterable since OpenGL ES 3.0 or OpenGL ES 2.0 + OES_texture_half_float_linear.
1258 // OpenGL ES 3.0 allows initialization of GL_RG16F from 32-bit float data, but OpenGL ES 2.0 + OES_texture_half_float does not.
1259 // Note that it is expected that GL_RG16F has enough precision for this table, so that it can be used also on desktop OpenGL.
1260 const bool hasHalfFloat = aCtx->IsGlGreaterEqual (3, 0) || aCtx->CheckExtension ("GL_OES_texture_half_float_linear");
1261 toConvertHalfFloat = !aCtx->IsGlGreaterEqual (3, 0) && hasHalfFloat;
1263 Image_Format anImgFormat = Image_Format_UNKNOWN;
1266 anImgFormat = toConvertHalfFloat ? Image_Format_RGF_half : Image_Format_RGF;
1270 anImgFormat = toConvertHalfFloat ? Image_Format_RGBAF_half : Image_Format_RGBAF;
1273 Handle(Image_PixMap) aPixMap = new Image_PixMap();
1274 if (anImgFormat == Image_Format_RGF)
1276 aPixMap->InitWrapper (Image_Format_RGF, (Standard_Byte*)Textures_EnvLUT, Textures_EnvLUTSize, Textures_EnvLUTSize);
1280 aPixMap->InitZero (anImgFormat, Textures_EnvLUTSize, Textures_EnvLUTSize);
1281 Image_PixMap aPixMapRG;
1282 aPixMapRG.InitWrapper (Image_Format_RGF, (Standard_Byte*)Textures_EnvLUT, Textures_EnvLUTSize, Textures_EnvLUTSize);
1283 for (Standard_Size aRowIter = 0; aRowIter < aPixMapRG.SizeY(); ++aRowIter)
1285 for (Standard_Size aColIter = 0; aColIter < aPixMapRG.SizeX(); ++aColIter)
1287 const Image_ColorRGF& aPixelRG = aPixMapRG.Value<Image_ColorRGF> (aRowIter, aColIter);
1288 if (toConvertHalfFloat)
1290 NCollection_Vec2<uint16_t>& aPixelRGBA = aPixMap->ChangeValue<NCollection_Vec2<uint16_t>> (aRowIter, aColIter);
1291 aPixelRGBA.x() = Image_PixMap::ConvertToHalfFloat (aPixelRG.r());
1292 aPixelRGBA.y() = Image_PixMap::ConvertToHalfFloat (aPixelRG.g());
1296 Image_ColorRGBAF& aPixelRGBA = aPixMap->ChangeValue<Image_ColorRGBAF> (aRowIter, aColIter);
1297 aPixelRGBA.r() = aPixelRG.r();
1298 aPixelRGBA.g() = aPixelRG.g();
1304 OpenGl_TextureFormat aTexFormat = OpenGl_TextureFormat::FindFormat (aCtx, aPixMap->Format(), false);
1305 #if defined(GL_ES_VERSION_2_0)
1306 if (aTexFormat.IsValid()
1309 aTexFormat.SetInternalFormat (aCtx->arbTexRG ? GL_RG16F : GL_RGBA16F);
1313 Handle(Graphic3d_TextureParams) aParams = new Graphic3d_TextureParams();
1314 aParams->SetFilter (Graphic3d_TOTF_BILINEAR);
1315 aParams->SetRepeat (Standard_False);
1316 aParams->SetTextureUnit (aCtx->PBREnvLUTTexUnit());
1317 anEnvLUT = new OpenGl_Texture(THE_SHARED_ENV_LUT_KEY, aParams);
1318 if (!aTexFormat.IsValid()
1319 || !anEnvLUT->Init (aCtx, aTexFormat, Graphic3d_Vec2i((Standard_Integer)Textures_EnvLUTSize), Graphic3d_TOT_2D, aPixMap.get()))
1321 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed allocation of LUT for PBR");
1324 aCtx->ShareResource (THE_SHARED_ENV_LUT_KEY, anEnvLUT);
1326 if (!anEnvLUT.IsNull())
1328 anEnvLUT->Bind (aCtx);
1330 myWorkspace->ApplyAspects();
1333 updatePBREnvironment (aCtx);
1336 // create color and coverage accumulation buffers required for OIT algorithm
1338 && myRenderParams.TransparencyMethod == Graphic3d_RTM_DEPTH_PEELING_OIT)
1340 if (myDepthPeelingFbos->BlendBackFboOit()->GetSize() != aRendSize)
1342 if (myDepthPeelingFbos->BlendBackFboOit()->Init (aCtx, aRendSize, GL_RGBA16F, 0))
1344 for (int aPairIter = 0; aPairIter < 2; ++aPairIter)
1346 OpenGl_ColorFormats aColorFormats;
1347 aColorFormats.Append (GL_RG32F);
1348 aColorFormats.Append (GL_RGBA16F);
1349 aColorFormats.Append (GL_RGBA16F);
1350 myDepthPeelingFbos->DepthPeelFbosOit()[aPairIter]->Init (aCtx, aRendSize, aColorFormats, 0);
1352 NCollection_Sequence<Handle(OpenGl_Texture)> anAttachments;
1353 anAttachments.Append (myDepthPeelingFbos->DepthPeelFbosOit()[aPairIter]->ColorTexture (1));
1354 anAttachments.Append (myDepthPeelingFbos->DepthPeelFbosOit()[aPairIter]->ColorTexture (2));
1355 myDepthPeelingFbos->FrontBackColorFbosOit()[aPairIter]->InitWrapper (aCtx, anAttachments);
1361 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1362 "Initialization of float texture framebuffer for use with\n"
1363 " Depth-Peeling order-independent transparency rendering algorithm has failed.");
1369 myDepthPeelingFbos->Release (aCtx.operator->());
1373 && myRenderParams.TransparencyMethod == Graphic3d_RTM_BLEND_OIT)
1375 Standard_Integer anFboIt = 0;
1376 for (; anFboIt < 2; ++anFboIt)
1378 Handle(OpenGl_FrameBuffer)& aMainSceneFbo = myMainSceneFbos [anFboIt];
1379 Handle(OpenGl_FrameBuffer)& aMainSceneFboOit = myMainSceneFbosOit [anFboIt];
1380 Handle(OpenGl_FrameBuffer)& anImmediateSceneFbo = myImmediateSceneFbos [anFboIt];
1381 Handle(OpenGl_FrameBuffer)& anImmediateSceneFboOit = myImmediateSceneFbosOit[anFboIt];
1382 if (aMainSceneFbo->IsValid()
1383 && (aMainSceneFboOit->GetVPSize() != aRendSize
1384 || aMainSceneFboOit->NbSamples() != aNbSamples))
1386 Standard_Integer aColorConfig = 0;
1387 for (;;) // seemly responding to driver limitation (GL_FRAMEBUFFER_UNSUPPORTED)
1389 if (myFboOitColorConfig.IsEmpty())
1391 if (!chooseOitColorConfiguration (aCtx, aColorConfig++, myFboOitColorConfig))
1396 if (aMainSceneFboOit->Init (aCtx, aRendSize, myFboOitColorConfig, aMainSceneFbo->DepthStencilTexture(), aNbSamples))
1400 myFboOitColorConfig.Clear();
1402 if (!aMainSceneFboOit->IsValid())
1407 else if (!aMainSceneFbo->IsValid())
1409 aMainSceneFboOit->Release (aCtx.operator->());
1410 aMainSceneFboOit->ChangeViewport (0, 0);
1413 if (anImmediateSceneFbo->IsValid()
1414 && (anImmediateSceneFboOit->GetVPSize() != aRendSize
1415 || anImmediateSceneFboOit->NbSamples() != aNbSamples))
1417 if (!anImmediateSceneFboOit->Init (aCtx, aRendSize, myFboOitColorConfig,
1418 anImmediateSceneFbo->DepthStencilTexture(), aNbSamples))
1423 else if (!anImmediateSceneFbo->IsValid())
1425 anImmediateSceneFboOit->Release (aCtx.operator->());
1426 anImmediateSceneFboOit->ChangeViewport (0, 0);
1429 if (anFboIt == 0) // only the first OIT framebuffer is mandatory
1431 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1432 "Initialization of float texture framebuffer for use with\n"
1433 " blended order-independent transparency rendering algorithm has failed.\n"
1434 " Blended order-independent transparency will not be available.\n");
1437 myToDisableOITMSAA = Standard_True;
1441 myToDisableOIT = Standard_True;
1446 if (!toUseOit && myMainSceneFbosOit[0]->IsValid())
1448 myDepthPeelingFbos->Release (aCtx.operator->());
1449 myMainSceneFbosOit [0]->Release (aCtx.operator->());
1450 myMainSceneFbosOit [1]->Release (aCtx.operator->());
1451 myImmediateSceneFbosOit[0]->Release (aCtx.operator->());
1452 myImmediateSceneFbosOit[1]->Release (aCtx.operator->());
1453 myMainSceneFbosOit [0]->ChangeViewport (0, 0);
1454 myMainSceneFbosOit [1]->ChangeViewport (0, 0);
1455 myImmediateSceneFbosOit[0]->ChangeViewport (0, 0);
1456 myImmediateSceneFbosOit[1]->ChangeViewport (0, 0);
1459 // allocate shadow maps
1460 const Handle(Graphic3d_LightSet)& aLights = myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_Unlit ? myNoShadingLight : myLights;
1461 if (!aLights.IsNull())
1463 aLights->UpdateRevision();
1465 bool toUseShadowMap = myRenderParams.IsShadowEnabled
1466 && myRenderParams.ShadowMapResolution > 0
1467 && !myLights.IsNull()
1468 && myLights->NbCastShadows() > 0
1469 && myRenderParams.Method != Graphic3d_RM_RAYTRACING;
1472 if (myShadowMaps->Size() != myLights->NbCastShadows())
1474 myShadowMaps->Release (aCtx.get());
1475 myShadowMaps->Resize (0, myLights->NbCastShadows() - 1, true);
1478 const GLint aSamplFrom = GLint(aCtx->ShadowMapTexUnit()) - myLights->NbCastShadows() + 1;
1479 for (Standard_Integer aShadowIter = 0; aShadowIter < myShadowMaps->Size(); ++aShadowIter)
1481 Handle(OpenGl_ShadowMap)& aShadow = myShadowMaps->ChangeValue (aShadowIter);
1482 if (aShadow.IsNull())
1484 aShadow = new OpenGl_ShadowMap();
1486 aShadow->SetShadowMapBias (myRenderParams.ShadowMapBias);
1487 aShadow->Texture()->Sampler()->Parameters()->SetTextureUnit ((Graphic3d_TextureUnit )(aSamplFrom + aShadowIter));
1489 const Handle(OpenGl_FrameBuffer)& aShadowFbo = aShadow->FrameBuffer();
1490 if (aShadowFbo->GetVPSizeX() != myRenderParams.ShadowMapResolution
1493 OpenGl_ColorFormats aDummy;
1494 if (!aShadowFbo->Init (aCtx, Graphic3d_Vec2i (myRenderParams.ShadowMapResolution), aDummy, myFboDepthFormat, 0))
1496 toUseShadowMap = false;
1501 if (!toUseShadowMap && myShadowMaps->IsValid())
1503 myShadowMaps->Release (aCtx.get());
1509 //=======================================================================
1512 //=======================================================================
1513 void OpenGl_View::Redraw()
1515 const Standard_Boolean wasDisabledMSAA = myToDisableMSAA;
1516 const Standard_Boolean hadFboBlit = myHasFboBlit;
1517 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
1518 && !myCaps->vboDisable
1519 && !myCaps->keepArrayData)
1521 // caps are shared across all views, thus we need to invalidate all of them
1522 // if (myWasRedrawnGL) { myStructureManager->SetDeviceLost(); }
1523 myDriver->setDeviceLost();
1524 myCaps->keepArrayData = Standard_True;
1527 if (!myWorkspace->Activate())
1532 // implicitly disable VSync when using HMD composer (can be mirrored in window for debugging)
1533 myWindow->SetSwapInterval (IsActiveXR());
1536 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1537 aCtx->FrameStats()->FrameStart (myWorkspace->View(), false);
1538 aCtx->SetLineFeather (myRenderParams.LineFeather);
1540 const Standard_Integer anSRgbState = aCtx->ToRenderSRGB() ? 1 : 0;
1541 if (mySRgbState != -1
1542 && mySRgbState != anSRgbState)
1544 releaseSrgbResources (aCtx);
1545 initTextureEnv (aCtx);
1547 mySRgbState = anSRgbState;
1548 aCtx->ShaderManager()->UpdateSRgbState();
1550 // release pending GL resources
1551 aCtx->ReleaseDelayed();
1553 // fetch OpenGl context state
1556 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
1557 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
1558 if (!prepareFrameBuffers (aProjectType))
1560 myBackBufferRestored = Standard_False;
1561 myIsImmediateDrawn = Standard_False;
1566 if (myShadowMaps->IsValid())
1568 Standard_Integer aShadowIndex = myShadowMaps->Lower();
1569 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ActiveShadowCasters);
1570 aLightIter.More(); aLightIter.Next())
1572 const Handle(Graphic3d_CLight)& aLight = aLightIter.Value();
1573 if (aLight->ToCastShadows())
1575 const Handle(OpenGl_ShadowMap)& aShadowMap = myShadowMaps->ChangeValue (aShadowIndex);
1576 aShadowMap->SetLightSource (aLight);
1577 renderShadowMap (aShadowMap);
1581 for (; aShadowIndex <= myShadowMaps->Upper(); ++aShadowIndex)
1583 myShadowMaps->ChangeValue (aShadowIndex)->SetLightSource (Handle(Graphic3d_CLight)());
1587 OpenGl_FrameBuffer* aFrameBuffer = myFBO.get();
1588 bool toSwap = aCtx->IsRender()
1589 && !aCtx->caps->buffersNoSwap
1590 && aFrameBuffer == NULL
1591 && (!IsActiveXR() || myRenderParams.ToMirrorComposer);
1592 if ( aFrameBuffer == NULL
1593 && !aCtx->DefaultFrameBuffer().IsNull()
1594 && aCtx->DefaultFrameBuffer()->IsValid())
1596 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
1599 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
1601 OpenGl_FrameBuffer* aMainFbos[2] =
1603 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
1604 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
1606 OpenGl_FrameBuffer* aMainFbosOit[2] =
1608 myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL,
1609 myMainSceneFbosOit[1]->IsValid() ? myMainSceneFbosOit[1].operator->() :
1610 myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL
1613 OpenGl_FrameBuffer* anImmFbos[2] =
1615 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1616 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1618 OpenGl_FrameBuffer* anImmFbosOit[2] =
1620 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
1621 myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
1622 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
1627 // use single frame for both views - caching main scene content makes no sense
1628 // when head position is expected to be updated each frame redraw with high accuracy
1629 aMainFbos[1] = aMainFbos[0];
1630 aMainFbosOit[1] = aMainFbosOit[0];
1631 anImmFbos[0] = aMainFbos[0];
1632 anImmFbos[1] = aMainFbos[1];
1633 anImmFbosOit[0] = aMainFbosOit[0];
1634 anImmFbosOit[1] = aMainFbosOit[1];
1636 else if (!myTransientDrawToFront)
1638 anImmFbos [0] = aMainFbos [0];
1639 anImmFbos [1] = aMainFbos [1];
1640 anImmFbosOit[0] = aMainFbosOit[0];
1641 anImmFbosOit[1] = aMainFbosOit[1];
1643 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
1644 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
1646 anImmFbos [0] = NULL;
1647 anImmFbos [1] = NULL;
1648 anImmFbosOit[0] = NULL;
1649 anImmFbosOit[1] = NULL;
1652 #if !defined(GL_ES_VERSION_2_0)
1653 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
1655 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1656 aMainFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1658 redraw (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], aMainFbosOit[0]);
1659 myBackBufferRestored = Standard_True;
1660 myIsImmediateDrawn = Standard_False;
1661 #if !defined(GL_ES_VERSION_2_0)
1662 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
1664 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1665 anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1666 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], anImmFbos[0], anImmFbosOit[0]))
1670 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip && toSwap)
1672 aCtx->SwapBuffers();
1677 // push Left frame to HMD display composer
1678 OpenGl_FrameBuffer* anXRFbo = myXrSceneFbo->IsValid() ? myXrSceneFbo.get() : aMainFbos[0];
1679 if (anXRFbo != aMainFbos[0])
1681 blitBuffers (aMainFbos[0], anXRFbo); // resize or resolve MSAA samples
1683 #if !defined(GL_ES_VERSION_2_0)
1684 const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGL;
1686 const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGLES;
1688 myXRSession->SubmitEye ((void* )(size_t )anXRFbo->ColorTexture()->TextureId(),
1689 aGraphicsLib, Aspect_ColorSpace_sRGB, Aspect_Eye_Left);
1692 #if !defined(GL_ES_VERSION_2_0)
1693 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
1695 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1696 aMainFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1698 redraw (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], aMainFbosOit[1]);
1699 myBackBufferRestored = Standard_True;
1700 myIsImmediateDrawn = Standard_False;
1701 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1702 anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1703 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], anImmFbos[1], anImmFbosOit[1]))
1710 // push Right frame to HMD display composer
1711 OpenGl_FrameBuffer* anXRFbo = myXrSceneFbo->IsValid() ? myXrSceneFbo.get() : aMainFbos[1];
1712 if (anXRFbo != aMainFbos[1])
1714 blitBuffers (aMainFbos[1], anXRFbo); // resize or resolve MSAA samples
1716 #if !defined(GL_ES_VERSION_2_0)
1717 const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGL;
1719 const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGLES;
1721 myXRSession->SubmitEye ((void* )(size_t )anXRFbo->ColorTexture()->TextureId(),
1722 aGraphicsLib, Aspect_ColorSpace_sRGB, Aspect_Eye_Right);
1723 aCtx->core11fwd->glFinish();
1725 if (myRenderParams.ToMirrorComposer)
1727 blitBuffers (anXRFbo, aFrameBuffer, myToFlipOutput);
1730 else if (anImmFbos[0] != NULL)
1732 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(), 1.0f);
1733 drawStereoPair (aFrameBuffer);
1738 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : aFrameBuffer;
1739 OpenGl_FrameBuffer* aMainFboOit = myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL;
1740 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
1741 OpenGl_FrameBuffer* anImmFboOit = NULL;
1742 if (!myTransientDrawToFront)
1744 anImmFbo = aMainFbo;
1745 anImmFboOit = aMainFboOit;
1747 else if (myImmediateSceneFbos[0]->IsValid())
1749 anImmFbo = myImmediateSceneFbos[0].operator->();
1750 anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
1753 #if !defined(GL_ES_VERSION_2_0)
1754 if (aMainFbo == NULL)
1756 aCtx->SetReadDrawBuffer (GL_BACK);
1759 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1760 aMainFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
1762 redraw (aProjectType, aMainFbo, aMainFboOit);
1763 myBackBufferRestored = Standard_True;
1764 myIsImmediateDrawn = Standard_False;
1765 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1766 anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
1767 if (!redrawImmediate (aProjectType, aMainFbo, anImmFbo, anImmFboOit))
1772 if (anImmFbo != NULL
1773 && anImmFbo != aFrameBuffer)
1775 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
1779 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
1780 && myRenderParams.IsGlobalIlluminationEnabled)
1788 if (wasDisabledMSAA != myToDisableMSAA
1789 || hadFboBlit != myHasFboBlit)
1795 // reset state for safety
1796 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1797 if (aCtx->caps->ffpEnable)
1799 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1805 aCtx->SwapBuffers();
1806 if (!myMainSceneFbos[0]->IsValid())
1808 myBackBufferRestored = Standard_False;
1813 aCtx->core11fwd->glFlush();
1816 // reset render mode state
1818 aCtx->FrameStats()->FrameEnd (myWorkspace->View(), false);
1820 myWasRedrawnGL = Standard_True;
1823 // =======================================================================
1824 // function : RedrawImmediate
1826 // =======================================================================
1827 void OpenGl_View::RedrawImmediate()
1829 if (!myWorkspace->Activate())
1832 // no special handling of HMD display, since it will force full Redraw() due to no frame caching (myBackBufferRestored)
1833 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1834 if (!myTransientDrawToFront
1835 || !myBackBufferRestored
1836 || (aCtx->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
1842 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
1843 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
1844 OpenGl_FrameBuffer* aFrameBuffer = myFBO.get();
1845 aCtx->FrameStats()->FrameStart (myWorkspace->View(), true);
1847 if ( aFrameBuffer == NULL
1848 && !aCtx->DefaultFrameBuffer().IsNull()
1849 && aCtx->DefaultFrameBuffer()->IsValid())
1851 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
1854 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
1856 if (myMainSceneFbos[0]->IsValid()
1857 && !myMainSceneFbos[1]->IsValid())
1859 aProjectType = Graphic3d_Camera::Projection_Perspective;
1863 bool toSwap = false;
1864 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
1866 OpenGl_FrameBuffer* aMainFbos[2] =
1868 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
1869 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
1871 OpenGl_FrameBuffer* anImmFbos[2] =
1873 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1874 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1876 OpenGl_FrameBuffer* anImmFbosOit[2] =
1878 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
1879 myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
1880 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
1882 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
1883 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
1885 anImmFbos[0] = NULL;
1886 anImmFbos[1] = NULL;
1887 anImmFbosOit[0] = NULL;
1888 anImmFbosOit[1] = NULL;
1891 if (aCtx->arbFBO != NULL)
1893 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1895 #if !defined(GL_ES_VERSION_2_0)
1896 if (anImmFbos[0] == NULL)
1898 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
1902 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1903 anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1904 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye,
1908 Standard_True) || toSwap;
1909 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
1911 && myFBO.get() == NULL
1912 && !aCtx->caps->buffersNoSwap)
1914 aCtx->SwapBuffers();
1917 if (aCtx->arbFBO != NULL)
1919 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1921 #if !defined(GL_ES_VERSION_2_0)
1922 if (anImmFbos[1] == NULL)
1924 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
1927 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1928 anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1929 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye,
1933 Standard_True) || toSwap;
1934 if (anImmFbos[0] != NULL)
1936 drawStereoPair (aFrameBuffer);
1941 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1942 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
1943 OpenGl_FrameBuffer* anImmFboOit = NULL;
1944 if (myImmediateSceneFbos[0]->IsValid())
1946 anImmFbo = myImmediateSceneFbos[0].operator->();
1947 anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
1949 #if !defined(GL_ES_VERSION_2_0)
1950 if (aMainFbo == NULL)
1952 aCtx->SetReadDrawBuffer (GL_BACK);
1955 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1956 anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
1957 toSwap = redrawImmediate (aProjectType,
1961 Standard_True) || toSwap;
1962 if (anImmFbo != NULL
1963 && anImmFbo != aFrameBuffer)
1965 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
1972 // reset state for safety
1973 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1974 if (aCtx->caps->ffpEnable)
1976 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1980 && myFBO.get() == NULL
1981 && !aCtx->caps->buffersNoSwap)
1983 aCtx->SwapBuffers();
1987 aCtx->core11fwd->glFlush();
1989 aCtx->FrameStats()->FrameEnd (myWorkspace->View(), true);
1991 myWasRedrawnGL = Standard_True;
1994 // =======================================================================
1995 // function : redraw
1997 // =======================================================================
1998 void OpenGl_View::redraw (const Graphic3d_Camera::Projection theProjection,
1999 OpenGl_FrameBuffer* theReadDrawFbo,
2000 OpenGl_FrameBuffer* theOitAccumFbo)
2002 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2003 if (theReadDrawFbo != NULL)
2005 theReadDrawFbo->BindBuffer (aCtx);
2006 theReadDrawFbo->SetupViewport (aCtx);
2010 const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
2011 aCtx->ResizeViewport (aViewport);
2014 // request reset of material
2015 aCtx->ShaderManager()->UpdateMaterialState();
2017 myWorkspace->UseZBuffer() = Standard_True;
2018 myWorkspace->UseDepthWrite() = Standard_True;
2019 GLbitfield toClear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
2020 aCtx->core11fwd->glDepthFunc (GL_LEQUAL);
2021 aCtx->core11fwd->glDepthMask (GL_TRUE);
2022 aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
2024 aCtx->core11fwd->glClearDepth (1.0);
2026 const OpenGl_Vec4 aBgColor = aCtx->Vec4FromQuantityColor (myBgColor);
2027 aCtx->SetColorMaskRGBA (NCollection_Vec4<bool> (true)); // force writes into all components, including alpha
2028 aCtx->core11fwd->glClearColor (aBgColor.r(), aBgColor.g(), aBgColor.b(), aCtx->caps->buffersOpaqueAlpha ? 1.0f : 0.0f);
2029 aCtx->core11fwd->glClear (toClear);
2030 aCtx->SetColorMask (true); // restore default alpha component write state
2032 render (theProjection, theReadDrawFbo, theOitAccumFbo, Standard_False);
2035 // =======================================================================
2036 // function : redrawImmediate
2038 // =======================================================================
2039 bool OpenGl_View::redrawImmediate (const Graphic3d_Camera::Projection theProjection,
2040 OpenGl_FrameBuffer* theReadFbo,
2041 OpenGl_FrameBuffer* theDrawFbo,
2042 OpenGl_FrameBuffer* theOitAccumFbo,
2043 const Standard_Boolean theIsPartialUpdate)
2045 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2046 GLboolean toCopyBackToFront = GL_FALSE;
2047 if (theDrawFbo == theReadFbo
2048 && theDrawFbo != NULL
2049 && theDrawFbo->IsValid())
2051 myBackBufferRestored = Standard_False;
2052 theDrawFbo->BindBuffer (aCtx);
2054 else if (theReadFbo != NULL
2055 && theReadFbo->IsValid()
2056 && aCtx->IsRender())
2058 if (!blitBuffers (theReadFbo, theDrawFbo))
2063 else if (theDrawFbo == NULL)
2065 #if !defined(GL_ES_VERSION_2_0)
2066 aCtx->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
2068 if (toCopyBackToFront
2069 && myTransientDrawToFront)
2071 if (!HasImmediateStructures()
2072 && !theIsPartialUpdate)
2074 // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
2077 if (!copyBackToFront())
2079 toCopyBackToFront = GL_FALSE;
2080 myBackBufferRestored = Standard_False;
2085 toCopyBackToFront = GL_FALSE;
2086 myBackBufferRestored = Standard_False;
2091 myBackBufferRestored = Standard_False;
2093 myIsImmediateDrawn = Standard_True;
2095 myWorkspace->UseZBuffer() = Standard_True;
2096 myWorkspace->UseDepthWrite() = Standard_True;
2097 aCtx->core11fwd->glDepthFunc (GL_LEQUAL);
2098 aCtx->core11fwd->glDepthMask (GL_TRUE);
2099 aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
2100 aCtx->core11fwd->glClearDepth (1.0);
2102 render (theProjection, theDrawFbo, theOitAccumFbo, Standard_True);
2104 return !toCopyBackToFront;
2107 //=======================================================================
2108 //function : renderShadowMap
2110 //=======================================================================
2111 void OpenGl_View::renderShadowMap (const Handle(OpenGl_ShadowMap)& theShadowMap)
2113 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2114 if (!theShadowMap->UpdateCamera (*this))
2119 myBVHSelector.SetViewVolume (theShadowMap->Camera());
2120 myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height(), myRenderParams.ResolutionRatio());
2121 myBVHSelector.CacheClipPtsProjections();
2123 myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
2124 aCtx->SetCamera (theShadowMap->Camera());
2125 aCtx->ProjectionState.SetCurrent (theShadowMap->Camera()->ProjectionMatrixF());
2126 aCtx->ApplyProjectionMatrix();
2128 aCtx->ShaderManager()->UpdateMaterialState();
2129 aCtx->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
2130 aCtx->ShaderManager()->SetShadingModel (Graphic3d_TypeOfShadingModel_Unlit);
2132 const Handle(OpenGl_FrameBuffer)& aShadowBuffer = theShadowMap->FrameBuffer();
2133 aShadowBuffer->BindBuffer (aCtx);
2134 aShadowBuffer->SetupViewport (aCtx);
2136 aCtx->SetColorMask (false);
2137 aCtx->SetAllowSampleAlphaToCoverage (false);
2138 aCtx->SetSampleAlphaToCoverage (false);
2140 myWorkspace->UseZBuffer() = true;
2141 myWorkspace->UseDepthWrite() = true;
2142 aCtx->core11fwd->glDepthFunc (GL_LEQUAL);
2143 aCtx->core11fwd->glDepthMask (GL_TRUE);
2144 aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
2145 aCtx->core11fwd->glClearDepth (1.0);
2146 aCtx->core11fwd->glClear (GL_DEPTH_BUFFER_BIT);
2148 renderScene (Graphic3d_Camera::Projection_Orthographic, aShadowBuffer.get(), NULL, false);
2150 aCtx->SetColorMask (true);
2151 myWorkspace->ResetAppliedAspect();
2152 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
2154 //Image_AlienPixMap anImage; anImage.InitZero (Image_Format_Gray, aShadowBuffer->GetVPSizeX(), aShadowBuffer->GetVPSizeY());
2155 //OpenGl_FrameBuffer::BufferDump (aCtx, aShadowBuffer, anImage, Graphic3d_BT_Depth);
2156 //anImage.Save (TCollection_AsciiString ("shadow") + theShadowMap->Texture()->Sampler()->Parameters()->TextureUnit() + ".png");
2161 //=======================================================================
2164 //=======================================================================
2165 void OpenGl_View::render (Graphic3d_Camera::Projection theProjection,
2166 OpenGl_FrameBuffer* theOutputFBO,
2167 OpenGl_FrameBuffer* theOitAccumFbo,
2168 const Standard_Boolean theToDrawImmediate)
2170 // ==================================
2171 // Step 1: Prepare for render
2172 // ==================================
2174 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
2175 aContext->SetAllowSampleAlphaToCoverage (myRenderParams.ToEnableAlphaToCoverage
2176 && theOutputFBO != NULL
2177 && theOutputFBO->NbSamples() != 0);
2179 #if !defined(GL_ES_VERSION_2_0)
2180 // Disable current clipping planes
2181 if (aContext->core11ffp != NULL)
2183 const Standard_Integer aMaxPlanes = aContext->MaxClipPlanes();
2184 for (Standard_Integer aClipPlaneId = GL_CLIP_PLANE0; aClipPlaneId < GL_CLIP_PLANE0 + aMaxPlanes; ++aClipPlaneId)
2186 aContext->core11fwd->glDisable (aClipPlaneId);
2191 // update states of OpenGl_BVHTreeSelector (frustum culling algorithm);
2192 // note that we pass here window dimensions ignoring Graphic3d_RenderingParams::RenderResolutionScale
2193 myBVHSelector.SetViewVolume (myCamera);
2194 myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height(), myRenderParams.ResolutionRatio());
2195 myBVHSelector.CacheClipPtsProjections();
2197 const Handle(OpenGl_ShaderManager)& aManager = aContext->ShaderManager();
2198 const Handle(Graphic3d_LightSet)& aLights = myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_Unlit ? myNoShadingLight : myLights;
2199 Standard_Size aLightsRevision = 0;
2200 if (!aLights.IsNull())
2202 aLightsRevision = aLights->UpdateRevision();
2204 if (StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index()) != myLastLightSourceState
2205 || aLightsRevision != myLightsRevision)
2207 myLightsRevision = aLightsRevision;
2208 aManager->UpdateLightSourceStateTo (aLights, SpecIBLMapLevels(), myShadowMaps->IsValid() ? myShadowMaps : Handle(OpenGl_ShadowMapArray)());
2209 myLastLightSourceState = StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index());
2212 // Update matrices if camera has changed.
2213 Graphic3d_WorldViewProjState aWVPState = myCamera->WorldViewProjState();
2214 if (myWorldViewProjState != aWVPState)
2217 myWorldViewProjState = aWVPState;
2220 myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
2221 aContext->SetCamera (myCamera);
2222 if (aManager->ModelWorldState().Index() == 0)
2224 aContext->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
2227 // ====================================
2228 // Step 2: Redraw background
2229 // ====================================
2231 // Render background
2232 if (!theToDrawImmediate)
2234 drawBackground (myWorkspace, theProjection);
2237 #if !defined(GL_ES_VERSION_2_0)
2238 // Switch off lighting by default
2239 if (aContext->core11ffp != NULL
2240 && aContext->caps->ffpEnable)
2242 aContext->core11fwd->glDisable (GL_LIGHTING);
2246 // =================================
2247 // Step 3: Redraw main plane
2248 // =================================
2250 #if !defined(GL_ES_VERSION_2_0)
2251 // if the view is scaled normal vectors are scaled to unit
2252 // length for correct displaying of shaded objects
2253 const gp_Pnt anAxialScale = aContext->Camera()->AxialScale();
2254 if (anAxialScale.X() != 1.F ||
2255 anAxialScale.Y() != 1.F ||
2256 anAxialScale.Z() != 1.F)
2258 aContext->SetGlNormalizeEnabled (Standard_True);
2262 aContext->SetGlNormalizeEnabled (Standard_False);
2266 aManager->SetShadingModel (OpenGl_ShaderManager::PBRShadingModelFallback (myRenderParams.ShadingModel, checkPBRAvailability()));
2269 if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
2271 aContext->ProjectionState.SetCurrent (aContext->Camera()->ProjectionStereoLeftF());
2272 aContext->ApplyProjectionMatrix();
2274 else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
2276 aContext->ProjectionState.SetCurrent (aContext->Camera()->ProjectionStereoRightF());
2277 aContext->ApplyProjectionMatrix();
2280 myWorkspace->SetEnvironmentTexture (myTextureEnv);
2282 const bool hasShadowMap = aContext->ShaderManager()->LightSourceState().HasShadowMaps();
2285 for (Standard_Integer aShadowIter = myShadowMaps->Lower(); aShadowIter <= myShadowMaps->Upper(); ++aShadowIter)
2287 const Handle(OpenGl_ShadowMap)& aShadow = myShadowMaps->Value (aShadowIter);
2288 aShadow->Texture()->Bind (aContext);
2292 renderScene (theProjection, theOutputFBO, theOitAccumFbo, theToDrawImmediate);
2296 for (Standard_Integer aShadowIter = myShadowMaps->Lower(); aShadowIter <= myShadowMaps->Upper(); ++aShadowIter)
2298 const Handle(OpenGl_ShadowMap)& aShadow = myShadowMaps->Value (aShadowIter);
2299 aShadow->Texture()->Unbind (aContext);
2301 if (aContext->core15fwd != NULL)
2303 aContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2307 myWorkspace->SetEnvironmentTexture (Handle(OpenGl_TextureSet)());
2309 // ===============================
2310 // Step 4: Trihedron
2311 // ===============================
2313 // Resetting GL parameters according to the default aspects
2314 // in order to synchronize GL state with the graphic driver state
2315 // before drawing auxiliary stuff (trihedrons, overlayer)
2316 myWorkspace->ResetAppliedAspect();
2319 if (!theToDrawImmediate)
2321 renderTrihedron (myWorkspace);
2328 myWorkspace->ResetAppliedAspect();
2329 aContext->SetAllowSampleAlphaToCoverage (false);
2330 aContext->SetSampleAlphaToCoverage (false);
2332 // reset FFP state for safety
2333 aContext->BindProgram (Handle(OpenGl_ShaderProgram)());
2334 if (aContext->caps->ffpEnable)
2336 aContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
2340 // =======================================================================
2341 // function : InvalidateBVHData
2343 // =======================================================================
2344 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
2346 myZLayers.InvalidateBVHData (theLayerId);
2349 //=======================================================================
2350 //function : renderStructs
2352 //=======================================================================
2353 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
2354 OpenGl_FrameBuffer* theReadDrawFbo,
2355 OpenGl_FrameBuffer* theOitAccumFbo,
2356 const Standard_Boolean theToDrawImmediate)
2358 myZLayers.UpdateCulling (myWorkspace, theToDrawImmediate);
2359 if ( myZLayers.NbStructures() <= 0 )
2362 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2363 Standard_Boolean toRenderGL = theToDrawImmediate ||
2364 myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
2365 myRaytraceInitStatus == OpenGl_RT_FAIL ||
2370 const Graphic3d_Vec2i aSizeXY = theReadDrawFbo != NULL
2371 ? theReadDrawFbo->GetVPSize()
2372 : Graphic3d_Vec2i (myWindow->Width(), myWindow->Height());
2374 toRenderGL = !initRaytraceResources (aSizeXY.x(), aSizeXY.y(), aCtx)
2375 || !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
2377 toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
2381 myOpenGlFBO ->InitLazy (aCtx, aSizeXY, myFboColorFormat, myFboDepthFormat, 0);
2382 if (theReadDrawFbo != NULL)
2384 theReadDrawFbo->UnbindBuffer (aCtx);
2387 // Prepare preliminary OpenGL output
2388 if (aCtx->arbFBOBlit != NULL)
2390 // Render bottom OSD layer
2391 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom, theReadDrawFbo, theOitAccumFbo);
2393 const Standard_Integer aPrevFilter = myWorkspace->RenderFilter() & ~(Standard_Integer )(OpenGl_RenderFilter_NonRaytraceableOnly);
2394 myWorkspace->SetRenderFilter (aPrevFilter | OpenGl_RenderFilter_NonRaytraceableOnly);
2396 if (theReadDrawFbo != NULL)
2398 theReadDrawFbo->BindDrawBuffer (aCtx);
2402 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
2403 aCtx->SetFrameBufferSRGB (false);
2406 // Render non-polygonal elements in default layer
2407 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_RayTracable, theReadDrawFbo, theOitAccumFbo);
2409 myWorkspace->SetRenderFilter (aPrevFilter);
2412 if (theReadDrawFbo != NULL)
2414 theReadDrawFbo->BindBuffer (aCtx);
2418 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
2419 aCtx->SetFrameBufferSRGB (false);
2422 // Reset OpenGl aspects state to default to avoid enabling of
2423 // backface culling which is not supported in ray-tracing.
2424 myWorkspace->ResetAppliedAspect();
2426 // Ray-tracing polygonal primitive arrays
2427 raytrace (aSizeXY.x(), aSizeXY.y(), theProjection, theReadDrawFbo, aCtx);
2429 // Render upper (top and topmost) OpenGL layers
2430 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper, theReadDrawFbo, theOitAccumFbo);
2434 // Redraw 3D scene using OpenGL in standard
2435 // mode or in case of ray-tracing failure
2438 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All, theReadDrawFbo, theOitAccumFbo);
2440 // Set flag that scene was redrawn by standard pipeline
2441 myWasRedrawnGL = Standard_True;
2445 //=======================================================================
2446 //function : renderTrihedron
2448 //=======================================================================
2449 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
2451 if (myToShowGradTrihedron)
2453 myGraduatedTrihedron.Render (theWorkspace);
2457 //=======================================================================
2458 //function : renderFrameStats
2460 //=======================================================================
2461 void OpenGl_View::renderFrameStats()
2463 if (myRenderParams.ToShowStats
2464 && myRenderParams.CollectedStats != Graphic3d_RenderingParams::PerfCounters_NONE)
2466 myFrameStatsPrs.Update (myWorkspace);
2467 myFrameStatsPrs.Render (myWorkspace);
2471 // =======================================================================
2472 // function : Invalidate
2474 // =======================================================================
2475 void OpenGl_View::Invalidate()
2477 myBackBufferRestored = Standard_False;
2480 //=======================================================================
2481 //function : renderScene
2483 //=======================================================================
2484 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
2485 OpenGl_FrameBuffer* theReadDrawFbo,
2486 OpenGl_FrameBuffer* theOitAccumFbo,
2487 const Standard_Boolean theToDrawImmediate)
2489 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
2491 // Specify clipping planes in view transformation space
2492 aContext->ChangeClipping().Reset (myClipPlanes);
2493 if (!myClipPlanes.IsNull()
2494 && !myClipPlanes->IsEmpty())
2496 aContext->ShaderManager()->UpdateClippingState();
2499 renderStructs (theProjection, theReadDrawFbo, theOitAccumFbo, theToDrawImmediate);
2500 aContext->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
2502 // Apply restored view matrix.
2503 aContext->ApplyWorldViewMatrix();
2505 aContext->ChangeClipping().Reset (Handle(Graphic3d_SequenceOfHClipPlane)());
2506 if (!myClipPlanes.IsNull()
2507 && !myClipPlanes->IsEmpty())
2509 aContext->ShaderManager()->RevertClippingState();
2513 // =======================================================================
2514 // function : bindDefaultFbo
2516 // =======================================================================
2517 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
2519 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2520 OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
2522 : (!aCtx->DefaultFrameBuffer().IsNull()
2523 && aCtx->DefaultFrameBuffer()->IsValid()
2524 ? aCtx->DefaultFrameBuffer().operator->()
2528 anFbo->BindBuffer (aCtx);
2529 anFbo->SetupViewport (aCtx);
2533 #if !defined(GL_ES_VERSION_2_0)
2534 aCtx->SetReadDrawBuffer (GL_BACK);
2536 if (aCtx->arbFBO != NULL)
2538 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2541 const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
2542 aCtx->ResizeViewport (aViewport);
2546 // =======================================================================
2547 // function : initBlitQuad
2549 // =======================================================================
2550 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
2552 OpenGl_VertexBuffer* aVerts = NULL;
2555 aVerts = &myFullScreenQuad;
2556 if (!aVerts->IsValid())
2558 OpenGl_Vec4 aQuad[4] =
2560 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
2561 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 1.0f),
2562 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
2563 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 1.0f)
2565 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
2570 aVerts = &myFullScreenQuadFlip;
2571 if (!aVerts->IsValid())
2573 OpenGl_Vec4 aQuad[4] =
2575 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
2576 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 0.0f),
2577 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
2578 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 0.0f)
2580 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
2586 // =======================================================================
2587 // function : blitBuffers
2589 // =======================================================================
2590 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer* theReadFbo,
2591 OpenGl_FrameBuffer* theDrawFbo,
2592 const Standard_Boolean theToFlip)
2594 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2595 const Standard_Integer aReadSizeX = theReadFbo != NULL ? theReadFbo->GetVPSizeX() : myWindow->Width();
2596 const Standard_Integer aReadSizeY = theReadFbo != NULL ? theReadFbo->GetVPSizeY() : myWindow->Height();
2597 const Standard_Integer aDrawSizeX = theDrawFbo != NULL ? theDrawFbo->GetVPSizeX() : myWindow->Width();
2598 const Standard_Integer aDrawSizeY = theDrawFbo != NULL ? theDrawFbo->GetVPSizeY() : myWindow->Height();
2599 if (theReadFbo == NULL || aCtx->IsFeedback())
2603 else if (theReadFbo == theDrawFbo)
2608 // clear destination before blitting
2609 if (theDrawFbo != NULL
2610 && theDrawFbo->IsValid())
2612 theDrawFbo->BindBuffer (aCtx);
2616 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2617 aCtx->SetFrameBufferSRGB (false);
2619 const Standard_Integer aViewport[4] = { 0, 0, aDrawSizeX, aDrawSizeY };
2620 aCtx->ResizeViewport (aViewport);
2622 aCtx->SetColorMaskRGBA (NCollection_Vec4<bool> (true)); // force writes into all components, including alpha
2623 aCtx->core20fwd->glClearDepth (1.0);
2624 aCtx->core20fwd->glClearColor (0.0f, 0.0f, 0.0f, aCtx->caps->buffersOpaqueAlpha ? 1.0f : 0.0f);
2625 aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
2626 aCtx->SetColorMask (true); // restore default alpha component write state
2628 const bool toApplyGamma = aCtx->ToRenderSRGB() != aCtx->IsFrameBufferSRGB();
2629 if (aCtx->arbFBOBlit != NULL
2631 && theReadFbo->NbSamples() != 0)
2633 GLbitfield aCopyMask = 0;
2634 theReadFbo->BindReadBuffer (aCtx);
2635 if (theDrawFbo != NULL
2636 && theDrawFbo->IsValid())
2638 theDrawFbo->BindDrawBuffer (aCtx);
2639 if (theDrawFbo->HasColor()
2640 && theReadFbo->HasColor())
2642 aCopyMask |= GL_COLOR_BUFFER_BIT;
2644 if (theDrawFbo->HasDepth()
2645 && theReadFbo->HasDepth())
2647 aCopyMask |= GL_DEPTH_BUFFER_BIT;
2652 if (theReadFbo->HasColor())
2654 aCopyMask |= GL_COLOR_BUFFER_BIT;
2656 if (theReadFbo->HasDepth())
2658 aCopyMask |= GL_DEPTH_BUFFER_BIT;
2660 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2661 aCtx->SetFrameBufferSRGB (false);
2664 // we don't copy stencil buffer here... does it matter for performance?
2665 aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aReadSizeX, aReadSizeY,
2666 0, 0, aDrawSizeX, aDrawSizeY,
2667 aCopyMask, GL_NEAREST);
2668 const int anErr = aCtx->core11fwd->glGetError();
2669 if (anErr != GL_NO_ERROR)
2671 // glBlitFramebuffer() might fail in several cases:
2672 // - Both FBOs have MSAA and they are samples number does not match.
2673 // OCCT checks that this does not happen,
2674 // however some graphics drivers provide an option for overriding MSAA.
2675 // In this case window MSAA might be non-zero (and application can not check it)
2676 // and might not match MSAA of our offscreen FBOs.
2677 // - Pixel formats of FBOs do not match.
2678 // This also might happen with window has pixel format,
2679 // e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
2680 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error " + OpenGl_Context::FormatGlError (anErr) + "]\n"
2681 + " Please check your graphics driver settings or try updating driver.";
2682 if (theReadFbo->NbSamples() != 0)
2684 myToDisableMSAA = true;
2685 aMsg += "\n MSAA settings should not be overridden by driver!";
2687 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
2690 if (theDrawFbo != NULL
2691 && theDrawFbo->IsValid())
2693 theDrawFbo->BindBuffer (aCtx);
2697 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2698 aCtx->SetFrameBufferSRGB (false);
2703 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
2704 aCtx->core20fwd->glDepthMask (GL_TRUE);
2705 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
2706 #if defined(GL_ES_VERSION_2_0)
2707 if (!aCtx->IsGlGreaterEqual (3, 0)
2708 && !aCtx->extFragDepth)
2710 aCtx->core20fwd->glDisable (GL_DEPTH_TEST);
2714 aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
2716 const Graphic3d_TypeOfTextureFilter aFilter = (aDrawSizeX == aReadSizeX && aDrawSizeY == aReadSizeY) ? Graphic3d_TOTF_NEAREST : Graphic3d_TOTF_BILINEAR;
2717 const GLint aFilterGl = aFilter == Graphic3d_TOTF_NEAREST ? GL_NEAREST : GL_LINEAR;
2719 OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
2720 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
2721 if (aVerts->IsValid()
2722 && aManager->BindFboBlitProgram (theReadFbo != NULL ? theReadFbo->NbSamples() : 0, toApplyGamma))
2724 aCtx->SetSampleAlphaToCoverage (false);
2725 theReadFbo->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
2726 if (theReadFbo->ColorTexture()->Sampler()->Parameters()->Filter() != aFilter)
2728 theReadFbo->ColorTexture()->Sampler()->Parameters()->SetFilter (aFilter);
2729 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
2730 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
2733 theReadFbo->DepthStencilTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
2734 if (theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->Filter() != aFilter)
2736 theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->SetFilter (aFilter);
2737 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
2738 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
2741 aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
2743 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2745 aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
2746 theReadFbo->DepthStencilTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
2747 theReadFbo->ColorTexture() ->Unbind (aCtx, Graphic3d_TextureUnit_0);
2748 aCtx->BindProgram (NULL);
2752 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
2753 + "Error! FBO blitting has failed";
2754 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
2755 GL_DEBUG_TYPE_ERROR,
2757 GL_DEBUG_SEVERITY_HIGH,
2759 myHasFboBlit = Standard_False;
2760 theReadFbo->Release (aCtx.operator->());
2767 // =======================================================================
2768 // function : drawStereoPair
2770 // =======================================================================
2771 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
2773 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2774 bindDefaultFbo (theDrawFbo);
2775 OpenGl_FrameBuffer* aPair[2] =
2777 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
2778 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
2780 if (aPair[0] == NULL
2782 || !myTransientDrawToFront)
2784 aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
2785 aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
2788 if (aPair[0] == NULL
2789 || aPair[1] == NULL)
2794 if (aPair[0]->NbSamples() != 0)
2796 // resolve MSAA buffers before drawing
2797 if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSize(), myFboColorFormat, myFboDepthFormat, 0)
2798 || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSize(), myFboColorFormat, 0, 0))
2800 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
2801 GL_DEBUG_TYPE_ERROR,
2803 GL_DEBUG_SEVERITY_HIGH,
2804 "Error! Unable to allocate FBO for blitting stereo pair");
2805 bindDefaultFbo (theDrawFbo);
2809 if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
2810 || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
2812 bindDefaultFbo (theDrawFbo);
2816 aPair[0] = myOpenGlFBO .operator->();
2817 aPair[1] = myOpenGlFBO2.operator->();
2818 bindDefaultFbo (theDrawFbo);
2823 Standard_Integer left;
2824 Standard_Integer top;
2825 Standard_Integer right;
2826 Standard_Integer bottom;
2827 Standard_Integer dx() { return right - left; }
2828 Standard_Integer dy() { return bottom - top; }
2831 myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
2833 Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
2834 const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
2835 const Standard_Boolean isOddX = aGeom.left % 2 == 1;
2837 && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
2838 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
2840 toReverse = !toReverse;
2843 && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
2844 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
2846 toReverse = !toReverse;
2851 std::swap (aPair[0], aPair[1]);
2854 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
2855 aCtx->core20fwd->glDepthMask (GL_TRUE);
2856 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
2858 aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
2859 OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
2861 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
2862 if (aVerts->IsValid()
2863 && aManager->BindStereoProgram (myRenderParams.StereoMode))
2865 if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
2867 OpenGl_Mat4 aFilterL, aFilterR;
2868 aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
2869 aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
2870 switch (myRenderParams.AnaglyphFilter)
2872 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
2874 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
2875 aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
2876 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
2879 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
2881 aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f, 0.4710f, 0.16666667f, 0.0f));
2882 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f, -0.0484f, -0.0257f, 0.0f));
2883 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f, -0.0615f, 0.0128f, 0.0f));
2884 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
2885 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
2886 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f, 0.73333333f, 0.01111111f, 0.0f));
2887 aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f, 1.29710000f, 0.0f));
2888 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
2891 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
2893 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
2894 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
2895 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
2898 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
2900 aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f, 0.299f, 0.0f));
2901 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f, 0.908f, 0.068f, 0.0f));
2902 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f, 0.022f, 0.0f));
2903 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
2904 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
2905 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f, 0.062f, -0.017f, 0.0f));
2906 aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f, 0.185f, 0.911f, 0.0f));
2907 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
2910 case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
2912 aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
2913 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
2914 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
2917 case Graphic3d_RenderingParams::Anaglyph_UserDefined:
2919 aFilterL = myRenderParams.AnaglyphLeft;
2920 aFilterR = myRenderParams.AnaglyphRight;
2924 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
2925 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
2928 aPair[0]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
2929 aPair[1]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
2930 aVerts->BindVertexAttrib (aCtx, 0);
2932 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2934 aVerts->UnbindVertexAttrib (aCtx, 0);
2935 aPair[1]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
2936 aPair[0]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_0);
2940 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
2941 + "Error! Anaglyph has failed";
2942 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
2943 GL_DEBUG_TYPE_ERROR,
2945 GL_DEBUG_SEVERITY_HIGH,
2950 // =======================================================================
2951 // function : copyBackToFront
2953 // =======================================================================
2954 bool OpenGl_View::copyBackToFront()
2956 myIsImmediateDrawn = Standard_False;
2957 #if !defined(GL_ES_VERSION_2_0)
2958 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2959 if (aCtx->core11ffp == NULL)
2964 OpenGl_Mat4 aProjectMat;
2965 Graphic3d_TransformUtils::Ortho2D (aProjectMat,
2966 0.0f, static_cast<GLfloat> (myWindow->Width()),
2967 0.0f, static_cast<GLfloat> (myWindow->Height()));
2969 aCtx->WorldViewState.Push();
2970 aCtx->ProjectionState.Push();
2972 aCtx->WorldViewState.SetIdentity();
2973 aCtx->ProjectionState.SetCurrent (aProjectMat);
2975 aCtx->ApplyProjectionMatrix();
2976 aCtx->ApplyWorldViewMatrix();
2978 // synchronize FFP state before copying pixels
2979 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
2980 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
2981 aCtx->DisableFeatures();
2983 switch (aCtx->DrawBuffer())
2987 aCtx->SetReadBuffer (GL_BACK_LEFT);
2988 aCtx->SetDrawBuffer (GL_FRONT_LEFT);
2993 aCtx->SetReadBuffer (GL_BACK_RIGHT);
2994 aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
2999 aCtx->SetReadBuffer (GL_BACK);
3000 aCtx->SetDrawBuffer (GL_FRONT);
3005 aCtx->core11ffp->glRasterPos2i (0, 0);
3006 aCtx->core11ffp->glCopyPixels (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
3007 //aCtx->core11ffp->glCopyPixels (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
3009 aCtx->EnableFeatures();
3011 aCtx->WorldViewState.Pop();
3012 aCtx->ProjectionState.Pop();
3013 aCtx->ApplyProjectionMatrix();
3015 // read/write from front buffer now
3016 aCtx->SetReadBuffer (aCtx->DrawBuffer());
3023 // =======================================================================
3024 // function : checkOitCompatibility
3026 // =======================================================================
3027 Standard_Boolean OpenGl_View::checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
3028 const Standard_Boolean theMSAA)
3030 // determine if OIT is supported by current OpenGl context
3031 Standard_Boolean& aToDisableOIT = theMSAA ? myToDisableMSAA : myToDisableOIT;
3034 return Standard_False;
3037 TCollection_ExtendedString aCompatibilityMsg;
3038 if (theGlContext->hasFloatBuffer == OpenGl_FeatureNotAvailable
3039 && theGlContext->hasHalfFloatBuffer == OpenGl_FeatureNotAvailable)
3041 aCompatibilityMsg += "OpenGL context does not support floating-point RGBA color buffer format.\n";
3043 if (theMSAA && theGlContext->hasSampleVariables == OpenGl_FeatureNotAvailable)
3045 aCompatibilityMsg += "Current version of GLSL does not support built-in sample variables.\n";
3047 if (theGlContext->hasDrawBuffers == OpenGl_FeatureNotAvailable)
3049 aCompatibilityMsg += "OpenGL context does not support multiple draw buffers.\n";
3051 if (aCompatibilityMsg.IsEmpty())
3053 return Standard_True;
3056 aCompatibilityMsg += " Blended order-independent transparency will not be available.\n";
3057 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
3058 GL_DEBUG_TYPE_ERROR,
3060 GL_DEBUG_SEVERITY_HIGH,
3063 aToDisableOIT = Standard_True;
3064 return Standard_False;
3067 // =======================================================================
3068 // function : checkPBRAvailability
3070 // =======================================================================
3071 Standard_Boolean OpenGl_View::checkPBRAvailability() const
3073 return myWorkspace->GetGlContext()->HasPBR()
3074 && !myPBREnvironment.IsNull();
3077 // =======================================================================
3078 // function : updatePBREnvironment
3080 // =======================================================================
3081 void OpenGl_View::updatePBREnvironment (const Handle(OpenGl_Context)& theCtx)
3083 if (myPBREnvState != OpenGl_PBREnvState_CREATED
3084 || !myPBREnvRequest)
3086 myPBREnvRequest = false;
3090 myPBREnvRequest = false;
3092 Handle(OpenGl_TextureSet) aGlTextureSet;
3093 OpenGl_Aspects* aTmpGlAspects = NULL;
3094 if (!myCubeMapIBL.IsNull()
3095 && myCubeMapIBL == myCubeMapBackground)
3097 aGlTextureSet = myCubeMapParams->TextureSet (theCtx);
3099 else if (!myCubeMapIBL.IsNull())
3101 myCubeMapIBL->SetMipmapsGeneration (Standard_True);
3103 Handle(Graphic3d_AspectFillArea3d) anAspect = new Graphic3d_AspectFillArea3d();
3105 Handle(Graphic3d_TextureSet) aTextureSet = new Graphic3d_TextureSet (myCubeMapIBL);
3106 anAspect->SetInteriorStyle (Aspect_IS_SOLID);
3107 anAspect->SetTextureSet (aTextureSet);
3108 anAspect->SetTextureMapOn (true);
3111 aTmpGlAspects = new OpenGl_Aspects();
3112 aTmpGlAspects->SetAspect (anAspect);
3113 aGlTextureSet = aTmpGlAspects->TextureSet (theCtx);
3116 if (!aGlTextureSet.IsNull()
3117 && !aGlTextureSet->IsEmpty())
3119 myPBREnvironment->Bake (theCtx,
3120 aGlTextureSet->First(),
3121 myCubeMapIBL->ZIsInverted(),
3122 myCubeMapIBL->IsTopDown(),
3123 myRenderParams.PbrEnvBakingDiffNbSamples,
3124 myRenderParams.PbrEnvBakingSpecNbSamples,
3125 myRenderParams.PbrEnvBakingProbability);
3129 myPBREnvironment->Clear (theCtx);
3131 aGlTextureSet.Nullify();
3132 OpenGl_Element::Destroy (theCtx.get(), aTmpGlAspects);