1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_View.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
32 //! Use this macro to output ray-tracing debug info
33 // #define RAY_TRACE_PRINT_INFO
35 #ifdef RAY_TRACE_PRINT_INFO
36 #include <OSD_Timer.hxx>
41 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
42 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
47 //! Defines OpenGL texture samplers.
48 static const Graphic3d_TextureUnit OpenGl_RT_EnvMapTexture = Graphic3d_TextureUnit_0;
50 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
51 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
52 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
53 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
55 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
56 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
57 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
58 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
60 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
61 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
63 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
64 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
66 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
69 // =======================================================================
70 // function : updateRaytraceGeometry
71 // purpose : Updates 3D scene geometry for ray-tracing
72 // =======================================================================
73 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
74 const Standard_Integer theViewId,
75 const Handle(OpenGl_Context)& theGlContext)
77 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
78 // modifications. This is light-weight procedure performed on each frame
79 if (theMode == OpenGl_GUM_CHECK)
81 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
83 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
86 else if (theMode == OpenGl_GUM_PREPARE)
88 myRaytraceGeometry.ClearMaterials();
90 myArrayToTrianglesMap.clear();
92 myIsRaytraceDataValid = Standard_False;
95 // The set of processed structures (reflected to ray-tracing)
96 // This set is used to remove out-of-date records from the
97 // hash map of structures
98 std::set<const OpenGl_Structure*> anElements;
100 // Set to store all currently visible OpenGL primitive arrays
101 // applicable for ray-tracing
102 std::set<Standard_Size> anArrayIDs;
104 // Set to store all non-raytracable elements allowing tracking
105 // of changes in OpenGL scene (only for path tracing)
106 std::set<Standard_Integer> aNonRaytraceIDs;
108 for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
110 const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
111 if (aLayer->NbStructures() == 0
112 || !aLayer->LayerSettings().IsRaytracable()
113 || aLayer->LayerSettings().IsImmediate())
118 const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
119 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
121 for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
123 const OpenGl_Structure* aStructure = aStructIt.Value();
125 if (theMode == OpenGl_GUM_CHECK)
127 if (toUpdateStructure (aStructure))
129 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
131 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
133 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
136 else if (theMode == OpenGl_GUM_PREPARE)
138 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
142 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
147 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
149 // Extract OpenGL elements from the group (primitives arrays)
150 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
152 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
154 if (aPrimArray != NULL)
156 anArrayIDs.insert (aPrimArray->GetUID());
161 else if (theMode == OpenGl_GUM_REBUILD)
163 if (!aStructure->IsRaytracable())
167 else if (addRaytraceStructure (aStructure, theGlContext))
169 anElements.insert (aStructure); // structure was processed
176 if (theMode == OpenGl_GUM_PREPARE)
178 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
180 // Filter out unchanged objects so only their transformations and materials
181 // will be updated (and newly added objects will be processed from scratch)
182 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
184 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
185 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
187 if (aTriangleSet == NULL)
192 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
194 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
196 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
200 myRaytraceGeometry.Objects() = anUnchangedObjects;
202 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
204 else if (theMode == OpenGl_GUM_REBUILD)
206 // Actualize the hash map of structures - remove out-of-date records
207 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
209 while (anIter != myStructureStates.end())
211 if (anElements.find (anIter->first) == anElements.end())
213 myStructureStates.erase (anIter++);
221 // Actualize OpenGL layer list state
222 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
224 // Rebuild two-level acceleration structure
225 myRaytraceGeometry.ProcessAcceleration();
227 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
228 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
229 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
231 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
233 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
235 return uploadRaytraceData (theGlContext);
238 if (myRaytraceParameters.GlobalIllumination)
240 Standard_Boolean toRestart =
241 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
243 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
245 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
247 toRestart = Standard_True;
256 myNonRaytraceStructureIDs = aNonRaytraceIDs;
259 return Standard_True;
262 // =======================================================================
263 // function : toUpdateStructure
264 // purpose : Checks to see if the structure is modified
265 // =======================================================================
266 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
268 if (!theStructure->IsRaytracable())
270 if (theStructure->ModificationState() > 0)
272 theStructure->ResetModificationState();
274 return Standard_True; // ray-trace element was removed - need to rebuild
277 return Standard_False; // did not contain ray-trace elements
280 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
282 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
284 return Standard_True;
286 else if (theStructure->InstancedStructure() != NULL)
288 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
291 return Standard_False;
294 // =======================================================================
295 // function : buildTextureTransform
296 // purpose : Constructs texture transformation matrix
297 // =======================================================================
298 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
300 theMatrix.InitIdentity();
301 if (theParams.IsNull())
307 const Graphic3d_Vec2& aScale = theParams->Scale();
309 theMatrix.ChangeValue (0, 0) *= aScale.x();
310 theMatrix.ChangeValue (1, 0) *= aScale.x();
311 theMatrix.ChangeValue (2, 0) *= aScale.x();
312 theMatrix.ChangeValue (3, 0) *= aScale.x();
314 theMatrix.ChangeValue (0, 1) *= aScale.y();
315 theMatrix.ChangeValue (1, 1) *= aScale.y();
316 theMatrix.ChangeValue (2, 1) *= aScale.y();
317 theMatrix.ChangeValue (3, 1) *= aScale.y();
320 const Graphic3d_Vec2 aTrans = -theParams->Translation();
322 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
323 theMatrix.GetValue (0, 1) * aTrans.y();
325 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
326 theMatrix.GetValue (1, 1) * aTrans.y();
328 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
329 theMatrix.GetValue (2, 1) * aTrans.y();
332 const Standard_ShortReal aSin = std::sin (
333 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
334 const Standard_ShortReal aCos = std::cos (
335 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
337 BVH_Mat4f aRotationMat;
338 aRotationMat.SetValue (0, 0, aCos);
339 aRotationMat.SetValue (1, 1, aCos);
340 aRotationMat.SetValue (0, 1, -aSin);
341 aRotationMat.SetValue (1, 0, aSin);
343 theMatrix = theMatrix * aRotationMat;
346 // =======================================================================
347 // function : convertMaterial
348 // purpose : Creates ray-tracing material properties
349 // =======================================================================
350 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
351 const Handle(OpenGl_Context)& theGlContext)
353 OpenGl_RaytraceMaterial aResMat;
355 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
356 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
357 const float aShine = 128.0f * float(aSrcMat.Shininess());
359 const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
360 const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
361 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
362 const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
363 switch (aSrcMat.MaterialType())
365 case Graphic3d_MATERIAL_ASPECT:
367 aResMat.Ambient .SetValues (aSrcAmb * aMatCol, 1.0f);
368 aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
369 aResMat.Emission.SetValues (aSrcEms * aMatCol, 1.0f);
372 case Graphic3d_MATERIAL_PHYSIC:
374 aResMat.Ambient .SetValues (aSrcAmb, 1.0f);
375 aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
376 aResMat.Emission.SetValues (aSrcEms, 1.0f);
382 // interior color is always ignored for Specular
383 aResMat.Specular.SetValues (aSrcSpe, aShine);
384 const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
385 Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
386 aResMat.Diffuse.z() + aResMat.Specular.z()));
387 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
388 aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
391 const float anIndex = (float )aSrcMat.RefractionIndex();
392 aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
393 anIndex == 0 ? 1.0f : anIndex,
394 anIndex == 0 ? 1.0f : 1.0f / anIndex);
396 aResMat.Ambient = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
397 aResMat.Diffuse = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
398 aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
399 aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
401 // Serialize physically-based material properties
402 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
404 aResMat.BSDF.Kc = aBSDF.Kc;
405 aResMat.BSDF.Ks = aBSDF.Ks;
406 aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.0f); // no base color texture
407 aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, -1.0f); // no metallic-roughness texture
408 aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, -1.0f); // no emissive texture
410 aResMat.BSDF.Absorption = aBSDF.Absorption;
412 aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
413 aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
415 // Handle material textures
416 if (!theAspect->Aspect()->ToMapTexture())
421 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
422 if (aTextureSet.IsNull()
423 || aTextureSet->IsEmpty()
424 || aTextureSet->First().IsNull())
429 if (theGlContext->HasRayTracingTextures())
431 // write texture ID to diffuse w-components
432 for (OpenGl_TextureSet::Iterator aTexIter (aTextureSet); aTexIter.More(); aTexIter.Next())
434 const Handle(OpenGl_Texture)& aTexture = aTexIter.Value();
435 if (aTexIter.Unit() == Graphic3d_TextureUnit_BaseColor)
437 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
438 aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
440 else if (aTexIter.Unit() == Graphic3d_TextureUnit_MetallicRoughness)
442 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
443 aResMat.BSDF.Kt.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
445 else if (aTexIter.Unit() == Graphic3d_TextureUnit_Emissive)
447 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
448 aResMat.BSDF.Le.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
452 else if (!myIsRaytraceWarnTextures)
454 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
455 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
456 "Please try to update graphics card driver. At the moment textures will be ignored.");
457 myIsRaytraceWarnTextures = Standard_True;
463 // =======================================================================
464 // function : addRaytraceStructure
465 // purpose : Adds OpenGL structure to ray-traced scene geometry
466 // =======================================================================
467 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
468 const Handle(OpenGl_Context)& theGlContext)
470 if (!theStructure->IsVisible())
472 myStructureStates[theStructure] = StructState (theStructure);
474 return Standard_True;
477 // Get structure material
478 OpenGl_RaytraceMaterial aDefaultMaterial;
479 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
481 // Process all connected OpenGL structures
482 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
484 if (anInstanced != NULL && anInstanced->IsRaytracable())
486 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
489 myStructureStates[theStructure] = StructState (theStructure);
494 // =======================================================================
495 // function : addRaytraceGroups
496 // purpose : Adds OpenGL groups to ray-traced scene geometry
497 // =======================================================================
498 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
499 const OpenGl_RaytraceMaterial& theStructMat,
500 const Handle(Geom_Transformation)& theTrsf,
501 const Handle(OpenGl_Context)& theGlContext)
504 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
506 // Get group material
507 OpenGl_RaytraceMaterial aGroupMaterial;
508 if (aGroupIter.Value()->GlAspects() != NULL)
510 aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
513 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
515 // Use group material if available, otherwise use structure material
516 myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
518 // Add OpenGL elements from group (extract primitives arrays and aspects)
519 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
521 OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
523 if (anAspect != NULL)
525 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
527 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
529 myRaytraceGeometry.Materials.push_back (aMaterial);
533 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
535 if (aPrimArray != NULL)
537 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
539 if (aSetIter != myArrayToTrianglesMap.end())
541 OpenGl_TriangleSet* aSet = aSetIter->second;
542 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
543 if (!theTrsf.IsNull())
545 theTrsf->Trsf().GetMat4 (aMat4);
546 aTransform->SetTransform (aMat4);
549 aSet->SetProperties (aTransform);
550 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
552 aSet->SetMaterialIndex (aMatID);
557 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
559 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
560 if (!theTrsf.IsNull())
562 theTrsf->Trsf().GetMat4 (aMat4);
563 aTransform->SetTransform (aMat4);
566 aSet->SetProperties (aTransform);
567 myRaytraceGeometry.Objects().Append (aSet);
575 return Standard_True;
578 // =======================================================================
579 // function : addRaytracePrimitiveArray
580 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
581 // =======================================================================
582 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
583 const Standard_Integer theMaterial,
584 const OpenGl_Mat4* theTransform)
586 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
587 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
588 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
590 if (theArray->DrawMode() < GL_TRIANGLES
591 #ifndef GL_ES_VERSION_2_0
592 || theArray->DrawMode() > GL_POLYGON
594 || theArray->DrawMode() > GL_TRIANGLE_FAN
596 || anAttribs.IsNull())
598 return Handle(OpenGl_TriangleSet)();
601 OpenGl_Mat4 aNormalMatrix;
602 if (theTransform != NULL)
604 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
605 "Error: Failed to compute normal transformation matrix", NULL);
607 aNormalMatrix.Transpose();
610 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
612 aSet->Vertices.reserve (anAttribs->NbElements);
613 aSet->Normals.reserve (anAttribs->NbElements);
614 aSet->TexCrds.reserve (anAttribs->NbElements);
616 const size_t aVertFrom = aSet->Vertices.size();
618 Standard_Integer anAttribIndex = 0;
619 Standard_Size anAttribStride = 0;
620 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
622 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
623 if (anAttrib.DataType == Graphic3d_TOD_VEC2
624 || anAttrib.DataType == Graphic3d_TOD_VEC3
625 || anAttrib.DataType == Graphic3d_TOD_VEC4)
627 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
629 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
630 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
634 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
636 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
637 if (anAttrib.DataType == Graphic3d_TOD_VEC3
638 || anAttrib.DataType == Graphic3d_TOD_VEC4)
640 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
642 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
646 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
648 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
649 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
651 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
653 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
658 if (aSet->Normals.size() != aSet->Vertices.size())
660 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
662 aSet->Normals.push_back (BVH_Vec3f());
666 if (aSet->TexCrds.size() != aSet->Vertices.size())
668 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
670 aSet->TexCrds.push_back (BVH_Vec2f());
674 if (theTransform != NULL)
676 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
678 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
680 BVH_Vec4f aTransVertex = *theTransform *
681 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
683 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
685 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
687 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
689 BVH_Vec4f aTransNormal = aNormalMatrix *
690 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
692 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
696 if (!aBounds.IsNull())
698 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
700 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
702 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
705 return Handle(OpenGl_TriangleSet)();
708 aBoundStart += aVertNum;
713 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
715 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
718 return Handle(OpenGl_TriangleSet)();
723 if (aSet->Size() != 0)
731 // =======================================================================
732 // function : addRaytraceVertexIndices
733 // purpose : Adds vertex indices to ray-traced scene geometry
734 // =======================================================================
735 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
736 const Standard_Integer theMatID,
737 const Standard_Integer theCount,
738 const Standard_Integer theOffset,
739 const OpenGl_PrimitiveArray& theArray)
741 switch (theArray.DrawMode())
743 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
744 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
745 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
746 #if !defined(GL_ES_VERSION_2_0)
747 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
748 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
749 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
753 return Standard_False;
756 // =======================================================================
757 // function : addRaytraceTriangleArray
758 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
759 // =======================================================================
760 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
761 const Standard_Integer theMatID,
762 const Standard_Integer theCount,
763 const Standard_Integer theOffset,
764 const Handle(Graphic3d_IndexBuffer)& theIndices)
768 return Standard_True;
771 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
773 if (!theIndices.IsNull())
775 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
777 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
778 theIndices->Index (aVert + 1),
779 theIndices->Index (aVert + 2),
785 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
787 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
791 return Standard_True;
794 // =======================================================================
795 // function : addRaytraceTriangleFanArray
796 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
797 // =======================================================================
798 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
799 const Standard_Integer theMatID,
800 const Standard_Integer theCount,
801 const Standard_Integer theOffset,
802 const Handle(Graphic3d_IndexBuffer)& theIndices)
806 return Standard_True;
809 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
811 if (!theIndices.IsNull())
813 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
815 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
816 theIndices->Index (aVert + 1),
817 theIndices->Index (aVert + 2),
823 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
825 theSet.Elements.push_back (BVH_Vec4i (theOffset,
832 return Standard_True;
835 // =======================================================================
836 // function : addRaytraceTriangleStripArray
837 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
838 // =======================================================================
839 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
840 const Standard_Integer theMatID,
841 const Standard_Integer theCount,
842 const Standard_Integer theOffset,
843 const Handle(Graphic3d_IndexBuffer)& theIndices)
847 return Standard_True;
850 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
852 if (!theIndices.IsNull())
854 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
856 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
857 theIndices->Index (aVert + (aCW ? 0 : 1)),
858 theIndices->Index (aVert + 2),
864 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
866 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
867 aVert + (aCW ? 0 : 1),
873 return Standard_True;
876 // =======================================================================
877 // function : addRaytraceQuadrangleArray
878 // purpose : Adds OpenGL quad array to ray-traced scene geometry
879 // =======================================================================
880 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
881 const Standard_Integer theMatID,
882 const Standard_Integer theCount,
883 const Standard_Integer theOffset,
884 const Handle(Graphic3d_IndexBuffer)& theIndices)
888 return Standard_True;
891 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
893 if (!theIndices.IsNull())
895 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
897 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
898 theIndices->Index (aVert + 1),
899 theIndices->Index (aVert + 2),
901 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
902 theIndices->Index (aVert + 2),
903 theIndices->Index (aVert + 3),
909 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
911 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
913 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
918 return Standard_True;
921 // =======================================================================
922 // function : addRaytraceQuadrangleStripArray
923 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
924 // =======================================================================
925 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
926 const Standard_Integer theMatID,
927 const Standard_Integer theCount,
928 const Standard_Integer theOffset,
929 const Handle(Graphic3d_IndexBuffer)& theIndices)
933 return Standard_True;
936 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
938 if (!theIndices.IsNull())
940 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
942 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
943 theIndices->Index (aVert + 1),
944 theIndices->Index (aVert + 2),
947 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
948 theIndices->Index (aVert + 3),
949 theIndices->Index (aVert + 2),
955 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
957 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
962 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
969 return Standard_True;
972 // =======================================================================
973 // function : addRaytracePolygonArray
974 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
975 // =======================================================================
976 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
977 const Standard_Integer theMatID,
978 const Standard_Integer theCount,
979 const Standard_Integer theOffset,
980 const Handle(Graphic3d_IndexBuffer)& theIndices)
984 return Standard_True;
987 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
989 if (!theIndices.IsNull())
991 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
993 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
994 theIndices->Index (aVert + 1),
995 theIndices->Index (aVert + 2),
1001 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1003 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1010 return Standard_True;
1013 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1015 // =======================================================================
1016 // function : Source
1017 // purpose : Returns shader source combined with prefix
1018 // =======================================================================
1019 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1021 const TCollection_AsciiString aVersion = "#version 140";
1023 if (myPrefix.IsEmpty())
1025 return aVersion + "\n" + mySource;
1028 return aVersion + "\n" + myPrefix + "\n" + mySource;
1031 // =======================================================================
1032 // function : LoadFromFiles
1033 // purpose : Loads shader source from specified files
1034 // =======================================================================
1035 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1036 const TCollection_AsciiString& thePrefix)
1040 myPrefix = thePrefix;
1042 TCollection_AsciiString aMissingFiles;
1043 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1045 OSD_File aFile (theFileNames[anIndex]);
1048 aFile.Open (OSD_ReadOnly, OSD_Protection());
1050 if (!aFile.IsOpen())
1052 if (!aMissingFiles.IsEmpty())
1054 aMissingFiles += ", ";
1056 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1059 else if (!aMissingFiles.IsEmpty())
1065 TCollection_AsciiString aSource;
1066 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1067 if (!aSource.IsEmpty())
1069 mySource += TCollection_AsciiString ("\n") + aSource;
1074 if (!aMissingFiles.IsEmpty())
1076 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1077 return Standard_False;
1079 return Standard_True;
1082 // =======================================================================
1083 // function : LoadFromStrings
1085 // =======================================================================
1086 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1087 const TCollection_AsciiString& thePrefix)
1091 myPrefix = thePrefix;
1093 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1095 TCollection_AsciiString aSource = theStrings[anIndex];
1096 if (!aSource.IsEmpty())
1098 mySource += TCollection_AsciiString ("\n") + aSource;
1101 return Standard_True;
1104 // =======================================================================
1105 // function : generateShaderPrefix
1106 // purpose : Generates shader prefix based on current ray-tracing options
1107 // =======================================================================
1108 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1110 TCollection_AsciiString aPrefixString =
1111 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1112 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1114 if (myRaytraceParameters.TransparentShadows)
1116 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1118 if (!theGlContext->ToRenderSRGB())
1120 aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
1123 // If OpenGL driver supports bindless textures and texturing
1124 // is actually used, activate texturing in ray-tracing mode
1125 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1127 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1128 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1131 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1133 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1135 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1137 if (theGlContext->IsGlGreaterEqual (4, 4))
1139 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1140 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1141 && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1143 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1148 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1150 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1153 switch (myRaytraceParameters.ToneMappingMethod)
1155 case Graphic3d_ToneMappingMethod_Disabled:
1157 case Graphic3d_ToneMappingMethod_Filmic:
1158 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1163 if (myRaytraceParameters.CubemapForBack)
1165 aPrefixString += TCollection_AsciiString("\n#define BACKGROUND_CUBEMAP");
1168 if (myRaytraceParameters.DepthOfField)
1170 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1173 return aPrefixString;
1176 // =======================================================================
1177 // function : safeFailBack
1178 // purpose : Performs safe exit when shaders initialization fails
1179 // =======================================================================
1180 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1181 const Handle(OpenGl_Context)& theGlContext)
1183 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1184 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1186 myRaytraceInitStatus = OpenGl_RT_FAIL;
1188 releaseRaytraceResources (theGlContext);
1190 return Standard_False;
1193 // =======================================================================
1194 // function : initShader
1195 // purpose : Creates new shader object with specified source
1196 // =======================================================================
1197 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1198 const ShaderSource& theSource,
1199 const Handle(OpenGl_Context)& theGlContext)
1201 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1202 if (!aShader->Create (theGlContext))
1204 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1205 TCollection_ExtendedString ("Error: Failed to create ") +
1206 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1207 aShader->Release (theGlContext.get());
1208 return Handle(OpenGl_ShaderObject)();
1211 if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
1213 aShader->Release (theGlContext.get());
1214 return Handle(OpenGl_ShaderObject)();
1219 // =======================================================================
1220 // function : initProgram
1221 // purpose : Creates GLSL program from the given shader objects
1222 // =======================================================================
1223 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1224 const Handle(OpenGl_ShaderObject)& theVertShader,
1225 const Handle(OpenGl_ShaderObject)& theFragShader,
1226 const TCollection_AsciiString& theName)
1228 const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1229 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1231 if (!aProgram->Create (theGlContext))
1233 theVertShader->Release (theGlContext.operator->());
1235 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1236 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1238 return Handle(OpenGl_ShaderProgram)();
1241 if (!aProgram->AttachShader (theGlContext, theVertShader)
1242 || !aProgram->AttachShader (theGlContext, theFragShader))
1244 theVertShader->Release (theGlContext.operator->());
1246 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1247 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1249 return Handle(OpenGl_ShaderProgram)();
1252 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1254 TCollection_AsciiString aLinkLog;
1256 if (!aProgram->Link (theGlContext))
1258 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1260 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1261 "Failed to link shader program:\n") + aLinkLog;
1263 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1264 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1266 return Handle(OpenGl_ShaderProgram)();
1268 else if (theGlContext->caps->glslWarnings)
1270 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1271 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1273 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1274 "Shader program was linked with following warnings:\n") + aLinkLog;
1276 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1277 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1284 // =======================================================================
1285 // function : initRaytraceResources
1286 // purpose : Initializes OpenGL/GLSL shader programs
1287 // =======================================================================
1288 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1289 const Standard_Integer theSizeY,
1290 const Handle(OpenGl_Context)& theGlContext)
1292 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1294 return Standard_False;
1297 Standard_Boolean aToRebuildShaders = Standard_False;
1299 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1301 myRaytraceInitStatus = OpenGl_RT_NONE;
1302 releaseRaytraceResources (theGlContext, Standard_True);
1303 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1306 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1308 if (!myIsRaytraceDataValid)
1310 return Standard_True;
1313 const Standard_Integer aRequiredStackSize =
1314 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1316 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1318 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1320 aToRebuildShaders = Standard_True;
1324 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1326 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1328 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1329 aToRebuildShaders = Standard_True;
1334 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1335 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1336 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1337 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1338 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
1340 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1341 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1342 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1343 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1344 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1345 aToRebuildShaders = Standard_True;
1348 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling
1349 || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1351 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1352 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1353 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1355 if (!theGlContext->HasRayTracingAdaptiveSampling())
1357 // disable the feature if it is not supported
1358 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1359 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1360 "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1362 else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1363 && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1365 // disable the feature if it is not supported
1366 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1367 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1368 "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1372 aToRebuildShaders = Standard_True;
1374 myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1376 const bool isCubemapForBack = !myBackgroundCubeMap.IsNull();
1377 if (myRaytraceParameters.CubemapForBack != isCubemapForBack)
1379 myRaytraceParameters.CubemapForBack = isCubemapForBack;
1380 aToRebuildShaders = Standard_True;
1383 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1384 if (myRaytraceParameters.DepthOfField != toEnableDof)
1386 myRaytraceParameters.DepthOfField = toEnableDof;
1387 aToRebuildShaders = Standard_True;
1390 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1392 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1393 aToRebuildShaders = true;
1396 if (aToRebuildShaders)
1398 // Reject accumulated frames
1401 // Environment map should be updated
1402 myToUpdateEnvironmentMap = Standard_True;
1404 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1406 #ifdef RAY_TRACE_PRINT_INFO
1407 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1410 myRaytraceShaderSource.SetPrefix (aPrefixString);
1411 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1412 myOutImageShaderSource.SetPrefix (aPrefixString);
1414 if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
1415 || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
1416 || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source()))
1418 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1421 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1422 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1423 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1425 if (!myRaytraceProgram->Link (theGlContext)
1426 || !myPostFSAAProgram->Link (theGlContext)
1427 || !myOutImageProgram->Link (theGlContext))
1429 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1434 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1436 myAccumFrames = 0; // accumulation should be restarted
1438 if (!theGlContext->IsGlGreaterEqual (3, 1))
1440 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1442 else if (!theGlContext->arbTboRGB32)
1444 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1446 else if (!theGlContext->arbFBOBlit)
1448 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1451 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1453 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1454 if (myIsRaytraceDataValid)
1456 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1457 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1460 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1462 #ifdef RAY_TRACE_PRINT_INFO
1463 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1466 ShaderSource aBasicVertShaderSrc;
1468 if (!aShaderFolder.IsEmpty())
1470 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1471 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1473 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1478 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1479 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1484 if (!aShaderFolder.IsEmpty())
1486 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1487 aShaderFolder + "/PathtraceBase.fs",
1488 aShaderFolder + "/RaytraceRender.fs",
1490 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1492 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1497 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1498 Shaders_PathtraceBase_fs,
1499 Shaders_RaytraceRender_fs,
1501 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1504 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1505 if (aBasicVertShader.IsNull())
1507 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1510 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1511 if (myRaytraceShader.IsNull())
1513 aBasicVertShader->Release (theGlContext.operator->());
1514 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1517 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1518 if (myRaytraceProgram.IsNull())
1520 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1525 if (!aShaderFolder.IsEmpty())
1527 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1528 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1530 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1535 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1536 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1539 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1540 if (aBasicVertShader.IsNull())
1542 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1545 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1546 if (myPostFSAAShader.IsNull())
1548 aBasicVertShader->Release (theGlContext.operator->());
1549 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1552 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1553 if (myPostFSAAProgram.IsNull())
1555 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1560 if (!aShaderFolder.IsEmpty())
1562 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1563 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1565 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1570 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1571 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1574 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1575 if (aBasicVertShader.IsNull())
1577 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1580 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1581 if (myOutImageShader.IsNull())
1583 aBasicVertShader->Release (theGlContext.operator->());
1584 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1587 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1588 if (myOutImageProgram.IsNull())
1590 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1595 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1597 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1599 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1600 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1602 theGlContext->BindProgram (aShaderProgram);
1604 aShaderProgram->SetSampler (theGlContext,
1605 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1606 aShaderProgram->SetSampler (theGlContext,
1607 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1608 aShaderProgram->SetSampler (theGlContext,
1609 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1610 aShaderProgram->SetSampler (theGlContext,
1611 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1612 aShaderProgram->SetSampler (theGlContext,
1613 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1614 aShaderProgram->SetSampler (theGlContext,
1615 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1616 aShaderProgram->SetSampler (theGlContext,
1617 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1618 aShaderProgram->SetSampler (theGlContext,
1619 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1620 aShaderProgram->SetSampler (theGlContext,
1621 "uEnvMapTexture", OpenGl_RT_EnvMapTexture);
1622 aShaderProgram->SetSampler (theGlContext,
1623 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1624 aShaderProgram->SetSampler (theGlContext,
1625 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1629 aShaderProgram->SetSampler (theGlContext,
1630 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1634 aShaderProgram->SetSampler (theGlContext,
1635 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1638 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1639 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1641 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1642 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1643 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1644 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1645 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1646 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1647 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1648 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1649 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1650 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1651 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1652 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1653 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1654 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1655 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1656 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1657 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1658 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1659 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1660 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1662 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1663 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1664 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1665 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1666 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1667 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1668 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1669 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1671 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1672 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1673 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1674 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1675 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1676 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1678 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1679 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1681 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1682 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1683 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1684 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1685 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnabled] =
1686 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapEnabled");
1687 myUniformLocations[anIndex][OpenGl_RT_uEnvMapForBack] =
1688 aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapForBack");
1689 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1690 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1692 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1693 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1694 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1695 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1697 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1698 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1699 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1700 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1702 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1703 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1704 myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1705 aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1706 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1707 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1708 myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1709 aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1710 myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1711 aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1713 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1714 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1715 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1716 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1718 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1719 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1722 theGlContext->BindProgram (myOutImageProgram);
1724 myOutImageProgram->SetSampler (theGlContext,
1725 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1727 myOutImageProgram->SetSampler (theGlContext,
1728 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1730 theGlContext->BindProgram (NULL);
1733 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1735 return myRaytraceInitStatus == OpenGl_RT_INIT;
1738 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1745 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1747 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1749 return Standard_True;
1752 // =======================================================================
1753 // function : nullifyResource
1754 // purpose : Releases OpenGL resource
1755 // =======================================================================
1757 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1759 if (!theResource.IsNull())
1761 theResource->Release (theGlContext.get());
1762 theResource.Nullify();
1766 // =======================================================================
1767 // function : releaseRaytraceResources
1768 // purpose : Releases OpenGL/GLSL shader programs
1769 // =======================================================================
1770 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1772 // release shader resources
1773 nullifyResource (theGlContext, myRaytraceShader);
1774 nullifyResource (theGlContext, myPostFSAAShader);
1776 nullifyResource (theGlContext, myRaytraceProgram);
1777 nullifyResource (theGlContext, myPostFSAAProgram);
1778 nullifyResource (theGlContext, myOutImageProgram);
1780 if (!theToRebuild) // complete release
1782 myRaytraceFBO1[0]->Release (theGlContext.get());
1783 myRaytraceFBO1[1]->Release (theGlContext.get());
1784 myRaytraceFBO2[0]->Release (theGlContext.get());
1785 myRaytraceFBO2[1]->Release (theGlContext.get());
1787 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1788 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1790 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1791 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1792 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1793 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1794 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1795 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1797 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1798 nullifyResource (theGlContext, mySceneMinPointTexture);
1799 nullifyResource (theGlContext, mySceneMaxPointTexture);
1801 nullifyResource (theGlContext, myGeometryVertexTexture);
1802 nullifyResource (theGlContext, myGeometryNormalTexture);
1803 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1804 nullifyResource (theGlContext, myGeometryTriangTexture);
1805 nullifyResource (theGlContext, mySceneTransformTexture);
1807 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1808 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1810 myRaytraceGeometry.ReleaseResources (theGlContext);
1812 if (myRaytraceScreenQuad.IsValid ())
1814 myRaytraceScreenQuad.Release (theGlContext.get());
1819 // =======================================================================
1820 // function : updateRaytraceBuffers
1821 // purpose : Updates auxiliary OpenGL frame buffers.
1822 // =======================================================================
1823 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1824 const Standard_Integer theSizeY,
1825 const Handle(OpenGl_Context)& theGlContext)
1827 // Auxiliary buffers are not used
1828 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1830 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1831 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1832 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1833 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1835 return Standard_True;
1838 if (myRaytraceParameters.AdaptiveScreenSampling)
1840 Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1841 myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1842 myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1843 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1845 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1846 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1850 for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1852 if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1854 myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1855 myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1856 myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1857 myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1861 && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1863 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1864 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1865 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1866 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1867 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1871 if (myRaytraceParameters.AdaptiveScreenSampling)
1873 if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1874 && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1875 && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1876 && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1878 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1880 continue; // offsets texture is dynamically resized
1882 else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1883 && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1891 // Due to limitations of OpenGL image load-store extension
1892 // atomic operations are supported only for single-channel
1893 // images, so we define GL_R32F image. It is used as array
1894 // of 6D floating point vectors:
1895 // 0 - R color channel
1896 // 1 - G color channel
1897 // 2 - B color channel
1898 // 3 - hit time transformed into OpenGL NDC space
1899 // 4 - luminance accumulated for odd samples only
1900 myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1902 // workaround for some NVIDIA drivers
1903 myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1904 myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1905 myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
1906 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1907 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1909 if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1911 myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
1912 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1913 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1917 else // non-adaptive mode
1919 if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1920 || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1922 myAccumFrames = 0; // accumulation should be restarted
1925 myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1926 myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1929 return Standard_True;
1932 // =======================================================================
1933 // function : updateCamera
1934 // purpose : Generates viewing rays for corners of screen quad
1935 // =======================================================================
1936 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1937 const OpenGl_Mat4& theViewMapping,
1938 OpenGl_Vec3* theOrigins,
1939 OpenGl_Vec3* theDirects,
1940 OpenGl_Mat4& theViewPr,
1941 OpenGl_Mat4& theUnview)
1943 // compute view-projection matrix
1944 theViewPr = theViewMapping * theOrientation;
1946 // compute inverse view-projection matrix
1947 theViewPr.Inverted (theUnview);
1949 Standard_Integer aOriginIndex = 0;
1950 Standard_Integer aDirectIndex = 0;
1952 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1954 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1956 OpenGl_Vec4 aOrigin (GLfloat(aX),
1961 aOrigin = theUnview * aOrigin;
1963 aOrigin.x() = aOrigin.x() / aOrigin.w();
1964 aOrigin.y() = aOrigin.y() / aOrigin.w();
1965 aOrigin.z() = aOrigin.z() / aOrigin.w();
1967 OpenGl_Vec4 aDirect (GLfloat(aX),
1972 aDirect = theUnview * aDirect;
1974 aDirect.x() = aDirect.x() / aDirect.w();
1975 aDirect.y() = aDirect.y() / aDirect.w();
1976 aDirect.z() = aDirect.z() / aDirect.w();
1978 aDirect = aDirect - aOrigin;
1980 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1981 static_cast<GLfloat> (aOrigin.y()),
1982 static_cast<GLfloat> (aOrigin.z()));
1984 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1985 static_cast<GLfloat> (aDirect.y()),
1986 static_cast<GLfloat> (aDirect.z()));
1991 // =======================================================================
1992 // function : updatePerspCameraPT
1993 // purpose : Generates viewing rays (path tracing, perspective camera)
1994 // =======================================================================
1995 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
1996 const OpenGl_Mat4& theViewMapping,
1997 Graphic3d_Camera::Projection theProjection,
1998 OpenGl_Mat4& theViewPr,
1999 OpenGl_Mat4& theUnview,
2000 const int theWinSizeX,
2001 const int theWinSizeY)
2003 // compute view-projection matrix
2004 theViewPr = theViewMapping * theOrientation;
2006 // compute inverse view-projection matrix
2007 theViewPr.Inverted(theUnview);
2009 // get camera stereo params
2010 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2011 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2012 : static_cast<float> (myCamera->IOD());
2014 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2015 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2016 : static_cast<float> (myCamera->ZFocus());
2018 // get camera view vectors
2019 const gp_Pnt anOrig = myCamera->Eye();
2021 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2022 static_cast<float> (anOrig.Y()),
2023 static_cast<float> (anOrig.Z()));
2025 const gp_Dir aView = myCamera->Direction();
2027 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2028 static_cast<float> (aView.Y()),
2029 static_cast<float> (aView.Z()));
2031 const gp_Dir anUp = myCamera->Up();
2033 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2034 static_cast<float> (anUp.Y()),
2035 static_cast<float> (anUp.Z()));
2037 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2039 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2040 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2042 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2043 static_cast<float> (aScaleY));
2045 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2047 myEyeView = anEyeViewMono;
2049 else // stereo camera
2051 // compute z-focus point
2052 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2054 // compute stereo camera shift
2055 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2056 myEyeOrig += myEyeSide.Normalized() * aDx;
2058 // estimate new camera direction vector and correct its length
2059 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2060 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2064 // =======================================================================
2065 // function : uploadRaytraceData
2066 // purpose : Uploads ray-trace data to the GPU
2067 // =======================================================================
2068 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2070 if (!theGlContext->IsGlGreaterEqual (3, 1))
2072 #ifdef RAY_TRACE_PRINT_INFO
2073 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2075 return Standard_False;
2078 myAccumFrames = 0; // accumulation should be restarted
2080 /////////////////////////////////////////////////////////////////////////////
2081 // Prepare OpenGL textures
2083 if (theGlContext->arbTexBindless != NULL)
2085 // If OpenGL driver supports bindless textures we need
2086 // to get unique 64- bit handles for using on the GPU
2087 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2089 #ifdef RAY_TRACE_PRINT_INFO
2090 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2092 return Standard_False;
2096 /////////////////////////////////////////////////////////////////////////////
2097 // Create OpenGL BVH buffers
2099 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2101 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2102 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2103 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2104 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2106 if (!mySceneNodeInfoTexture->Create (theGlContext)
2107 || !mySceneMinPointTexture->Create (theGlContext)
2108 || !mySceneMaxPointTexture->Create (theGlContext)
2109 || !mySceneTransformTexture->Create (theGlContext))
2111 #ifdef RAY_TRACE_PRINT_INFO
2112 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2114 return Standard_False;
2118 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2120 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2121 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2122 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2123 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2125 if (!myGeometryVertexTexture->Create (theGlContext)
2126 || !myGeometryNormalTexture->Create (theGlContext)
2127 || !myGeometryTexCrdTexture->Create (theGlContext)
2128 || !myGeometryTriangTexture->Create (theGlContext))
2130 #ifdef RAY_TRACE_PRINT_INFO
2131 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2133 return Standard_False;
2137 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2139 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2141 if (!myRaytraceMaterialTexture->Create (theGlContext))
2143 #ifdef RAY_TRACE_PRINT_INFO
2144 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2146 return Standard_False;
2150 /////////////////////////////////////////////////////////////////////////////
2151 // Write transform buffer
2153 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2155 bool aResult = true;
2157 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2159 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2160 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2162 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2163 Standard_ASSERT_RETURN (aTransform != NULL,
2164 "OpenGl_TriangleSet does not contain transform", Standard_False);
2166 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2169 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2170 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2172 delete [] aNodeTransforms;
2174 /////////////////////////////////////////////////////////////////////////////
2175 // Write geometry and bottom-level BVH buffers
2177 Standard_Size aTotalVerticesNb = 0;
2178 Standard_Size aTotalElementsNb = 0;
2179 Standard_Size aTotalBVHNodesNb = 0;
2181 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2183 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2184 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2186 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2187 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2189 aTotalVerticesNb += aTriangleSet->Vertices.size();
2190 aTotalElementsNb += aTriangleSet->Elements.size();
2192 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2193 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2195 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2198 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2200 if (aTotalBVHNodesNb != 0)
2202 aResult &= mySceneNodeInfoTexture->Init (
2203 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2204 aResult &= mySceneMinPointTexture->Init (
2205 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2206 aResult &= mySceneMaxPointTexture->Init (
2207 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2212 #ifdef RAY_TRACE_PRINT_INFO
2213 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2215 return Standard_False;
2218 if (aTotalElementsNb != 0)
2220 aResult &= myGeometryTriangTexture->Init (
2221 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2224 if (aTotalVerticesNb != 0)
2226 aResult &= myGeometryVertexTexture->Init (
2227 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2228 aResult &= myGeometryNormalTexture->Init (
2229 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2230 aResult &= myGeometryTexCrdTexture->Init (
2231 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2236 #ifdef RAY_TRACE_PRINT_INFO
2237 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2239 return Standard_False;
2242 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2244 if (aBVH->Length() > 0)
2246 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2247 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2248 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2249 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2250 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2251 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2254 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2256 if (!aBVH->IsOuter (aNodeIdx))
2259 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2261 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2262 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2264 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2266 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2267 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2269 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2271 if (aBvhBuffersSize != 0)
2273 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2274 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2275 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2276 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2277 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2278 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2282 #ifdef RAY_TRACE_PRINT_INFO
2283 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2285 return Standard_False;
2289 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2291 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2292 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2294 if (!aTriangleSet->Vertices.empty())
2296 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2297 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2298 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2299 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2300 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2301 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2304 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2306 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2307 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2309 if (!aTriangleSet->Elements.empty())
2311 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2312 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2317 #ifdef RAY_TRACE_PRINT_INFO
2318 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2320 return Standard_False;
2324 /////////////////////////////////////////////////////////////////////////////
2325 // Write material buffer
2327 if (myRaytraceGeometry.Materials.size() != 0)
2329 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2330 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2334 #ifdef RAY_TRACE_PRINT_INFO
2335 std::cout << "Error: Failed to upload material buffer" << std::endl;
2337 return Standard_False;
2341 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2343 #ifdef RAY_TRACE_PRINT_INFO
2345 Standard_ShortReal aMemTrgUsed = 0.f;
2346 Standard_ShortReal aMemBvhUsed = 0.f;
2348 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2350 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2352 aMemTrgUsed += static_cast<Standard_ShortReal> (
2353 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2354 aMemTrgUsed += static_cast<Standard_ShortReal> (
2355 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2356 aMemTrgUsed += static_cast<Standard_ShortReal> (
2357 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2358 aMemTrgUsed += static_cast<Standard_ShortReal> (
2359 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2361 aMemBvhUsed += static_cast<Standard_ShortReal> (
2362 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2363 aMemBvhUsed += static_cast<Standard_ShortReal> (
2364 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2365 aMemBvhUsed += static_cast<Standard_ShortReal> (
2366 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2369 aMemBvhUsed += static_cast<Standard_ShortReal> (
2370 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2371 aMemBvhUsed += static_cast<Standard_ShortReal> (
2372 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2373 aMemBvhUsed += static_cast<Standard_ShortReal> (
2374 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2376 std::cout << "GPU Memory Used (Mb):\n"
2377 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2378 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2385 // =======================================================================
2386 // function : updateRaytraceLightSources
2387 // purpose : Updates 3D scene light sources for ray-tracing
2388 // =======================================================================
2389 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2391 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2392 Graphic3d_Vec4 aNewAmbient (0.0f);
2393 if (myShadingModel != Graphic3d_TOSM_UNLIT
2394 && !myLights.IsNull())
2396 aNewAmbient.SetValues (myLights->AmbientColor().rgb(), 0.0f);
2398 // move positional light sources at the front of the list
2399 aLightSources.reserve (myLights->Extent());
2400 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2401 aLightIter.More(); aLightIter.Next())
2403 const Graphic3d_CLight& aLight = *aLightIter.Value();
2404 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2406 aLightSources.push_back (aLightIter.Value());
2410 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2411 aLightIter.More(); aLightIter.Next())
2413 if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2415 aLightSources.push_back (aLightIter.Value());
2420 if (!myRaytraceGeometry.Ambient.IsEqual (aNewAmbient))
2423 myRaytraceGeometry.Ambient = aNewAmbient;
2426 // get number of 'real' (not ambient) light sources
2427 const size_t aNbLights = aLightSources.size();
2428 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2431 myRaytraceGeometry.Sources.resize (aNbLights);
2434 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2436 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2437 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2438 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2439 aLightColor.g() * aLight.Intensity(),
2440 aLightColor.b() * aLight.Intensity(),
2443 BVH_Vec4f aPosition (-aLight.PackedDirectionRange().x(),
2444 -aLight.PackedDirectionRange().y(),
2445 -aLight.PackedDirectionRange().z(),
2448 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2450 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2451 static_cast<float>(aLight.Position().Y()),
2452 static_cast<float>(aLight.Position().Z()),
2455 // store smoothing radius in W-component
2456 aEmission.w() = Max (aLight.Smoothness(), 0.f);
2460 // store cosine of smoothing angle in W-component
2461 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2464 if (aLight.IsHeadlight())
2466 aPosition = theInvModelView * aPosition;
2469 for (int aK = 0; aK < 4; ++aK)
2471 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2472 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2477 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2483 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2485 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2488 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2490 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2491 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2493 #ifdef RAY_TRACE_PRINT_INFO
2494 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2496 return Standard_False;
2499 myAccumFrames = 0; // accumulation should be restarted
2502 return Standard_True;
2505 // =======================================================================
2506 // function : setUniformState
2507 // purpose : Sets uniform state for the given ray-tracing shader program
2508 // =======================================================================
2509 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2510 const Standard_Integer theWinSizeX,
2511 const Standard_Integer theWinSizeY,
2512 Graphic3d_Camera::Projection theProjection,
2513 const Handle(OpenGl_Context)& theGlContext)
2515 // Get projection state
2516 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2518 OpenGl_Mat4 aViewPrjMat;
2519 OpenGl_Mat4 anUnviewMat;
2520 OpenGl_Vec3 aOrigins[4];
2521 OpenGl_Vec3 aDirects[4];
2523 if (myCamera->IsOrthographic()
2524 || !myRenderParams.IsGlobalIlluminationEnabled)
2526 updateCamera (myCamera->OrientationMatrixF(),
2527 aCntxProjectionState.Current(),
2535 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2536 aCntxProjectionState.Current(),
2544 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2546 : myPostFSAAProgram;
2548 if (theProgram.IsNull())
2550 return Standard_False;
2553 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2554 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2555 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2556 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2557 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2559 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2560 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2563 theProgram->SetUniform (theGlContext,
2564 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2565 theProgram->SetUniform (theGlContext,
2566 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2567 theProgram->SetUniform (theGlContext,
2568 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2569 theProgram->SetUniform (theGlContext,
2570 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2571 theProgram->SetUniform (theGlContext,
2572 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2573 theProgram->SetUniform (theGlContext,
2574 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2575 theProgram->SetUniform (theGlContext,
2576 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2577 theProgram->SetUniform (theGlContext,
2578 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2579 theProgram->SetUniform (theGlContext,
2580 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2581 theProgram->SetUniform (theGlContext,
2582 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2584 // Set screen dimensions
2585 myRaytraceProgram->SetUniform (theGlContext,
2586 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2587 myRaytraceProgram->SetUniform (theGlContext,
2588 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2590 // Set 3D scene parameters
2591 theProgram->SetUniform (theGlContext,
2592 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2593 theProgram->SetUniform (theGlContext,
2594 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2596 // Set light source parameters
2597 const Standard_Integer aLightSourceBufferSize =
2598 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2600 theProgram->SetUniform (theGlContext,
2601 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2603 // Set array of 64-bit texture handles
2604 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2606 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2608 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2609 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2612 // Set background colors (only vertical gradient background supported)
2613 OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
2614 if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2615 && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2617 aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
2618 aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
2620 if (myCamera->Tile().IsValid())
2622 Standard_Integer aTileOffset = myCamera->Tile().OffsetLowerLeft().y();
2623 Standard_Integer aTileSize = myCamera->Tile().TileSize.y();
2624 Standard_Integer aViewSize = myCamera->Tile().TotalSize.y();
2625 OpenGl_Vec4 aColorRange = aBackColorTop - aBackColorBot;
2626 aBackColorBot = aBackColorBot + aColorRange * ((float) aTileOffset / aViewSize);
2627 aBackColorTop = aBackColorBot + aColorRange * ((float) aTileSize / aViewSize);
2630 aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
2631 aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
2632 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
2633 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
2635 // Set environment map parameters
2636 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2637 ? myCubeMapParams->TextureSet (theGlContext)
2639 const bool toDisableEnvironmentMap = anEnvTextureSet.IsNull()
2640 || anEnvTextureSet->IsEmpty()
2641 || !anEnvTextureSet->First()->IsValid();
2642 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapEnabled],
2643 toDisableEnvironmentMap ? 0 : 1);
2644 if (myRaytraceParameters.CubemapForBack)
2646 theProgram->SetUniform (theGlContext, "uZCoeff", myBackgroundCubeMap->ZIsInverted() ? -1 : 1);
2647 theProgram->SetUniform (theGlContext, "uYCoeff", myBackgroundCubeMap->IsTopDown() ? 1 : -1);
2648 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2649 myBackgroundType == Graphic3d_TOB_CUBEMAP ? 1 : 0);
2653 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
2654 myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2657 // Set ambient light source
2658 theProgram->SetUniform (theGlContext,
2659 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2660 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2662 theProgram->SetUniform (theGlContext,
2663 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2665 theProgram->SetUniform (theGlContext,
2666 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2668 // Check whether we should restart accumulation for run-time parameters
2669 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2670 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2672 myAccumFrames = 0; // accumulation should be restarted
2674 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2675 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2678 else // RT parameters
2680 // Enable/disable run-time ray-tracing effects
2681 theProgram->SetUniform (theGlContext,
2682 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2683 theProgram->SetUniform (theGlContext,
2684 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2687 return Standard_True;
2690 // =======================================================================
2691 // function : bindRaytraceTextures
2692 // purpose : Binds ray-trace textures to corresponding texture units
2693 // =======================================================================
2694 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2697 if (myRaytraceParameters.AdaptiveScreenSampling
2698 && myRaytraceParameters.GlobalIllumination)
2700 #if !defined(GL_ES_VERSION_2_0)
2701 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2702 myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2703 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2704 myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2705 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2707 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2708 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2712 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2713 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2716 (void )theStereoView;
2720 const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
2721 ? myCubeMapParams->TextureSet (theGlContext)
2723 if (!anEnvTextureSet.IsNull()
2724 && !anEnvTextureSet->IsEmpty()
2725 && anEnvTextureSet->First()->IsValid())
2727 anEnvTextureSet->First()->Bind (theGlContext, OpenGl_RT_EnvMapTexture);
2730 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2731 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2732 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2733 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2734 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2735 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2736 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2737 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2738 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2739 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2742 // =======================================================================
2743 // function : unbindRaytraceTextures
2744 // purpose : Unbinds ray-trace textures from corresponding texture units
2745 // =======================================================================
2746 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2748 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2749 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2750 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2751 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2752 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2753 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2754 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2755 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2756 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2757 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2759 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2762 // =======================================================================
2763 // function : runRaytraceShaders
2764 // purpose : Runs ray-tracing shader programs
2765 // =======================================================================
2766 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2767 const Standard_Integer theSizeY,
2768 Graphic3d_Camera::Projection theProjection,
2769 OpenGl_FrameBuffer* theReadDrawFbo,
2770 const Handle(OpenGl_Context)& theGlContext)
2772 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2774 aResult &= setUniformState (0,
2780 if (myRaytraceParameters.GlobalIllumination) // path tracing
2782 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
2783 aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2785 else // Whitted-style ray-tracing
2787 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2793 // =======================================================================
2794 // function : runRaytrace
2795 // purpose : Runs Whitted-style ray-tracing
2796 // =======================================================================
2797 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2798 const Standard_Integer theSizeY,
2799 Graphic3d_Camera::Projection theProjection,
2800 OpenGl_FrameBuffer* theReadDrawFbo,
2801 const Handle(OpenGl_Context)& theGlContext)
2803 Standard_Boolean aResult = Standard_True;
2805 // Choose proper set of frame buffers for stereo rendering
2806 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2807 bindRaytraceTextures (theGlContext, aFBOIdx);
2809 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2811 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2813 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2816 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2818 if (myRenderParams.IsAntialiasingEnabled)
2820 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2822 // bind ray-tracing output image as input
2823 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2825 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2827 aResult &= setUniformState (1 /* FSAA ID */,
2833 // Perform multi-pass adaptive FSAA using ping-pong technique.
2834 // We use 'FLIPTRI' sampling pattern changing for every pixel
2835 // (3 additional samples per pixel, the 1st sample is already
2836 // available from initial ray-traced image).
2837 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2839 GLfloat aOffsetX = 1.f / theSizeX;
2840 GLfloat aOffsetY = 1.f / theSizeY;
2858 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2859 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2860 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2861 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2862 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2863 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2865 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2866 ? myRaytraceFBO2[aFBOIdx]
2867 : myRaytraceFBO1[aFBOIdx];
2869 aFramebuffer->BindBuffer (theGlContext);
2871 // perform adaptive FSAA pass
2872 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2874 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2877 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2878 const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2880 glEnable (GL_DEPTH_TEST);
2882 // Display filtered image
2883 theGlContext->BindProgram (myOutImageProgram);
2885 if (theReadDrawFbo != NULL)
2887 theReadDrawFbo->BindBuffer (theGlContext);
2891 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2894 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2895 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2897 // copy the output image with depth values
2898 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2900 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2901 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2904 unbindRaytraceTextures (theGlContext);
2906 theGlContext->BindProgram (NULL);
2911 // =======================================================================
2912 // function : runPathtrace
2913 // purpose : Runs path tracing shader
2914 // =======================================================================
2915 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2916 const Standard_Integer theSizeY,
2917 const Graphic3d_Camera::Projection theProjection,
2918 const Handle(OpenGl_Context)& theGlContext)
2920 if (myToUpdateEnvironmentMap) // check whether the map was changed
2922 myAccumFrames = myToUpdateEnvironmentMap = 0;
2925 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2926 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2928 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2929 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2933 // Choose proper set of frame buffers for stereo rendering
2934 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2936 if (myRaytraceParameters.AdaptiveScreenSampling)
2938 if (myAccumFrames == 0)
2940 myTileSampler.Reset(); // reset tile sampler to its initial state
2942 // Adaptive sampling is starting at the second frame
2943 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2945 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2949 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2952 #if !defined(GL_ES_VERSION_2_0)
2953 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2957 // Clear adaptive screen sampling images
2958 #if !defined(GL_ES_VERSION_2_0)
2959 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2963 bindRaytraceTextures (theGlContext, aFBOIdx);
2965 const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2966 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2968 // Set frame accumulation weight
2969 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
2971 // Set image uniforms for render program
2972 if (myRaytraceParameters.AdaptiveScreenSampling)
2974 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
2975 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage], OpenGl_RT_TileSamplesImage);
2976 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2977 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
2980 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2981 aRenderImageFramebuffer->BindBuffer (theGlContext);
2982 if (myRaytraceParameters.AdaptiveScreenSampling
2983 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2985 // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
2986 // redirected to inner tiles (full tile size) are drawn entirely
2987 const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
2988 glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
2991 // Generate for the given RNG seed
2992 glDisable (GL_DEPTH_TEST);
2994 // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
2995 // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
2997 // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
2998 // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
2999 // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
3001 // Single-pass rendering is more optimal due to smaller amount of draw calls,
3002 // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
3003 // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
3004 // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
3005 const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
3006 && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
3007 ? myTileSampler.MaxTileSamples()
3009 if (myAccumFrames == 0)
3011 myRNG.SetSeed(); // start RNG from beginning
3013 for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
3015 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3016 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3017 if (myRaytraceParameters.AdaptiveScreenSampling)
3019 #if !defined(GL_ES_VERSION_2_0)
3020 theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
3024 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3026 if (myRaytraceParameters.AdaptiveScreenSampling
3027 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3029 glViewport (0, 0, theSizeX, theSizeY);
3034 // =======================================================================
3035 // function : runPathtraceOut
3037 // =======================================================================
3038 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
3039 OpenGl_FrameBuffer* theReadDrawFbo,
3040 const Handle(OpenGl_Context)& theGlContext)
3042 // Output accumulated path traced image
3043 theGlContext->BindProgram (myOutImageProgram);
3045 // Choose proper set of frame buffers for stereo rendering
3046 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
3048 if (myRaytraceParameters.AdaptiveScreenSampling)
3050 // Set uniforms for display program
3051 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
3052 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
3053 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
3054 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3055 myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
3056 myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
3059 if (myRaytraceParameters.GlobalIllumination)
3061 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3062 switch (myRaytraceParameters.ToneMappingMethod)
3064 case Graphic3d_ToneMappingMethod_Disabled:
3066 case Graphic3d_ToneMappingMethod_Filmic:
3067 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3072 if (theReadDrawFbo != NULL)
3074 theReadDrawFbo->BindBuffer (theGlContext);
3077 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3078 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3080 // Copy accumulated image with correct depth values
3081 glEnable (GL_DEPTH_TEST);
3082 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3084 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3086 if (myRaytraceParameters.AdaptiveScreenSampling)
3088 // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3089 myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3090 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3092 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3096 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3100 unbindRaytraceTextures (theGlContext);
3101 theGlContext->BindProgram (NULL);
3105 // =======================================================================
3106 // function : raytrace
3107 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3108 // =======================================================================
3109 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3110 const Standard_Integer theSizeY,
3111 Graphic3d_Camera::Projection theProjection,
3112 OpenGl_FrameBuffer* theReadDrawFbo,
3113 const Handle(OpenGl_Context)& theGlContext)
3115 if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3117 return Standard_False;
3120 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3122 return Standard_False;
3125 OpenGl_Mat4 aLightSourceMatrix;
3127 // Get inversed model-view matrix for transforming lights
3128 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3130 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3132 return Standard_False;
3135 // Generate image using Whitted-style ray-tracing or path tracing
3136 if (myIsRaytraceDataValid)
3138 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3140 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3142 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3143 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3146 glDisable (GL_BLEND);
3148 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3156 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3157 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3160 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3162 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3163 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3166 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3169 return Standard_True;