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"
31 #include "../Shaders/Shaders_TangentSpaceNormal_glsl.pxx"
33 //! Use this macro to output ray-tracing debug info
34 // #define RAY_TRACE_PRINT_INFO
36 #ifdef RAY_TRACE_PRINT_INFO
37 #include <OSD_Timer.hxx>
42 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
43 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
48 //! Defines OpenGL texture samplers.
49 static const Graphic3d_TextureUnit OpenGl_RT_EnvMapTexture = Graphic3d_TextureUnit_0;
51 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
52 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
53 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
54 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
56 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
57 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
58 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
59 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
61 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
62 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
64 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
65 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
67 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
70 // =======================================================================
71 // function : updateRaytraceGeometry
72 // purpose : Updates 3D scene geometry for ray-tracing
73 // =======================================================================
74 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
75 const Standard_Integer theViewId,
76 const Handle(OpenGl_Context)& theGlContext)
78 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
79 // modifications. This is light-weight procedure performed on each frame
80 if (theMode == OpenGl_GUM_CHECK)
82 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
84 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
87 else if (theMode == OpenGl_GUM_PREPARE)
89 myRaytraceGeometry.ClearMaterials();
91 myArrayToTrianglesMap.clear();
93 myIsRaytraceDataValid = Standard_False;
96 // The set of processed structures (reflected to ray-tracing)
97 // This set is used to remove out-of-date records from the
98 // hash map of structures
99 std::set<const OpenGl_Structure*> anElements;
101 // Set to store all currently visible OpenGL primitive arrays
102 // applicable for ray-tracing
103 std::set<Standard_Size> anArrayIDs;
105 // Set to store all non-raytracable elements allowing tracking
106 // of changes in OpenGL scene (only for path tracing)
107 std::set<Standard_Integer> aNonRaytraceIDs;
109 for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
111 const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
112 if (aLayer->NbStructures() == 0
113 || !aLayer->LayerSettings().IsRaytracable()
114 || aLayer->LayerSettings().IsImmediate())
119 const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
120 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
122 for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
124 const OpenGl_Structure* aStructure = aStructIt.Value();
126 if (theMode == OpenGl_GUM_CHECK)
128 if (toUpdateStructure (aStructure))
130 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
132 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
134 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
137 else if (theMode == OpenGl_GUM_PREPARE)
139 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
143 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
148 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
150 // Extract OpenGL elements from the group (primitives arrays)
151 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
153 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
155 if (aPrimArray != NULL)
157 anArrayIDs.insert (aPrimArray->GetUID());
162 else if (theMode == OpenGl_GUM_REBUILD)
164 if (!aStructure->IsRaytracable())
168 else if (addRaytraceStructure (aStructure, theGlContext))
170 anElements.insert (aStructure); // structure was processed
177 if (theMode == OpenGl_GUM_PREPARE)
179 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
181 // Filter out unchanged objects so only their transformations and materials
182 // will be updated (and newly added objects will be processed from scratch)
183 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
185 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
186 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
188 if (aTriangleSet == NULL)
193 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
195 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
197 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
201 myRaytraceGeometry.Objects() = anUnchangedObjects;
203 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
205 else if (theMode == OpenGl_GUM_REBUILD)
207 // Actualize the hash map of structures - remove out-of-date records
208 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
210 while (anIter != myStructureStates.end())
212 if (anElements.find (anIter->first) == anElements.end())
214 myStructureStates.erase (anIter++);
222 // Actualize OpenGL layer list state
223 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
225 // Rebuild two-level acceleration structure
226 myRaytraceGeometry.ProcessAcceleration();
228 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
229 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
230 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
232 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
234 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
236 return uploadRaytraceData (theGlContext);
239 if (myRaytraceParameters.GlobalIllumination)
241 Standard_Boolean toRestart =
242 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
244 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
246 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
248 toRestart = Standard_True;
257 myNonRaytraceStructureIDs = aNonRaytraceIDs;
260 return Standard_True;
263 // =======================================================================
264 // function : toUpdateStructure
265 // purpose : Checks to see if the structure is modified
266 // =======================================================================
267 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
269 if (!theStructure->IsRaytracable())
271 if (theStructure->ModificationState() > 0)
273 theStructure->ResetModificationState();
275 return Standard_True; // ray-trace element was removed - need to rebuild
278 return Standard_False; // did not contain ray-trace elements
281 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
283 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
285 return Standard_True;
287 else if (theStructure->InstancedStructure() != NULL)
289 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
292 return Standard_False;
295 // =======================================================================
296 // function : buildTextureTransform
297 // purpose : Constructs texture transformation matrix
298 // =======================================================================
299 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
301 theMatrix.InitIdentity();
302 if (theParams.IsNull())
308 const Graphic3d_Vec2& aScale = theParams->Scale();
310 theMatrix.ChangeValue (0, 0) *= aScale.x();
311 theMatrix.ChangeValue (1, 0) *= aScale.x();
312 theMatrix.ChangeValue (2, 0) *= aScale.x();
313 theMatrix.ChangeValue (3, 0) *= aScale.x();
315 theMatrix.ChangeValue (0, 1) *= aScale.y();
316 theMatrix.ChangeValue (1, 1) *= aScale.y();
317 theMatrix.ChangeValue (2, 1) *= aScale.y();
318 theMatrix.ChangeValue (3, 1) *= aScale.y();
321 const Graphic3d_Vec2 aTrans = -theParams->Translation();
323 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
324 theMatrix.GetValue (0, 1) * aTrans.y();
326 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
327 theMatrix.GetValue (1, 1) * aTrans.y();
329 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
330 theMatrix.GetValue (2, 1) * aTrans.y();
333 const Standard_ShortReal aSin = std::sin (
334 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
335 const Standard_ShortReal aCos = std::cos (
336 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
338 BVH_Mat4f aRotationMat;
339 aRotationMat.SetValue (0, 0, aCos);
340 aRotationMat.SetValue (1, 1, aCos);
341 aRotationMat.SetValue (0, 1, -aSin);
342 aRotationMat.SetValue (1, 0, aSin);
344 theMatrix = theMatrix * aRotationMat;
347 // =======================================================================
348 // function : convertMaterial
349 // purpose : Creates ray-tracing material properties
350 // =======================================================================
351 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
352 const Handle(OpenGl_Context)& theGlContext)
354 OpenGl_RaytraceMaterial aResMat;
356 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
357 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
358 const float aShine = 128.0f * float(aSrcMat.Shininess());
360 const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
361 const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
362 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
363 const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
364 switch (aSrcMat.MaterialType())
366 case Graphic3d_MATERIAL_ASPECT:
368 aResMat.Ambient .SetValues (aSrcAmb * aMatCol, 1.0f);
369 aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
370 aResMat.Emission.SetValues (aSrcEms * aMatCol, 1.0f);
373 case Graphic3d_MATERIAL_PHYSIC:
375 aResMat.Ambient .SetValues (aSrcAmb, 1.0f);
376 aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
377 aResMat.Emission.SetValues (aSrcEms, 1.0f);
383 // interior color is always ignored for Specular
384 aResMat.Specular.SetValues (aSrcSpe, aShine);
385 const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
386 Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
387 aResMat.Diffuse.z() + aResMat.Specular.z()));
388 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
389 aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
392 const float anIndex = (float )aSrcMat.RefractionIndex();
393 aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
394 anIndex == 0 ? 1.0f : anIndex,
395 anIndex == 0 ? 1.0f : 1.0f / anIndex);
397 aResMat.Ambient = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
398 aResMat.Diffuse = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
399 aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
400 aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
402 // Serialize physically-based material properties
403 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
405 aResMat.BSDF.Kc = aBSDF.Kc;
406 aResMat.BSDF.Ks = aBSDF.Ks;
407 aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.0f); // no base color texture
408 aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, -1.0f); // no metallic-roughness texture
409 aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, -1.0f); // no emissive texture
411 aResMat.BSDF.Absorption = aBSDF.Absorption;
413 aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
414 aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
415 aResMat.BSDF.FresnelBase.w() = -1.0; // no normal map texture
417 // Handle material textures
418 if (!theAspect->Aspect()->ToMapTexture())
423 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
424 if (aTextureSet.IsNull()
425 || aTextureSet->IsEmpty()
426 || aTextureSet->First().IsNull())
431 if (theGlContext->HasRayTracingTextures())
433 // write texture ID to diffuse w-components
434 for (OpenGl_TextureSet::Iterator aTexIter (aTextureSet); aTexIter.More(); aTexIter.Next())
436 const Handle(OpenGl_Texture)& aTexture = aTexIter.Value();
437 if (aTexIter.Unit() == Graphic3d_TextureUnit_BaseColor)
439 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
440 aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
442 else if (aTexIter.Unit() == Graphic3d_TextureUnit_MetallicRoughness)
444 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
445 aResMat.BSDF.Kt.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
447 else if (aTexIter.Unit() == Graphic3d_TextureUnit_Emissive)
449 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
450 aResMat.BSDF.Le.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
452 else if (aTexIter.Unit() == Graphic3d_TextureUnit_Normal)
454 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
455 aResMat.BSDF.FresnelBase.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
459 else if (!myIsRaytraceWarnTextures)
461 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
462 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
463 "Please try to update graphics card driver. At the moment textures will be ignored.");
464 myIsRaytraceWarnTextures = Standard_True;
470 // =======================================================================
471 // function : addRaytraceStructure
472 // purpose : Adds OpenGL structure to ray-traced scene geometry
473 // =======================================================================
474 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
475 const Handle(OpenGl_Context)& theGlContext)
477 if (!theStructure->IsVisible())
479 myStructureStates[theStructure] = StructState (theStructure);
481 return Standard_True;
484 // Get structure material
485 OpenGl_RaytraceMaterial aDefaultMaterial;
486 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
488 // Process all connected OpenGL structures
489 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
491 if (anInstanced != NULL && anInstanced->IsRaytracable())
493 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
496 myStructureStates[theStructure] = StructState (theStructure);
501 // =======================================================================
502 // function : addRaytraceGroups
503 // purpose : Adds OpenGL groups to ray-traced scene geometry
504 // =======================================================================
505 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
506 const OpenGl_RaytraceMaterial& theStructMat,
507 const Handle(Geom_Transformation)& theTrsf,
508 const Handle(OpenGl_Context)& theGlContext)
511 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
513 // Get group material
514 OpenGl_RaytraceMaterial aGroupMaterial;
515 if (aGroupIter.Value()->GlAspects() != NULL)
517 aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
520 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
522 // Use group material if available, otherwise use structure material
523 myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
525 // Add OpenGL elements from group (extract primitives arrays and aspects)
526 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
528 OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
530 if (anAspect != NULL)
532 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
534 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
536 myRaytraceGeometry.Materials.push_back (aMaterial);
540 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
542 if (aPrimArray != NULL)
544 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
546 if (aSetIter != myArrayToTrianglesMap.end())
548 OpenGl_TriangleSet* aSet = aSetIter->second;
549 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
550 if (!theTrsf.IsNull())
552 theTrsf->Trsf().GetMat4 (aMat4);
553 aTransform->SetTransform (aMat4);
556 aSet->SetProperties (aTransform);
557 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
559 aSet->SetMaterialIndex (aMatID);
564 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
566 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
567 if (!theTrsf.IsNull())
569 theTrsf->Trsf().GetMat4 (aMat4);
570 aTransform->SetTransform (aMat4);
573 aSet->SetProperties (aTransform);
574 myRaytraceGeometry.Objects().Append (aSet);
582 return Standard_True;
585 // =======================================================================
586 // function : addRaytracePrimitiveArray
587 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
588 // =======================================================================
589 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
590 const Standard_Integer theMaterial,
591 const OpenGl_Mat4* theTransform)
593 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
594 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
595 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
597 if (theArray->DrawMode() < GL_TRIANGLES
598 #ifndef GL_ES_VERSION_2_0
599 || theArray->DrawMode() > GL_POLYGON
601 || theArray->DrawMode() > GL_TRIANGLE_FAN
603 || anAttribs.IsNull())
605 return Handle(OpenGl_TriangleSet)();
608 OpenGl_Mat4 aNormalMatrix;
609 if (theTransform != NULL)
611 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
612 "Error: Failed to compute normal transformation matrix", NULL);
614 aNormalMatrix.Transpose();
617 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
619 aSet->Vertices.reserve (anAttribs->NbElements);
620 aSet->Normals.reserve (anAttribs->NbElements);
621 aSet->TexCrds.reserve (anAttribs->NbElements);
623 const size_t aVertFrom = aSet->Vertices.size();
625 Standard_Integer anAttribIndex = 0;
626 Standard_Size anAttribStride = 0;
627 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
629 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
630 if (anAttrib.DataType == Graphic3d_TOD_VEC2
631 || anAttrib.DataType == Graphic3d_TOD_VEC3
632 || anAttrib.DataType == Graphic3d_TOD_VEC4)
634 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
636 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
637 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
641 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
643 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
644 if (anAttrib.DataType == Graphic3d_TOD_VEC3
645 || anAttrib.DataType == Graphic3d_TOD_VEC4)
647 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
649 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
653 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
655 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
656 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
658 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
660 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
665 if (aSet->Normals.size() != aSet->Vertices.size())
667 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
669 aSet->Normals.push_back (BVH_Vec3f());
673 if (aSet->TexCrds.size() != aSet->Vertices.size())
675 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
677 aSet->TexCrds.push_back (BVH_Vec2f());
681 if (theTransform != NULL)
683 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
685 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
687 BVH_Vec4f aTransVertex = *theTransform *
688 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
690 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
692 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
694 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
696 BVH_Vec4f aTransNormal = aNormalMatrix *
697 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
699 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
703 if (!aBounds.IsNull())
705 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
707 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
709 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
712 return Handle(OpenGl_TriangleSet)();
715 aBoundStart += aVertNum;
720 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
722 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
725 return Handle(OpenGl_TriangleSet)();
730 if (aSet->Size() != 0)
738 // =======================================================================
739 // function : addRaytraceVertexIndices
740 // purpose : Adds vertex indices to ray-traced scene geometry
741 // =======================================================================
742 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
743 const Standard_Integer theMatID,
744 const Standard_Integer theCount,
745 const Standard_Integer theOffset,
746 const OpenGl_PrimitiveArray& theArray)
748 switch (theArray.DrawMode())
750 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
751 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
752 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
753 #if !defined(GL_ES_VERSION_2_0)
754 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
755 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
756 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
760 return Standard_False;
763 // =======================================================================
764 // function : addRaytraceTriangleArray
765 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
766 // =======================================================================
767 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
768 const Standard_Integer theMatID,
769 const Standard_Integer theCount,
770 const Standard_Integer theOffset,
771 const Handle(Graphic3d_IndexBuffer)& theIndices)
775 return Standard_True;
778 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
780 if (!theIndices.IsNull())
782 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
784 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
785 theIndices->Index (aVert + 1),
786 theIndices->Index (aVert + 2),
792 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
794 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
798 return Standard_True;
801 // =======================================================================
802 // function : addRaytraceTriangleFanArray
803 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
804 // =======================================================================
805 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
806 const Standard_Integer theMatID,
807 const Standard_Integer theCount,
808 const Standard_Integer theOffset,
809 const Handle(Graphic3d_IndexBuffer)& theIndices)
813 return Standard_True;
816 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
818 if (!theIndices.IsNull())
820 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
822 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
823 theIndices->Index (aVert + 1),
824 theIndices->Index (aVert + 2),
830 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
832 theSet.Elements.push_back (BVH_Vec4i (theOffset,
839 return Standard_True;
842 // =======================================================================
843 // function : addRaytraceTriangleStripArray
844 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
845 // =======================================================================
846 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
847 const Standard_Integer theMatID,
848 const Standard_Integer theCount,
849 const Standard_Integer theOffset,
850 const Handle(Graphic3d_IndexBuffer)& theIndices)
854 return Standard_True;
857 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
859 if (!theIndices.IsNull())
861 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
863 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
864 theIndices->Index (aVert + (aCW ? 0 : 1)),
865 theIndices->Index (aVert + 2),
871 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
873 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
874 aVert + (aCW ? 0 : 1),
880 return Standard_True;
883 // =======================================================================
884 // function : addRaytraceQuadrangleArray
885 // purpose : Adds OpenGL quad array to ray-traced scene geometry
886 // =======================================================================
887 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
888 const Standard_Integer theMatID,
889 const Standard_Integer theCount,
890 const Standard_Integer theOffset,
891 const Handle(Graphic3d_IndexBuffer)& theIndices)
895 return Standard_True;
898 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
900 if (!theIndices.IsNull())
902 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
904 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
905 theIndices->Index (aVert + 1),
906 theIndices->Index (aVert + 2),
908 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
909 theIndices->Index (aVert + 2),
910 theIndices->Index (aVert + 3),
916 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
918 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
920 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
925 return Standard_True;
928 // =======================================================================
929 // function : addRaytraceQuadrangleStripArray
930 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
931 // =======================================================================
932 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
933 const Standard_Integer theMatID,
934 const Standard_Integer theCount,
935 const Standard_Integer theOffset,
936 const Handle(Graphic3d_IndexBuffer)& theIndices)
940 return Standard_True;
943 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
945 if (!theIndices.IsNull())
947 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
949 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
950 theIndices->Index (aVert + 1),
951 theIndices->Index (aVert + 2),
954 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
955 theIndices->Index (aVert + 3),
956 theIndices->Index (aVert + 2),
962 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
964 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
969 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
976 return Standard_True;
979 // =======================================================================
980 // function : addRaytracePolygonArray
981 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
982 // =======================================================================
983 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
984 const Standard_Integer theMatID,
985 const Standard_Integer theCount,
986 const Standard_Integer theOffset,
987 const Handle(Graphic3d_IndexBuffer)& theIndices)
991 return Standard_True;
994 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
996 if (!theIndices.IsNull())
998 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1000 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
1001 theIndices->Index (aVert + 1),
1002 theIndices->Index (aVert + 2),
1008 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1010 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1017 return Standard_True;
1020 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1022 // =======================================================================
1023 // function : Source
1024 // purpose : Returns shader source combined with prefix
1025 // =======================================================================
1026 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1028 const TCollection_AsciiString aVersion = "#version 140";
1030 if (myPrefix.IsEmpty())
1032 return aVersion + "\n" + mySource;
1035 return aVersion + "\n" + myPrefix + "\n" + mySource;
1038 // =======================================================================
1039 // function : LoadFromFiles
1040 // purpose : Loads shader source from specified files
1041 // =======================================================================
1042 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1043 const TCollection_AsciiString& thePrefix)
1047 myPrefix = thePrefix;
1049 TCollection_AsciiString aMissingFiles;
1050 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1052 OSD_File aFile (theFileNames[anIndex]);
1055 aFile.Open (OSD_ReadOnly, OSD_Protection());
1057 if (!aFile.IsOpen())
1059 if (!aMissingFiles.IsEmpty())
1061 aMissingFiles += ", ";
1063 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1066 else if (!aMissingFiles.IsEmpty())
1072 TCollection_AsciiString aSource;
1073 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1074 if (!aSource.IsEmpty())
1076 mySource += TCollection_AsciiString ("\n") + aSource;
1081 if (!aMissingFiles.IsEmpty())
1083 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1084 return Standard_False;
1086 return Standard_True;
1089 // =======================================================================
1090 // function : LoadFromStrings
1092 // =======================================================================
1093 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1094 const TCollection_AsciiString& thePrefix)
1098 myPrefix = thePrefix;
1100 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1102 TCollection_AsciiString aSource = theStrings[anIndex];
1103 if (!aSource.IsEmpty())
1105 mySource += TCollection_AsciiString ("\n") + aSource;
1108 return Standard_True;
1111 // =======================================================================
1112 // function : generateShaderPrefix
1113 // purpose : Generates shader prefix based on current ray-tracing options
1114 // =======================================================================
1115 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1117 TCollection_AsciiString aPrefixString =
1118 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1119 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1121 if (myRaytraceParameters.TransparentShadows)
1123 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1125 if (!theGlContext->ToRenderSRGB())
1127 aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
1130 // If OpenGL driver supports bindless textures and texturing
1131 // is actually used, activate texturing in ray-tracing mode
1132 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1134 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1135 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1138 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1140 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1142 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1144 if (theGlContext->IsGlGreaterEqual (4, 4))
1146 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1147 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1148 && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1150 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1155 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1157 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1160 switch (myRaytraceParameters.ToneMappingMethod)
1162 case Graphic3d_ToneMappingMethod_Disabled:
1164 case Graphic3d_ToneMappingMethod_Filmic:
1165 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1170 if (myRaytraceParameters.ToIgnoreNormalMap)
1172 aPrefixString += TCollection_AsciiString("\n#define IGNORE_NORMAL_MAP");
1175 if (myRaytraceParameters.CubemapForBack)
1177 aPrefixString += TCollection_AsciiString("\n#define BACKGROUND_CUBEMAP");
1180 if (myRaytraceParameters.DepthOfField)
1182 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1185 return aPrefixString;
1188 // =======================================================================
1189 // function : safeFailBack
1190 // purpose : Performs safe exit when shaders initialization fails
1191 // =======================================================================
1192 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1193 const Handle(OpenGl_Context)& theGlContext)
1195 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1196 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1198 myRaytraceInitStatus = OpenGl_RT_FAIL;
1200 releaseRaytraceResources (theGlContext);
1202 return Standard_False;
1205 // =======================================================================
1206 // function : initShader
1207 // purpose : Creates new shader object with specified source
1208 // =======================================================================
1209 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1210 const ShaderSource& theSource,
1211 const Handle(OpenGl_Context)& theGlContext)
1213 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1214 if (!aShader->Create (theGlContext))
1216 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1217 TCollection_ExtendedString ("Error: Failed to create ") +
1218 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1219 aShader->Release (theGlContext.get());
1220 return Handle(OpenGl_ShaderObject)();
1223 if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
1225 aShader->Release (theGlContext.get());
1226 return Handle(OpenGl_ShaderObject)();
1231 // =======================================================================
1232 // function : initProgram
1233 // purpose : Creates GLSL program from the given shader objects
1234 // =======================================================================
1235 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1236 const Handle(OpenGl_ShaderObject)& theVertShader,
1237 const Handle(OpenGl_ShaderObject)& theFragShader,
1238 const TCollection_AsciiString& theName)
1240 const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1241 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1243 if (!aProgram->Create (theGlContext))
1245 theVertShader->Release (theGlContext.operator->());
1247 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1248 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1250 return Handle(OpenGl_ShaderProgram)();
1253 if (!aProgram->AttachShader (theGlContext, theVertShader)
1254 || !aProgram->AttachShader (theGlContext, theFragShader))
1256 theVertShader->Release (theGlContext.operator->());
1258 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1259 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1261 return Handle(OpenGl_ShaderProgram)();
1264 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1266 TCollection_AsciiString aLinkLog;
1268 if (!aProgram->Link (theGlContext))
1270 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1272 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1273 "Failed to link shader program:\n") + aLinkLog;
1275 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1276 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1278 return Handle(OpenGl_ShaderProgram)();
1280 else if (theGlContext->caps->glslWarnings)
1282 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1283 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1285 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1286 "Shader program was linked with following warnings:\n") + aLinkLog;
1288 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1289 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1296 // =======================================================================
1297 // function : initRaytraceResources
1298 // purpose : Initializes OpenGL/GLSL shader programs
1299 // =======================================================================
1300 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1301 const Standard_Integer theSizeY,
1302 const Handle(OpenGl_Context)& theGlContext)
1304 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1306 return Standard_False;
1309 Standard_Boolean aToRebuildShaders = Standard_False;
1311 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1313 myRaytraceInitStatus = OpenGl_RT_NONE;
1314 releaseRaytraceResources (theGlContext, Standard_True);
1315 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1318 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1320 if (!myIsRaytraceDataValid)
1322 return Standard_True;
1325 const Standard_Integer aRequiredStackSize =
1326 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1328 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1330 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1332 aToRebuildShaders = Standard_True;
1336 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1338 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1340 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1341 aToRebuildShaders = Standard_True;
1346 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1347 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1348 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1349 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1350 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures
1351 || myRenderParams.ToIgnoreNormalMapInRayTracing != myRaytraceParameters.ToIgnoreNormalMap)
1353 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1354 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1355 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1356 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1357 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1358 myRaytraceParameters.ToIgnoreNormalMap = myRenderParams.ToIgnoreNormalMapInRayTracing;
1359 aToRebuildShaders = Standard_True;
1362 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling
1363 || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1365 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1366 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1367 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1369 if (!theGlContext->HasRayTracingAdaptiveSampling())
1371 // disable the feature if it is not supported
1372 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1373 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1374 "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1376 else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1377 && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1379 // disable the feature if it is not supported
1380 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1381 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1382 "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1386 aToRebuildShaders = Standard_True;
1388 myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1390 const bool isCubemapForBack = !myBackgroundCubeMap.IsNull();
1391 if (myRaytraceParameters.CubemapForBack != isCubemapForBack)
1393 myRaytraceParameters.CubemapForBack = isCubemapForBack;
1394 aToRebuildShaders = Standard_True;
1397 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1398 if (myRaytraceParameters.DepthOfField != toEnableDof)
1400 myRaytraceParameters.DepthOfField = toEnableDof;
1401 aToRebuildShaders = Standard_True;
1404 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1406 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1407 aToRebuildShaders = true;
1410 if (aToRebuildShaders)
1412 // Reject accumulated frames
1415 // Environment map should be updated
1416 myToUpdateEnvironmentMap = Standard_True;
1418 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1420 #ifdef RAY_TRACE_PRINT_INFO
1421 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1424 myRaytraceShaderSource.SetPrefix (aPrefixString);
1425 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1426 myOutImageShaderSource.SetPrefix (aPrefixString);
1428 if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
1429 || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
1430 || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source()))
1432 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1435 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1436 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1437 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1439 if (!myRaytraceProgram->Link (theGlContext)
1440 || !myPostFSAAProgram->Link (theGlContext)
1441 || !myOutImageProgram->Link (theGlContext))
1443 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1448 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1450 myAccumFrames = 0; // accumulation should be restarted
1452 if (!theGlContext->IsGlGreaterEqual (3, 1))
1454 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1456 else if (!theGlContext->arbTboRGB32)
1458 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1460 else if (!theGlContext->arbFBOBlit)
1462 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1465 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1467 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1468 if (myIsRaytraceDataValid)
1470 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1471 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1474 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1476 #ifdef RAY_TRACE_PRINT_INFO
1477 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1480 ShaderSource aBasicVertShaderSrc;
1482 if (!aShaderFolder.IsEmpty())
1484 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1485 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1487 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1492 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1493 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1498 if (!aShaderFolder.IsEmpty())
1500 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1501 aShaderFolder + "/TangentSpaceNormal.glsl",
1502 aShaderFolder + "/PathtraceBase.fs",
1503 aShaderFolder + "/RaytraceRender.fs",
1505 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1507 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1512 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1513 Shaders_TangentSpaceNormal_glsl,
1514 Shaders_PathtraceBase_fs,
1515 Shaders_RaytraceRender_fs,
1517 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1520 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1521 if (aBasicVertShader.IsNull())
1523 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1526 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1527 if (myRaytraceShader.IsNull())
1529 aBasicVertShader->Release (theGlContext.operator->());
1530 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1533 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1534 if (myRaytraceProgram.IsNull())
1536 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1541 if (!aShaderFolder.IsEmpty())
1543 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1544 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1546 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1551 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1552 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1555 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1556 if (aBasicVertShader.IsNull())
1558 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1561 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1562 if (myPostFSAAShader.IsNull())
1564 aBasicVertShader->Release (theGlContext.operator->());
1565 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1568 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1569 if (myPostFSAAProgram.IsNull())
1571 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1576 if (!aShaderFolder.IsEmpty())
1578 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1579 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1581 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1586 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1587 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1590 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1591 if (aBasicVertShader.IsNull())
1593 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1596 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1597 if (myOutImageShader.IsNull())
1599 aBasicVertShader->Release (theGlContext.operator->());
1600 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1603 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1604 if (myOutImageProgram.IsNull())
1606 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1611 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1613 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1615 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1616 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1618 theGlContext->BindProgram (aShaderProgram);
1620 aShaderProgram->SetSampler (theGlContext,
1621 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1622 aShaderProgram->SetSampler (theGlContext,
1623 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1624 aShaderProgram->SetSampler (theGlContext,
1625 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1626 aShaderProgram->SetSampler (theGlContext,
1627 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1628 aShaderProgram->SetSampler (theGlContext,
1629 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1630 aShaderProgram->SetSampler (theGlContext,
1631 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1632 aShaderProgram->SetSampler (theGlContext,
1633 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1634 aShaderProgram->SetSampler (theGlContext,
1635 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1636 aShaderProgram->SetSampler (theGlContext,
1637 "uEnvMapTexture", OpenGl_RT_EnvMapTexture);
1638 aShaderProgram->SetSampler (theGlContext,
1639 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1640 aShaderProgram->SetSampler (theGlContext,
1641 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1645 aShaderProgram->SetSampler (theGlContext,
1646 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1650 aShaderProgram->SetSampler (theGlContext,
1651 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1654 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1655 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1657 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1658 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1659 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1660 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1661 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1662 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1663 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1664 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1665 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1666 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1667 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1668 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1669 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1670 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1671 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1672 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1673 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1674 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1675 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1676 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1678 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1679 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1680 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1681 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1682 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1683 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1684 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1685 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1687 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1688 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1689 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1690 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1691 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1692 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1694 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1695 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1697 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1698 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1699 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1700 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1701 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnabled] =
1702 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapEnabled");
1703 myUniformLocations[anIndex][OpenGl_RT_uEnvMapForBack] =
1704 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapForBack");
1705 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1706 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1708 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1709 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1710 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1711 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1713 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1714 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1715 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1716 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1718 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1719 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1720 myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1721 aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1722 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1723 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1724 myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1725 aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1726 myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1727 aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1729 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1730 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1731 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1732 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1734 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1735 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1738 theGlContext->BindProgram (myOutImageProgram);
1740 myOutImageProgram->SetSampler (theGlContext,
1741 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1743 myOutImageProgram->SetSampler (theGlContext,
1744 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1746 theGlContext->BindProgram (NULL);
1749 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1751 return myRaytraceInitStatus == OpenGl_RT_INIT;
1754 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1761 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1763 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1765 return Standard_True;
1768 // =======================================================================
1769 // function : nullifyResource
1770 // purpose : Releases OpenGL resource
1771 // =======================================================================
1773 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1775 if (!theResource.IsNull())
1777 theResource->Release (theGlContext.get());
1778 theResource.Nullify();
1782 // =======================================================================
1783 // function : releaseRaytraceResources
1784 // purpose : Releases OpenGL/GLSL shader programs
1785 // =======================================================================
1786 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1788 // release shader resources
1789 nullifyResource (theGlContext, myRaytraceShader);
1790 nullifyResource (theGlContext, myPostFSAAShader);
1792 nullifyResource (theGlContext, myRaytraceProgram);
1793 nullifyResource (theGlContext, myPostFSAAProgram);
1794 nullifyResource (theGlContext, myOutImageProgram);
1796 if (!theToRebuild) // complete release
1798 myRaytraceFBO1[0]->Release (theGlContext.get());
1799 myRaytraceFBO1[1]->Release (theGlContext.get());
1800 myRaytraceFBO2[0]->Release (theGlContext.get());
1801 myRaytraceFBO2[1]->Release (theGlContext.get());
1803 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1804 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1806 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1807 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1808 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1809 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1810 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1811 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1813 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1814 nullifyResource (theGlContext, mySceneMinPointTexture);
1815 nullifyResource (theGlContext, mySceneMaxPointTexture);
1817 nullifyResource (theGlContext, myGeometryVertexTexture);
1818 nullifyResource (theGlContext, myGeometryNormalTexture);
1819 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1820 nullifyResource (theGlContext, myGeometryTriangTexture);
1821 nullifyResource (theGlContext, mySceneTransformTexture);
1823 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1824 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1826 myRaytraceGeometry.ReleaseResources (theGlContext);
1828 if (myRaytraceScreenQuad.IsValid ())
1830 myRaytraceScreenQuad.Release (theGlContext.get());
1835 // =======================================================================
1836 // function : updateRaytraceBuffers
1837 // purpose : Updates auxiliary OpenGL frame buffers.
1838 // =======================================================================
1839 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1840 const Standard_Integer theSizeY,
1841 const Handle(OpenGl_Context)& theGlContext)
1843 // Auxiliary buffers are not used
1844 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1846 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1847 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1848 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1849 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1851 return Standard_True;
1854 if (myRaytraceParameters.AdaptiveScreenSampling)
1856 Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1857 myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1858 myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1859 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1861 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1862 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1866 for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1868 if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1870 myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1871 myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1872 myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1873 myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1877 && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1879 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1880 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1881 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1882 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1883 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1887 if (myRaytraceParameters.AdaptiveScreenSampling)
1889 if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1890 && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1891 && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1892 && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1894 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1896 continue; // offsets texture is dynamically resized
1898 else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1899 && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1907 // Due to limitations of OpenGL image load-store extension
1908 // atomic operations are supported only for single-channel
1909 // images, so we define GL_R32F image. It is used as array
1910 // of 6D floating point vectors:
1911 // 0 - R color channel
1912 // 1 - G color channel
1913 // 2 - B color channel
1914 // 3 - hit time transformed into OpenGL NDC space
1915 // 4 - luminance accumulated for odd samples only
1916 myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1918 // workaround for some NVIDIA drivers
1919 myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1920 myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1921 myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
1922 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1923 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1925 if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1927 myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
1928 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1929 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1933 else // non-adaptive mode
1935 if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1936 || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1938 myAccumFrames = 0; // accumulation should be restarted
1941 myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1942 myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1945 return Standard_True;
1948 // =======================================================================
1949 // function : updateCamera
1950 // purpose : Generates viewing rays for corners of screen quad
1951 // =======================================================================
1952 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1953 const OpenGl_Mat4& theViewMapping,
1954 OpenGl_Vec3* theOrigins,
1955 OpenGl_Vec3* theDirects,
1956 OpenGl_Mat4& theViewPr,
1957 OpenGl_Mat4& theUnview)
1959 // compute view-projection matrix
1960 theViewPr = theViewMapping * theOrientation;
1962 // compute inverse view-projection matrix
1963 theViewPr.Inverted (theUnview);
1965 Standard_Integer aOriginIndex = 0;
1966 Standard_Integer aDirectIndex = 0;
1968 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1970 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1972 OpenGl_Vec4 aOrigin (GLfloat(aX),
1977 aOrigin = theUnview * aOrigin;
1979 aOrigin.x() = aOrigin.x() / aOrigin.w();
1980 aOrigin.y() = aOrigin.y() / aOrigin.w();
1981 aOrigin.z() = aOrigin.z() / aOrigin.w();
1983 OpenGl_Vec4 aDirect (GLfloat(aX),
1988 aDirect = theUnview * aDirect;
1990 aDirect.x() = aDirect.x() / aDirect.w();
1991 aDirect.y() = aDirect.y() / aDirect.w();
1992 aDirect.z() = aDirect.z() / aDirect.w();
1994 aDirect = aDirect - aOrigin;
1996 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1997 static_cast<GLfloat> (aOrigin.y()),
1998 static_cast<GLfloat> (aOrigin.z()));
2000 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2001 static_cast<GLfloat> (aDirect.y()),
2002 static_cast<GLfloat> (aDirect.z()));
2007 // =======================================================================
2008 // function : updatePerspCameraPT
2009 // purpose : Generates viewing rays (path tracing, perspective camera)
2010 // =======================================================================
2011 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
2012 const OpenGl_Mat4& theViewMapping,
2013 Graphic3d_Camera::Projection theProjection,
2014 OpenGl_Mat4& theViewPr,
2015 OpenGl_Mat4& theUnview,
2016 const int theWinSizeX,
2017 const int theWinSizeY)
2019 // compute view-projection matrix
2020 theViewPr = theViewMapping * theOrientation;
2022 // compute inverse view-projection matrix
2023 theViewPr.Inverted(theUnview);
2025 // get camera stereo params
2026 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2027 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2028 : static_cast<float> (myCamera->IOD());
2030 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2031 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2032 : static_cast<float> (myCamera->ZFocus());
2034 // get camera view vectors
2035 const gp_Pnt anOrig = myCamera->Eye();
2037 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2038 static_cast<float> (anOrig.Y()),
2039 static_cast<float> (anOrig.Z()));
2041 const gp_Dir aView = myCamera->Direction();
2043 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2044 static_cast<float> (aView.Y()),
2045 static_cast<float> (aView.Z()));
2047 const gp_Dir anUp = myCamera->Up();
2049 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2050 static_cast<float> (anUp.Y()),
2051 static_cast<float> (anUp.Z()));
2053 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2055 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2056 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2058 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2059 static_cast<float> (aScaleY));
2061 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2063 myEyeView = anEyeViewMono;
2065 else // stereo camera
2067 // compute z-focus point
2068 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2070 // compute stereo camera shift
2071 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2072 myEyeOrig += myEyeSide.Normalized() * aDx;
2074 // estimate new camera direction vector and correct its length
2075 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2076 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2080 // =======================================================================
2081 // function : uploadRaytraceData
2082 // purpose : Uploads ray-trace data to the GPU
2083 // =======================================================================
2084 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2086 if (!theGlContext->IsGlGreaterEqual (3, 1))
2088 #ifdef RAY_TRACE_PRINT_INFO
2089 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2091 return Standard_False;
2094 myAccumFrames = 0; // accumulation should be restarted
2096 /////////////////////////////////////////////////////////////////////////////
2097 // Prepare OpenGL textures
2099 if (theGlContext->arbTexBindless != NULL)
2101 // If OpenGL driver supports bindless textures we need
2102 // to get unique 64- bit handles for using on the GPU
2103 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2105 #ifdef RAY_TRACE_PRINT_INFO
2106 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2108 return Standard_False;
2112 /////////////////////////////////////////////////////////////////////////////
2113 // Create OpenGL BVH buffers
2115 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2117 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2118 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2119 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2120 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2122 if (!mySceneNodeInfoTexture->Create (theGlContext)
2123 || !mySceneMinPointTexture->Create (theGlContext)
2124 || !mySceneMaxPointTexture->Create (theGlContext)
2125 || !mySceneTransformTexture->Create (theGlContext))
2127 #ifdef RAY_TRACE_PRINT_INFO
2128 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2130 return Standard_False;
2134 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2136 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2137 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2138 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2139 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2141 if (!myGeometryVertexTexture->Create (theGlContext)
2142 || !myGeometryNormalTexture->Create (theGlContext)
2143 || !myGeometryTexCrdTexture->Create (theGlContext)
2144 || !myGeometryTriangTexture->Create (theGlContext))
2146 #ifdef RAY_TRACE_PRINT_INFO
2147 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2149 return Standard_False;
2153 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2155 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2157 if (!myRaytraceMaterialTexture->Create (theGlContext))
2159 #ifdef RAY_TRACE_PRINT_INFO
2160 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2162 return Standard_False;
2166 /////////////////////////////////////////////////////////////////////////////
2167 // Write transform buffer
2169 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2171 bool aResult = true;
2173 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2175 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2176 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2178 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2179 Standard_ASSERT_RETURN (aTransform != NULL,
2180 "OpenGl_TriangleSet does not contain transform", Standard_False);
2182 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2185 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2186 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2188 delete [] aNodeTransforms;
2190 /////////////////////////////////////////////////////////////////////////////
2191 // Write geometry and bottom-level BVH buffers
2193 Standard_Size aTotalVerticesNb = 0;
2194 Standard_Size aTotalElementsNb = 0;
2195 Standard_Size aTotalBVHNodesNb = 0;
2197 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2199 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2200 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2202 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2203 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2205 aTotalVerticesNb += aTriangleSet->Vertices.size();
2206 aTotalElementsNb += aTriangleSet->Elements.size();
2208 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2209 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2211 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2214 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2216 if (aTotalBVHNodesNb != 0)
2218 aResult &= mySceneNodeInfoTexture->Init (
2219 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2220 aResult &= mySceneMinPointTexture->Init (
2221 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2222 aResult &= mySceneMaxPointTexture->Init (
2223 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2228 #ifdef RAY_TRACE_PRINT_INFO
2229 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2231 return Standard_False;
2234 if (aTotalElementsNb != 0)
2236 aResult &= myGeometryTriangTexture->Init (
2237 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2240 if (aTotalVerticesNb != 0)
2242 aResult &= myGeometryVertexTexture->Init (
2243 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2244 aResult &= myGeometryNormalTexture->Init (
2245 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2246 aResult &= myGeometryTexCrdTexture->Init (
2247 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2252 #ifdef RAY_TRACE_PRINT_INFO
2253 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2255 return Standard_False;
2258 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2260 if (aBVH->Length() > 0)
2262 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2263 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2264 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2265 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2266 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2267 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2270 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2272 if (!aBVH->IsOuter (aNodeIdx))
2275 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2277 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2278 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2280 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2282 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2283 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2285 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2287 if (aBvhBuffersSize != 0)
2289 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2290 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2291 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2292 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2293 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2294 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2298 #ifdef RAY_TRACE_PRINT_INFO
2299 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2301 return Standard_False;
2305 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2307 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2308 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2310 if (!aTriangleSet->Vertices.empty())
2312 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2313 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2314 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2315 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2316 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2317 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2320 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2322 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2323 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2325 if (!aTriangleSet->Elements.empty())
2327 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2328 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2333 #ifdef RAY_TRACE_PRINT_INFO
2334 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2336 return Standard_False;
2340 /////////////////////////////////////////////////////////////////////////////
2341 // Write material buffer
2343 if (myRaytraceGeometry.Materials.size() != 0)
2345 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2346 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2350 #ifdef RAY_TRACE_PRINT_INFO
2351 std::cout << "Error: Failed to upload material buffer" << std::endl;
2353 return Standard_False;
2357 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2359 #ifdef RAY_TRACE_PRINT_INFO
2361 Standard_ShortReal aMemTrgUsed = 0.f;
2362 Standard_ShortReal aMemBvhUsed = 0.f;
2364 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2366 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2368 aMemTrgUsed += static_cast<Standard_ShortReal> (
2369 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2370 aMemTrgUsed += static_cast<Standard_ShortReal> (
2371 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2372 aMemTrgUsed += static_cast<Standard_ShortReal> (
2373 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2374 aMemTrgUsed += static_cast<Standard_ShortReal> (
2375 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2377 aMemBvhUsed += static_cast<Standard_ShortReal> (
2378 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2379 aMemBvhUsed += static_cast<Standard_ShortReal> (
2380 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2381 aMemBvhUsed += static_cast<Standard_ShortReal> (
2382 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2385 aMemBvhUsed += static_cast<Standard_ShortReal> (
2386 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2387 aMemBvhUsed += static_cast<Standard_ShortReal> (
2388 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2389 aMemBvhUsed += static_cast<Standard_ShortReal> (
2390 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2392 std::cout << "GPU Memory Used (Mb):\n"
2393 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2394 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2401 // =======================================================================
2402 // function : updateRaytraceLightSources
2403 // purpose : Updates 3D scene light sources for ray-tracing
2404 // =======================================================================
2405 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2407 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2408 Graphic3d_Vec4 aNewAmbient (0.0f);
2409 if (myShadingModel != Graphic3d_TOSM_UNLIT
2410 && !myLights.IsNull())
2412 aNewAmbient.SetValues (myLights->AmbientColor().rgb(), 0.0f);
2414 // move positional light sources at the front of the list
2415 aLightSources.reserve (myLights->Extent());
2416 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2417 aLightIter.More(); aLightIter.Next())
2419 const Graphic3d_CLight& aLight = *aLightIter.Value();
2420 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2422 aLightSources.push_back (aLightIter.Value());
2426 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2427 aLightIter.More(); aLightIter.Next())
2429 if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2431 aLightSources.push_back (aLightIter.Value());
2436 if (!myRaytraceGeometry.Ambient.IsEqual (aNewAmbient))
2439 myRaytraceGeometry.Ambient = aNewAmbient;
2442 // get number of 'real' (not ambient) light sources
2443 const size_t aNbLights = aLightSources.size();
2444 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2447 myRaytraceGeometry.Sources.resize (aNbLights);
2450 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2452 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2453 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2454 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2455 aLightColor.g() * aLight.Intensity(),
2456 aLightColor.b() * aLight.Intensity(),
2459 BVH_Vec4f aPosition (-aLight.PackedDirectionRange().x(),
2460 -aLight.PackedDirectionRange().y(),
2461 -aLight.PackedDirectionRange().z(),
2464 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2466 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2467 static_cast<float>(aLight.Position().Y()),
2468 static_cast<float>(aLight.Position().Z()),
2471 // store smoothing radius in W-component
2472 aEmission.w() = Max (aLight.Smoothness(), 0.f);
2476 // store cosine of smoothing angle in W-component
2477 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2480 if (aLight.IsHeadlight())
2482 aPosition = theInvModelView * aPosition;
2485 for (int aK = 0; aK < 4; ++aK)
2487 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2488 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2493 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2499 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2501 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2504 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2506 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2507 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2509 #ifdef RAY_TRACE_PRINT_INFO
2510 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2512 return Standard_False;
2515 myAccumFrames = 0; // accumulation should be restarted
2518 return Standard_True;
2521 // =======================================================================
2522 // function : setUniformState
2523 // purpose : Sets uniform state for the given ray-tracing shader program
2524 // =======================================================================
2525 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2526 const Standard_Integer theWinSizeX,
2527 const Standard_Integer theWinSizeY,
2528 Graphic3d_Camera::Projection theProjection,
2529 const Handle(OpenGl_Context)& theGlContext)
2531 // Get projection state
2532 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2534 OpenGl_Mat4 aViewPrjMat;
2535 OpenGl_Mat4 anUnviewMat;
2536 OpenGl_Vec3 aOrigins[4];
2537 OpenGl_Vec3 aDirects[4];
2539 if (myCamera->IsOrthographic()
2540 || !myRenderParams.IsGlobalIlluminationEnabled)
2542 updateCamera (myCamera->OrientationMatrixF(),
2543 aCntxProjectionState.Current(),
2551 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2552 aCntxProjectionState.Current(),
2560 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2562 : myPostFSAAProgram;
2564 if (theProgram.IsNull())
2566 return Standard_False;
2569 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2570 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2571 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2572 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2573 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2575 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2576 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2579 theProgram->SetUniform (theGlContext,
2580 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2581 theProgram->SetUniform (theGlContext,
2582 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2583 theProgram->SetUniform (theGlContext,
2584 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2585 theProgram->SetUniform (theGlContext,
2586 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2587 theProgram->SetUniform (theGlContext,
2588 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2589 theProgram->SetUniform (theGlContext,
2590 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2591 theProgram->SetUniform (theGlContext,
2592 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2593 theProgram->SetUniform (theGlContext,
2594 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2595 theProgram->SetUniform (theGlContext,
2596 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2597 theProgram->SetUniform (theGlContext,
2598 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2600 // Set screen dimensions
2601 myRaytraceProgram->SetUniform (theGlContext,
2602 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2603 myRaytraceProgram->SetUniform (theGlContext,
2604 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2606 // Set 3D scene parameters
2607 theProgram->SetUniform (theGlContext,
2608 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2609 theProgram->SetUniform (theGlContext,
2610 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2612 // Set light source parameters
2613 const Standard_Integer aLightSourceBufferSize =
2614 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2616 theProgram->SetUniform (theGlContext,
2617 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2619 // Set array of 64-bit texture handles
2620 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2622 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2624 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2625 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2628 // Set background colors (only vertical gradient background supported)
2629 OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
2630 if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2631 && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2633 aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
2634 aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
2636 if (myCamera->Tile().IsValid())
2638 Standard_Integer aTileOffset = myCamera->Tile().OffsetLowerLeft().y();
2639 Standard_Integer aTileSize = myCamera->Tile().TileSize.y();
2640 Standard_Integer aViewSize = myCamera->Tile().TotalSize.y();
2641 OpenGl_Vec4 aColorRange = aBackColorTop - aBackColorBot;
2642 aBackColorBot = aBackColorBot + aColorRange * ((float) aTileOffset / aViewSize);
2643 aBackColorTop = aBackColorBot + aColorRange * ((float) aTileSize / aViewSize);
2646 aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
2647 aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
2648 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
2649 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
2651 // Set environment map parameters
2652 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2653 ? myCubeMapParams->TextureSet (theGlContext)
2655 const bool toDisableEnvironmentMap = anEnvTextureSet.IsNull()
2656 || anEnvTextureSet->IsEmpty()
2657 || !anEnvTextureSet->First()->IsValid();
2658 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapEnabled],
2659 toDisableEnvironmentMap ? 0 : 1);
2660 if (myRaytraceParameters.CubemapForBack)
2662 theProgram->SetUniform (theGlContext, "uZCoeff", myBackgroundCubeMap->ZIsInverted() ? -1 : 1);
2663 theProgram->SetUniform (theGlContext, "uYCoeff", myBackgroundCubeMap->IsTopDown() ? 1 : -1);
2664 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2665 myBackgroundType == Graphic3d_TOB_CUBEMAP ? 1 : 0);
2669 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2670 myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2673 // Set ambient light source
2674 theProgram->SetUniform (theGlContext,
2675 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2676 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2678 theProgram->SetUniform (theGlContext,
2679 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2681 theProgram->SetUniform (theGlContext,
2682 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2684 // Check whether we should restart accumulation for run-time parameters
2685 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2686 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2688 myAccumFrames = 0; // accumulation should be restarted
2690 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2691 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2694 else // RT parameters
2696 // Enable/disable run-time ray-tracing effects
2697 theProgram->SetUniform (theGlContext,
2698 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2699 theProgram->SetUniform (theGlContext,
2700 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2703 return Standard_True;
2706 // =======================================================================
2707 // function : bindRaytraceTextures
2708 // purpose : Binds ray-trace textures to corresponding texture units
2709 // =======================================================================
2710 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2713 if (myRaytraceParameters.AdaptiveScreenSampling
2714 && myRaytraceParameters.GlobalIllumination)
2716 #if !defined(GL_ES_VERSION_2_0)
2717 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2718 myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2719 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2720 myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2721 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2723 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2724 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2728 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2729 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2732 (void )theStereoView;
2736 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2737 ? myCubeMapParams->TextureSet (theGlContext)
2739 if (!anEnvTextureSet.IsNull()
2740 && !anEnvTextureSet->IsEmpty()
2741 && anEnvTextureSet->First()->IsValid())
2743 anEnvTextureSet->First()->Bind (theGlContext, OpenGl_RT_EnvMapTexture);
2746 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2747 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2748 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2749 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2750 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2751 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2752 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2753 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2754 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2755 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2758 // =======================================================================
2759 // function : unbindRaytraceTextures
2760 // purpose : Unbinds ray-trace textures from corresponding texture units
2761 // =======================================================================
2762 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2764 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2765 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2766 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2767 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2768 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2769 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2770 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2771 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2772 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2773 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2775 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2778 // =======================================================================
2779 // function : runRaytraceShaders
2780 // purpose : Runs ray-tracing shader programs
2781 // =======================================================================
2782 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2783 const Standard_Integer theSizeY,
2784 Graphic3d_Camera::Projection theProjection,
2785 OpenGl_FrameBuffer* theReadDrawFbo,
2786 const Handle(OpenGl_Context)& theGlContext)
2788 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2790 aResult &= setUniformState (0,
2796 if (myRaytraceParameters.GlobalIllumination) // path tracing
2798 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
2799 aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2801 else // Whitted-style ray-tracing
2803 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2809 // =======================================================================
2810 // function : runRaytrace
2811 // purpose : Runs Whitted-style ray-tracing
2812 // =======================================================================
2813 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2814 const Standard_Integer theSizeY,
2815 Graphic3d_Camera::Projection theProjection,
2816 OpenGl_FrameBuffer* theReadDrawFbo,
2817 const Handle(OpenGl_Context)& theGlContext)
2819 Standard_Boolean aResult = Standard_True;
2821 // Choose proper set of frame buffers for stereo rendering
2822 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2823 bindRaytraceTextures (theGlContext, aFBOIdx);
2825 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2827 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2829 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2832 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2834 if (myRenderParams.IsAntialiasingEnabled)
2836 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2838 // bind ray-tracing output image as input
2839 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2841 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2843 aResult &= setUniformState (1 /* FSAA ID */,
2849 // Perform multi-pass adaptive FSAA using ping-pong technique.
2850 // We use 'FLIPTRI' sampling pattern changing for every pixel
2851 // (3 additional samples per pixel, the 1st sample is already
2852 // available from initial ray-traced image).
2853 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2855 GLfloat aOffsetX = 1.f / theSizeX;
2856 GLfloat aOffsetY = 1.f / theSizeY;
2874 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2875 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2876 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2877 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2878 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2879 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2881 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2882 ? myRaytraceFBO2[aFBOIdx]
2883 : myRaytraceFBO1[aFBOIdx];
2885 aFramebuffer->BindBuffer (theGlContext);
2887 // perform adaptive FSAA pass
2888 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2890 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2893 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2894 const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2896 glEnable (GL_DEPTH_TEST);
2898 // Display filtered image
2899 theGlContext->BindProgram (myOutImageProgram);
2901 if (theReadDrawFbo != NULL)
2903 theReadDrawFbo->BindBuffer (theGlContext);
2907 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2910 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2911 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2913 // copy the output image with depth values
2914 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2916 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2917 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2920 unbindRaytraceTextures (theGlContext);
2922 theGlContext->BindProgram (NULL);
2927 // =======================================================================
2928 // function : runPathtrace
2929 // purpose : Runs path tracing shader
2930 // =======================================================================
2931 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2932 const Standard_Integer theSizeY,
2933 const Graphic3d_Camera::Projection theProjection,
2934 const Handle(OpenGl_Context)& theGlContext)
2936 if (myToUpdateEnvironmentMap) // check whether the map was changed
2938 myAccumFrames = myToUpdateEnvironmentMap = 0;
2941 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2942 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2944 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2945 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2949 // Choose proper set of frame buffers for stereo rendering
2950 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2952 if (myRaytraceParameters.AdaptiveScreenSampling)
2954 if (myAccumFrames == 0)
2956 myTileSampler.Reset(); // reset tile sampler to its initial state
2958 // Adaptive sampling is starting at the second frame
2959 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2961 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2965 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2968 #if !defined(GL_ES_VERSION_2_0)
2969 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2973 // Clear adaptive screen sampling images
2974 #if !defined(GL_ES_VERSION_2_0)
2975 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2979 bindRaytraceTextures (theGlContext, aFBOIdx);
2981 const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2982 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2984 // Set frame accumulation weight
2985 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
2987 // Set image uniforms for render program
2988 if (myRaytraceParameters.AdaptiveScreenSampling)
2990 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
2991 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage], OpenGl_RT_TileSamplesImage);
2992 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2993 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
2996 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2997 aRenderImageFramebuffer->BindBuffer (theGlContext);
2998 if (myRaytraceParameters.AdaptiveScreenSampling
2999 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3001 // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
3002 // redirected to inner tiles (full tile size) are drawn entirely
3003 const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
3004 glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
3007 // Generate for the given RNG seed
3008 glDisable (GL_DEPTH_TEST);
3010 // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
3011 // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
3013 // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
3014 // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
3015 // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
3017 // Single-pass rendering is more optimal due to smaller amount of draw calls,
3018 // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
3019 // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
3020 // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
3021 const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
3022 && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
3023 ? myTileSampler.MaxTileSamples()
3025 if (myAccumFrames == 0)
3027 myRNG.SetSeed(); // start RNG from beginning
3029 for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
3031 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3032 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3033 if (myRaytraceParameters.AdaptiveScreenSampling)
3035 #if !defined(GL_ES_VERSION_2_0)
3036 theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
3040 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3042 if (myRaytraceParameters.AdaptiveScreenSampling
3043 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3045 glViewport (0, 0, theSizeX, theSizeY);
3050 // =======================================================================
3051 // function : runPathtraceOut
3053 // =======================================================================
3054 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
3055 OpenGl_FrameBuffer* theReadDrawFbo,
3056 const Handle(OpenGl_Context)& theGlContext)
3058 // Output accumulated path traced image
3059 theGlContext->BindProgram (myOutImageProgram);
3061 // Choose proper set of frame buffers for stereo rendering
3062 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
3064 if (myRaytraceParameters.AdaptiveScreenSampling)
3066 // Set uniforms for display program
3067 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
3068 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
3069 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
3070 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3071 myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
3072 myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
3075 if (myRaytraceParameters.GlobalIllumination)
3077 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3078 switch (myRaytraceParameters.ToneMappingMethod)
3080 case Graphic3d_ToneMappingMethod_Disabled:
3082 case Graphic3d_ToneMappingMethod_Filmic:
3083 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3088 if (theReadDrawFbo != NULL)
3090 theReadDrawFbo->BindBuffer (theGlContext);
3093 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3094 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3096 // Copy accumulated image with correct depth values
3097 glEnable (GL_DEPTH_TEST);
3098 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3100 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3102 if (myRaytraceParameters.AdaptiveScreenSampling)
3104 // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3105 myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3106 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3108 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3112 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3116 unbindRaytraceTextures (theGlContext);
3117 theGlContext->BindProgram (NULL);
3121 // =======================================================================
3122 // function : raytrace
3123 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3124 // =======================================================================
3125 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3126 const Standard_Integer theSizeY,
3127 Graphic3d_Camera::Projection theProjection,
3128 OpenGl_FrameBuffer* theReadDrawFbo,
3129 const Handle(OpenGl_Context)& theGlContext)
3131 if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3133 return Standard_False;
3136 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3138 return Standard_False;
3141 OpenGl_Mat4 aLightSourceMatrix;
3143 // Get inversed model-view matrix for transforming lights
3144 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3146 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3148 return Standard_False;
3151 // Generate image using Whitted-style ray-tracing or path tracing
3152 if (myIsRaytraceDataValid)
3154 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3156 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3158 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3159 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3162 glDisable (GL_BLEND);
3164 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3172 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3173 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3176 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3178 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3179 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3182 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3185 return Standard_True;