1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_View.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_BackgroundArray.hxx>
20 #include <OpenGl_FrameBuffer.hxx>
21 #include <OpenGl_PrimitiveArray.hxx>
22 #include <OpenGl_VertexBuffer.hxx>
23 #include <OpenGl_SceneGeometry.hxx>
24 #include <OpenGl_ShaderProgram.hxx>
25 #include <OpenGl_TextureBuffer.hxx>
26 #include <OpenGl_GlCore44.hxx>
27 #include <OSD_Protection.hxx>
28 #include <OSD_File.hxx>
30 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
31 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
32 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
33 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
34 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
35 #include "../Shaders/Shaders_Display_fs.pxx"
36 #include "../Shaders/Shaders_TangentSpaceNormal_glsl.pxx"
38 //! Use this macro to output ray-tracing debug info
39 // #define RAY_TRACE_PRINT_INFO
41 #ifdef RAY_TRACE_PRINT_INFO
42 #include <OSD_Timer.hxx>
47 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
48 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
53 //! Defines OpenGL texture samplers.
54 static const Graphic3d_TextureUnit OpenGl_RT_EnvMapTexture = Graphic3d_TextureUnit_0;
56 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
57 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
58 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
59 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
61 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
62 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
63 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
64 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
66 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
67 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
69 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
70 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
72 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
75 // =======================================================================
76 // function : updateRaytraceGeometry
77 // purpose : Updates 3D scene geometry for ray-tracing
78 // =======================================================================
79 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
80 const Standard_Integer theViewId,
81 const Handle(OpenGl_Context)& theGlContext)
83 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
84 // modifications. This is light-weight procedure performed on each frame
85 if (theMode == OpenGl_GUM_CHECK)
87 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
89 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
92 else if (theMode == OpenGl_GUM_PREPARE)
94 myRaytraceGeometry.ClearMaterials();
96 myArrayToTrianglesMap.clear();
98 myIsRaytraceDataValid = Standard_False;
101 // The set of processed structures (reflected to ray-tracing)
102 // This set is used to remove out-of-date records from the
103 // hash map of structures
104 std::set<const OpenGl_Structure*> anElements;
106 // Set to store all currently visible OpenGL primitive arrays
107 // applicable for ray-tracing
108 std::set<Standard_Size> anArrayIDs;
110 // Set to store all non-raytracable elements allowing tracking
111 // of changes in OpenGL scene (only for path tracing)
112 std::set<Standard_Integer> aNonRaytraceIDs;
114 for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
116 const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
117 if (aLayer->NbStructures() == 0
118 || !aLayer->LayerSettings().IsRaytracable()
119 || aLayer->LayerSettings().IsImmediate())
124 const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
125 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
127 for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
129 const OpenGl_Structure* aStructure = aStructIt.Value();
131 if (theMode == OpenGl_GUM_CHECK)
133 if (toUpdateStructure (aStructure))
135 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
137 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
139 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
142 else if (theMode == OpenGl_GUM_PREPARE)
144 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
148 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
153 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
155 // Extract OpenGL elements from the group (primitives arrays)
156 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
158 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
160 if (aPrimArray != NULL)
162 anArrayIDs.insert (aPrimArray->GetUID());
167 else if (theMode == OpenGl_GUM_REBUILD)
169 if (!aStructure->IsRaytracable())
173 else if (addRaytraceStructure (aStructure, theGlContext))
175 anElements.insert (aStructure); // structure was processed
182 if (theMode == OpenGl_GUM_PREPARE)
184 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
186 // Filter out unchanged objects so only their transformations and materials
187 // will be updated (and newly added objects will be processed from scratch)
188 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
190 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
191 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
193 if (aTriangleSet == NULL)
198 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
200 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
202 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
206 myRaytraceGeometry.Objects() = anUnchangedObjects;
208 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
210 else if (theMode == OpenGl_GUM_REBUILD)
212 // Actualize the hash map of structures - remove out-of-date records
213 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
215 while (anIter != myStructureStates.end())
217 if (anElements.find (anIter->first) == anElements.end())
219 myStructureStates.erase (anIter++);
227 // Actualize OpenGL layer list state
228 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
230 // Rebuild two-level acceleration structure
231 myRaytraceGeometry.ProcessAcceleration();
233 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
234 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
235 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
237 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
239 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
241 return uploadRaytraceData (theGlContext);
244 if (myRaytraceParameters.GlobalIllumination)
246 Standard_Boolean toRestart =
247 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
249 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
251 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
253 toRestart = Standard_True;
262 myNonRaytraceStructureIDs = aNonRaytraceIDs;
265 return Standard_True;
268 // =======================================================================
269 // function : toUpdateStructure
270 // purpose : Checks to see if the structure is modified
271 // =======================================================================
272 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
274 if (!theStructure->IsRaytracable())
276 if (theStructure->ModificationState() > 0)
278 theStructure->ResetModificationState();
280 return Standard_True; // ray-trace element was removed - need to rebuild
283 return Standard_False; // did not contain ray-trace elements
286 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
288 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
290 return Standard_True;
292 else if (theStructure->InstancedStructure() != NULL)
294 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
297 return Standard_False;
300 // =======================================================================
301 // function : buildTextureTransform
302 // purpose : Constructs texture transformation matrix
303 // =======================================================================
304 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
306 theMatrix.InitIdentity();
307 if (theParams.IsNull())
313 const Graphic3d_Vec2& aScale = theParams->Scale();
315 theMatrix.ChangeValue (0, 0) *= aScale.x();
316 theMatrix.ChangeValue (1, 0) *= aScale.x();
317 theMatrix.ChangeValue (2, 0) *= aScale.x();
318 theMatrix.ChangeValue (3, 0) *= aScale.x();
320 theMatrix.ChangeValue (0, 1) *= aScale.y();
321 theMatrix.ChangeValue (1, 1) *= aScale.y();
322 theMatrix.ChangeValue (2, 1) *= aScale.y();
323 theMatrix.ChangeValue (3, 1) *= aScale.y();
326 const Graphic3d_Vec2 aTrans = -theParams->Translation();
328 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
329 theMatrix.GetValue (0, 1) * aTrans.y();
331 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
332 theMatrix.GetValue (1, 1) * aTrans.y();
334 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
335 theMatrix.GetValue (2, 1) * aTrans.y();
338 const Standard_ShortReal aSin = std::sin (
339 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
340 const Standard_ShortReal aCos = std::cos (
341 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
343 BVH_Mat4f aRotationMat;
344 aRotationMat.SetValue (0, 0, aCos);
345 aRotationMat.SetValue (1, 1, aCos);
346 aRotationMat.SetValue (0, 1, -aSin);
347 aRotationMat.SetValue (1, 0, aSin);
349 theMatrix = theMatrix * aRotationMat;
352 // =======================================================================
353 // function : convertMaterial
354 // purpose : Creates ray-tracing material properties
355 // =======================================================================
356 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
357 const Handle(OpenGl_Context)& theGlContext)
359 OpenGl_RaytraceMaterial aResMat;
361 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
362 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
363 const float aShine = 128.0f * float(aSrcMat.Shininess());
365 const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
366 const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
367 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
368 const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
369 switch (aSrcMat.MaterialType())
371 case Graphic3d_MATERIAL_ASPECT:
373 aResMat.Ambient .SetValues (aSrcAmb * aMatCol, 1.0f);
374 aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
375 aResMat.Emission.SetValues (aSrcEms * aMatCol, 1.0f);
378 case Graphic3d_MATERIAL_PHYSIC:
380 aResMat.Ambient .SetValues (aSrcAmb, 1.0f);
381 aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
382 aResMat.Emission.SetValues (aSrcEms, 1.0f);
388 // interior color is always ignored for Specular
389 aResMat.Specular.SetValues (aSrcSpe, aShine);
390 const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
391 Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
392 aResMat.Diffuse.z() + aResMat.Specular.z()));
393 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
394 aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
397 const float anIndex = (float )aSrcMat.RefractionIndex();
398 aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
399 anIndex == 0 ? 1.0f : anIndex,
400 anIndex == 0 ? 1.0f : 1.0f / anIndex);
402 aResMat.Ambient = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
403 aResMat.Diffuse = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
404 aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
405 aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
407 // Serialize physically-based material properties
408 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
410 aResMat.BSDF.Kc = aBSDF.Kc;
411 aResMat.BSDF.Ks = aBSDF.Ks;
412 aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.0f); // no base color texture
413 aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, -1.0f); // no metallic-roughness texture
414 aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, -1.0f); // no emissive texture
416 aResMat.BSDF.Absorption = aBSDF.Absorption;
418 aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
419 aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
420 aResMat.BSDF.FresnelBase.w() = -1.0; // no normal map texture
422 // Handle material textures
423 if (!theAspect->Aspect()->ToMapTexture())
428 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
429 if (aTextureSet.IsNull()
430 || aTextureSet->IsEmpty()
431 || aTextureSet->First().IsNull())
436 if (theGlContext->HasRayTracingTextures())
438 // write texture ID to diffuse w-components
439 for (OpenGl_TextureSet::Iterator aTexIter (aTextureSet); aTexIter.More(); aTexIter.Next())
441 const Handle(OpenGl_Texture)& aTexture = aTexIter.Value();
442 if (aTexIter.Unit() == Graphic3d_TextureUnit_BaseColor)
444 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
445 aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
447 else if (aTexIter.Unit() == Graphic3d_TextureUnit_MetallicRoughness)
449 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
450 aResMat.BSDF.Kt.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
452 else if (aTexIter.Unit() == Graphic3d_TextureUnit_Emissive)
454 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
455 aResMat.BSDF.Le.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
457 else if (aTexIter.Unit() == Graphic3d_TextureUnit_Normal)
459 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
460 aResMat.BSDF.FresnelBase.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
464 else if (!myIsRaytraceWarnTextures)
466 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
467 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
468 "Please try to update graphics card driver. At the moment textures will be ignored.");
469 myIsRaytraceWarnTextures = Standard_True;
475 // =======================================================================
476 // function : addRaytraceStructure
477 // purpose : Adds OpenGL structure to ray-traced scene geometry
478 // =======================================================================
479 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
480 const Handle(OpenGl_Context)& theGlContext)
482 if (!theStructure->IsVisible())
484 myStructureStates[theStructure] = StructState (theStructure);
486 return Standard_True;
489 // Get structure material
490 OpenGl_RaytraceMaterial aDefaultMaterial;
491 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
493 // Process all connected OpenGL structures
494 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
496 if (anInstanced != NULL && anInstanced->IsRaytracable())
498 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
501 myStructureStates[theStructure] = StructState (theStructure);
506 // =======================================================================
507 // function : addRaytraceGroups
508 // purpose : Adds OpenGL groups to ray-traced scene geometry
509 // =======================================================================
510 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
511 const OpenGl_RaytraceMaterial& theStructMat,
512 const Handle(TopLoc_Datum3D)& theTrsf,
513 const Handle(OpenGl_Context)& theGlContext)
516 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
518 // Get group material
519 OpenGl_RaytraceMaterial aGroupMaterial;
520 if (aGroupIter.Value()->GlAspects() != NULL)
522 aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
525 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
527 // Use group material if available, otherwise use structure material
528 myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
530 // Add OpenGL elements from group (extract primitives arrays and aspects)
531 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
533 OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
535 if (anAspect != NULL)
537 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
539 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
541 myRaytraceGeometry.Materials.push_back (aMaterial);
545 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
547 if (aPrimArray != NULL)
549 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
551 if (aSetIter != myArrayToTrianglesMap.end())
553 OpenGl_TriangleSet* aSet = aSetIter->second;
554 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
555 if (!theTrsf.IsNull())
557 theTrsf->Trsf().GetMat4 (aMat4);
558 aTransform->SetTransform (aMat4);
561 aSet->SetProperties (aTransform);
562 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
564 aSet->SetMaterialIndex (aMatID);
569 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
571 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
572 if (!theTrsf.IsNull())
574 theTrsf->Trsf().GetMat4 (aMat4);
575 aTransform->SetTransform (aMat4);
578 aSet->SetProperties (aTransform);
579 myRaytraceGeometry.Objects().Append (aSet);
587 return Standard_True;
590 // =======================================================================
591 // function : addRaytracePrimitiveArray
592 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
593 // =======================================================================
594 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
595 const Standard_Integer theMaterial,
596 const OpenGl_Mat4* theTransform)
598 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
599 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
600 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
602 if (theArray->DrawMode() < GL_TRIANGLES
603 || theArray->DrawMode() > GL_POLYGON
604 || anAttribs.IsNull())
606 return Handle(OpenGl_TriangleSet)();
609 OpenGl_Mat4 aNormalMatrix;
610 if (theTransform != NULL)
612 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
613 "Error: Failed to compute normal transformation matrix", NULL);
615 aNormalMatrix.Transpose();
618 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
620 aSet->Vertices.reserve (anAttribs->NbElements);
621 aSet->Normals.reserve (anAttribs->NbElements);
622 aSet->TexCrds.reserve (anAttribs->NbElements);
624 const size_t aVertFrom = aSet->Vertices.size();
626 Standard_Integer anAttribIndex = 0;
627 Standard_Size anAttribStride = 0;
628 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
630 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
631 if (anAttrib.DataType == Graphic3d_TOD_VEC2
632 || anAttrib.DataType == Graphic3d_TOD_VEC3
633 || anAttrib.DataType == Graphic3d_TOD_VEC4)
635 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
637 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
638 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
642 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
644 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
645 if (anAttrib.DataType == Graphic3d_TOD_VEC3
646 || anAttrib.DataType == Graphic3d_TOD_VEC4)
648 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
650 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
654 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
656 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
657 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
659 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
661 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
666 if (aSet->Normals.size() != aSet->Vertices.size())
668 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
670 aSet->Normals.push_back (BVH_Vec3f());
674 if (aSet->TexCrds.size() != aSet->Vertices.size())
676 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
678 aSet->TexCrds.push_back (BVH_Vec2f());
682 if (theTransform != NULL)
684 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
686 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
688 BVH_Vec4f aTransVertex = *theTransform *
689 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
691 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
693 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
695 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
697 BVH_Vec4f aTransNormal = aNormalMatrix *
698 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
700 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
704 if (!aBounds.IsNull())
706 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
708 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
710 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
713 return Handle(OpenGl_TriangleSet)();
716 aBoundStart += aVertNum;
721 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
723 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
726 return Handle(OpenGl_TriangleSet)();
731 if (aSet->Size() != 0)
739 // =======================================================================
740 // function : addRaytraceVertexIndices
741 // purpose : Adds vertex indices to ray-traced scene geometry
742 // =======================================================================
743 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
744 const Standard_Integer theMatID,
745 const Standard_Integer theCount,
746 const Standard_Integer theOffset,
747 const OpenGl_PrimitiveArray& theArray)
749 switch (theArray.DrawMode())
751 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
752 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
753 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
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());
759 return Standard_False;
762 // =======================================================================
763 // function : addRaytraceTriangleArray
764 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
765 // =======================================================================
766 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
767 const Standard_Integer theMatID,
768 const Standard_Integer theCount,
769 const Standard_Integer theOffset,
770 const Handle(Graphic3d_IndexBuffer)& theIndices)
774 return Standard_True;
777 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
779 if (!theIndices.IsNull())
781 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
783 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
784 theIndices->Index (aVert + 1),
785 theIndices->Index (aVert + 2),
791 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
793 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
797 return Standard_True;
800 // =======================================================================
801 // function : addRaytraceTriangleFanArray
802 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
803 // =======================================================================
804 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
805 const Standard_Integer theMatID,
806 const Standard_Integer theCount,
807 const Standard_Integer theOffset,
808 const Handle(Graphic3d_IndexBuffer)& theIndices)
812 return Standard_True;
815 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
817 if (!theIndices.IsNull())
819 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
821 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
822 theIndices->Index (aVert + 1),
823 theIndices->Index (aVert + 2),
829 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
831 theSet.Elements.push_back (BVH_Vec4i (theOffset,
838 return Standard_True;
841 // =======================================================================
842 // function : addRaytraceTriangleStripArray
843 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
844 // =======================================================================
845 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
846 const Standard_Integer theMatID,
847 const Standard_Integer theCount,
848 const Standard_Integer theOffset,
849 const Handle(Graphic3d_IndexBuffer)& theIndices)
853 return Standard_True;
856 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
858 if (!theIndices.IsNull())
860 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
862 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
863 theIndices->Index (aVert + (aCW ? 0 : 1)),
864 theIndices->Index (aVert + 2),
870 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
872 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
873 aVert + (aCW ? 0 : 1),
879 return Standard_True;
882 // =======================================================================
883 // function : addRaytraceQuadrangleArray
884 // purpose : Adds OpenGL quad array to ray-traced scene geometry
885 // =======================================================================
886 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
887 const Standard_Integer theMatID,
888 const Standard_Integer theCount,
889 const Standard_Integer theOffset,
890 const Handle(Graphic3d_IndexBuffer)& theIndices)
894 return Standard_True;
897 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
899 if (!theIndices.IsNull())
901 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
903 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
904 theIndices->Index (aVert + 1),
905 theIndices->Index (aVert + 2),
907 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
908 theIndices->Index (aVert + 2),
909 theIndices->Index (aVert + 3),
915 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
917 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
919 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
924 return Standard_True;
927 // =======================================================================
928 // function : addRaytraceQuadrangleStripArray
929 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
930 // =======================================================================
931 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
932 const Standard_Integer theMatID,
933 const Standard_Integer theCount,
934 const Standard_Integer theOffset,
935 const Handle(Graphic3d_IndexBuffer)& theIndices)
939 return Standard_True;
942 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
944 if (!theIndices.IsNull())
946 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
948 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
949 theIndices->Index (aVert + 1),
950 theIndices->Index (aVert + 2),
953 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
954 theIndices->Index (aVert + 3),
955 theIndices->Index (aVert + 2),
961 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
963 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
968 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
975 return Standard_True;
978 // =======================================================================
979 // function : addRaytracePolygonArray
980 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
981 // =======================================================================
982 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
983 const Standard_Integer theMatID,
984 const Standard_Integer theCount,
985 const Standard_Integer theOffset,
986 const Handle(Graphic3d_IndexBuffer)& theIndices)
990 return Standard_True;
993 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
995 if (!theIndices.IsNull())
997 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
999 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
1000 theIndices->Index (aVert + 1),
1001 theIndices->Index (aVert + 2),
1007 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1009 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1016 return Standard_True;
1019 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1021 // =======================================================================
1022 // function : Source
1023 // purpose : Returns shader source combined with prefix
1024 // =======================================================================
1025 TCollection_AsciiString OpenGl_View::ShaderSource::Source (const Handle(OpenGl_Context)& theCtx,
1026 const GLenum theType) const
1028 TCollection_AsciiString aVersion = theCtx->GraphicsLibrary() == Aspect_GraphicsLibrary_OpenGLES
1029 ? "#version 320 es\n"
1032 TCollection_AsciiString aPrecisionHeader;
1033 if (theType == GL_FRAGMENT_SHADER
1034 && theCtx->GraphicsLibrary() == Aspect_GraphicsLibrary_OpenGLES)
1036 aPrecisionHeader = theCtx->hasHighp
1037 ? "precision highp float;\n"
1038 "precision highp int;\n"
1039 "precision highp samplerBuffer;\n"
1040 "precision highp isamplerBuffer;\n"
1041 : "precision mediump float;\n"
1042 "precision mediump int;\n"
1043 "precision mediump samplerBuffer;\n"
1044 "precision mediump isamplerBuffer;\n";
1046 if (myPrefix.IsEmpty())
1048 return aVersion + aPrecisionHeader + mySource;
1050 return aVersion + aPrecisionHeader + myPrefix + "\n" + mySource;
1053 // =======================================================================
1054 // function : LoadFromFiles
1055 // purpose : Loads shader source from specified files
1056 // =======================================================================
1057 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1058 const TCollection_AsciiString& thePrefix)
1062 myPrefix = thePrefix;
1064 TCollection_AsciiString aMissingFiles;
1065 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1067 OSD_File aFile (theFileNames[anIndex]);
1070 aFile.Open (OSD_ReadOnly, OSD_Protection());
1072 if (!aFile.IsOpen())
1074 if (!aMissingFiles.IsEmpty())
1076 aMissingFiles += ", ";
1078 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1081 else if (!aMissingFiles.IsEmpty())
1087 TCollection_AsciiString aSource;
1088 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1089 if (!aSource.IsEmpty())
1091 mySource += TCollection_AsciiString ("\n") + aSource;
1096 if (!aMissingFiles.IsEmpty())
1098 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1099 return Standard_False;
1101 return Standard_True;
1104 // =======================================================================
1105 // function : LoadFromStrings
1107 // =======================================================================
1108 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1109 const TCollection_AsciiString& thePrefix)
1113 myPrefix = thePrefix;
1115 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1117 TCollection_AsciiString aSource = theStrings[anIndex];
1118 if (!aSource.IsEmpty())
1120 mySource += TCollection_AsciiString ("\n") + aSource;
1123 return Standard_True;
1126 // =======================================================================
1127 // function : generateShaderPrefix
1128 // purpose : Generates shader prefix based on current ray-tracing options
1129 // =======================================================================
1130 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1132 TCollection_AsciiString aPrefixString =
1133 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1134 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1136 if (myRaytraceParameters.IsZeroToOneDepth)
1138 aPrefixString += TCollection_AsciiString ("\n#define THE_ZERO_TO_ONE_DEPTH");
1141 if (myRaytraceParameters.TransparentShadows)
1143 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1145 if (!theGlContext->ToRenderSRGB())
1147 aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
1150 // If OpenGL driver supports bindless textures and texturing
1151 // is actually used, activate texturing in ray-tracing mode
1152 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1154 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1155 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1158 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1160 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1162 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1164 if (theGlContext->IsGlGreaterEqual (4, 4))
1166 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1167 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1168 && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1170 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1175 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1177 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1180 switch (myRaytraceParameters.ToneMappingMethod)
1182 case Graphic3d_ToneMappingMethod_Disabled:
1184 case Graphic3d_ToneMappingMethod_Filmic:
1185 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1190 if (myRaytraceParameters.ToIgnoreNormalMap)
1192 aPrefixString += TCollection_AsciiString("\n#define IGNORE_NORMAL_MAP");
1195 if (myRaytraceParameters.CubemapForBack)
1197 aPrefixString += TCollection_AsciiString("\n#define BACKGROUND_CUBEMAP");
1200 if (myRaytraceParameters.DepthOfField)
1202 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1205 return aPrefixString;
1208 // =======================================================================
1209 // function : safeFailBack
1210 // purpose : Performs safe exit when shaders initialization fails
1211 // =======================================================================
1212 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1213 const Handle(OpenGl_Context)& theGlContext)
1215 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1216 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1218 myRaytraceInitStatus = OpenGl_RT_FAIL;
1220 releaseRaytraceResources (theGlContext);
1222 return Standard_False;
1225 // =======================================================================
1226 // function : initShader
1227 // purpose : Creates new shader object with specified source
1228 // =======================================================================
1229 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1230 const ShaderSource& theSource,
1231 const Handle(OpenGl_Context)& theGlContext)
1233 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1234 if (!aShader->Create (theGlContext))
1236 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1237 TCollection_ExtendedString ("Error: Failed to create ") +
1238 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1239 aShader->Release (theGlContext.get());
1240 return Handle(OpenGl_ShaderObject)();
1243 if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source (theGlContext, theType)))
1245 aShader->Release (theGlContext.get());
1246 return Handle(OpenGl_ShaderObject)();
1251 // =======================================================================
1252 // function : initProgram
1253 // purpose : Creates GLSL program from the given shader objects
1254 // =======================================================================
1255 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1256 const Handle(OpenGl_ShaderObject)& theVertShader,
1257 const Handle(OpenGl_ShaderObject)& theFragShader,
1258 const TCollection_AsciiString& theName)
1260 const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1261 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1263 if (!aProgram->Create (theGlContext))
1265 theVertShader->Release (theGlContext.operator->());
1267 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1268 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1270 return Handle(OpenGl_ShaderProgram)();
1273 if (!aProgram->AttachShader (theGlContext, theVertShader)
1274 || !aProgram->AttachShader (theGlContext, theFragShader))
1276 theVertShader->Release (theGlContext.operator->());
1278 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1279 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1281 return Handle(OpenGl_ShaderProgram)();
1284 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1286 TCollection_AsciiString aLinkLog;
1288 if (!aProgram->Link (theGlContext))
1290 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1292 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1293 "Failed to link shader program:\n") + aLinkLog;
1295 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1296 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1298 return Handle(OpenGl_ShaderProgram)();
1300 else if (theGlContext->caps->glslWarnings)
1302 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1303 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1305 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1306 "Shader program was linked with following warnings:\n") + aLinkLog;
1308 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1309 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1316 // =======================================================================
1317 // function : initRaytraceResources
1318 // purpose : Initializes OpenGL/GLSL shader programs
1319 // =======================================================================
1320 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1321 const Standard_Integer theSizeY,
1322 const Handle(OpenGl_Context)& theGlContext)
1324 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1326 return Standard_False;
1329 Standard_Boolean aToRebuildShaders = Standard_False;
1331 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1333 myRaytraceInitStatus = OpenGl_RT_NONE;
1334 releaseRaytraceResources (theGlContext, Standard_True);
1335 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1338 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1340 if (!myIsRaytraceDataValid)
1342 return Standard_True;
1345 const Standard_Integer aRequiredStackSize =
1346 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1348 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1350 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1352 aToRebuildShaders = Standard_True;
1356 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1358 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1360 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1361 aToRebuildShaders = Standard_True;
1366 const bool isZeroToOneDepth = myCaps->useZeroToOneDepth
1367 && myWorkspace->GetGlContext()->arbClipControl;
1368 if (isZeroToOneDepth != myRaytraceParameters.IsZeroToOneDepth
1369 || myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1370 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1371 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1372 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1373 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures
1374 || myRenderParams.ToIgnoreNormalMapInRayTracing != myRaytraceParameters.ToIgnoreNormalMap)
1376 myRaytraceParameters.IsZeroToOneDepth = isZeroToOneDepth;
1377 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1378 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1379 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1380 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1381 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1382 myRaytraceParameters.ToIgnoreNormalMap = myRenderParams.ToIgnoreNormalMapInRayTracing;
1383 aToRebuildShaders = Standard_True;
1386 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling
1387 || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1389 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1390 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1391 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1393 if (!theGlContext->HasRayTracingAdaptiveSampling())
1395 // disable the feature if it is not supported
1396 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1397 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1398 "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1400 else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1401 && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1403 // disable the feature if it is not supported
1404 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1405 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1406 "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1410 aToRebuildShaders = Standard_True;
1412 myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1414 const bool isCubemapForBack = !myCubeMapBackground.IsNull();
1415 if (myRaytraceParameters.CubemapForBack != isCubemapForBack)
1417 myRaytraceParameters.CubemapForBack = isCubemapForBack;
1418 aToRebuildShaders = Standard_True;
1421 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1422 if (myRaytraceParameters.DepthOfField != toEnableDof)
1424 myRaytraceParameters.DepthOfField = toEnableDof;
1425 aToRebuildShaders = Standard_True;
1428 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1430 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1431 aToRebuildShaders = true;
1434 if (aToRebuildShaders)
1436 // Reject accumulated frames
1439 // Environment map should be updated
1440 myToUpdateEnvironmentMap = Standard_True;
1442 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1443 #ifdef RAY_TRACE_PRINT_INFO
1444 Message::SendTrace() << "GLSL prefix string:" << std::endl << aPrefixString;
1446 myRaytraceShaderSource.SetPrefix (aPrefixString);
1447 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1448 myOutImageShaderSource.SetPrefix (aPrefixString);
1449 if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source (theGlContext, GL_FRAGMENT_SHADER))
1450 || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source (theGlContext, GL_FRAGMENT_SHADER))
1451 || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source (theGlContext, GL_FRAGMENT_SHADER)))
1453 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1456 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1457 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1458 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1459 if (!myRaytraceProgram->Link (theGlContext)
1460 || !myPostFSAAProgram->Link (theGlContext)
1461 || !myOutImageProgram->Link (theGlContext))
1463 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1468 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1470 myAccumFrames = 0; // accumulation should be restarted
1472 if (theGlContext->GraphicsLibrary() == Aspect_GraphicsLibrary_OpenGLES)
1474 if (!theGlContext->IsGlGreaterEqual (3, 2))
1476 return safeFailBack ("Ray-tracing requires OpenGL ES 3.2 and higher", theGlContext);
1481 if (!theGlContext->IsGlGreaterEqual (3, 1))
1483 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1485 else if (!theGlContext->arbTboRGB32)
1487 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1489 else if (!theGlContext->arbFBOBlit)
1491 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1495 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1497 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1498 if (myIsRaytraceDataValid)
1500 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1501 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1504 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1506 #ifdef RAY_TRACE_PRINT_INFO
1507 Message::SendTrace() << "GLSL prefix string:" << std::endl << aPrefixString;
1510 ShaderSource aBasicVertShaderSrc;
1512 if (!aShaderFolder.IsEmpty())
1514 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1515 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1517 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1522 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1523 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1528 if (!aShaderFolder.IsEmpty())
1530 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1531 aShaderFolder + "/TangentSpaceNormal.glsl",
1532 aShaderFolder + "/PathtraceBase.fs",
1533 aShaderFolder + "/RaytraceRender.fs",
1535 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1537 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1542 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1543 Shaders_TangentSpaceNormal_glsl,
1544 Shaders_PathtraceBase_fs,
1545 Shaders_RaytraceRender_fs,
1547 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1550 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1551 if (aBasicVertShader.IsNull())
1553 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1556 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1557 if (myRaytraceShader.IsNull())
1559 aBasicVertShader->Release (theGlContext.operator->());
1560 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1563 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1564 if (myRaytraceProgram.IsNull())
1566 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1571 if (!aShaderFolder.IsEmpty())
1573 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1574 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1576 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1581 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1582 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1585 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1586 if (aBasicVertShader.IsNull())
1588 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1591 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1592 if (myPostFSAAShader.IsNull())
1594 aBasicVertShader->Release (theGlContext.operator->());
1595 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1598 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1599 if (myPostFSAAProgram.IsNull())
1601 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1606 if (!aShaderFolder.IsEmpty())
1608 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1609 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1611 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1616 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1617 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1620 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1621 if (aBasicVertShader.IsNull())
1623 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1626 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1627 if (myOutImageShader.IsNull())
1629 aBasicVertShader->Release (theGlContext.operator->());
1630 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1633 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1634 if (myOutImageProgram.IsNull())
1636 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1641 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1643 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1645 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1646 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1648 theGlContext->BindProgram (aShaderProgram);
1650 aShaderProgram->SetSampler (theGlContext,
1651 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1652 aShaderProgram->SetSampler (theGlContext,
1653 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1654 aShaderProgram->SetSampler (theGlContext,
1655 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1656 aShaderProgram->SetSampler (theGlContext,
1657 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1658 aShaderProgram->SetSampler (theGlContext,
1659 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1660 aShaderProgram->SetSampler (theGlContext,
1661 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1662 aShaderProgram->SetSampler (theGlContext,
1663 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1664 aShaderProgram->SetSampler (theGlContext,
1665 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1666 aShaderProgram->SetSampler (theGlContext,
1667 "uEnvMapTexture", OpenGl_RT_EnvMapTexture);
1668 aShaderProgram->SetSampler (theGlContext,
1669 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1670 aShaderProgram->SetSampler (theGlContext,
1671 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1675 aShaderProgram->SetSampler (theGlContext,
1676 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1680 aShaderProgram->SetSampler (theGlContext,
1681 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1684 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1685 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1687 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1688 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1689 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1690 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1691 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1692 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1693 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1694 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1695 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1696 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1697 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1698 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1699 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1700 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1701 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1702 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1703 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1704 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1705 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1706 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1708 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1709 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1710 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1711 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1712 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1713 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1714 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1715 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1717 myUniformLocations[anIndex][OpenGl_RT_uFsaaOffset] =
1718 aShaderProgram->GetUniformLocation (theGlContext, "uFsaaOffset");
1719 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1720 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1722 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1723 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1725 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1726 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1727 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1728 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1729 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnabled] =
1730 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapEnabled");
1731 myUniformLocations[anIndex][OpenGl_RT_uEnvMapForBack] =
1732 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapForBack");
1733 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1734 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1736 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1737 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1738 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1739 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1741 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1742 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1743 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1744 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1746 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1747 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1748 myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1749 aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1750 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1751 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1752 myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1753 aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1754 myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1755 aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1757 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1758 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1759 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1760 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1762 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1763 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1766 theGlContext->BindProgram (myOutImageProgram);
1768 myOutImageProgram->SetSampler (theGlContext,
1769 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1771 myOutImageProgram->SetSampler (theGlContext,
1772 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1774 theGlContext->BindProgram (NULL);
1777 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1779 return myRaytraceInitStatus == OpenGl_RT_INIT;
1782 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1789 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1791 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1793 return Standard_True;
1796 // =======================================================================
1797 // function : nullifyResource
1798 // purpose : Releases OpenGL resource
1799 // =======================================================================
1801 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1803 if (!theResource.IsNull())
1805 theResource->Release (theGlContext.get());
1806 theResource.Nullify();
1810 // =======================================================================
1811 // function : releaseRaytraceResources
1812 // purpose : Releases OpenGL/GLSL shader programs
1813 // =======================================================================
1814 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1816 // release shader resources
1817 nullifyResource (theGlContext, myRaytraceShader);
1818 nullifyResource (theGlContext, myPostFSAAShader);
1820 nullifyResource (theGlContext, myRaytraceProgram);
1821 nullifyResource (theGlContext, myPostFSAAProgram);
1822 nullifyResource (theGlContext, myOutImageProgram);
1824 if (!theToRebuild) // complete release
1826 myRaytraceFBO1[0]->Release (theGlContext.get());
1827 myRaytraceFBO1[1]->Release (theGlContext.get());
1828 myRaytraceFBO2[0]->Release (theGlContext.get());
1829 myRaytraceFBO2[1]->Release (theGlContext.get());
1831 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1832 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1834 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1835 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1836 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1837 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1838 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1839 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1841 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1842 nullifyResource (theGlContext, mySceneMinPointTexture);
1843 nullifyResource (theGlContext, mySceneMaxPointTexture);
1845 nullifyResource (theGlContext, myGeometryVertexTexture);
1846 nullifyResource (theGlContext, myGeometryNormalTexture);
1847 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1848 nullifyResource (theGlContext, myGeometryTriangTexture);
1849 nullifyResource (theGlContext, mySceneTransformTexture);
1851 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1852 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1854 myRaytraceGeometry.ReleaseResources (theGlContext);
1856 if (myRaytraceScreenQuad.IsValid ())
1858 myRaytraceScreenQuad.Release (theGlContext.get());
1863 // =======================================================================
1864 // function : updateRaytraceBuffers
1865 // purpose : Updates auxiliary OpenGL frame buffers.
1866 // =======================================================================
1867 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1868 const Standard_Integer theSizeY,
1869 const Handle(OpenGl_Context)& theGlContext)
1871 // Auxiliary buffers are not used
1872 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1874 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1875 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1876 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1877 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1879 return Standard_True;
1882 if (myRaytraceParameters.AdaptiveScreenSampling)
1884 Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1885 myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport, GL_RGBA32F, myFboDepthFormat);
1886 myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport, GL_RGBA32F, myFboDepthFormat);
1887 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1889 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1890 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1894 for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1896 if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1898 myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1899 myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1900 myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1901 myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1905 && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1907 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1908 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1909 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1910 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1911 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1915 if (myRaytraceParameters.AdaptiveScreenSampling)
1917 if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1918 && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1919 && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1920 && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1922 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1924 continue; // offsets texture is dynamically resized
1926 else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1927 && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1935 // Due to limitations of OpenGL image load-store extension
1936 // atomic operations are supported only for single-channel
1937 // images, so we define GL_R32F image. It is used as array
1938 // of 6D floating point vectors:
1939 // 0 - R color channel
1940 // 1 - G color channel
1941 // 2 - B color channel
1942 // 3 - hit time transformed into OpenGL NDC space
1943 // 4 - luminance accumulated for odd samples only
1944 myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1946 // workaround for some NVIDIA drivers
1947 myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1948 myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1949 myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
1950 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1951 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1953 if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1955 myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
1956 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1957 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1961 else // non-adaptive mode
1963 if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1964 || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1966 myAccumFrames = 0; // accumulation should be restarted
1969 myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, Graphic3d_Vec2i (theSizeX, theSizeY), GL_RGBA32F, myFboDepthFormat);
1970 myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, Graphic3d_Vec2i (theSizeX, theSizeY), GL_RGBA32F, myFboDepthFormat);
1973 return Standard_True;
1976 // =======================================================================
1977 // function : updateCamera
1978 // purpose : Generates viewing rays for corners of screen quad
1979 // =======================================================================
1980 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1981 const OpenGl_Mat4& theViewMapping,
1982 OpenGl_Vec3* theOrigins,
1983 OpenGl_Vec3* theDirects,
1984 OpenGl_Mat4& theViewPr,
1985 OpenGl_Mat4& theUnview)
1987 // compute view-projection matrix
1988 theViewPr = theViewMapping * theOrientation;
1990 // compute inverse view-projection matrix
1991 theViewPr.Inverted (theUnview);
1993 Standard_Integer aOriginIndex = 0;
1994 Standard_Integer aDirectIndex = 0;
1996 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1998 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2000 OpenGl_Vec4 aOrigin (GLfloat(aX),
2005 aOrigin = theUnview * aOrigin;
2007 aOrigin.x() = aOrigin.x() / aOrigin.w();
2008 aOrigin.y() = aOrigin.y() / aOrigin.w();
2009 aOrigin.z() = aOrigin.z() / aOrigin.w();
2011 OpenGl_Vec4 aDirect (GLfloat(aX),
2016 aDirect = theUnview * aDirect;
2018 aDirect.x() = aDirect.x() / aDirect.w();
2019 aDirect.y() = aDirect.y() / aDirect.w();
2020 aDirect.z() = aDirect.z() / aDirect.w();
2022 aDirect = aDirect - aOrigin;
2024 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2025 static_cast<GLfloat> (aOrigin.y()),
2026 static_cast<GLfloat> (aOrigin.z()));
2028 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2029 static_cast<GLfloat> (aDirect.y()),
2030 static_cast<GLfloat> (aDirect.z()));
2035 // =======================================================================
2036 // function : updatePerspCameraPT
2037 // purpose : Generates viewing rays (path tracing, perspective camera)
2038 // =======================================================================
2039 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
2040 const OpenGl_Mat4& theViewMapping,
2041 Graphic3d_Camera::Projection theProjection,
2042 OpenGl_Mat4& theViewPr,
2043 OpenGl_Mat4& theUnview,
2044 const int theWinSizeX,
2045 const int theWinSizeY)
2047 // compute view-projection matrix
2048 theViewPr = theViewMapping * theOrientation;
2050 // compute inverse view-projection matrix
2051 theViewPr.Inverted(theUnview);
2053 // get camera stereo params
2054 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2055 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2056 : static_cast<float> (myCamera->IOD());
2058 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2059 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2060 : static_cast<float> (myCamera->ZFocus());
2062 // get camera view vectors
2063 const gp_Pnt anOrig = myCamera->Eye();
2065 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2066 static_cast<float> (anOrig.Y()),
2067 static_cast<float> (anOrig.Z()));
2069 const gp_Dir aView = myCamera->Direction();
2071 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2072 static_cast<float> (aView.Y()),
2073 static_cast<float> (aView.Z()));
2075 const gp_Dir anUp = myCamera->Up();
2077 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2078 static_cast<float> (anUp.Y()),
2079 static_cast<float> (anUp.Z()));
2081 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2083 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2084 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2086 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2087 static_cast<float> (aScaleY));
2089 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2091 myEyeView = anEyeViewMono;
2093 else // stereo camera
2095 // compute z-focus point
2096 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2098 // compute stereo camera shift
2099 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2100 myEyeOrig += myEyeSide.Normalized() * aDx;
2102 // estimate new camera direction vector and correct its length
2103 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2104 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2108 // =======================================================================
2109 // function : uploadRaytraceData
2110 // purpose : Uploads ray-trace data to the GPU
2111 // =======================================================================
2112 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2114 if (theGlContext->GraphicsLibrary() == Aspect_GraphicsLibrary_OpenGLES)
2116 if (!theGlContext->IsGlGreaterEqual (3, 2))
2118 Message::SendFail() << "Error: OpenGL ES version is less than 3.2";
2119 return Standard_False;
2124 if (!theGlContext->IsGlGreaterEqual (3, 1))
2126 Message::SendFail() << "Error: OpenGL version is less than 3.1";
2127 return Standard_False;
2131 myAccumFrames = 0; // accumulation should be restarted
2133 /////////////////////////////////////////////////////////////////////////////
2134 // Prepare OpenGL textures
2136 if (theGlContext->arbTexBindless != NULL)
2138 // If OpenGL driver supports bindless textures we need
2139 // to get unique 64- bit handles for using on the GPU
2140 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2142 Message::SendTrace() << "Error: Failed to get OpenGL texture handles";
2143 return Standard_False;
2147 /////////////////////////////////////////////////////////////////////////////
2148 // Create OpenGL BVH buffers
2150 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2152 mySceneNodeInfoTexture = new OpenGl_TextureBuffer();
2153 mySceneMinPointTexture = new OpenGl_TextureBuffer();
2154 mySceneMaxPointTexture = new OpenGl_TextureBuffer();
2155 mySceneTransformTexture = new OpenGl_TextureBuffer();
2157 if (!mySceneNodeInfoTexture->Create (theGlContext)
2158 || !mySceneMinPointTexture->Create (theGlContext)
2159 || !mySceneMaxPointTexture->Create (theGlContext)
2160 || !mySceneTransformTexture->Create (theGlContext))
2162 Message::SendTrace() << "Error: Failed to create scene BVH buffers";
2163 return Standard_False;
2167 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2169 myGeometryVertexTexture = new OpenGl_TextureBuffer();
2170 myGeometryNormalTexture = new OpenGl_TextureBuffer();
2171 myGeometryTexCrdTexture = new OpenGl_TextureBuffer();
2172 myGeometryTriangTexture = new OpenGl_TextureBuffer();
2174 if (!myGeometryVertexTexture->Create (theGlContext)
2175 || !myGeometryNormalTexture->Create (theGlContext)
2176 || !myGeometryTexCrdTexture->Create (theGlContext)
2177 || !myGeometryTriangTexture->Create (theGlContext))
2179 Message::SendTrace() << "\nError: Failed to create buffers for triangulation data";
2180 return Standard_False;
2184 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2186 myRaytraceMaterialTexture = new OpenGl_TextureBuffer();
2187 if (!myRaytraceMaterialTexture->Create (theGlContext))
2189 Message::SendTrace() << "Error: Failed to create buffers for material data";
2190 return Standard_False;
2194 /////////////////////////////////////////////////////////////////////////////
2195 // Write transform buffer
2197 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2199 bool aResult = true;
2201 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2203 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2204 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2206 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2207 Standard_ASSERT_RETURN (aTransform != NULL,
2208 "OpenGl_TriangleSet does not contain transform", Standard_False);
2210 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2213 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2214 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2216 delete [] aNodeTransforms;
2218 /////////////////////////////////////////////////////////////////////////////
2219 // Write geometry and bottom-level BVH buffers
2221 Standard_Size aTotalVerticesNb = 0;
2222 Standard_Size aTotalElementsNb = 0;
2223 Standard_Size aTotalBVHNodesNb = 0;
2225 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2227 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2228 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2230 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2231 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2233 aTotalVerticesNb += aTriangleSet->Vertices.size();
2234 aTotalElementsNb += aTriangleSet->Elements.size();
2236 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2237 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2239 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2242 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2244 if (aTotalBVHNodesNb != 0)
2246 aResult &= mySceneNodeInfoTexture->Init (
2247 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2248 aResult &= mySceneMinPointTexture->Init (
2249 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2250 aResult &= mySceneMaxPointTexture->Init (
2251 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2256 Message::SendTrace() << "Error: Failed to upload buffers for bottom-level scene BVH";
2257 return Standard_False;
2260 if (aTotalElementsNb != 0)
2262 aResult &= myGeometryTriangTexture->Init (
2263 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2266 if (aTotalVerticesNb != 0)
2268 aResult &= myGeometryVertexTexture->Init (
2269 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2270 aResult &= myGeometryNormalTexture->Init (
2271 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2272 aResult &= myGeometryTexCrdTexture->Init (
2273 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2278 Message::SendTrace() << "Error: Failed to upload buffers for scene geometry";
2279 return Standard_False;
2282 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2284 if (aBVH->Length() > 0)
2286 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2287 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2288 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2289 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2290 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2291 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2294 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2296 if (!aBVH->IsOuter (aNodeIdx))
2299 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2301 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2302 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2304 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2306 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2307 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2309 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2311 if (aBvhBuffersSize != 0)
2313 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2314 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2315 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2316 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2317 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2318 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2322 Message::SendTrace() << "Error: Failed to upload buffers for bottom-level scene BVHs";
2323 return Standard_False;
2327 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2329 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2330 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2332 if (!aTriangleSet->Vertices.empty())
2334 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2335 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2336 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2337 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2338 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2339 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2342 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2344 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2345 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2347 if (!aTriangleSet->Elements.empty())
2349 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2350 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2355 Message::SendTrace() << "Error: Failed to upload triangulation buffers for OpenGL element";
2356 return Standard_False;
2360 /////////////////////////////////////////////////////////////////////////////
2361 // Write material buffer
2363 if (myRaytraceGeometry.Materials.size() != 0)
2365 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2366 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2370 Message::SendTrace() << "Error: Failed to upload material buffer";
2371 return Standard_False;
2375 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2377 #ifdef RAY_TRACE_PRINT_INFO
2379 Standard_ShortReal aMemTrgUsed = 0.f;
2380 Standard_ShortReal aMemBvhUsed = 0.f;
2382 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2384 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2386 aMemTrgUsed += static_cast<Standard_ShortReal> (
2387 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2388 aMemTrgUsed += static_cast<Standard_ShortReal> (
2389 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2390 aMemTrgUsed += static_cast<Standard_ShortReal> (
2391 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2392 aMemTrgUsed += static_cast<Standard_ShortReal> (
2393 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2395 aMemBvhUsed += static_cast<Standard_ShortReal> (
2396 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2397 aMemBvhUsed += static_cast<Standard_ShortReal> (
2398 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2399 aMemBvhUsed += static_cast<Standard_ShortReal> (
2400 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2403 aMemBvhUsed += static_cast<Standard_ShortReal> (
2404 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2405 aMemBvhUsed += static_cast<Standard_ShortReal> (
2406 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2407 aMemBvhUsed += static_cast<Standard_ShortReal> (
2408 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2410 std::cout << "GPU Memory Used (Mb):\n"
2411 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2412 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2419 // =======================================================================
2420 // function : updateRaytraceLightSources
2421 // purpose : Updates 3D scene light sources for ray-tracing
2422 // =======================================================================
2423 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2425 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2426 Graphic3d_Vec4 aNewAmbient (0.0f);
2427 if (myRenderParams.ShadingModel != Graphic3d_TypeOfShadingModel_Unlit
2428 && !myLights.IsNull())
2430 aNewAmbient.SetValues (myLights->AmbientColor().rgb(), 0.0f);
2432 // move positional light sources at the front of the list
2433 aLightSources.reserve (myLights->Extent());
2434 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2435 aLightIter.More(); aLightIter.Next())
2437 const Graphic3d_CLight& aLight = *aLightIter.Value();
2438 if (aLight.Type() != Graphic3d_TypeOfLightSource_Directional)
2440 aLightSources.push_back (aLightIter.Value());
2444 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2445 aLightIter.More(); aLightIter.Next())
2447 if (aLightIter.Value()->Type() == Graphic3d_TypeOfLightSource_Directional)
2449 aLightSources.push_back (aLightIter.Value());
2454 if (!myRaytraceGeometry.Ambient.IsEqual (aNewAmbient))
2457 myRaytraceGeometry.Ambient = aNewAmbient;
2460 // get number of 'real' (not ambient) light sources
2461 const size_t aNbLights = aLightSources.size();
2462 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2465 myRaytraceGeometry.Sources.resize (aNbLights);
2468 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2470 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2471 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2472 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2473 aLightColor.g() * aLight.Intensity(),
2474 aLightColor.b() * aLight.Intensity(),
2477 BVH_Vec4f aPosition (-aLight.PackedDirectionRange().x(),
2478 -aLight.PackedDirectionRange().y(),
2479 -aLight.PackedDirectionRange().z(),
2482 if (aLight.Type() != Graphic3d_TypeOfLightSource_Directional)
2484 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2485 static_cast<float>(aLight.Position().Y()),
2486 static_cast<float>(aLight.Position().Z()),
2489 // store smoothing radius in W-component
2490 aEmission.w() = Max (aLight.Smoothness(), 0.f);
2494 // store cosine of smoothing angle in W-component
2495 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2498 if (aLight.IsHeadlight())
2500 aPosition = theInvModelView * aPosition;
2503 for (int aK = 0; aK < 4; ++aK)
2505 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2506 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2511 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2517 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2519 myRaytraceLightSrcTexture = new OpenGl_TextureBuffer();
2522 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2524 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2525 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2527 Message::SendTrace() << "Error: Failed to upload light source buffer";
2528 return Standard_False;
2531 myAccumFrames = 0; // accumulation should be restarted
2534 return Standard_True;
2537 // =======================================================================
2538 // function : setUniformState
2539 // purpose : Sets uniform state for the given ray-tracing shader program
2540 // =======================================================================
2541 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2542 const Standard_Integer theWinSizeX,
2543 const Standard_Integer theWinSizeY,
2544 Graphic3d_Camera::Projection theProjection,
2545 const Handle(OpenGl_Context)& theGlContext)
2547 // Get projection state
2548 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2550 OpenGl_Mat4 aViewPrjMat;
2551 OpenGl_Mat4 anUnviewMat;
2552 OpenGl_Vec3 aOrigins[4];
2553 OpenGl_Vec3 aDirects[4];
2555 if (myCamera->IsOrthographic()
2556 || !myRenderParams.IsGlobalIlluminationEnabled)
2558 updateCamera (myCamera->OrientationMatrixF(),
2559 aCntxProjectionState.Current(),
2565 if (myRenderParams.UseEnvironmentMapBackground
2566 || myRaytraceParameters.CubemapForBack)
2568 OpenGl_Mat4 aTempMat;
2569 OpenGl_Mat4 aTempInvMat;
2570 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2571 aCntxProjectionState.Current(),
2581 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2582 aCntxProjectionState.Current(),
2590 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2592 : myPostFSAAProgram;
2594 if (theProgram.IsNull())
2596 return Standard_False;
2599 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2600 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2601 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2602 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2603 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2605 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2606 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2609 theProgram->SetUniform (theGlContext,
2610 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2611 theProgram->SetUniform (theGlContext,
2612 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2613 theProgram->SetUniform (theGlContext,
2614 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2615 theProgram->SetUniform (theGlContext,
2616 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2617 theProgram->SetUniform (theGlContext,
2618 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2619 theProgram->SetUniform (theGlContext,
2620 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2621 theProgram->SetUniform (theGlContext,
2622 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2623 theProgram->SetUniform (theGlContext,
2624 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2625 theProgram->SetUniform (theGlContext,
2626 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2627 theProgram->SetUniform (theGlContext,
2628 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2630 // Set screen dimensions
2631 myRaytraceProgram->SetUniform (theGlContext,
2632 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2633 myRaytraceProgram->SetUniform (theGlContext,
2634 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2636 // Set 3D scene parameters
2637 theProgram->SetUniform (theGlContext,
2638 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2639 theProgram->SetUniform (theGlContext,
2640 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2642 // Set light source parameters
2643 const Standard_Integer aLightSourceBufferSize =
2644 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2646 theProgram->SetUniform (theGlContext,
2647 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2649 // Set array of 64-bit texture handles
2650 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2652 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2654 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2655 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2658 // Set background colors (only vertical gradient background supported)
2659 OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
2660 if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2661 && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2663 aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
2664 aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
2666 if (myCamera->Tile().IsValid())
2668 Standard_Integer aTileOffset = myCamera->Tile().OffsetLowerLeft().y();
2669 Standard_Integer aTileSize = myCamera->Tile().TileSize.y();
2670 Standard_Integer aViewSize = myCamera->Tile().TotalSize.y();
2671 OpenGl_Vec4 aColorRange = aBackColorTop - aBackColorBot;
2672 aBackColorBot = aBackColorBot + aColorRange * ((float) aTileOffset / aViewSize);
2673 aBackColorTop = aBackColorBot + aColorRange * ((float) aTileSize / aViewSize);
2676 aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
2677 aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
2678 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
2679 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
2681 // Set environment map parameters
2682 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2683 ? myCubeMapParams->TextureSet (theGlContext)
2685 const bool toDisableEnvironmentMap = anEnvTextureSet.IsNull()
2686 || anEnvTextureSet->IsEmpty()
2687 || !anEnvTextureSet->First()->IsValid();
2688 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapEnabled],
2689 toDisableEnvironmentMap ? 0 : 1);
2690 if (myRaytraceParameters.CubemapForBack)
2692 theProgram->SetUniform (theGlContext, "uZCoeff", myCubeMapBackground->ZIsInverted() ? -1 : 1);
2693 theProgram->SetUniform (theGlContext, "uYCoeff", myCubeMapBackground->IsTopDown() ? 1 : -1);
2694 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2695 myBackgroundType == Graphic3d_TOB_CUBEMAP ? 1 : 0);
2699 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2700 myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2703 // Set ambient light source
2704 theProgram->SetUniform (theGlContext,
2705 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2706 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2708 theProgram->SetUniform (theGlContext,
2709 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2711 theProgram->SetUniform (theGlContext,
2712 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2714 // Check whether we should restart accumulation for run-time parameters
2715 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2716 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2718 myAccumFrames = 0; // accumulation should be restarted
2720 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2721 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2724 else // RT parameters
2726 // Enable/disable run-time ray-tracing effects
2727 theProgram->SetUniform (theGlContext,
2728 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2729 theProgram->SetUniform (theGlContext,
2730 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2733 return Standard_True;
2736 // =======================================================================
2737 // function : bindRaytraceTextures
2738 // purpose : Binds ray-trace textures to corresponding texture units
2739 // =======================================================================
2740 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2743 if (myRaytraceParameters.AdaptiveScreenSampling
2744 && myRaytraceParameters.GlobalIllumination)
2746 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2747 myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2748 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2749 myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2750 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2752 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2753 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2757 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2758 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2762 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2763 ? myCubeMapParams->TextureSet (theGlContext)
2765 if (!anEnvTextureSet.IsNull()
2766 && !anEnvTextureSet->IsEmpty()
2767 && anEnvTextureSet->First()->IsValid())
2769 anEnvTextureSet->First()->Bind (theGlContext, OpenGl_RT_EnvMapTexture);
2772 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2773 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2774 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2775 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2776 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2777 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2778 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2779 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2780 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2781 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2784 // =======================================================================
2785 // function : unbindRaytraceTextures
2786 // purpose : Unbinds ray-trace textures from corresponding texture units
2787 // =======================================================================
2788 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2790 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2791 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2792 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2793 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2794 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2795 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2796 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2797 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2798 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2799 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2801 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2804 // =======================================================================
2805 // function : runRaytraceShaders
2806 // purpose : Runs ray-tracing shader programs
2807 // =======================================================================
2808 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2809 const Standard_Integer theSizeY,
2810 Graphic3d_Camera::Projection theProjection,
2811 OpenGl_FrameBuffer* theReadDrawFbo,
2812 const Handle(OpenGl_Context)& theGlContext)
2814 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2816 aResult &= setUniformState (0,
2822 if (myRaytraceParameters.GlobalIllumination) // path tracing
2824 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
2825 aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2827 else // Whitted-style ray-tracing
2829 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2835 // =======================================================================
2836 // function : runRaytrace
2837 // purpose : Runs Whitted-style ray-tracing
2838 // =======================================================================
2839 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2840 const Standard_Integer theSizeY,
2841 Graphic3d_Camera::Projection theProjection,
2842 OpenGl_FrameBuffer* theReadDrawFbo,
2843 const Handle(OpenGl_Context)& theGlContext)
2845 Standard_Boolean aResult = Standard_True;
2847 // Choose proper set of frame buffers for stereo rendering
2848 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2849 bindRaytraceTextures (theGlContext, aFBOIdx);
2851 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2853 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2855 theGlContext->core11fwd->glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2858 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2860 if (myRenderParams.IsAntialiasingEnabled)
2862 theGlContext->core11fwd->glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2864 // bind ray-tracing output image as input
2865 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2867 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2869 aResult &= setUniformState (1 /* FSAA ID */,
2875 // Perform multi-pass adaptive FSAA using ping-pong technique.
2876 // We use 'FLIPTRI' sampling pattern changing for every pixel
2877 // (3 additional samples per pixel, the 1st sample is already
2878 // available from initial ray-traced image).
2879 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2881 OpenGl_Vec2 aFsaaOffset (1.f / theSizeX, 1.f / theSizeY);
2884 aFsaaOffset.x() *= -0.55f;
2885 aFsaaOffset.y() *= 0.55f;
2889 aFsaaOffset.x() *= 0.00f;
2890 aFsaaOffset.y() *= -0.55f;
2894 aFsaaOffset.x() *= 0.55f;
2895 aFsaaOffset.y() *= 0.00f;
2898 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2899 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2900 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2901 myUniformLocations[1][OpenGl_RT_uFsaaOffset], aFsaaOffset);
2903 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2904 ? myRaytraceFBO2[aFBOIdx]
2905 : myRaytraceFBO1[aFBOIdx];
2907 aFramebuffer->BindBuffer (theGlContext);
2909 // perform adaptive FSAA pass
2910 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2912 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2915 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2916 const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2918 theGlContext->core11fwd->glEnable (GL_DEPTH_TEST);
2920 // Display filtered image
2921 theGlContext->BindProgram (myOutImageProgram);
2923 if (theReadDrawFbo != NULL)
2925 theReadDrawFbo->BindBuffer (theGlContext);
2929 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2932 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2933 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2935 // copy the output image with depth values
2936 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2938 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2939 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2942 unbindRaytraceTextures (theGlContext);
2944 theGlContext->BindProgram (NULL);
2949 // =======================================================================
2950 // function : runPathtrace
2951 // purpose : Runs path tracing shader
2952 // =======================================================================
2953 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2954 const Standard_Integer theSizeY,
2955 const Graphic3d_Camera::Projection theProjection,
2956 const Handle(OpenGl_Context)& theGlContext)
2958 if (myToUpdateEnvironmentMap) // check whether the map was changed
2960 myAccumFrames = myToUpdateEnvironmentMap = 0;
2963 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2964 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2966 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2967 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2971 // Choose proper set of frame buffers for stereo rendering
2972 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2974 if (myRaytraceParameters.AdaptiveScreenSampling)
2976 if (myAccumFrames == 0)
2978 myTileSampler.Reset(); // reset tile sampler to its initial state
2980 // Adaptive sampling is starting at the second frame
2981 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2983 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2987 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2990 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2993 // Clear adaptive screen sampling images
2994 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2997 bindRaytraceTextures (theGlContext, aFBOIdx);
2999 const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
3000 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3002 // Set frame accumulation weight
3003 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
3005 // Set image uniforms for render program
3006 if (myRaytraceParameters.AdaptiveScreenSampling)
3008 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
3009 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage], OpenGl_RT_TileSamplesImage);
3010 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
3011 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
3014 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3015 aRenderImageFramebuffer->BindBuffer (theGlContext);
3016 if (myRaytraceParameters.AdaptiveScreenSampling
3017 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3019 // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
3020 // redirected to inner tiles (full tile size) are drawn entirely
3021 const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
3022 theGlContext->core11fwd->glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
3024 const NCollection_Vec4<bool> aColorMask = theGlContext->ColorMaskRGBA();
3025 theGlContext->SetColorMaskRGBA (NCollection_Vec4<bool> (true)); // force writes into all components, including alpha
3027 // Generate for the given RNG seed
3028 theGlContext->core11fwd->glDisable (GL_DEPTH_TEST);
3030 // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
3031 // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
3033 // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
3034 // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
3035 // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
3037 // Single-pass rendering is more optimal due to smaller amount of draw calls,
3038 // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
3039 // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
3040 // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
3041 const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
3042 && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
3043 ? myTileSampler.MaxTileSamples()
3045 if (myAccumFrames == 0)
3047 myRNG.SetSeed(); // start RNG from beginning
3049 for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
3051 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3052 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3053 if (myRaytraceParameters.AdaptiveScreenSampling)
3055 theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
3058 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3060 theGlContext->SetColorMaskRGBA (aColorMask);
3061 if (myRaytraceParameters.AdaptiveScreenSampling
3062 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3064 theGlContext->core11fwd->glViewport (0, 0, theSizeX, theSizeY);
3069 // =======================================================================
3070 // function : runPathtraceOut
3072 // =======================================================================
3073 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
3074 OpenGl_FrameBuffer* theReadDrawFbo,
3075 const Handle(OpenGl_Context)& theGlContext)
3077 // Output accumulated path traced image
3078 theGlContext->BindProgram (myOutImageProgram);
3080 // Choose proper set of frame buffers for stereo rendering
3081 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
3083 if (myRaytraceParameters.AdaptiveScreenSampling)
3085 // Set uniforms for display program
3086 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
3087 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
3088 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
3089 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3090 myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
3091 myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
3094 if (myRaytraceParameters.GlobalIllumination)
3096 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3097 switch (myRaytraceParameters.ToneMappingMethod)
3099 case Graphic3d_ToneMappingMethod_Disabled:
3101 case Graphic3d_ToneMappingMethod_Filmic:
3102 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3107 if (theReadDrawFbo != NULL)
3109 theReadDrawFbo->BindBuffer (theGlContext);
3112 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3113 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3115 // Copy accumulated image with correct depth values
3116 theGlContext->core11fwd->glEnable (GL_DEPTH_TEST);
3117 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3119 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3121 if (myRaytraceParameters.AdaptiveScreenSampling)
3123 // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3124 myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3125 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3127 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3131 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3135 unbindRaytraceTextures (theGlContext);
3136 theGlContext->BindProgram (NULL);
3140 // =======================================================================
3141 // function : raytrace
3142 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3143 // =======================================================================
3144 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3145 const Standard_Integer theSizeY,
3146 Graphic3d_Camera::Projection theProjection,
3147 OpenGl_FrameBuffer* theReadDrawFbo,
3148 const Handle(OpenGl_Context)& theGlContext)
3150 if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3152 return Standard_False;
3155 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3157 return Standard_False;
3160 OpenGl_Mat4 aLightSourceMatrix;
3162 // Get inversed model-view matrix for transforming lights
3163 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3165 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3167 return Standard_False;
3170 // Generate image using Whitted-style ray-tracing or path tracing
3171 if (myIsRaytraceDataValid)
3173 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3175 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3177 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3178 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3181 theGlContext->core11fwd->glDisable (GL_BLEND);
3183 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3191 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3192 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3195 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3197 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3198 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3201 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3204 return Standard_True;