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_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
32 using namespace OpenGl_Raytrace;
34 //! Use this macro to output ray-tracing debug info
35 // #define RAY_TRACE_PRINT_INFO
37 #ifdef RAY_TRACE_PRINT_INFO
38 #include <OSD_Timer.hxx>
43 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
44 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
46 //! Operator returning TRUE for positional light sources.
47 struct IsLightPositional
49 bool operator() (const OpenGl_Light& theLight)
51 return theLight.Type != Graphic3d_TOLS_DIRECTIONAL;
55 //! Operator returning TRUE for any non-ambient light sources.
58 bool operator() (const OpenGl_Light& theLight)
60 return theLight.Type != Graphic3d_TOLS_AMBIENT;
65 // =======================================================================
66 // function : updateRaytraceGeometry
67 // purpose : Updates 3D scene geometry for ray-tracing
68 // =======================================================================
69 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
70 const Standard_Integer theViewId,
71 const Handle(OpenGl_Context)& theGlContext)
73 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
74 // modifications. This is light-weight procedure performed on each frame
75 if (theMode == OpenGl_GUM_CHECK)
77 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
79 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
82 else if (theMode == OpenGl_GUM_PREPARE)
84 myRaytraceGeometry.ClearMaterials();
86 myArrayToTrianglesMap.clear();
88 myIsRaytraceDataValid = Standard_False;
91 // The set of processed structures (reflected to ray-tracing)
92 // This set is used to remove out-of-date records from the
93 // hash map of structures
94 std::set<const OpenGl_Structure*> anElements;
96 // Set to store all currently visible OpenGL primitive arrays
97 // applicable for ray-tracing
98 std::set<Standard_Size> anArrayIDs;
100 // Set to store all non-raytracable elements allowing tracking
101 // of changes in OpenGL scene (only for path tracing)
102 std::set<Standard_Integer> aNonRaytraceIDs;
104 const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
106 if (aLayer.NbStructures() != 0)
108 const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
110 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
112 for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
114 const OpenGl_Structure* aStructure = aStructIt.Value();
116 if (theMode == OpenGl_GUM_CHECK)
118 if (toUpdateStructure (aStructure))
120 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
122 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
124 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
127 else if (theMode == OpenGl_GUM_PREPARE)
129 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
133 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
138 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
140 // Extract OpenGL elements from the group (primitives arrays)
141 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
143 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
145 if (aPrimArray != NULL)
147 anArrayIDs.insert (aPrimArray->GetUID());
152 else if (theMode == OpenGl_GUM_REBUILD)
154 if (!aStructure->IsRaytracable())
158 else if (addRaytraceStructure (aStructure, theGlContext))
160 anElements.insert (aStructure); // structure was processed
167 if (theMode == OpenGl_GUM_PREPARE)
169 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
171 // Filter out unchanged objects so only their transformations and materials
172 // will be updated (and newly added objects will be processed from scratch)
173 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
175 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
176 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
178 if (aTriangleSet == NULL)
183 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
185 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
187 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
191 myRaytraceGeometry.Objects() = anUnchangedObjects;
193 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
195 else if (theMode == OpenGl_GUM_REBUILD)
197 // Actualize the hash map of structures - remove out-of-date records
198 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
200 while (anIter != myStructureStates.end())
202 if (anElements.find (anIter->first) == anElements.end())
204 myStructureStates.erase (anIter++);
212 // Actualize OpenGL layer list state
213 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
215 // Rebuild two-level acceleration structure
216 myRaytraceGeometry.ProcessAcceleration();
218 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
219 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
220 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
222 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
224 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
226 return uploadRaytraceData (theGlContext);
229 if (myRaytraceParameters.GlobalIllumination)
231 Standard_Boolean toRestart =
232 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
234 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
236 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
238 toRestart = Standard_True;
247 myNonRaytraceStructureIDs = aNonRaytraceIDs;
250 return Standard_True;
253 // =======================================================================
254 // function : toUpdateStructure
255 // purpose : Checks to see if the structure is modified
256 // =======================================================================
257 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
259 if (!theStructure->IsRaytracable())
261 if (theStructure->ModificationState() > 0)
263 theStructure->ResetModificationState();
265 return Standard_True; // ray-trace element was removed - need to rebuild
268 return Standard_False; // did not contain ray-trace elements
271 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
273 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
275 return Standard_True;
277 else if (theStructure->InstancedStructure() != NULL)
279 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
282 return Standard_False;
285 // =======================================================================
286 // function : buildTextureTransform
287 // purpose : Constructs texture transformation matrix
288 // =======================================================================
289 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
291 theMatrix.InitIdentity();
294 const Graphic3d_Vec2& aScale = theParams->Scale();
296 theMatrix.ChangeValue (0, 0) *= aScale.x();
297 theMatrix.ChangeValue (1, 0) *= aScale.x();
298 theMatrix.ChangeValue (2, 0) *= aScale.x();
299 theMatrix.ChangeValue (3, 0) *= aScale.x();
301 theMatrix.ChangeValue (0, 1) *= aScale.y();
302 theMatrix.ChangeValue (1, 1) *= aScale.y();
303 theMatrix.ChangeValue (2, 1) *= aScale.y();
304 theMatrix.ChangeValue (3, 1) *= aScale.y();
307 const Graphic3d_Vec2 aTrans = -theParams->Translation();
309 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
310 theMatrix.GetValue (0, 1) * aTrans.y();
312 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
313 theMatrix.GetValue (1, 1) * aTrans.y();
315 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
316 theMatrix.GetValue (2, 1) * aTrans.y();
319 const Standard_ShortReal aSin = std::sin (
320 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
321 const Standard_ShortReal aCos = std::cos (
322 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
324 BVH_Mat4f aRotationMat;
325 aRotationMat.SetValue (0, 0, aCos);
326 aRotationMat.SetValue (1, 1, aCos);
327 aRotationMat.SetValue (0, 1, -aSin);
328 aRotationMat.SetValue (1, 0, aSin);
330 theMatrix = theMatrix * aRotationMat;
333 // =======================================================================
334 // function : convertMaterial
335 // purpose : Creates ray-tracing material properties
336 // =======================================================================
337 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
338 const Handle(OpenGl_Context)& theGlContext)
340 OpenGl_RaytraceMaterial theMaterial;
342 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
343 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
344 const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC);
345 const float aShine = 128.0f * float(aSrcMat.Shininess());
348 if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
350 const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
351 theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f);
355 theMaterial.Ambient = THE_BLACK_COLOR;
358 // diffusion component
359 if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
361 const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
362 theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
366 theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
369 // specular component
370 if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
372 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
373 const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
374 theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
376 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
377 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
378 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
380 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
382 // ignore isPhysic here
383 theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
387 theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
390 // emission component
391 if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
393 const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
394 theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
398 theMaterial.Emission = THE_BLACK_COLOR;
401 const float anIndex = (float )aSrcMat.RefractionIndex();
402 theMaterial.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
403 anIndex == 0 ? 1.0f : anIndex,
404 anIndex == 0 ? 1.0f : 1.0f / anIndex);
406 // Serialize physically-based material properties
407 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
409 theMaterial.BSDF.Kc = aBSDF.Kc;
410 theMaterial.BSDF.Ks = aBSDF.Ks;
411 theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
412 theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
413 theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
415 theMaterial.BSDF.Absorption = aBSDF.Absorption;
417 theMaterial.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
418 theMaterial.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
420 // Handle material textures
421 if (theAspect->Aspect()->ToMapTexture())
423 if (theGlContext->HasRayTracingTextures())
425 buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
427 // write texture ID to diffuse w-component
428 theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() =
429 static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext)));
431 else if (!myIsRaytraceWarnTextures)
433 const TCollection_ExtendedString aWarnMessage =
434 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
435 "Please try to update graphics card driver. At the moment textures will be ignored.";
437 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
438 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
440 myIsRaytraceWarnTextures = Standard_True;
447 // =======================================================================
448 // function : addRaytraceStructure
449 // purpose : Adds OpenGL structure to ray-traced scene geometry
450 // =======================================================================
451 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
452 const Handle(OpenGl_Context)& theGlContext)
454 if (!theStructure->IsVisible())
456 myStructureStates[theStructure] = StructState (theStructure);
458 return Standard_True;
461 // Get structure material
462 OpenGl_RaytraceMaterial aDefaultMaterial;
463 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
465 // Process all connected OpenGL structures
466 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
468 if (anInstanced != NULL && anInstanced->IsRaytracable())
470 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
473 myStructureStates[theStructure] = StructState (theStructure);
478 // =======================================================================
479 // function : addRaytraceGroups
480 // purpose : Adds OpenGL groups to ray-traced scene geometry
481 // =======================================================================
482 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
483 const OpenGl_RaytraceMaterial& theStructMat,
484 const Handle(Geom_Transformation)& theTrsf,
485 const Handle(OpenGl_Context)& theGlContext)
488 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
490 // Get group material
491 OpenGl_RaytraceMaterial aGroupMaterial;
492 if (aGroupIter.Value()->AspectFace() != NULL)
494 aGroupMaterial = convertMaterial (
495 aGroupIter.Value()->AspectFace(), theGlContext);
498 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
500 // Use group material if available, otherwise use structure material
501 myRaytraceGeometry.Materials.push_back (
502 aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
504 // Add OpenGL elements from group (extract primitives arrays and aspects)
505 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
507 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
509 if (anAspect != NULL)
511 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
513 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
515 myRaytraceGeometry.Materials.push_back (aMaterial);
519 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
521 if (aPrimArray != NULL)
523 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
525 if (aSetIter != myArrayToTrianglesMap.end())
527 OpenGl_TriangleSet* aSet = aSetIter->second;
528 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
529 if (!theTrsf.IsNull())
531 theTrsf->Trsf().GetMat4 (aMat4);
532 aTransform->SetTransform (aMat4);
535 aSet->SetProperties (aTransform);
536 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
538 aSet->SetMaterialIndex (aMatID);
543 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
545 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
546 if (!theTrsf.IsNull())
548 theTrsf->Trsf().GetMat4 (aMat4);
549 aTransform->SetTransform (aMat4);
552 aSet->SetProperties (aTransform);
553 myRaytraceGeometry.Objects().Append (aSet);
561 return Standard_True;
564 // =======================================================================
565 // function : addRaytracePrimitiveArray
566 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
567 // =======================================================================
568 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
569 const Standard_Integer theMaterial,
570 const OpenGl_Mat4* theTransform)
572 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
573 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
574 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
576 if (theArray->DrawMode() < GL_TRIANGLES
577 #ifndef GL_ES_VERSION_2_0
578 || theArray->DrawMode() > GL_POLYGON
580 || theArray->DrawMode() > GL_TRIANGLE_FAN
582 || anAttribs.IsNull())
584 return Handle(OpenGl_TriangleSet)();
587 OpenGl_Mat4 aNormalMatrix;
588 if (theTransform != NULL)
590 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
591 "Error: Failed to compute normal transformation matrix", NULL);
593 aNormalMatrix.Transpose();
596 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
598 aSet->Vertices.reserve (anAttribs->NbElements);
599 aSet->Normals.reserve (anAttribs->NbElements);
600 aSet->TexCrds.reserve (anAttribs->NbElements);
602 const size_t aVertFrom = aSet->Vertices.size();
603 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
605 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
606 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
607 if (anAttrib.Id == Graphic3d_TOA_POS)
609 if (anAttrib.DataType == Graphic3d_TOD_VEC3
610 || anAttrib.DataType == Graphic3d_TOD_VEC4)
612 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
614 aSet->Vertices.push_back (
615 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
618 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
620 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
622 const Standard_ShortReal* aCoords =
623 reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
625 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
629 else if (anAttrib.Id == Graphic3d_TOA_NORM)
631 if (anAttrib.DataType == Graphic3d_TOD_VEC3
632 || anAttrib.DataType == Graphic3d_TOD_VEC4)
634 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
636 aSet->Normals.push_back (
637 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
641 else if (anAttrib.Id == Graphic3d_TOA_UV)
643 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
645 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
647 aSet->TexCrds.push_back (
648 *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
654 if (aSet->Normals.size() != aSet->Vertices.size())
656 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
658 aSet->Normals.push_back (BVH_Vec3f());
662 if (aSet->TexCrds.size() != aSet->Vertices.size())
664 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
666 aSet->TexCrds.push_back (BVH_Vec2f());
670 if (theTransform != NULL)
672 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
674 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
676 BVH_Vec4f aTransVertex = *theTransform *
677 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
679 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
681 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
683 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
685 BVH_Vec4f aTransNormal = aNormalMatrix *
686 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
688 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
692 if (!aBounds.IsNull())
694 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
696 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
698 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
701 return Handle(OpenGl_TriangleSet)();
704 aBoundStart += aVertNum;
709 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
711 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
714 return Handle(OpenGl_TriangleSet)();
719 if (aSet->Size() != 0)
727 // =======================================================================
728 // function : addRaytraceVertexIndices
729 // purpose : Adds vertex indices to ray-traced scene geometry
730 // =======================================================================
731 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
732 const Standard_Integer theMatID,
733 const Standard_Integer theCount,
734 const Standard_Integer theOffset,
735 const OpenGl_PrimitiveArray& theArray)
737 switch (theArray.DrawMode())
739 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
740 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
741 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
742 #if !defined(GL_ES_VERSION_2_0)
743 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
744 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
745 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
749 return Standard_False;
752 // =======================================================================
753 // function : addRaytraceTriangleArray
754 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
755 // =======================================================================
756 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
757 const Standard_Integer theMatID,
758 const Standard_Integer theCount,
759 const Standard_Integer theOffset,
760 const Handle(Graphic3d_IndexBuffer)& theIndices)
764 return Standard_True;
767 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
769 if (!theIndices.IsNull())
771 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
773 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
774 theIndices->Index (aVert + 1),
775 theIndices->Index (aVert + 2),
781 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
783 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
787 return Standard_True;
790 // =======================================================================
791 // function : addRaytraceTriangleFanArray
792 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
793 // =======================================================================
794 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
795 const Standard_Integer theMatID,
796 const Standard_Integer theCount,
797 const Standard_Integer theOffset,
798 const Handle(Graphic3d_IndexBuffer)& theIndices)
802 return Standard_True;
805 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
807 if (!theIndices.IsNull())
809 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
811 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
812 theIndices->Index (aVert + 1),
813 theIndices->Index (aVert + 2),
819 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
821 theSet.Elements.push_back (BVH_Vec4i (theOffset,
828 return Standard_True;
831 // =======================================================================
832 // function : addRaytraceTriangleStripArray
833 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
834 // =======================================================================
835 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
836 const Standard_Integer theMatID,
837 const Standard_Integer theCount,
838 const Standard_Integer theOffset,
839 const Handle(Graphic3d_IndexBuffer)& theIndices)
843 return Standard_True;
846 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
848 if (!theIndices.IsNull())
850 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
852 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
853 theIndices->Index (aVert + (aCW ? 0 : 1)),
854 theIndices->Index (aVert + 2),
860 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
862 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
863 aVert + (aCW ? 0 : 1),
869 return Standard_True;
872 // =======================================================================
873 // function : addRaytraceQuadrangleArray
874 // purpose : Adds OpenGL quad array to ray-traced scene geometry
875 // =======================================================================
876 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
877 const Standard_Integer theMatID,
878 const Standard_Integer theCount,
879 const Standard_Integer theOffset,
880 const Handle(Graphic3d_IndexBuffer)& theIndices)
884 return Standard_True;
887 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
889 if (!theIndices.IsNull())
891 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
893 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
894 theIndices->Index (aVert + 1),
895 theIndices->Index (aVert + 2),
897 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
898 theIndices->Index (aVert + 2),
899 theIndices->Index (aVert + 3),
905 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
907 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
909 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
914 return Standard_True;
917 // =======================================================================
918 // function : addRaytraceQuadrangleStripArray
919 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
920 // =======================================================================
921 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
922 const Standard_Integer theMatID,
923 const Standard_Integer theCount,
924 const Standard_Integer theOffset,
925 const Handle(Graphic3d_IndexBuffer)& theIndices)
929 return Standard_True;
932 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
934 if (!theIndices.IsNull())
936 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
938 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
939 theIndices->Index (aVert + 1),
940 theIndices->Index (aVert + 2),
943 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
944 theIndices->Index (aVert + 3),
945 theIndices->Index (aVert + 2),
951 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
953 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
958 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
965 return Standard_True;
968 // =======================================================================
969 // function : addRaytracePolygonArray
970 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
971 // =======================================================================
972 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
973 const Standard_Integer theMatID,
974 const Standard_Integer theCount,
975 const Standard_Integer theOffset,
976 const Handle(Graphic3d_IndexBuffer)& theIndices)
980 return Standard_True;
983 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
985 if (!theIndices.IsNull())
987 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
989 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
990 theIndices->Index (aVert + 1),
991 theIndices->Index (aVert + 2),
997 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
999 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1006 return Standard_True;
1009 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1011 // =======================================================================
1012 // function : Source
1013 // purpose : Returns shader source combined with prefix
1014 // =======================================================================
1015 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1017 const TCollection_AsciiString aVersion = "#version 140";
1019 if (myPrefix.IsEmpty())
1021 return aVersion + "\n" + mySource;
1024 return aVersion + "\n" + myPrefix + "\n" + mySource;
1027 // =======================================================================
1028 // function : LoadFromFiles
1029 // purpose : Loads shader source from specified files
1030 // =======================================================================
1031 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1032 const TCollection_AsciiString& thePrefix)
1036 myPrefix = thePrefix;
1038 TCollection_AsciiString aMissingFiles;
1039 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1041 OSD_File aFile (theFileNames[anIndex]);
1044 aFile.Open (OSD_ReadOnly, OSD_Protection());
1046 if (!aFile.IsOpen())
1048 if (!aMissingFiles.IsEmpty())
1050 aMissingFiles += ", ";
1052 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1055 else if (!aMissingFiles.IsEmpty())
1061 TCollection_AsciiString aSource;
1062 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1063 if (!aSource.IsEmpty())
1065 mySource += TCollection_AsciiString ("\n") + aSource;
1070 if (!aMissingFiles.IsEmpty())
1072 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1073 return Standard_False;
1075 return Standard_True;
1078 // =======================================================================
1079 // function : LoadFromStrings
1081 // =======================================================================
1082 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1083 const TCollection_AsciiString& thePrefix)
1087 myPrefix = thePrefix;
1089 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1091 TCollection_AsciiString aSource = theStrings[anIndex];
1092 if (!aSource.IsEmpty())
1094 mySource += TCollection_AsciiString ("\n") + aSource;
1097 return Standard_True;
1100 // =======================================================================
1101 // function : generateShaderPrefix
1102 // purpose : Generates shader prefix based on current ray-tracing options
1103 // =======================================================================
1104 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1106 TCollection_AsciiString aPrefixString =
1107 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1108 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1110 if (myRaytraceParameters.TransparentShadows)
1112 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1115 // If OpenGL driver supports bindless textures and texturing
1116 // is actually used, activate texturing in ray-tracing mode
1117 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1119 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1120 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1123 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1125 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1127 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1129 // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
1130 if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1132 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
1133 TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
1137 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1139 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1142 switch (myRaytraceParameters.ToneMappingMethod)
1144 case Graphic3d_ToneMappingMethod_Disabled:
1146 case Graphic3d_ToneMappingMethod_Filmic:
1147 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1152 return aPrefixString;
1155 // =======================================================================
1156 // function : safeFailBack
1157 // purpose : Performs safe exit when shaders initialization fails
1158 // =======================================================================
1159 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1160 const Handle(OpenGl_Context)& theGlContext)
1162 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1163 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1165 myRaytraceInitStatus = OpenGl_RT_FAIL;
1167 releaseRaytraceResources (theGlContext);
1169 return Standard_False;
1172 // =======================================================================
1173 // function : initShader
1174 // purpose : Creates new shader object with specified source
1175 // =======================================================================
1176 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1177 const ShaderSource& theSource,
1178 const Handle(OpenGl_Context)& theGlContext)
1180 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1182 if (!aShader->Create (theGlContext))
1184 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1185 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1187 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1188 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1190 aShader->Release (theGlContext.operator->());
1192 return Handle(OpenGl_ShaderObject)();
1195 if (!aShader->LoadSource (theGlContext, theSource.Source()))
1197 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1198 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1200 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1201 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1203 aShader->Release (theGlContext.operator->());
1205 return Handle(OpenGl_ShaderObject)();
1208 TCollection_AsciiString aBuildLog;
1210 if (!aShader->Compile (theGlContext))
1212 aShader->FetchInfoLog (theGlContext, aBuildLog);
1214 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1215 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1217 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1218 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1220 aShader->Release (theGlContext.operator->());
1222 #ifdef RAY_TRACE_PRINT_INFO
1223 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1226 return Handle(OpenGl_ShaderObject)();
1228 else if (theGlContext->caps->glslWarnings)
1230 aShader->FetchInfoLog (theGlContext, aBuildLog);
1232 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1234 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1235 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1237 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1238 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1241 #ifdef RAY_TRACE_PRINT_INFO
1242 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1249 // =======================================================================
1250 // function : initProgram
1251 // purpose : Creates GLSL program from the given shader objects
1252 // =======================================================================
1253 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1254 const Handle(OpenGl_ShaderObject)& theVertShader,
1255 const Handle(OpenGl_ShaderObject)& theFragShader)
1257 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1259 if (!aProgram->Create (theGlContext))
1261 theVertShader->Release (theGlContext.operator->());
1263 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1264 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1266 return Handle(OpenGl_ShaderProgram)();
1269 if (!aProgram->AttachShader (theGlContext, theVertShader)
1270 || !aProgram->AttachShader (theGlContext, theFragShader))
1272 theVertShader->Release (theGlContext.operator->());
1274 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1275 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1277 return Handle(OpenGl_ShaderProgram)();
1280 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1282 TCollection_AsciiString aLinkLog;
1284 if (!aProgram->Link (theGlContext))
1286 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1288 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1289 "Failed to link shader program:\n") + aLinkLog;
1291 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1292 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1294 return Handle(OpenGl_ShaderProgram)();
1296 else if (theGlContext->caps->glslWarnings)
1298 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1299 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1301 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1302 "Shader program was linked with following warnings:\n") + aLinkLog;
1304 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1305 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1312 // =======================================================================
1313 // function : initRaytraceResources
1314 // purpose : Initializes OpenGL/GLSL shader programs
1315 // =======================================================================
1316 Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1318 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1320 return Standard_False;
1323 Standard_Boolean aToRebuildShaders = Standard_False;
1325 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1327 myRaytraceInitStatus = OpenGl_RT_NONE;
1328 releaseRaytraceResources (theGlContext, Standard_True);
1329 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1332 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1334 if (!myIsRaytraceDataValid)
1336 return Standard_True;
1339 const Standard_Integer aRequiredStackSize =
1340 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1342 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1344 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1346 aToRebuildShaders = Standard_True;
1350 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1352 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1354 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1355 aToRebuildShaders = Standard_True;
1360 Standard_Integer aNbTilesX = 8;
1361 Standard_Integer aNbTilesY = 8;
1363 for (Standard_Integer anIdx = 0; aNbTilesX * aNbTilesY < myRenderParams.NbRayTracingTiles; ++anIdx)
1365 (anIdx % 2 == 0 ? aNbTilesX : aNbTilesY) <<= 1;
1368 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1369 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1370 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1371 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1372 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures
1373 || aNbTilesX != myRaytraceParameters.NbTilesX
1374 || aNbTilesY != myRaytraceParameters.NbTilesY)
1376 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1377 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1378 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1379 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1380 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1382 #ifdef RAY_TRACE_PRINT_INFO
1383 if (aNbTilesX != myRaytraceParameters.NbTilesX
1384 || aNbTilesY != myRaytraceParameters.NbTilesY)
1386 std::cout << "Number of tiles X: " << aNbTilesX << "\n";
1387 std::cout << "Number of tiles Y: " << aNbTilesY << "\n";
1391 myRaytraceParameters.NbTilesX = aNbTilesX;
1392 myRaytraceParameters.NbTilesY = aNbTilesY;
1394 aToRebuildShaders = Standard_True;
1397 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
1399 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1400 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1402 if (!theGlContext->HasRayTracingAdaptiveSampling())
1404 // disable the feature if it is not supported
1405 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1406 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1407 "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
1411 aToRebuildShaders = Standard_True;
1414 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1416 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1417 aToRebuildShaders = true;
1420 if (aToRebuildShaders)
1422 // Reject accumulated frames
1425 // Environment map should be updated
1426 myToUpdateEnvironmentMap = Standard_True;
1428 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1430 #ifdef RAY_TRACE_PRINT_INFO
1431 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1434 myRaytraceShaderSource.SetPrefix (aPrefixString);
1435 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1436 myOutImageShaderSource.SetPrefix (aPrefixString);
1438 if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1439 || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
1440 || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
1442 return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1445 TCollection_AsciiString aLog;
1447 if (!myRaytraceShader->Compile (theGlContext)
1448 || !myPostFSAAShader->Compile (theGlContext)
1449 || !myOutImageShader->Compile (theGlContext))
1451 #ifdef RAY_TRACE_PRINT_INFO
1452 myRaytraceShader->FetchInfoLog (theGlContext, aLog);
1454 if (!aLog.IsEmpty())
1456 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1459 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1462 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1463 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1464 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1466 if (!myRaytraceProgram->Link (theGlContext)
1467 || !myPostFSAAProgram->Link (theGlContext)
1468 || !myOutImageProgram->Link (theGlContext))
1470 #ifdef RAY_TRACE_PRINT_INFO
1471 myRaytraceProgram->FetchInfoLog (theGlContext, aLog);
1473 if (!aLog.IsEmpty())
1475 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1478 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1483 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1485 myAccumFrames = 0; // accumulation should be restarted
1487 if (!theGlContext->IsGlGreaterEqual (3, 1))
1489 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1491 else if (!theGlContext->arbTboRGB32)
1493 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1495 else if (!theGlContext->arbFBOBlit)
1497 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1500 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1502 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1503 if (myIsRaytraceDataValid)
1505 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1506 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1509 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1511 #ifdef RAY_TRACE_PRINT_INFO
1512 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1515 ShaderSource aBasicVertShaderSrc;
1517 if (!aShaderFolder.IsEmpty())
1519 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1520 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1522 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1527 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1528 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1533 if (!aShaderFolder.IsEmpty())
1535 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1536 aShaderFolder + "/PathtraceBase.fs",
1537 aShaderFolder + "/RaytraceRender.fs",
1539 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1541 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1546 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1547 Shaders_PathtraceBase_fs,
1548 Shaders_RaytraceRender_fs,
1550 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1553 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1554 if (aBasicVertShader.IsNull())
1556 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1559 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1560 if (myRaytraceShader.IsNull())
1562 aBasicVertShader->Release (theGlContext.operator->());
1563 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1566 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1567 if (myRaytraceProgram.IsNull())
1569 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1574 if (!aShaderFolder.IsEmpty())
1576 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1577 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1579 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1584 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1585 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1588 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1589 if (aBasicVertShader.IsNull())
1591 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1594 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1595 if (myPostFSAAShader.IsNull())
1597 aBasicVertShader->Release (theGlContext.operator->());
1598 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1601 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1602 if (myPostFSAAProgram.IsNull())
1604 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1609 if (!aShaderFolder.IsEmpty())
1611 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1612 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1614 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1619 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1620 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1623 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1624 if (aBasicVertShader.IsNull())
1626 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1629 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1630 if (myOutImageShader.IsNull())
1632 aBasicVertShader->Release (theGlContext.operator->());
1633 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1636 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
1637 if (myOutImageProgram.IsNull())
1639 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1644 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1646 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1648 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1649 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1651 theGlContext->BindProgram (aShaderProgram);
1653 aShaderProgram->SetSampler (theGlContext,
1654 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1655 aShaderProgram->SetSampler (theGlContext,
1656 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1657 aShaderProgram->SetSampler (theGlContext,
1658 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1659 aShaderProgram->SetSampler (theGlContext,
1660 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1661 aShaderProgram->SetSampler (theGlContext,
1662 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1663 aShaderProgram->SetSampler (theGlContext,
1664 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1665 aShaderProgram->SetSampler (theGlContext,
1666 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1667 aShaderProgram->SetSampler (theGlContext,
1668 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1669 aShaderProgram->SetSampler (theGlContext,
1670 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1671 aShaderProgram->SetSampler (theGlContext,
1672 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1673 aShaderProgram->SetSampler (theGlContext,
1674 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1678 aShaderProgram->SetSampler (theGlContext,
1679 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1683 aShaderProgram->SetSampler (theGlContext,
1684 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1687 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1688 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1690 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1691 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1692 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1693 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1694 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1695 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1696 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1697 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1698 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1699 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1700 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1701 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1702 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1703 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1704 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1705 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1706 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1707 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1708 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1709 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1711 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1712 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1713 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1714 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1715 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1716 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1717 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1718 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1720 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1721 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1722 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1723 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1724 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1725 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1727 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1728 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1730 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1731 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1732 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1733 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1734 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1735 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1736 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1737 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1738 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1739 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1741 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1742 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1743 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1744 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1746 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1747 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1748 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1749 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1751 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1752 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1753 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1754 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1756 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1757 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1758 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1759 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1761 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1762 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1765 theGlContext->BindProgram (myOutImageProgram);
1767 myOutImageProgram->SetSampler (theGlContext,
1768 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1770 myOutImageProgram->SetSampler (theGlContext,
1771 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1773 theGlContext->BindProgram (NULL);
1776 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1778 return myRaytraceInitStatus == OpenGl_RT_INIT;
1781 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1788 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1790 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1792 return Standard_True;
1795 // =======================================================================
1796 // function : nullifyResource
1797 // purpose : Releases OpenGL resource
1798 // =======================================================================
1800 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1802 if (!theResource.IsNull())
1804 theResource->Release (theGlContext.operator->());
1805 theResource.Nullify();
1809 // =======================================================================
1810 // function : releaseRaytraceResources
1811 // purpose : Releases OpenGL/GLSL shader programs
1812 // =======================================================================
1813 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1815 // release shader resources
1816 nullifyResource (theGlContext, myRaytraceShader);
1817 nullifyResource (theGlContext, myPostFSAAShader);
1819 nullifyResource (theGlContext, myRaytraceProgram);
1820 nullifyResource (theGlContext, myPostFSAAProgram);
1821 nullifyResource (theGlContext, myOutImageProgram);
1823 if (!theToRebuild) // complete release
1825 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1826 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1827 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1828 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1830 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1831 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1833 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture);
1834 nullifyResource (theGlContext, myRaytraceVisualErrorTexture);
1836 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1837 nullifyResource (theGlContext, mySceneMinPointTexture);
1838 nullifyResource (theGlContext, mySceneMaxPointTexture);
1840 nullifyResource (theGlContext, myGeometryVertexTexture);
1841 nullifyResource (theGlContext, myGeometryNormalTexture);
1842 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1843 nullifyResource (theGlContext, myGeometryTriangTexture);
1844 nullifyResource (theGlContext, mySceneTransformTexture);
1846 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1847 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1849 myRaytraceGeometry.ReleaseResources (theGlContext);
1851 if (myRaytraceScreenQuad.IsValid ())
1853 myRaytraceScreenQuad.Release (theGlContext.operator->());
1858 // =======================================================================
1859 // function : updateRaytraceBuffers
1860 // purpose : Updates auxiliary OpenGL frame buffers.
1861 // =======================================================================
1862 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1863 const Standard_Integer theSizeY,
1864 const Handle(OpenGl_Context)& theGlContext)
1866 // Auxiliary buffers are not used
1867 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1869 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1870 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1871 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1872 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1874 return Standard_True;
1877 if (myRaytraceParameters.AdaptiveScreenSampling)
1879 const Standard_Integer aSizeX = std::max (myRaytraceParameters.NbTilesX * 64, theSizeX);
1880 const Standard_Integer aSizeY = std::max (myRaytraceParameters.NbTilesY * 64, theSizeY);
1882 myRaytraceFBO1[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1883 myRaytraceFBO2[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1885 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1887 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1888 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1891 else // non-adaptive mode
1893 if (myRaytraceFBO1[0]->GetSizeX() != theSizeX
1894 || myRaytraceFBO1[0]->GetSizeY() != theSizeY)
1896 myAccumFrames = 0; // accumulation should be restarted
1899 myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1900 myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1902 // Init second set of buffers for stereographic rendering
1903 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1905 myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1906 myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1908 else if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1910 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1911 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1915 myTileSampler.SetSize (theSizeX, theSizeY);
1917 if (myRaytraceTileOffsetsTexture.IsNull())
1919 myRaytraceOutputTexture[0] = new OpenGl_Texture();
1920 myRaytraceOutputTexture[1] = new OpenGl_Texture();
1922 myRaytraceTileOffsetsTexture = new OpenGl_Texture();
1923 myRaytraceVisualErrorTexture = new OpenGl_Texture();
1926 if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
1927 || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
1931 // Due to limitations of OpenGL image load-store extension
1932 // atomic operations are supported only for single-channel
1933 // images, so we define GL_R32F image. It is used as array
1934 // of 6D floating point vectors:
1935 // 0 - R color channel
1936 // 1 - G color channel
1937 // 2 - B color channel
1938 // 3 - hit time transformed into OpenGL NDC space
1939 // 4 - luminance accumulated for odd samples only
1940 myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
1941 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1943 // workaround for some NVIDIA drivers
1944 myRaytraceVisualErrorTexture->Release (theGlContext.operator->());
1945 myRaytraceTileOffsetsTexture->Release (theGlContext.operator->());
1947 myRaytraceVisualErrorTexture->Init (theGlContext,
1948 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1950 myRaytraceTileOffsetsTexture->Init (theGlContext,
1951 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1954 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1956 if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
1957 || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
1959 myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
1960 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1965 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1968 return Standard_True;
1971 // =======================================================================
1972 // function : updateCamera
1973 // purpose : Generates viewing rays for corners of screen quad
1974 // =======================================================================
1975 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1976 const OpenGl_Mat4& theViewMapping,
1977 OpenGl_Vec3* theOrigins,
1978 OpenGl_Vec3* theDirects,
1979 OpenGl_Mat4& theViewPr,
1980 OpenGl_Mat4& theUnview)
1982 // compute view-projection matrix
1983 theViewPr = theViewMapping * theOrientation;
1985 // compute inverse view-projection matrix
1986 theViewPr.Inverted (theUnview);
1988 Standard_Integer aOriginIndex = 0;
1989 Standard_Integer aDirectIndex = 0;
1991 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1993 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1995 OpenGl_Vec4 aOrigin (GLfloat(aX),
2000 aOrigin = theUnview * aOrigin;
2002 aOrigin.x() = aOrigin.x() / aOrigin.w();
2003 aOrigin.y() = aOrigin.y() / aOrigin.w();
2004 aOrigin.z() = aOrigin.z() / aOrigin.w();
2006 OpenGl_Vec4 aDirect (GLfloat(aX),
2011 aDirect = theUnview * aDirect;
2013 aDirect.x() = aDirect.x() / aDirect.w();
2014 aDirect.y() = aDirect.y() / aDirect.w();
2015 aDirect.z() = aDirect.z() / aDirect.w();
2017 aDirect = aDirect - aOrigin;
2019 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2020 static_cast<GLfloat> (aOrigin.y()),
2021 static_cast<GLfloat> (aOrigin.z()));
2023 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2024 static_cast<GLfloat> (aDirect.y()),
2025 static_cast<GLfloat> (aDirect.z()));
2030 // =======================================================================
2031 // function : uploadRaytraceData
2032 // purpose : Uploads ray-trace data to the GPU
2033 // =======================================================================
2034 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2036 if (!theGlContext->IsGlGreaterEqual (3, 1))
2038 #ifdef RAY_TRACE_PRINT_INFO
2039 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2041 return Standard_False;
2044 myAccumFrames = 0; // accumulation should be restarted
2046 /////////////////////////////////////////////////////////////////////////////
2047 // Prepare OpenGL textures
2049 if (theGlContext->arbTexBindless != NULL)
2051 // If OpenGL driver supports bindless textures we need
2052 // to get unique 64- bit handles for using on the GPU
2053 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2055 #ifdef RAY_TRACE_PRINT_INFO
2056 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2058 return Standard_False;
2062 /////////////////////////////////////////////////////////////////////////////
2063 // Create OpenGL BVH buffers
2065 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2067 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2068 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2069 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2070 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2072 if (!mySceneNodeInfoTexture->Create (theGlContext)
2073 || !mySceneMinPointTexture->Create (theGlContext)
2074 || !mySceneMaxPointTexture->Create (theGlContext)
2075 || !mySceneTransformTexture->Create (theGlContext))
2077 #ifdef RAY_TRACE_PRINT_INFO
2078 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2080 return Standard_False;
2084 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2086 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2087 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2088 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2089 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2091 if (!myGeometryVertexTexture->Create (theGlContext)
2092 || !myGeometryNormalTexture->Create (theGlContext)
2093 || !myGeometryTexCrdTexture->Create (theGlContext)
2094 || !myGeometryTriangTexture->Create (theGlContext))
2096 #ifdef RAY_TRACE_PRINT_INFO
2097 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2099 return Standard_False;
2103 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2105 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2107 if (!myRaytraceMaterialTexture->Create (theGlContext))
2109 #ifdef RAY_TRACE_PRINT_INFO
2110 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2112 return Standard_False;
2116 /////////////////////////////////////////////////////////////////////////////
2117 // Write transform buffer
2119 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2121 bool aResult = true;
2123 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2125 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2126 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2128 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2129 Standard_ASSERT_RETURN (aTransform != NULL,
2130 "OpenGl_TriangleSet does not contain transform", Standard_False);
2132 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2135 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2136 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2138 delete [] aNodeTransforms;
2140 /////////////////////////////////////////////////////////////////////////////
2141 // Write geometry and bottom-level BVH buffers
2143 Standard_Size aTotalVerticesNb = 0;
2144 Standard_Size aTotalElementsNb = 0;
2145 Standard_Size aTotalBVHNodesNb = 0;
2147 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2149 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2150 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2152 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2153 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2155 aTotalVerticesNb += aTriangleSet->Vertices.size();
2156 aTotalElementsNb += aTriangleSet->Elements.size();
2158 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2159 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2161 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2164 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2166 if (aTotalBVHNodesNb != 0)
2168 aResult &= mySceneNodeInfoTexture->Init (
2169 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2170 aResult &= mySceneMinPointTexture->Init (
2171 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2172 aResult &= mySceneMaxPointTexture->Init (
2173 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2178 #ifdef RAY_TRACE_PRINT_INFO
2179 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2181 return Standard_False;
2184 if (aTotalElementsNb != 0)
2186 aResult &= myGeometryTriangTexture->Init (
2187 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2190 if (aTotalVerticesNb != 0)
2192 aResult &= myGeometryVertexTexture->Init (
2193 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2194 aResult &= myGeometryNormalTexture->Init (
2195 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2196 aResult &= myGeometryTexCrdTexture->Init (
2197 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2202 #ifdef RAY_TRACE_PRINT_INFO
2203 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2205 return Standard_False;
2208 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2210 if (aBVH->Length() > 0)
2212 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2213 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2214 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2215 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2216 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2217 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2220 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2222 if (!aBVH->IsOuter (aNodeIdx))
2225 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2227 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2228 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2230 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2232 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2233 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2235 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2237 if (aBvhBuffersSize != 0)
2239 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2240 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2241 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2242 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2243 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2244 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2248 #ifdef RAY_TRACE_PRINT_INFO
2249 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2251 return Standard_False;
2255 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2257 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2258 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2260 if (!aTriangleSet->Vertices.empty())
2262 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2263 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2264 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2265 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2266 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2267 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2270 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2272 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2273 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2275 if (!aTriangleSet->Elements.empty())
2277 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2278 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2283 #ifdef RAY_TRACE_PRINT_INFO
2284 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2286 return Standard_False;
2290 /////////////////////////////////////////////////////////////////////////////
2291 // Write material buffer
2293 if (myRaytraceGeometry.Materials.size() != 0)
2295 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2296 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2300 #ifdef RAY_TRACE_PRINT_INFO
2301 std::cout << "Error: Failed to upload material buffer" << std::endl;
2303 return Standard_False;
2307 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2309 #ifdef RAY_TRACE_PRINT_INFO
2311 Standard_ShortReal aMemTrgUsed = 0.f;
2312 Standard_ShortReal aMemBvhUsed = 0.f;
2314 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2316 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2318 aMemTrgUsed += static_cast<Standard_ShortReal> (
2319 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2320 aMemTrgUsed += static_cast<Standard_ShortReal> (
2321 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2322 aMemTrgUsed += static_cast<Standard_ShortReal> (
2323 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2324 aMemTrgUsed += static_cast<Standard_ShortReal> (
2325 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2327 aMemBvhUsed += static_cast<Standard_ShortReal> (
2328 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2329 aMemBvhUsed += static_cast<Standard_ShortReal> (
2330 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2331 aMemBvhUsed += static_cast<Standard_ShortReal> (
2332 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2335 aMemBvhUsed += static_cast<Standard_ShortReal> (
2336 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2337 aMemBvhUsed += static_cast<Standard_ShortReal> (
2338 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2339 aMemBvhUsed += static_cast<Standard_ShortReal> (
2340 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2342 std::cout << "GPU Memory Used (Mb):\n"
2343 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2344 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2351 // =======================================================================
2352 // function : updateRaytraceLightSources
2353 // purpose : Updates 3D scene light sources for ray-tracing
2354 // =======================================================================
2355 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2357 std::vector<OpenGl_Light> aLightSources;
2359 if (myShadingModel != Graphic3d_TOSM_NONE)
2361 aLightSources.assign (myLights.begin(), myLights.end());
2363 // move positional light sources at the front of the list
2364 std::partition (aLightSources.begin(), aLightSources.end(), IsLightPositional());
2367 // get number of 'real' (not ambient) light sources
2368 const size_t aNbLights = std::count_if (aLightSources.begin(), aLightSources.end(), IsNotAmbient());
2370 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2374 myRaytraceGeometry.Sources.resize (aNbLights);
2377 myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2379 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2381 const OpenGl_Light& aLight = aLightSources[aLightIdx];
2383 if (aLight.Type == Graphic3d_TOLS_AMBIENT)
2385 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity,
2386 aLight.Color.g() * aLight.Intensity,
2387 aLight.Color.b() * aLight.Intensity,
2392 BVH_Vec4f aEmission (aLight.Color.r() * aLight.Intensity,
2393 aLight.Color.g() * aLight.Intensity,
2394 aLight.Color.b() * aLight.Intensity,
2397 BVH_Vec4f aPosition (-aLight.Direction.x(),
2398 -aLight.Direction.y(),
2399 -aLight.Direction.z(),
2402 if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL)
2404 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position.x()),
2405 static_cast<float>(aLight.Position.y()),
2406 static_cast<float>(aLight.Position.z()),
2409 // store smoothing radius in W-component
2410 aEmission.w() = Max (aLight.Smoothness, 0.f);
2414 // store cosine of smoothing angle in W-component
2415 aEmission.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2418 if (aLight.IsHeadlight)
2420 aPosition = theInvModelView * aPosition;
2423 for (int aK = 0; aK < 4; ++aK)
2425 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2426 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2431 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2437 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2439 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2442 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2444 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2445 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2447 #ifdef RAY_TRACE_PRINT_INFO
2448 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2450 return Standard_False;
2453 myAccumFrames = 0; // accumulation should be restarted
2456 return Standard_True;
2459 // =======================================================================
2460 // function : setUniformState
2461 // purpose : Sets uniform state for the given ray-tracing shader program
2462 // =======================================================================
2463 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2464 const Standard_Integer theWinSizeX,
2465 const Standard_Integer theWinSizeY,
2466 const Handle(OpenGl_Context)& theGlContext)
2468 // Get projection state
2469 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2471 OpenGl_Mat4 aViewPrjMat;
2472 OpenGl_Mat4 anUnviewMat;
2473 OpenGl_Vec3 aOrigins[4];
2474 OpenGl_Vec3 aDirects[4];
2476 updateCamera (myCamera->OrientationMatrixF(),
2477 aCntxProjectionState.Current(),
2483 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2485 : myPostFSAAProgram;
2487 if (theProgram.IsNull())
2489 return Standard_False;
2493 theProgram->SetUniform (theGlContext,
2494 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2495 theProgram->SetUniform (theGlContext,
2496 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2497 theProgram->SetUniform (theGlContext,
2498 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2499 theProgram->SetUniform (theGlContext,
2500 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2501 theProgram->SetUniform (theGlContext,
2502 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2503 theProgram->SetUniform (theGlContext,
2504 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2505 theProgram->SetUniform (theGlContext,
2506 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2507 theProgram->SetUniform (theGlContext,
2508 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2509 theProgram->SetUniform (theGlContext,
2510 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2511 theProgram->SetUniform (theGlContext,
2512 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2514 // Set screen dimensions
2515 myRaytraceProgram->SetUniform (theGlContext,
2516 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2517 myRaytraceProgram->SetUniform (theGlContext,
2518 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2520 // Set 3D scene parameters
2521 theProgram->SetUniform (theGlContext,
2522 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2523 theProgram->SetUniform (theGlContext,
2524 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2526 // Set light source parameters
2527 const Standard_Integer aLightSourceBufferSize =
2528 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2530 theProgram->SetUniform (theGlContext,
2531 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2533 // Set array of 64-bit texture handles
2534 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2536 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2538 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2539 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2542 // Set background colors (only gradient background supported)
2543 if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
2545 theProgram->SetUniform (theGlContext,
2546 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2547 theProgram->SetUniform (theGlContext,
2548 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2552 const OpenGl_Vec4& aBackColor = myBgColor;
2554 theProgram->SetUniform (theGlContext,
2555 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2556 theProgram->SetUniform (theGlContext,
2557 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2560 // Set environment map parameters
2561 const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull() || !myTextureEnv->IsValid();
2563 theProgram->SetUniform (theGlContext,
2564 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2566 theProgram->SetUniform (theGlContext,
2567 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2569 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2571 theProgram->SetUniform (theGlContext,
2572 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2574 theProgram->SetUniform (theGlContext,
2575 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2577 // Check whether we should restart accumulation for run-time parameters
2578 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2579 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2581 myAccumFrames = 0; // accumulation should be restarted
2583 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2584 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2587 else // RT parameters
2589 // Set ambient light source
2590 theProgram->SetUniform (theGlContext,
2591 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2593 // Enable/disable run-time ray-tracing effects
2594 theProgram->SetUniform (theGlContext,
2595 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2596 theProgram->SetUniform (theGlContext,
2597 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2600 return Standard_True;
2603 // =======================================================================
2604 // function : bindRaytraceTextures
2605 // purpose : Binds ray-trace textures to corresponding texture units
2606 // =======================================================================
2607 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2609 if (myRaytraceParameters.AdaptiveScreenSampling)
2611 #if !defined(GL_ES_VERSION_2_0)
2612 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
2613 myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2614 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
2615 myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2617 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2618 myRaytraceVisualErrorTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2619 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2620 myRaytraceTileOffsetsTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2624 if (!myTextureEnv.IsNull() && myTextureEnv->IsValid())
2626 myTextureEnv->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
2629 mySceneMinPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2630 mySceneMaxPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2631 mySceneNodeInfoTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2632 myGeometryVertexTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2633 myGeometryNormalTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2634 myGeometryTexCrdTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2635 myGeometryTriangTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2636 mySceneTransformTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2637 myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2638 myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2641 // =======================================================================
2642 // function : unbindRaytraceTextures
2643 // purpose : Unbinds ray-trace textures from corresponding texture units
2644 // =======================================================================
2645 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2647 mySceneMinPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2648 mySceneMaxPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2649 mySceneNodeInfoTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2650 myGeometryVertexTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2651 myGeometryNormalTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2652 myGeometryTexCrdTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2653 myGeometryTriangTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2654 mySceneTransformTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2655 myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2656 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2658 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2661 // =======================================================================
2662 // function : runRaytraceShaders
2663 // purpose : Runs ray-tracing shader programs
2664 // =======================================================================
2665 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2666 const Standard_Integer theSizeY,
2667 Graphic3d_Camera::Projection theProjection,
2668 OpenGl_FrameBuffer* theReadDrawFbo,
2669 const Handle(OpenGl_Context)& theGlContext)
2671 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2673 aResult &= setUniformState (0,
2678 if (myRaytraceParameters.GlobalIllumination) // path tracing
2680 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2682 else // Whitted-style ray-tracing
2684 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2690 // =======================================================================
2691 // function : runRaytrace
2692 // purpose : Runs Whitted-style ray-tracing
2693 // =======================================================================
2694 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2695 const Standard_Integer theSizeY,
2696 Graphic3d_Camera::Projection theProjection,
2697 OpenGl_FrameBuffer* theReadDrawFbo,
2698 const Handle(OpenGl_Context)& theGlContext)
2700 Standard_Boolean aResult = Standard_True;
2702 bindRaytraceTextures (theGlContext);
2704 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2705 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2707 // Choose proper set of frame buffers for stereo rendering
2708 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2710 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2712 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2714 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2717 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2719 if (myRenderParams.IsAntialiasingEnabled)
2721 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2723 // bind ray-tracing output image as input
2724 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2726 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2728 aResult &= setUniformState (1 /* FSAA ID */,
2733 // Perform multi-pass adaptive FSAA using ping-pong technique.
2734 // We use 'FLIPTRI' sampling pattern changing for every pixel
2735 // (3 additional samples per pixel, the 1st sample is already
2736 // available from initial ray-traced image).
2737 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2739 GLfloat aOffsetX = 1.f / theSizeX;
2740 GLfloat aOffsetY = 1.f / theSizeY;
2758 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2759 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2760 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2761 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2762 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2763 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2765 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2766 ? myRaytraceFBO2[aFBOIdx]
2767 : myRaytraceFBO1[aFBOIdx];
2769 aFramebuffer->BindBuffer (theGlContext);
2771 // perform adaptive FSAA pass
2772 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2774 aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2777 aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2778 aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2780 glEnable (GL_DEPTH_TEST);
2782 // Display filtered image
2783 theGlContext->BindProgram (myOutImageProgram);
2785 if (theReadDrawFbo != NULL)
2787 theReadDrawFbo->BindBuffer (theGlContext);
2791 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2794 aRenderImageFramebuffer->ColorTexture()->Bind (
2795 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2797 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (
2798 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2800 // copy the output image with depth values
2801 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2803 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (
2804 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2806 aRenderImageFramebuffer->ColorTexture()->Unbind (
2807 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2810 unbindRaytraceTextures (theGlContext);
2812 theGlContext->BindProgram (NULL);
2817 // =======================================================================
2818 // function : runPathtrace
2819 // purpose : Runs path tracing shader
2820 // =======================================================================
2821 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2822 const Standard_Integer theSizeY,
2823 const Graphic3d_Camera::Projection theProjection,
2824 OpenGl_FrameBuffer* theReadDrawFbo,
2825 const Handle(OpenGl_Context)& theGlContext)
2827 Standard_Boolean aResult = Standard_True;
2829 if (myToUpdateEnvironmentMap) // check whether the map was changed
2831 myAccumFrames = myToUpdateEnvironmentMap = 0;
2834 if (myRaytraceParameters.AdaptiveScreenSampling)
2836 if (myAccumFrames == 0)
2838 myTileSampler.Reset(); // reset tile sampler to its initial state
2841 // Adaptive sampling is starting at the second frame
2842 myTileSampler.Upload (theGlContext,
2843 myRaytraceTileOffsetsTexture,
2844 myRaytraceParameters.NbTilesX,
2845 myRaytraceParameters.NbTilesY,
2849 bindRaytraceTextures (theGlContext);
2851 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2852 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2853 Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
2855 // Choose proper set of frame buffers for stereo rendering
2856 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2858 const Standard_Integer anImageId = (aFBOIdx != 0)
2859 ? OpenGl_RT_OutputImageRgh
2860 : OpenGl_RT_OutputImageLft;
2862 aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2863 anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2865 aDepthSourceFramebuffer = aRenderImageFramebuffer;
2867 anAccumImageFramebuffer->ColorTexture()->Bind (
2868 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2870 aRenderImageFramebuffer->BindBuffer (theGlContext);
2872 if (myAccumFrames == 0)
2874 myRNG.SetSeed(); // start RNG from beginning
2877 // Clear adaptive screen sampling images
2878 if (myRaytraceParameters.AdaptiveScreenSampling)
2880 #if !defined(GL_ES_VERSION_2_0)
2881 if (myAccumFrames == 0)
2883 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2886 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2890 // Set frame accumulation weight
2891 myRaytraceProgram->SetUniform (theGlContext,
2892 myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
2894 // Set random number generator seed
2895 myRaytraceProgram->SetUniform (theGlContext,
2896 myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2898 // Set image uniforms for render program
2899 myRaytraceProgram->SetUniform (theGlContext,
2900 myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
2901 myRaytraceProgram->SetUniform (theGlContext,
2902 myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2904 glDisable (GL_DEPTH_TEST);
2906 if (myRaytraceParameters.AdaptiveScreenSampling && myAccumFrames > 0)
2910 myTileSampler.TileSize() * myRaytraceParameters.NbTilesX,
2911 myTileSampler.TileSize() * myRaytraceParameters.NbTilesY);
2914 // Generate for the given RNG seed
2915 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2917 if (myRaytraceParameters.AdaptiveScreenSampling && myAccumFrames > 0)
2925 // Output accumulated path traced image
2926 theGlContext->BindProgram (myOutImageProgram);
2928 if (myRaytraceParameters.AdaptiveScreenSampling)
2930 // Set uniforms for display program
2931 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", anImageId);
2932 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
2933 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
2934 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
2937 if (myRaytraceParameters.GlobalIllumination)
2939 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
2940 switch (myRaytraceParameters.ToneMappingMethod)
2942 case Graphic3d_ToneMappingMethod_Disabled:
2944 case Graphic3d_ToneMappingMethod_Filmic:
2945 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
2950 if (theReadDrawFbo != NULL)
2952 theReadDrawFbo->BindBuffer (theGlContext);
2956 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2959 aRenderImageFramebuffer->ColorTexture()->Bind (
2960 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2962 glEnable (GL_DEPTH_TEST);
2964 // Copy accumulated image with correct depth values
2965 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2967 aRenderImageFramebuffer->ColorTexture()->Unbind (
2968 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2970 if (myRaytraceParameters.AdaptiveScreenSampling)
2972 myRaytraceVisualErrorTexture->Bind (theGlContext);
2974 // Download visual error map from the GPU and build
2975 // adjusted tile offsets for optimal image sampling
2976 myTileSampler.GrabVarianceMap (theGlContext);
2979 unbindRaytraceTextures (theGlContext);
2981 theGlContext->BindProgram (NULL);
2986 // =======================================================================
2987 // function : raytrace
2988 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2989 // =======================================================================
2990 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
2991 const Standard_Integer theSizeY,
2992 Graphic3d_Camera::Projection theProjection,
2993 OpenGl_FrameBuffer* theReadDrawFbo,
2994 const Handle(OpenGl_Context)& theGlContext)
2996 if (!initRaytraceResources (theGlContext))
2998 return Standard_False;
3001 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3003 return Standard_False;
3006 OpenGl_Mat4 aLightSourceMatrix;
3008 // Get inversed model-view matrix for transforming lights
3009 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3011 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3013 return Standard_False;
3016 // Generate image using Whitted-style ray-tracing or path tracing
3017 if (myIsRaytraceDataValid)
3019 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3021 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3023 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3024 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3027 glDisable (GL_BLEND);
3029 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3037 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3038 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3041 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3043 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3044 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3047 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3050 return Standard_True;