1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 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 <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_BackgroundArray.hxx>
20 #include <OpenGl_FrameBuffer.hxx>
21 #include <OpenGl_PrimitiveArray.hxx>
22 #include <OpenGl_VertexBuffer.hxx>
23 #include <OpenGl_SceneGeometry.hxx>
24 #include <OpenGl_ShaderProgram.hxx>
25 #include <OpenGl_TextureBuffer.hxx>
26 #include <OpenGl_GlCore44.hxx>
27 #include <OSD_Protection.hxx>
28 #include <OSD_File.hxx>
30 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
31 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
32 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
33 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
34 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
35 #include "../Shaders/Shaders_Display_fs.pxx"
36 #include "../Shaders/Shaders_TangentSpaceNormal_glsl.pxx"
38 //! Use this macro to output ray-tracing debug info
39 // #define RAY_TRACE_PRINT_INFO
41 #ifdef RAY_TRACE_PRINT_INFO
42 #include <OSD_Timer.hxx>
47 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
48 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
53 //! Defines OpenGL texture samplers.
54 static const Graphic3d_TextureUnit OpenGl_RT_EnvMapTexture = Graphic3d_TextureUnit_0;
56 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
57 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
58 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
59 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
61 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
62 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
63 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
64 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
66 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
67 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
69 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
70 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
72 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
75 // =======================================================================
76 // function : updateRaytraceGeometry
77 // purpose : Updates 3D scene geometry for ray-tracing
78 // =======================================================================
79 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
80 const Standard_Integer theViewId,
81 const Handle(OpenGl_Context)& theGlContext)
83 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
84 // modifications. This is light-weight procedure performed on each frame
85 if (theMode == OpenGl_GUM_CHECK)
87 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
89 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
92 else if (theMode == OpenGl_GUM_PREPARE)
94 myRaytraceGeometry.ClearMaterials();
96 myArrayToTrianglesMap.clear();
98 myIsRaytraceDataValid = Standard_False;
101 // The set of processed structures (reflected to ray-tracing)
102 // This set is used to remove out-of-date records from the
103 // hash map of structures
104 std::set<const OpenGl_Structure*> anElements;
106 // Set to store all currently visible OpenGL primitive arrays
107 // applicable for ray-tracing
108 std::set<Standard_Size> anArrayIDs;
110 // Set to store all non-raytracable elements allowing tracking
111 // of changes in OpenGL scene (only for path tracing)
112 std::set<Standard_Integer> aNonRaytraceIDs;
114 for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
116 const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
117 if (aLayer->NbStructures() == 0
118 || !aLayer->LayerSettings().IsRaytracable()
119 || aLayer->LayerSettings().IsImmediate())
124 const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
125 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
127 for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
129 const OpenGl_Structure* aStructure = aStructIt.Value();
131 if (theMode == OpenGl_GUM_CHECK)
133 if (toUpdateStructure (aStructure))
135 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
137 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
139 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
142 else if (theMode == OpenGl_GUM_PREPARE)
144 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
148 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
153 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
155 // Extract OpenGL elements from the group (primitives arrays)
156 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
158 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
160 if (aPrimArray != NULL)
162 anArrayIDs.insert (aPrimArray->GetUID());
167 else if (theMode == OpenGl_GUM_REBUILD)
169 if (!aStructure->IsRaytracable())
173 else if (addRaytraceStructure (aStructure, theGlContext))
175 anElements.insert (aStructure); // structure was processed
182 if (theMode == OpenGl_GUM_PREPARE)
184 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
186 // Filter out unchanged objects so only their transformations and materials
187 // will be updated (and newly added objects will be processed from scratch)
188 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
190 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
191 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
193 if (aTriangleSet == NULL)
198 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
200 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
202 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
206 myRaytraceGeometry.Objects() = anUnchangedObjects;
208 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
210 else if (theMode == OpenGl_GUM_REBUILD)
212 // Actualize the hash map of structures - remove out-of-date records
213 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
215 while (anIter != myStructureStates.end())
217 if (anElements.find (anIter->first) == anElements.end())
219 myStructureStates.erase (anIter++);
227 // Actualize OpenGL layer list state
228 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
230 // Rebuild two-level acceleration structure
231 myRaytraceGeometry.ProcessAcceleration();
233 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
234 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
235 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
237 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
239 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
241 return uploadRaytraceData (theGlContext);
244 if (myRaytraceParameters.GlobalIllumination)
246 Standard_Boolean toRestart =
247 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
249 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
251 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
253 toRestart = Standard_True;
262 myNonRaytraceStructureIDs = aNonRaytraceIDs;
265 return Standard_True;
268 // =======================================================================
269 // function : toUpdateStructure
270 // purpose : Checks to see if the structure is modified
271 // =======================================================================
272 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
274 if (!theStructure->IsRaytracable())
276 if (theStructure->ModificationState() > 0)
278 theStructure->ResetModificationState();
280 return Standard_True; // ray-trace element was removed - need to rebuild
283 return Standard_False; // did not contain ray-trace elements
286 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
288 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
290 return Standard_True;
292 else if (theStructure->InstancedStructure() != NULL)
294 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
297 return Standard_False;
300 // =======================================================================
301 // function : buildTextureTransform
302 // purpose : Constructs texture transformation matrix
303 // =======================================================================
304 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
306 theMatrix.InitIdentity();
307 if (theParams.IsNull())
313 const Graphic3d_Vec2& aScale = theParams->Scale();
315 theMatrix.ChangeValue (0, 0) *= aScale.x();
316 theMatrix.ChangeValue (1, 0) *= aScale.x();
317 theMatrix.ChangeValue (2, 0) *= aScale.x();
318 theMatrix.ChangeValue (3, 0) *= aScale.x();
320 theMatrix.ChangeValue (0, 1) *= aScale.y();
321 theMatrix.ChangeValue (1, 1) *= aScale.y();
322 theMatrix.ChangeValue (2, 1) *= aScale.y();
323 theMatrix.ChangeValue (3, 1) *= aScale.y();
326 const Graphic3d_Vec2 aTrans = -theParams->Translation();
328 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
329 theMatrix.GetValue (0, 1) * aTrans.y();
331 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
332 theMatrix.GetValue (1, 1) * aTrans.y();
334 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
335 theMatrix.GetValue (2, 1) * aTrans.y();
338 const Standard_ShortReal aSin = std::sin (
339 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
340 const Standard_ShortReal aCos = std::cos (
341 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
343 BVH_Mat4f aRotationMat;
344 aRotationMat.SetValue (0, 0, aCos);
345 aRotationMat.SetValue (1, 1, aCos);
346 aRotationMat.SetValue (0, 1, -aSin);
347 aRotationMat.SetValue (1, 0, aSin);
349 theMatrix = theMatrix * aRotationMat;
352 // =======================================================================
353 // function : convertMaterial
354 // purpose : Creates ray-tracing material properties
355 // =======================================================================
356 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
357 const Handle(OpenGl_Context)& theGlContext)
359 OpenGl_RaytraceMaterial aResMat;
361 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
362 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
363 const float aShine = 128.0f * float(aSrcMat.Shininess());
365 const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
366 const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
367 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
368 const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
369 switch (aSrcMat.MaterialType())
371 case Graphic3d_MATERIAL_ASPECT:
373 aResMat.Ambient .SetValues (aSrcAmb * aMatCol, 1.0f);
374 aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
375 aResMat.Emission.SetValues (aSrcEms * aMatCol, 1.0f);
378 case Graphic3d_MATERIAL_PHYSIC:
380 aResMat.Ambient .SetValues (aSrcAmb, 1.0f);
381 aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
382 aResMat.Emission.SetValues (aSrcEms, 1.0f);
388 // interior color is always ignored for Specular
389 aResMat.Specular.SetValues (aSrcSpe, aShine);
390 const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
391 Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
392 aResMat.Diffuse.z() + aResMat.Specular.z()));
393 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
394 aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
397 const float anIndex = (float )aSrcMat.RefractionIndex();
398 aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
399 anIndex == 0 ? 1.0f : anIndex,
400 anIndex == 0 ? 1.0f : 1.0f / anIndex);
402 aResMat.Ambient = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
403 aResMat.Diffuse = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
404 aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
405 aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
407 // Serialize physically-based material properties
408 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
410 aResMat.BSDF.Kc = aBSDF.Kc;
411 aResMat.BSDF.Ks = aBSDF.Ks;
412 aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.0f); // no base color texture
413 aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, -1.0f); // no metallic-roughness texture
414 aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, -1.0f); // no emissive texture
416 aResMat.BSDF.Absorption = aBSDF.Absorption;
418 aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
419 aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
420 aResMat.BSDF.FresnelBase.w() = -1.0; // no normal map texture
422 // Handle material textures
423 if (!theAspect->Aspect()->ToMapTexture())
428 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
429 if (aTextureSet.IsNull()
430 || aTextureSet->IsEmpty()
431 || aTextureSet->First().IsNull())
436 if (theGlContext->HasRayTracingTextures())
438 // write texture ID to diffuse w-components
439 for (OpenGl_TextureSet::Iterator aTexIter (aTextureSet); aTexIter.More(); aTexIter.Next())
441 const Handle(OpenGl_Texture)& aTexture = aTexIter.Value();
442 if (aTexIter.Unit() == Graphic3d_TextureUnit_BaseColor)
444 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
445 aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
447 else if (aTexIter.Unit() == Graphic3d_TextureUnit_MetallicRoughness)
449 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
450 aResMat.BSDF.Kt.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
452 else if (aTexIter.Unit() == Graphic3d_TextureUnit_Emissive)
454 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
455 aResMat.BSDF.Le.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
457 else if (aTexIter.Unit() == Graphic3d_TextureUnit_Normal)
459 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
460 aResMat.BSDF.FresnelBase.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
464 else if (!myIsRaytraceWarnTextures)
466 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
467 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
468 "Please try to update graphics card driver. At the moment textures will be ignored.");
469 myIsRaytraceWarnTextures = Standard_True;
475 // =======================================================================
476 // function : addRaytraceStructure
477 // purpose : Adds OpenGL structure to ray-traced scene geometry
478 // =======================================================================
479 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
480 const Handle(OpenGl_Context)& theGlContext)
482 if (!theStructure->IsVisible())
484 myStructureStates[theStructure] = StructState (theStructure);
486 return Standard_True;
489 // Get structure material
490 OpenGl_RaytraceMaterial aDefaultMaterial;
491 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
493 // Process all connected OpenGL structures
494 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
496 if (anInstanced != NULL && anInstanced->IsRaytracable())
498 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
501 myStructureStates[theStructure] = StructState (theStructure);
506 // =======================================================================
507 // function : addRaytraceGroups
508 // purpose : Adds OpenGL groups to ray-traced scene geometry
509 // =======================================================================
510 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
511 const OpenGl_RaytraceMaterial& theStructMat,
512 const Handle(TopLoc_Datum3D)& theTrsf,
513 const Handle(OpenGl_Context)& theGlContext)
516 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
518 // Get group material
519 OpenGl_RaytraceMaterial aGroupMaterial;
520 if (aGroupIter.Value()->GlAspects() != NULL)
522 aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
525 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
527 // Use group material if available, otherwise use structure material
528 myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
530 // Add OpenGL elements from group (extract primitives arrays and aspects)
531 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
533 OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
535 if (anAspect != NULL)
537 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
539 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
541 myRaytraceGeometry.Materials.push_back (aMaterial);
545 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
547 if (aPrimArray != NULL)
549 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
551 if (aSetIter != myArrayToTrianglesMap.end())
553 OpenGl_TriangleSet* aSet = aSetIter->second;
554 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
555 if (!theTrsf.IsNull())
557 theTrsf->Trsf().GetMat4 (aMat4);
558 aTransform->SetTransform (aMat4);
561 aSet->SetProperties (aTransform);
562 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
564 aSet->SetMaterialIndex (aMatID);
569 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
571 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
572 if (!theTrsf.IsNull())
574 theTrsf->Trsf().GetMat4 (aMat4);
575 aTransform->SetTransform (aMat4);
578 aSet->SetProperties (aTransform);
579 myRaytraceGeometry.Objects().Append (aSet);
587 return Standard_True;
590 // =======================================================================
591 // function : addRaytracePrimitiveArray
592 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
593 // =======================================================================
594 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
595 const Standard_Integer theMaterial,
596 const OpenGl_Mat4* theTransform)
598 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
599 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
600 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
602 if (theArray->DrawMode() < GL_TRIANGLES
603 #ifndef GL_ES_VERSION_2_0
604 || theArray->DrawMode() > GL_POLYGON
606 || theArray->DrawMode() > GL_TRIANGLE_FAN
608 || anAttribs.IsNull())
610 return Handle(OpenGl_TriangleSet)();
613 OpenGl_Mat4 aNormalMatrix;
614 if (theTransform != NULL)
616 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
617 "Error: Failed to compute normal transformation matrix", NULL);
619 aNormalMatrix.Transpose();
622 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
624 aSet->Vertices.reserve (anAttribs->NbElements);
625 aSet->Normals.reserve (anAttribs->NbElements);
626 aSet->TexCrds.reserve (anAttribs->NbElements);
628 const size_t aVertFrom = aSet->Vertices.size();
630 Standard_Integer anAttribIndex = 0;
631 Standard_Size anAttribStride = 0;
632 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
634 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
635 if (anAttrib.DataType == Graphic3d_TOD_VEC2
636 || anAttrib.DataType == Graphic3d_TOD_VEC3
637 || anAttrib.DataType == Graphic3d_TOD_VEC4)
639 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
641 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
642 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
646 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
648 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
649 if (anAttrib.DataType == Graphic3d_TOD_VEC3
650 || anAttrib.DataType == Graphic3d_TOD_VEC4)
652 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
654 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
658 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
660 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
661 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
663 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
665 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
670 if (aSet->Normals.size() != aSet->Vertices.size())
672 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
674 aSet->Normals.push_back (BVH_Vec3f());
678 if (aSet->TexCrds.size() != aSet->Vertices.size())
680 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
682 aSet->TexCrds.push_back (BVH_Vec2f());
686 if (theTransform != NULL)
688 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
690 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
692 BVH_Vec4f aTransVertex = *theTransform *
693 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
695 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
697 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
699 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
701 BVH_Vec4f aTransNormal = aNormalMatrix *
702 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
704 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
708 if (!aBounds.IsNull())
710 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
712 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
714 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
717 return Handle(OpenGl_TriangleSet)();
720 aBoundStart += aVertNum;
725 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
727 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
730 return Handle(OpenGl_TriangleSet)();
735 if (aSet->Size() != 0)
743 // =======================================================================
744 // function : addRaytraceVertexIndices
745 // purpose : Adds vertex indices to ray-traced scene geometry
746 // =======================================================================
747 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
748 const Standard_Integer theMatID,
749 const Standard_Integer theCount,
750 const Standard_Integer theOffset,
751 const OpenGl_PrimitiveArray& theArray)
753 switch (theArray.DrawMode())
755 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
756 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
757 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
758 #if !defined(GL_ES_VERSION_2_0)
759 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
760 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
761 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
765 return Standard_False;
768 // =======================================================================
769 // function : addRaytraceTriangleArray
770 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
771 // =======================================================================
772 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
773 const Standard_Integer theMatID,
774 const Standard_Integer theCount,
775 const Standard_Integer theOffset,
776 const Handle(Graphic3d_IndexBuffer)& theIndices)
780 return Standard_True;
783 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
785 if (!theIndices.IsNull())
787 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
789 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
790 theIndices->Index (aVert + 1),
791 theIndices->Index (aVert + 2),
797 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
799 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
803 return Standard_True;
806 // =======================================================================
807 // function : addRaytraceTriangleFanArray
808 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
809 // =======================================================================
810 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
811 const Standard_Integer theMatID,
812 const Standard_Integer theCount,
813 const Standard_Integer theOffset,
814 const Handle(Graphic3d_IndexBuffer)& theIndices)
818 return Standard_True;
821 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
823 if (!theIndices.IsNull())
825 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
827 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
828 theIndices->Index (aVert + 1),
829 theIndices->Index (aVert + 2),
835 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
837 theSet.Elements.push_back (BVH_Vec4i (theOffset,
844 return Standard_True;
847 // =======================================================================
848 // function : addRaytraceTriangleStripArray
849 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
850 // =======================================================================
851 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
852 const Standard_Integer theMatID,
853 const Standard_Integer theCount,
854 const Standard_Integer theOffset,
855 const Handle(Graphic3d_IndexBuffer)& theIndices)
859 return Standard_True;
862 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
864 if (!theIndices.IsNull())
866 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
868 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
869 theIndices->Index (aVert + (aCW ? 0 : 1)),
870 theIndices->Index (aVert + 2),
876 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
878 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
879 aVert + (aCW ? 0 : 1),
885 return Standard_True;
888 // =======================================================================
889 // function : addRaytraceQuadrangleArray
890 // purpose : Adds OpenGL quad array to ray-traced scene geometry
891 // =======================================================================
892 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
893 const Standard_Integer theMatID,
894 const Standard_Integer theCount,
895 const Standard_Integer theOffset,
896 const Handle(Graphic3d_IndexBuffer)& theIndices)
900 return Standard_True;
903 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
905 if (!theIndices.IsNull())
907 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
909 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
910 theIndices->Index (aVert + 1),
911 theIndices->Index (aVert + 2),
913 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
914 theIndices->Index (aVert + 2),
915 theIndices->Index (aVert + 3),
921 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
923 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
925 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
930 return Standard_True;
933 // =======================================================================
934 // function : addRaytraceQuadrangleStripArray
935 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
936 // =======================================================================
937 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
938 const Standard_Integer theMatID,
939 const Standard_Integer theCount,
940 const Standard_Integer theOffset,
941 const Handle(Graphic3d_IndexBuffer)& theIndices)
945 return Standard_True;
948 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
950 if (!theIndices.IsNull())
952 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
954 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
955 theIndices->Index (aVert + 1),
956 theIndices->Index (aVert + 2),
959 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
960 theIndices->Index (aVert + 3),
961 theIndices->Index (aVert + 2),
967 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
969 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
974 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
981 return Standard_True;
984 // =======================================================================
985 // function : addRaytracePolygonArray
986 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
987 // =======================================================================
988 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
989 const Standard_Integer theMatID,
990 const Standard_Integer theCount,
991 const Standard_Integer theOffset,
992 const Handle(Graphic3d_IndexBuffer)& theIndices)
996 return Standard_True;
999 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
1001 if (!theIndices.IsNull())
1003 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1005 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
1006 theIndices->Index (aVert + 1),
1007 theIndices->Index (aVert + 2),
1013 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1015 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1022 return Standard_True;
1025 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1027 // =======================================================================
1028 // function : Source
1029 // purpose : Returns shader source combined with prefix
1030 // =======================================================================
1031 TCollection_AsciiString OpenGl_View::ShaderSource::Source (const Handle(OpenGl_Context)& theCtx,
1032 const GLenum theType) const
1034 TCollection_AsciiString aVersion =
1035 #if defined(GL_ES_VERSION_2_0)
1036 "#version 320 es\n";
1040 TCollection_AsciiString aPrecisionHeader;
1041 if (theType == GL_FRAGMENT_SHADER)
1043 #if defined(GL_ES_VERSION_2_0)
1044 aPrecisionHeader = theCtx->hasHighp
1045 ? "precision highp float;\n"
1046 "precision highp int;\n"
1047 "precision highp samplerBuffer;\n"
1048 "precision highp isamplerBuffer;\n"
1049 : "precision mediump float;\n"
1050 "precision mediump int;\n"
1051 "precision mediump samplerBuffer;\n"
1052 "precision mediump isamplerBuffer;\n";
1057 if (myPrefix.IsEmpty())
1059 return aVersion + aPrecisionHeader + mySource;
1061 return aVersion + aPrecisionHeader + myPrefix + "\n" + mySource;
1064 // =======================================================================
1065 // function : LoadFromFiles
1066 // purpose : Loads shader source from specified files
1067 // =======================================================================
1068 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1069 const TCollection_AsciiString& thePrefix)
1073 myPrefix = thePrefix;
1075 TCollection_AsciiString aMissingFiles;
1076 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1078 OSD_File aFile (theFileNames[anIndex]);
1081 aFile.Open (OSD_ReadOnly, OSD_Protection());
1083 if (!aFile.IsOpen())
1085 if (!aMissingFiles.IsEmpty())
1087 aMissingFiles += ", ";
1089 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1092 else if (!aMissingFiles.IsEmpty())
1098 TCollection_AsciiString aSource;
1099 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1100 if (!aSource.IsEmpty())
1102 mySource += TCollection_AsciiString ("\n") + aSource;
1107 if (!aMissingFiles.IsEmpty())
1109 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1110 return Standard_False;
1112 return Standard_True;
1115 // =======================================================================
1116 // function : LoadFromStrings
1118 // =======================================================================
1119 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1120 const TCollection_AsciiString& thePrefix)
1124 myPrefix = thePrefix;
1126 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1128 TCollection_AsciiString aSource = theStrings[anIndex];
1129 if (!aSource.IsEmpty())
1131 mySource += TCollection_AsciiString ("\n") + aSource;
1134 return Standard_True;
1137 // =======================================================================
1138 // function : generateShaderPrefix
1139 // purpose : Generates shader prefix based on current ray-tracing options
1140 // =======================================================================
1141 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1143 TCollection_AsciiString aPrefixString =
1144 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1145 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1147 if (myRaytraceParameters.IsZeroToOneDepth)
1149 aPrefixString += TCollection_AsciiString ("\n#define THE_ZERO_TO_ONE_DEPTH");
1152 if (myRaytraceParameters.TransparentShadows)
1154 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1156 if (!theGlContext->ToRenderSRGB())
1158 aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
1161 // If OpenGL driver supports bindless textures and texturing
1162 // is actually used, activate texturing in ray-tracing mode
1163 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1165 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1166 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1169 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1171 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1173 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1175 if (theGlContext->IsGlGreaterEqual (4, 4))
1177 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1178 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1179 && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1181 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1186 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1188 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1191 switch (myRaytraceParameters.ToneMappingMethod)
1193 case Graphic3d_ToneMappingMethod_Disabled:
1195 case Graphic3d_ToneMappingMethod_Filmic:
1196 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1201 if (myRaytraceParameters.ToIgnoreNormalMap)
1203 aPrefixString += TCollection_AsciiString("\n#define IGNORE_NORMAL_MAP");
1206 if (myRaytraceParameters.CubemapForBack)
1208 aPrefixString += TCollection_AsciiString("\n#define BACKGROUND_CUBEMAP");
1211 if (myRaytraceParameters.DepthOfField)
1213 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1216 return aPrefixString;
1219 // =======================================================================
1220 // function : safeFailBack
1221 // purpose : Performs safe exit when shaders initialization fails
1222 // =======================================================================
1223 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1224 const Handle(OpenGl_Context)& theGlContext)
1226 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1227 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1229 myRaytraceInitStatus = OpenGl_RT_FAIL;
1231 releaseRaytraceResources (theGlContext);
1233 return Standard_False;
1236 // =======================================================================
1237 // function : initShader
1238 // purpose : Creates new shader object with specified source
1239 // =======================================================================
1240 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1241 const ShaderSource& theSource,
1242 const Handle(OpenGl_Context)& theGlContext)
1244 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1245 if (!aShader->Create (theGlContext))
1247 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1248 TCollection_ExtendedString ("Error: Failed to create ") +
1249 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1250 aShader->Release (theGlContext.get());
1251 return Handle(OpenGl_ShaderObject)();
1254 if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source (theGlContext, theType)))
1256 aShader->Release (theGlContext.get());
1257 return Handle(OpenGl_ShaderObject)();
1262 // =======================================================================
1263 // function : initProgram
1264 // purpose : Creates GLSL program from the given shader objects
1265 // =======================================================================
1266 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1267 const Handle(OpenGl_ShaderObject)& theVertShader,
1268 const Handle(OpenGl_ShaderObject)& theFragShader,
1269 const TCollection_AsciiString& theName)
1271 const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1272 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1274 if (!aProgram->Create (theGlContext))
1276 theVertShader->Release (theGlContext.operator->());
1278 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1279 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1281 return Handle(OpenGl_ShaderProgram)();
1284 if (!aProgram->AttachShader (theGlContext, theVertShader)
1285 || !aProgram->AttachShader (theGlContext, theFragShader))
1287 theVertShader->Release (theGlContext.operator->());
1289 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1290 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1292 return Handle(OpenGl_ShaderProgram)();
1295 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1297 TCollection_AsciiString aLinkLog;
1299 if (!aProgram->Link (theGlContext))
1301 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1303 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1304 "Failed to link shader program:\n") + aLinkLog;
1306 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1307 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1309 return Handle(OpenGl_ShaderProgram)();
1311 else if (theGlContext->caps->glslWarnings)
1313 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1314 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1316 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1317 "Shader program was linked with following warnings:\n") + aLinkLog;
1319 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1320 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1327 // =======================================================================
1328 // function : initRaytraceResources
1329 // purpose : Initializes OpenGL/GLSL shader programs
1330 // =======================================================================
1331 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1332 const Standard_Integer theSizeY,
1333 const Handle(OpenGl_Context)& theGlContext)
1335 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1337 return Standard_False;
1340 Standard_Boolean aToRebuildShaders = Standard_False;
1342 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1344 myRaytraceInitStatus = OpenGl_RT_NONE;
1345 releaseRaytraceResources (theGlContext, Standard_True);
1346 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1349 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1351 if (!myIsRaytraceDataValid)
1353 return Standard_True;
1356 const Standard_Integer aRequiredStackSize =
1357 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1359 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1361 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1363 aToRebuildShaders = Standard_True;
1367 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1369 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1371 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1372 aToRebuildShaders = Standard_True;
1377 const bool isZeroToOneDepth = myCaps->useZeroToOneDepth
1378 && myWorkspace->GetGlContext()->arbClipControl;
1379 if (isZeroToOneDepth != myRaytraceParameters.IsZeroToOneDepth
1380 || myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1381 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1382 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1383 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1384 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures
1385 || myRenderParams.ToIgnoreNormalMapInRayTracing != myRaytraceParameters.ToIgnoreNormalMap)
1387 myRaytraceParameters.IsZeroToOneDepth = isZeroToOneDepth;
1388 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1389 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1390 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1391 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1392 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1393 myRaytraceParameters.ToIgnoreNormalMap = myRenderParams.ToIgnoreNormalMapInRayTracing;
1394 aToRebuildShaders = Standard_True;
1397 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling
1398 || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1400 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1401 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1402 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1404 if (!theGlContext->HasRayTracingAdaptiveSampling())
1406 // disable the feature if it is not supported
1407 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1408 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1409 "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1411 else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1412 && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1414 // disable the feature if it is not supported
1415 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1416 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1417 "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1421 aToRebuildShaders = Standard_True;
1423 myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1425 const bool isCubemapForBack = !myBackgroundCubeMap.IsNull();
1426 if (myRaytraceParameters.CubemapForBack != isCubemapForBack)
1428 myRaytraceParameters.CubemapForBack = isCubemapForBack;
1429 aToRebuildShaders = Standard_True;
1432 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1433 if (myRaytraceParameters.DepthOfField != toEnableDof)
1435 myRaytraceParameters.DepthOfField = toEnableDof;
1436 aToRebuildShaders = Standard_True;
1439 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1441 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1442 aToRebuildShaders = true;
1445 if (aToRebuildShaders)
1447 // Reject accumulated frames
1450 // Environment map should be updated
1451 myToUpdateEnvironmentMap = Standard_True;
1453 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1454 #ifdef RAY_TRACE_PRINT_INFO
1455 Message::SendTrace() << "GLSL prefix string:" << std::endl << aPrefixString;
1457 myRaytraceShaderSource.SetPrefix (aPrefixString);
1458 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1459 myOutImageShaderSource.SetPrefix (aPrefixString);
1460 if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source (theGlContext, GL_FRAGMENT_SHADER))
1461 || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source (theGlContext, GL_FRAGMENT_SHADER))
1462 || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source (theGlContext, GL_FRAGMENT_SHADER)))
1464 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1467 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1468 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1469 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1470 if (!myRaytraceProgram->Link (theGlContext)
1471 || !myPostFSAAProgram->Link (theGlContext)
1472 || !myOutImageProgram->Link (theGlContext))
1474 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1479 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1481 myAccumFrames = 0; // accumulation should be restarted
1483 #if defined(GL_ES_VERSION_2_0)
1484 if (!theGlContext->IsGlGreaterEqual (3, 2))
1486 return safeFailBack ("Ray-tracing requires OpenGL ES 3.2 and higher", theGlContext);
1489 if (!theGlContext->IsGlGreaterEqual (3, 1))
1491 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1493 else if (!theGlContext->arbTboRGB32)
1495 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1497 else if (!theGlContext->arbFBOBlit)
1499 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1503 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1505 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1506 if (myIsRaytraceDataValid)
1508 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1509 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1512 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1514 #ifdef RAY_TRACE_PRINT_INFO
1515 Message::SendTrace() << "GLSL prefix string:" << std::endl << aPrefixString;
1518 ShaderSource aBasicVertShaderSrc;
1520 if (!aShaderFolder.IsEmpty())
1522 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1523 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1525 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1530 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1531 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1536 if (!aShaderFolder.IsEmpty())
1538 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1539 aShaderFolder + "/TangentSpaceNormal.glsl",
1540 aShaderFolder + "/PathtraceBase.fs",
1541 aShaderFolder + "/RaytraceRender.fs",
1543 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1545 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1550 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1551 Shaders_TangentSpaceNormal_glsl,
1552 Shaders_PathtraceBase_fs,
1553 Shaders_RaytraceRender_fs,
1555 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1558 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1559 if (aBasicVertShader.IsNull())
1561 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1564 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1565 if (myRaytraceShader.IsNull())
1567 aBasicVertShader->Release (theGlContext.operator->());
1568 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1571 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1572 if (myRaytraceProgram.IsNull())
1574 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1579 if (!aShaderFolder.IsEmpty())
1581 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1582 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1584 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1589 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1590 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1593 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1594 if (aBasicVertShader.IsNull())
1596 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1599 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1600 if (myPostFSAAShader.IsNull())
1602 aBasicVertShader->Release (theGlContext.operator->());
1603 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1606 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1607 if (myPostFSAAProgram.IsNull())
1609 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1614 if (!aShaderFolder.IsEmpty())
1616 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1617 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1619 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1624 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1625 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1628 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1629 if (aBasicVertShader.IsNull())
1631 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1634 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1635 if (myOutImageShader.IsNull())
1637 aBasicVertShader->Release (theGlContext.operator->());
1638 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1641 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1642 if (myOutImageProgram.IsNull())
1644 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1649 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1651 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1653 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1654 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1656 theGlContext->BindProgram (aShaderProgram);
1658 aShaderProgram->SetSampler (theGlContext,
1659 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1660 aShaderProgram->SetSampler (theGlContext,
1661 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1662 aShaderProgram->SetSampler (theGlContext,
1663 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1664 aShaderProgram->SetSampler (theGlContext,
1665 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1666 aShaderProgram->SetSampler (theGlContext,
1667 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1668 aShaderProgram->SetSampler (theGlContext,
1669 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1670 aShaderProgram->SetSampler (theGlContext,
1671 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1672 aShaderProgram->SetSampler (theGlContext,
1673 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1674 aShaderProgram->SetSampler (theGlContext,
1675 "uEnvMapTexture", OpenGl_RT_EnvMapTexture);
1676 aShaderProgram->SetSampler (theGlContext,
1677 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1678 aShaderProgram->SetSampler (theGlContext,
1679 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1683 aShaderProgram->SetSampler (theGlContext,
1684 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1688 aShaderProgram->SetSampler (theGlContext,
1689 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1692 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1693 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1695 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1696 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1697 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1698 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1699 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1700 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1701 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1702 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1703 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1704 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1705 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1706 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1707 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1708 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1709 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1710 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1711 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1712 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1713 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1714 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1716 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1717 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1718 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1719 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1720 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1721 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1722 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1723 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1725 myUniformLocations[anIndex][OpenGl_RT_uFsaaOffset] =
1726 aShaderProgram->GetUniformLocation (theGlContext, "uFsaaOffset");
1727 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1728 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1730 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1731 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1733 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1734 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1735 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1736 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1737 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnabled] =
1738 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapEnabled");
1739 myUniformLocations[anIndex][OpenGl_RT_uEnvMapForBack] =
1740 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapForBack");
1741 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1742 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1744 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1745 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1746 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1747 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1749 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1750 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1751 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1752 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1754 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1755 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1756 myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1757 aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1758 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1759 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1760 myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1761 aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1762 myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1763 aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1765 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1766 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1767 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1768 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1770 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1771 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1774 theGlContext->BindProgram (myOutImageProgram);
1776 myOutImageProgram->SetSampler (theGlContext,
1777 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1779 myOutImageProgram->SetSampler (theGlContext,
1780 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1782 theGlContext->BindProgram (NULL);
1785 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1787 return myRaytraceInitStatus == OpenGl_RT_INIT;
1790 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1797 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1799 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1801 return Standard_True;
1804 // =======================================================================
1805 // function : nullifyResource
1806 // purpose : Releases OpenGL resource
1807 // =======================================================================
1809 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1811 if (!theResource.IsNull())
1813 theResource->Release (theGlContext.get());
1814 theResource.Nullify();
1818 // =======================================================================
1819 // function : releaseRaytraceResources
1820 // purpose : Releases OpenGL/GLSL shader programs
1821 // =======================================================================
1822 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1824 // release shader resources
1825 nullifyResource (theGlContext, myRaytraceShader);
1826 nullifyResource (theGlContext, myPostFSAAShader);
1828 nullifyResource (theGlContext, myRaytraceProgram);
1829 nullifyResource (theGlContext, myPostFSAAProgram);
1830 nullifyResource (theGlContext, myOutImageProgram);
1832 if (!theToRebuild) // complete release
1834 myRaytraceFBO1[0]->Release (theGlContext.get());
1835 myRaytraceFBO1[1]->Release (theGlContext.get());
1836 myRaytraceFBO2[0]->Release (theGlContext.get());
1837 myRaytraceFBO2[1]->Release (theGlContext.get());
1839 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1840 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1842 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1843 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1844 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1845 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1846 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1847 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1849 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1850 nullifyResource (theGlContext, mySceneMinPointTexture);
1851 nullifyResource (theGlContext, mySceneMaxPointTexture);
1853 nullifyResource (theGlContext, myGeometryVertexTexture);
1854 nullifyResource (theGlContext, myGeometryNormalTexture);
1855 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1856 nullifyResource (theGlContext, myGeometryTriangTexture);
1857 nullifyResource (theGlContext, mySceneTransformTexture);
1859 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1860 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1862 myRaytraceGeometry.ReleaseResources (theGlContext);
1864 if (myRaytraceScreenQuad.IsValid ())
1866 myRaytraceScreenQuad.Release (theGlContext.get());
1871 // =======================================================================
1872 // function : updateRaytraceBuffers
1873 // purpose : Updates auxiliary OpenGL frame buffers.
1874 // =======================================================================
1875 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1876 const Standard_Integer theSizeY,
1877 const Handle(OpenGl_Context)& theGlContext)
1879 // Auxiliary buffers are not used
1880 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1882 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1883 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1884 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1885 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1887 return Standard_True;
1890 if (myRaytraceParameters.AdaptiveScreenSampling)
1892 Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1893 myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport, GL_RGBA32F, myFboDepthFormat);
1894 myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport, GL_RGBA32F, myFboDepthFormat);
1895 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1897 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1898 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1902 for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1904 if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1906 myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1907 myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1908 myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1909 myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1913 && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1915 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1916 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1917 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1918 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1919 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1923 if (myRaytraceParameters.AdaptiveScreenSampling)
1925 if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1926 && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1927 && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1928 && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1930 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1932 continue; // offsets texture is dynamically resized
1934 else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1935 && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1943 // Due to limitations of OpenGL image load-store extension
1944 // atomic operations are supported only for single-channel
1945 // images, so we define GL_R32F image. It is used as array
1946 // of 6D floating point vectors:
1947 // 0 - R color channel
1948 // 1 - G color channel
1949 // 2 - B color channel
1950 // 3 - hit time transformed into OpenGL NDC space
1951 // 4 - luminance accumulated for odd samples only
1952 myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1954 // workaround for some NVIDIA drivers
1955 myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1956 myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1957 myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
1958 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1959 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1961 if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1963 myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
1964 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1965 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1969 else // non-adaptive mode
1971 if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1972 || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1974 myAccumFrames = 0; // accumulation should be restarted
1977 myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, Graphic3d_Vec2i (theSizeX, theSizeY), GL_RGBA32F, myFboDepthFormat);
1978 myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, Graphic3d_Vec2i (theSizeX, theSizeY), GL_RGBA32F, myFboDepthFormat);
1981 return Standard_True;
1984 // =======================================================================
1985 // function : updateCamera
1986 // purpose : Generates viewing rays for corners of screen quad
1987 // =======================================================================
1988 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1989 const OpenGl_Mat4& theViewMapping,
1990 OpenGl_Vec3* theOrigins,
1991 OpenGl_Vec3* theDirects,
1992 OpenGl_Mat4& theViewPr,
1993 OpenGl_Mat4& theUnview)
1995 // compute view-projection matrix
1996 theViewPr = theViewMapping * theOrientation;
1998 // compute inverse view-projection matrix
1999 theViewPr.Inverted (theUnview);
2001 Standard_Integer aOriginIndex = 0;
2002 Standard_Integer aDirectIndex = 0;
2004 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2006 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2008 OpenGl_Vec4 aOrigin (GLfloat(aX),
2013 aOrigin = theUnview * aOrigin;
2015 aOrigin.x() = aOrigin.x() / aOrigin.w();
2016 aOrigin.y() = aOrigin.y() / aOrigin.w();
2017 aOrigin.z() = aOrigin.z() / aOrigin.w();
2019 OpenGl_Vec4 aDirect (GLfloat(aX),
2024 aDirect = theUnview * aDirect;
2026 aDirect.x() = aDirect.x() / aDirect.w();
2027 aDirect.y() = aDirect.y() / aDirect.w();
2028 aDirect.z() = aDirect.z() / aDirect.w();
2030 aDirect = aDirect - aOrigin;
2032 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2033 static_cast<GLfloat> (aOrigin.y()),
2034 static_cast<GLfloat> (aOrigin.z()));
2036 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2037 static_cast<GLfloat> (aDirect.y()),
2038 static_cast<GLfloat> (aDirect.z()));
2043 // =======================================================================
2044 // function : updatePerspCameraPT
2045 // purpose : Generates viewing rays (path tracing, perspective camera)
2046 // =======================================================================
2047 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
2048 const OpenGl_Mat4& theViewMapping,
2049 Graphic3d_Camera::Projection theProjection,
2050 OpenGl_Mat4& theViewPr,
2051 OpenGl_Mat4& theUnview,
2052 const int theWinSizeX,
2053 const int theWinSizeY)
2055 // compute view-projection matrix
2056 theViewPr = theViewMapping * theOrientation;
2058 // compute inverse view-projection matrix
2059 theViewPr.Inverted(theUnview);
2061 // get camera stereo params
2062 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2063 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2064 : static_cast<float> (myCamera->IOD());
2066 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2067 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2068 : static_cast<float> (myCamera->ZFocus());
2070 // get camera view vectors
2071 const gp_Pnt anOrig = myCamera->Eye();
2073 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2074 static_cast<float> (anOrig.Y()),
2075 static_cast<float> (anOrig.Z()));
2077 const gp_Dir aView = myCamera->Direction();
2079 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2080 static_cast<float> (aView.Y()),
2081 static_cast<float> (aView.Z()));
2083 const gp_Dir anUp = myCamera->Up();
2085 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2086 static_cast<float> (anUp.Y()),
2087 static_cast<float> (anUp.Z()));
2089 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2091 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2092 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2094 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2095 static_cast<float> (aScaleY));
2097 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2099 myEyeView = anEyeViewMono;
2101 else // stereo camera
2103 // compute z-focus point
2104 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2106 // compute stereo camera shift
2107 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2108 myEyeOrig += myEyeSide.Normalized() * aDx;
2110 // estimate new camera direction vector and correct its length
2111 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2112 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2116 // =======================================================================
2117 // function : uploadRaytraceData
2118 // purpose : Uploads ray-trace data to the GPU
2119 // =======================================================================
2120 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2122 #if defined(GL_ES_VERSION_2_0)
2123 if (!theGlContext->IsGlGreaterEqual (3, 2))
2125 Message::SendFail() << "Error: OpenGL ES version is less than 3.2";
2126 return Standard_False;
2129 if (!theGlContext->IsGlGreaterEqual (3, 1))
2131 Message::SendFail() << "Error: OpenGL version is less than 3.1";
2132 return Standard_False;
2136 myAccumFrames = 0; // accumulation should be restarted
2138 /////////////////////////////////////////////////////////////////////////////
2139 // Prepare OpenGL textures
2141 if (theGlContext->arbTexBindless != NULL)
2143 // If OpenGL driver supports bindless textures we need
2144 // to get unique 64- bit handles for using on the GPU
2145 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2147 Message::SendTrace() << "Error: Failed to get OpenGL texture handles";
2148 return Standard_False;
2152 /////////////////////////////////////////////////////////////////////////////
2153 // Create OpenGL BVH buffers
2155 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2157 mySceneNodeInfoTexture = new OpenGl_TextureBuffer();
2158 mySceneMinPointTexture = new OpenGl_TextureBuffer();
2159 mySceneMaxPointTexture = new OpenGl_TextureBuffer();
2160 mySceneTransformTexture = new OpenGl_TextureBuffer();
2162 if (!mySceneNodeInfoTexture->Create (theGlContext)
2163 || !mySceneMinPointTexture->Create (theGlContext)
2164 || !mySceneMaxPointTexture->Create (theGlContext)
2165 || !mySceneTransformTexture->Create (theGlContext))
2167 Message::SendTrace() << "Error: Failed to create scene BVH buffers";
2168 return Standard_False;
2172 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2174 myGeometryVertexTexture = new OpenGl_TextureBuffer();
2175 myGeometryNormalTexture = new OpenGl_TextureBuffer();
2176 myGeometryTexCrdTexture = new OpenGl_TextureBuffer();
2177 myGeometryTriangTexture = new OpenGl_TextureBuffer();
2179 if (!myGeometryVertexTexture->Create (theGlContext)
2180 || !myGeometryNormalTexture->Create (theGlContext)
2181 || !myGeometryTexCrdTexture->Create (theGlContext)
2182 || !myGeometryTriangTexture->Create (theGlContext))
2184 Message::SendTrace() << "\nError: Failed to create buffers for triangulation data";
2185 return Standard_False;
2189 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2191 myRaytraceMaterialTexture = new OpenGl_TextureBuffer();
2192 if (!myRaytraceMaterialTexture->Create (theGlContext))
2194 Message::SendTrace() << "Error: Failed to create buffers for material data";
2195 return Standard_False;
2199 /////////////////////////////////////////////////////////////////////////////
2200 // Write transform buffer
2202 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2204 bool aResult = true;
2206 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2208 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2209 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2211 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2212 Standard_ASSERT_RETURN (aTransform != NULL,
2213 "OpenGl_TriangleSet does not contain transform", Standard_False);
2215 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2218 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2219 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2221 delete [] aNodeTransforms;
2223 /////////////////////////////////////////////////////////////////////////////
2224 // Write geometry and bottom-level BVH buffers
2226 Standard_Size aTotalVerticesNb = 0;
2227 Standard_Size aTotalElementsNb = 0;
2228 Standard_Size aTotalBVHNodesNb = 0;
2230 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2232 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2233 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2235 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2236 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2238 aTotalVerticesNb += aTriangleSet->Vertices.size();
2239 aTotalElementsNb += aTriangleSet->Elements.size();
2241 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2242 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2244 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2247 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2249 if (aTotalBVHNodesNb != 0)
2251 aResult &= mySceneNodeInfoTexture->Init (
2252 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2253 aResult &= mySceneMinPointTexture->Init (
2254 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2255 aResult &= mySceneMaxPointTexture->Init (
2256 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2261 Message::SendTrace() << "Error: Failed to upload buffers for bottom-level scene BVH";
2262 return Standard_False;
2265 if (aTotalElementsNb != 0)
2267 aResult &= myGeometryTriangTexture->Init (
2268 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2271 if (aTotalVerticesNb != 0)
2273 aResult &= myGeometryVertexTexture->Init (
2274 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2275 aResult &= myGeometryNormalTexture->Init (
2276 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2277 aResult &= myGeometryTexCrdTexture->Init (
2278 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2283 Message::SendTrace() << "Error: Failed to upload buffers for scene geometry";
2284 return Standard_False;
2287 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2289 if (aBVH->Length() > 0)
2291 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2292 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2293 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2294 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2295 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2296 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2299 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2301 if (!aBVH->IsOuter (aNodeIdx))
2304 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2306 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2307 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2309 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2311 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2312 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2314 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2316 if (aBvhBuffersSize != 0)
2318 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2319 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2320 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2321 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2322 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2323 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2327 Message::SendTrace() << "Error: Failed to upload buffers for bottom-level scene BVHs";
2328 return Standard_False;
2332 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2334 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2335 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2337 if (!aTriangleSet->Vertices.empty())
2339 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2340 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2341 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2342 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2343 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2344 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2347 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2349 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2350 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2352 if (!aTriangleSet->Elements.empty())
2354 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2355 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2360 Message::SendTrace() << "Error: Failed to upload triangulation buffers for OpenGL element";
2361 return Standard_False;
2365 /////////////////////////////////////////////////////////////////////////////
2366 // Write material buffer
2368 if (myRaytraceGeometry.Materials.size() != 0)
2370 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2371 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2375 Message::SendTrace() << "Error: Failed to upload material buffer";
2376 return Standard_False;
2380 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2382 #ifdef RAY_TRACE_PRINT_INFO
2384 Standard_ShortReal aMemTrgUsed = 0.f;
2385 Standard_ShortReal aMemBvhUsed = 0.f;
2387 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2389 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2391 aMemTrgUsed += static_cast<Standard_ShortReal> (
2392 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2393 aMemTrgUsed += static_cast<Standard_ShortReal> (
2394 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2395 aMemTrgUsed += static_cast<Standard_ShortReal> (
2396 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2397 aMemTrgUsed += static_cast<Standard_ShortReal> (
2398 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2400 aMemBvhUsed += static_cast<Standard_ShortReal> (
2401 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2402 aMemBvhUsed += static_cast<Standard_ShortReal> (
2403 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2404 aMemBvhUsed += static_cast<Standard_ShortReal> (
2405 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2408 aMemBvhUsed += static_cast<Standard_ShortReal> (
2409 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2410 aMemBvhUsed += static_cast<Standard_ShortReal> (
2411 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2412 aMemBvhUsed += static_cast<Standard_ShortReal> (
2413 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2415 std::cout << "GPU Memory Used (Mb):\n"
2416 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2417 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2424 // =======================================================================
2425 // function : updateRaytraceLightSources
2426 // purpose : Updates 3D scene light sources for ray-tracing
2427 // =======================================================================
2428 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2430 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2431 Graphic3d_Vec4 aNewAmbient (0.0f);
2432 if (myRenderParams.ShadingModel != Graphic3d_TOSM_UNLIT
2433 && !myLights.IsNull())
2435 aNewAmbient.SetValues (myLights->AmbientColor().rgb(), 0.0f);
2437 // move positional light sources at the front of the list
2438 aLightSources.reserve (myLights->Extent());
2439 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2440 aLightIter.More(); aLightIter.Next())
2442 const Graphic3d_CLight& aLight = *aLightIter.Value();
2443 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2445 aLightSources.push_back (aLightIter.Value());
2449 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2450 aLightIter.More(); aLightIter.Next())
2452 if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2454 aLightSources.push_back (aLightIter.Value());
2459 if (!myRaytraceGeometry.Ambient.IsEqual (aNewAmbient))
2462 myRaytraceGeometry.Ambient = aNewAmbient;
2465 // get number of 'real' (not ambient) light sources
2466 const size_t aNbLights = aLightSources.size();
2467 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2470 myRaytraceGeometry.Sources.resize (aNbLights);
2473 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2475 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2476 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2477 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2478 aLightColor.g() * aLight.Intensity(),
2479 aLightColor.b() * aLight.Intensity(),
2482 BVH_Vec4f aPosition (-aLight.PackedDirectionRange().x(),
2483 -aLight.PackedDirectionRange().y(),
2484 -aLight.PackedDirectionRange().z(),
2487 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2489 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2490 static_cast<float>(aLight.Position().Y()),
2491 static_cast<float>(aLight.Position().Z()),
2494 // store smoothing radius in W-component
2495 aEmission.w() = Max (aLight.Smoothness(), 0.f);
2499 // store cosine of smoothing angle in W-component
2500 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2503 if (aLight.IsHeadlight())
2505 aPosition = theInvModelView * aPosition;
2508 for (int aK = 0; aK < 4; ++aK)
2510 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2511 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2516 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2522 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2524 myRaytraceLightSrcTexture = new OpenGl_TextureBuffer();
2527 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2529 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2530 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2532 Message::SendTrace() << "Error: Failed to upload light source buffer";
2533 return Standard_False;
2536 myAccumFrames = 0; // accumulation should be restarted
2539 return Standard_True;
2542 // =======================================================================
2543 // function : setUniformState
2544 // purpose : Sets uniform state for the given ray-tracing shader program
2545 // =======================================================================
2546 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2547 const Standard_Integer theWinSizeX,
2548 const Standard_Integer theWinSizeY,
2549 Graphic3d_Camera::Projection theProjection,
2550 const Handle(OpenGl_Context)& theGlContext)
2552 // Get projection state
2553 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2555 OpenGl_Mat4 aViewPrjMat;
2556 OpenGl_Mat4 anUnviewMat;
2557 OpenGl_Vec3 aOrigins[4];
2558 OpenGl_Vec3 aDirects[4];
2560 if (myCamera->IsOrthographic()
2561 || !myRenderParams.IsGlobalIlluminationEnabled)
2563 updateCamera (myCamera->OrientationMatrixF(),
2564 aCntxProjectionState.Current(),
2570 if (myRenderParams.UseEnvironmentMapBackground
2571 || myRaytraceParameters.CubemapForBack)
2573 OpenGl_Mat4 aTempMat;
2574 OpenGl_Mat4 aTempInvMat;
2575 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2576 aCntxProjectionState.Current(),
2586 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2587 aCntxProjectionState.Current(),
2595 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2597 : myPostFSAAProgram;
2599 if (theProgram.IsNull())
2601 return Standard_False;
2604 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2605 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2606 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2607 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2608 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2610 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2611 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2614 theProgram->SetUniform (theGlContext,
2615 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2616 theProgram->SetUniform (theGlContext,
2617 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2618 theProgram->SetUniform (theGlContext,
2619 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2620 theProgram->SetUniform (theGlContext,
2621 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2622 theProgram->SetUniform (theGlContext,
2623 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2624 theProgram->SetUniform (theGlContext,
2625 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2626 theProgram->SetUniform (theGlContext,
2627 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2628 theProgram->SetUniform (theGlContext,
2629 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2630 theProgram->SetUniform (theGlContext,
2631 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2632 theProgram->SetUniform (theGlContext,
2633 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2635 // Set screen dimensions
2636 myRaytraceProgram->SetUniform (theGlContext,
2637 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2638 myRaytraceProgram->SetUniform (theGlContext,
2639 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2641 // Set 3D scene parameters
2642 theProgram->SetUniform (theGlContext,
2643 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2644 theProgram->SetUniform (theGlContext,
2645 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2647 // Set light source parameters
2648 const Standard_Integer aLightSourceBufferSize =
2649 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2651 theProgram->SetUniform (theGlContext,
2652 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2654 // Set array of 64-bit texture handles
2655 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2657 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2659 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2660 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2663 // Set background colors (only vertical gradient background supported)
2664 OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
2665 if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2666 && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2668 aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
2669 aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
2671 if (myCamera->Tile().IsValid())
2673 Standard_Integer aTileOffset = myCamera->Tile().OffsetLowerLeft().y();
2674 Standard_Integer aTileSize = myCamera->Tile().TileSize.y();
2675 Standard_Integer aViewSize = myCamera->Tile().TotalSize.y();
2676 OpenGl_Vec4 aColorRange = aBackColorTop - aBackColorBot;
2677 aBackColorBot = aBackColorBot + aColorRange * ((float) aTileOffset / aViewSize);
2678 aBackColorTop = aBackColorBot + aColorRange * ((float) aTileSize / aViewSize);
2681 aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
2682 aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
2683 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
2684 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
2686 // Set environment map parameters
2687 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2688 ? myCubeMapParams->TextureSet (theGlContext)
2690 const bool toDisableEnvironmentMap = anEnvTextureSet.IsNull()
2691 || anEnvTextureSet->IsEmpty()
2692 || !anEnvTextureSet->First()->IsValid();
2693 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapEnabled],
2694 toDisableEnvironmentMap ? 0 : 1);
2695 if (myRaytraceParameters.CubemapForBack)
2697 theProgram->SetUniform (theGlContext, "uZCoeff", myBackgroundCubeMap->ZIsInverted() ? -1 : 1);
2698 theProgram->SetUniform (theGlContext, "uYCoeff", myBackgroundCubeMap->IsTopDown() ? 1 : -1);
2699 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2700 myBackgroundType == Graphic3d_TOB_CUBEMAP ? 1 : 0);
2704 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2705 myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2708 // Set ambient light source
2709 theProgram->SetUniform (theGlContext,
2710 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2711 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2713 theProgram->SetUniform (theGlContext,
2714 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2716 theProgram->SetUniform (theGlContext,
2717 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2719 // Check whether we should restart accumulation for run-time parameters
2720 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2721 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2723 myAccumFrames = 0; // accumulation should be restarted
2725 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2726 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2729 else // RT parameters
2731 // Enable/disable run-time ray-tracing effects
2732 theProgram->SetUniform (theGlContext,
2733 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2734 theProgram->SetUniform (theGlContext,
2735 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2738 return Standard_True;
2741 // =======================================================================
2742 // function : bindRaytraceTextures
2743 // purpose : Binds ray-trace textures to corresponding texture units
2744 // =======================================================================
2745 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2748 if (myRaytraceParameters.AdaptiveScreenSampling
2749 && myRaytraceParameters.GlobalIllumination)
2751 #if !defined(GL_ES_VERSION_2_0)
2752 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2753 myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2754 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2755 myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2756 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2758 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2759 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2763 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2764 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2767 (void )theStereoView;
2771 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2772 ? myCubeMapParams->TextureSet (theGlContext)
2774 if (!anEnvTextureSet.IsNull()
2775 && !anEnvTextureSet->IsEmpty()
2776 && anEnvTextureSet->First()->IsValid())
2778 anEnvTextureSet->First()->Bind (theGlContext, OpenGl_RT_EnvMapTexture);
2781 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2782 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2783 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2784 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2785 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2786 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2787 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2788 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2789 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2790 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2793 // =======================================================================
2794 // function : unbindRaytraceTextures
2795 // purpose : Unbinds ray-trace textures from corresponding texture units
2796 // =======================================================================
2797 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2799 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2800 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2801 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2802 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2803 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2804 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2805 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2806 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2807 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2808 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2810 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2813 // =======================================================================
2814 // function : runRaytraceShaders
2815 // purpose : Runs ray-tracing shader programs
2816 // =======================================================================
2817 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2818 const Standard_Integer theSizeY,
2819 Graphic3d_Camera::Projection theProjection,
2820 OpenGl_FrameBuffer* theReadDrawFbo,
2821 const Handle(OpenGl_Context)& theGlContext)
2823 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2825 aResult &= setUniformState (0,
2831 if (myRaytraceParameters.GlobalIllumination) // path tracing
2833 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
2834 aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2836 else // Whitted-style ray-tracing
2838 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2844 // =======================================================================
2845 // function : runRaytrace
2846 // purpose : Runs Whitted-style ray-tracing
2847 // =======================================================================
2848 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2849 const Standard_Integer theSizeY,
2850 Graphic3d_Camera::Projection theProjection,
2851 OpenGl_FrameBuffer* theReadDrawFbo,
2852 const Handle(OpenGl_Context)& theGlContext)
2854 Standard_Boolean aResult = Standard_True;
2856 // Choose proper set of frame buffers for stereo rendering
2857 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2858 bindRaytraceTextures (theGlContext, aFBOIdx);
2860 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2862 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2864 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2867 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2869 if (myRenderParams.IsAntialiasingEnabled)
2871 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2873 // bind ray-tracing output image as input
2874 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2876 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2878 aResult &= setUniformState (1 /* FSAA ID */,
2884 // Perform multi-pass adaptive FSAA using ping-pong technique.
2885 // We use 'FLIPTRI' sampling pattern changing for every pixel
2886 // (3 additional samples per pixel, the 1st sample is already
2887 // available from initial ray-traced image).
2888 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2890 OpenGl_Vec2 aFsaaOffset (1.f / theSizeX, 1.f / theSizeY);
2893 aFsaaOffset.x() *= -0.55f;
2894 aFsaaOffset.y() *= 0.55f;
2898 aFsaaOffset.x() *= 0.00f;
2899 aFsaaOffset.y() *= -0.55f;
2903 aFsaaOffset.x() *= 0.55f;
2904 aFsaaOffset.y() *= 0.00f;
2907 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2908 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2909 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2910 myUniformLocations[1][OpenGl_RT_uFsaaOffset], aFsaaOffset);
2912 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2913 ? myRaytraceFBO2[aFBOIdx]
2914 : myRaytraceFBO1[aFBOIdx];
2916 aFramebuffer->BindBuffer (theGlContext);
2918 // perform adaptive FSAA pass
2919 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2921 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2924 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2925 const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2927 glEnable (GL_DEPTH_TEST);
2929 // Display filtered image
2930 theGlContext->BindProgram (myOutImageProgram);
2932 if (theReadDrawFbo != NULL)
2934 theReadDrawFbo->BindBuffer (theGlContext);
2938 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2941 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2942 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2944 // copy the output image with depth values
2945 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2947 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2948 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2951 unbindRaytraceTextures (theGlContext);
2953 theGlContext->BindProgram (NULL);
2958 // =======================================================================
2959 // function : runPathtrace
2960 // purpose : Runs path tracing shader
2961 // =======================================================================
2962 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2963 const Standard_Integer theSizeY,
2964 const Graphic3d_Camera::Projection theProjection,
2965 const Handle(OpenGl_Context)& theGlContext)
2967 if (myToUpdateEnvironmentMap) // check whether the map was changed
2969 myAccumFrames = myToUpdateEnvironmentMap = 0;
2972 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2973 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2975 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2976 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2980 // Choose proper set of frame buffers for stereo rendering
2981 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2983 if (myRaytraceParameters.AdaptiveScreenSampling)
2985 if (myAccumFrames == 0)
2987 myTileSampler.Reset(); // reset tile sampler to its initial state
2989 // Adaptive sampling is starting at the second frame
2990 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2992 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2996 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2999 #if !defined(GL_ES_VERSION_2_0)
3000 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
3004 // Clear adaptive screen sampling images
3005 #if !defined(GL_ES_VERSION_2_0)
3006 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
3010 bindRaytraceTextures (theGlContext, aFBOIdx);
3012 const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
3013 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3015 // Set frame accumulation weight
3016 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
3018 // Set image uniforms for render program
3019 if (myRaytraceParameters.AdaptiveScreenSampling)
3021 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
3022 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage], OpenGl_RT_TileSamplesImage);
3023 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
3024 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
3027 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3028 aRenderImageFramebuffer->BindBuffer (theGlContext);
3029 if (myRaytraceParameters.AdaptiveScreenSampling
3030 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3032 // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
3033 // redirected to inner tiles (full tile size) are drawn entirely
3034 const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
3035 glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
3038 // Generate for the given RNG seed
3039 glDisable (GL_DEPTH_TEST);
3041 // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
3042 // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
3044 // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
3045 // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
3046 // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
3048 // Single-pass rendering is more optimal due to smaller amount of draw calls,
3049 // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
3050 // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
3051 // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
3052 const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
3053 && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
3054 ? myTileSampler.MaxTileSamples()
3056 if (myAccumFrames == 0)
3058 myRNG.SetSeed(); // start RNG from beginning
3060 for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
3062 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3063 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3064 if (myRaytraceParameters.AdaptiveScreenSampling)
3066 #if !defined(GL_ES_VERSION_2_0)
3067 theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
3071 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3073 if (myRaytraceParameters.AdaptiveScreenSampling
3074 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3076 glViewport (0, 0, theSizeX, theSizeY);
3081 // =======================================================================
3082 // function : runPathtraceOut
3084 // =======================================================================
3085 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
3086 OpenGl_FrameBuffer* theReadDrawFbo,
3087 const Handle(OpenGl_Context)& theGlContext)
3089 // Output accumulated path traced image
3090 theGlContext->BindProgram (myOutImageProgram);
3092 // Choose proper set of frame buffers for stereo rendering
3093 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
3095 if (myRaytraceParameters.AdaptiveScreenSampling)
3097 // Set uniforms for display program
3098 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
3099 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
3100 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
3101 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3102 myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
3103 myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
3106 if (myRaytraceParameters.GlobalIllumination)
3108 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3109 switch (myRaytraceParameters.ToneMappingMethod)
3111 case Graphic3d_ToneMappingMethod_Disabled:
3113 case Graphic3d_ToneMappingMethod_Filmic:
3114 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3119 if (theReadDrawFbo != NULL)
3121 theReadDrawFbo->BindBuffer (theGlContext);
3124 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3125 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3127 // Copy accumulated image with correct depth values
3128 glEnable (GL_DEPTH_TEST);
3129 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3131 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3133 if (myRaytraceParameters.AdaptiveScreenSampling)
3135 // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3136 myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3137 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3139 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3143 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3147 unbindRaytraceTextures (theGlContext);
3148 theGlContext->BindProgram (NULL);
3152 // =======================================================================
3153 // function : raytrace
3154 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3155 // =======================================================================
3156 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3157 const Standard_Integer theSizeY,
3158 Graphic3d_Camera::Projection theProjection,
3159 OpenGl_FrameBuffer* theReadDrawFbo,
3160 const Handle(OpenGl_Context)& theGlContext)
3162 if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3164 return Standard_False;
3167 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3169 return Standard_False;
3172 OpenGl_Mat4 aLightSourceMatrix;
3174 // Get inversed model-view matrix for transforming lights
3175 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3177 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3179 return Standard_False;
3182 // Generate image using Whitted-style ray-tracing or path tracing
3183 if (myIsRaytraceDataValid)
3185 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3187 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3189 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3190 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3193 glDisable (GL_BLEND);
3195 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3203 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3204 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3207 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3209 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3210 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3213 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3216 return Standard_True;