1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_View.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
32 using namespace OpenGl_Raytrace;
34 //! Use this macro to output ray-tracing debug info
35 // #define RAY_TRACE_PRINT_INFO
37 #ifdef RAY_TRACE_PRINT_INFO
38 #include <OSD_Timer.hxx>
43 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
44 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
49 //! Defines OpenGL texture samplers.
50 static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
52 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
53 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
54 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
55 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
57 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
58 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
59 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
60 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
62 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
63 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
65 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
66 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
68 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
71 // =======================================================================
72 // function : updateRaytraceGeometry
73 // purpose : Updates 3D scene geometry for ray-tracing
74 // =======================================================================
75 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
76 const Standard_Integer theViewId,
77 const Handle(OpenGl_Context)& theGlContext)
79 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
80 // modifications. This is light-weight procedure performed on each frame
81 if (theMode == OpenGl_GUM_CHECK)
83 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
85 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
88 else if (theMode == OpenGl_GUM_PREPARE)
90 myRaytraceGeometry.ClearMaterials();
92 myArrayToTrianglesMap.clear();
94 myIsRaytraceDataValid = Standard_False;
97 // The set of processed structures (reflected to ray-tracing)
98 // This set is used to remove out-of-date records from the
99 // hash map of structures
100 std::set<const OpenGl_Structure*> anElements;
102 // Set to store all currently visible OpenGL primitive arrays
103 // applicable for ray-tracing
104 std::set<Standard_Size> anArrayIDs;
106 // Set to store all non-raytracable elements allowing tracking
107 // of changes in OpenGL scene (only for path tracing)
108 std::set<Standard_Integer> aNonRaytraceIDs;
110 const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
112 if (aLayer.NbStructures() != 0)
114 const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
116 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
118 for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
120 const OpenGl_Structure* aStructure = aStructIt.Value();
122 if (theMode == OpenGl_GUM_CHECK)
124 if (toUpdateStructure (aStructure))
126 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
128 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
130 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
133 else if (theMode == OpenGl_GUM_PREPARE)
135 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
139 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
144 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
146 // Extract OpenGL elements from the group (primitives arrays)
147 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
149 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
151 if (aPrimArray != NULL)
153 anArrayIDs.insert (aPrimArray->GetUID());
158 else if (theMode == OpenGl_GUM_REBUILD)
160 if (!aStructure->IsRaytracable())
164 else if (addRaytraceStructure (aStructure, theGlContext))
166 anElements.insert (aStructure); // structure was processed
173 if (theMode == OpenGl_GUM_PREPARE)
175 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
177 // Filter out unchanged objects so only their transformations and materials
178 // will be updated (and newly added objects will be processed from scratch)
179 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
181 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
182 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
184 if (aTriangleSet == NULL)
189 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
191 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
193 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
197 myRaytraceGeometry.Objects() = anUnchangedObjects;
199 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
201 else if (theMode == OpenGl_GUM_REBUILD)
203 // Actualize the hash map of structures - remove out-of-date records
204 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
206 while (anIter != myStructureStates.end())
208 if (anElements.find (anIter->first) == anElements.end())
210 myStructureStates.erase (anIter++);
218 // Actualize OpenGL layer list state
219 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
221 // Rebuild two-level acceleration structure
222 myRaytraceGeometry.ProcessAcceleration();
224 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
225 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
226 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
228 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
230 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
232 return uploadRaytraceData (theGlContext);
235 if (myRaytraceParameters.GlobalIllumination)
237 Standard_Boolean toRestart =
238 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
240 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
242 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
244 toRestart = Standard_True;
253 myNonRaytraceStructureIDs = aNonRaytraceIDs;
256 return Standard_True;
259 // =======================================================================
260 // function : toUpdateStructure
261 // purpose : Checks to see if the structure is modified
262 // =======================================================================
263 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
265 if (!theStructure->IsRaytracable())
267 if (theStructure->ModificationState() > 0)
269 theStructure->ResetModificationState();
271 return Standard_True; // ray-trace element was removed - need to rebuild
274 return Standard_False; // did not contain ray-trace elements
277 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
279 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
281 return Standard_True;
283 else if (theStructure->InstancedStructure() != NULL)
285 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
288 return Standard_False;
291 // =======================================================================
292 // function : buildTextureTransform
293 // purpose : Constructs texture transformation matrix
294 // =======================================================================
295 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
297 theMatrix.InitIdentity();
298 if (theParams.IsNull())
304 const Graphic3d_Vec2& aScale = theParams->Scale();
306 theMatrix.ChangeValue (0, 0) *= aScale.x();
307 theMatrix.ChangeValue (1, 0) *= aScale.x();
308 theMatrix.ChangeValue (2, 0) *= aScale.x();
309 theMatrix.ChangeValue (3, 0) *= aScale.x();
311 theMatrix.ChangeValue (0, 1) *= aScale.y();
312 theMatrix.ChangeValue (1, 1) *= aScale.y();
313 theMatrix.ChangeValue (2, 1) *= aScale.y();
314 theMatrix.ChangeValue (3, 1) *= aScale.y();
317 const Graphic3d_Vec2 aTrans = -theParams->Translation();
319 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
320 theMatrix.GetValue (0, 1) * aTrans.y();
322 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
323 theMatrix.GetValue (1, 1) * aTrans.y();
325 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
326 theMatrix.GetValue (2, 1) * aTrans.y();
329 const Standard_ShortReal aSin = std::sin (
330 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
331 const Standard_ShortReal aCos = std::cos (
332 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
334 BVH_Mat4f aRotationMat;
335 aRotationMat.SetValue (0, 0, aCos);
336 aRotationMat.SetValue (1, 1, aCos);
337 aRotationMat.SetValue (0, 1, -aSin);
338 aRotationMat.SetValue (1, 0, aSin);
340 theMatrix = theMatrix * aRotationMat;
343 // =======================================================================
344 // function : convertMaterial
345 // purpose : Creates ray-tracing material properties
346 // =======================================================================
347 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
348 const Handle(OpenGl_Context)& theGlContext)
350 OpenGl_RaytraceMaterial theMaterial;
352 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
353 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
354 const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC);
355 const float aShine = 128.0f * float(aSrcMat.Shininess());
358 if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
360 const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
361 theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f);
365 theMaterial.Ambient = THE_BLACK_COLOR;
368 // diffusion component
369 if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
371 const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
372 theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
376 theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
379 // specular component
380 if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
382 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
383 const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
384 theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
386 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
387 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
388 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
390 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
392 // ignore isPhysic here
393 theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
397 theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
400 // emission component
401 if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
403 const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
404 theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
408 theMaterial.Emission = THE_BLACK_COLOR;
411 const float anIndex = (float )aSrcMat.RefractionIndex();
412 theMaterial.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
413 anIndex == 0 ? 1.0f : anIndex,
414 anIndex == 0 ? 1.0f : 1.0f / anIndex);
416 // Serialize physically-based material properties
417 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
419 theMaterial.BSDF.Kc = aBSDF.Kc;
420 theMaterial.BSDF.Ks = aBSDF.Ks;
421 theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
422 theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
423 theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
425 theMaterial.BSDF.Absorption = aBSDF.Absorption;
427 theMaterial.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
428 theMaterial.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
430 // Handle material textures
431 if (!theAspect->Aspect()->ToMapTexture())
436 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
437 if (aTextureSet.IsNull()
438 || aTextureSet->IsEmpty()
439 || aTextureSet->First().IsNull())
444 if (theGlContext->HasRayTracingTextures())
446 const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
447 buildTextureTransform (aTexture->Sampler()->Parameters(), theMaterial.TextureTransform);
449 // write texture ID to diffuse w-component
450 theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
452 else if (!myIsRaytraceWarnTextures)
454 const TCollection_ExtendedString aWarnMessage =
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.";
458 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
459 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
461 myIsRaytraceWarnTextures = Standard_True;
467 // =======================================================================
468 // function : addRaytraceStructure
469 // purpose : Adds OpenGL structure to ray-traced scene geometry
470 // =======================================================================
471 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
472 const Handle(OpenGl_Context)& theGlContext)
474 if (!theStructure->IsVisible())
476 myStructureStates[theStructure] = StructState (theStructure);
478 return Standard_True;
481 // Get structure material
482 OpenGl_RaytraceMaterial aDefaultMaterial;
483 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
485 // Process all connected OpenGL structures
486 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
488 if (anInstanced != NULL && anInstanced->IsRaytracable())
490 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
493 myStructureStates[theStructure] = StructState (theStructure);
498 // =======================================================================
499 // function : addRaytraceGroups
500 // purpose : Adds OpenGL groups to ray-traced scene geometry
501 // =======================================================================
502 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
503 const OpenGl_RaytraceMaterial& theStructMat,
504 const Handle(Geom_Transformation)& theTrsf,
505 const Handle(OpenGl_Context)& theGlContext)
508 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
510 // Get group material
511 OpenGl_RaytraceMaterial aGroupMaterial;
512 if (aGroupIter.Value()->AspectFace() != NULL)
514 aGroupMaterial = convertMaterial (
515 aGroupIter.Value()->AspectFace(), theGlContext);
518 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
520 // Use group material if available, otherwise use structure material
521 myRaytraceGeometry.Materials.push_back (
522 aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
524 // Add OpenGL elements from group (extract primitives arrays and aspects)
525 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
527 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
529 if (anAspect != NULL)
531 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
533 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
535 myRaytraceGeometry.Materials.push_back (aMaterial);
539 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
541 if (aPrimArray != NULL)
543 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
545 if (aSetIter != myArrayToTrianglesMap.end())
547 OpenGl_TriangleSet* aSet = aSetIter->second;
548 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
549 if (!theTrsf.IsNull())
551 theTrsf->Trsf().GetMat4 (aMat4);
552 aTransform->SetTransform (aMat4);
555 aSet->SetProperties (aTransform);
556 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
558 aSet->SetMaterialIndex (aMatID);
563 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
565 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
566 if (!theTrsf.IsNull())
568 theTrsf->Trsf().GetMat4 (aMat4);
569 aTransform->SetTransform (aMat4);
572 aSet->SetProperties (aTransform);
573 myRaytraceGeometry.Objects().Append (aSet);
581 return Standard_True;
584 // =======================================================================
585 // function : addRaytracePrimitiveArray
586 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
587 // =======================================================================
588 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
589 const Standard_Integer theMaterial,
590 const OpenGl_Mat4* theTransform)
592 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
593 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
594 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
596 if (theArray->DrawMode() < GL_TRIANGLES
597 #ifndef GL_ES_VERSION_2_0
598 || theArray->DrawMode() > GL_POLYGON
600 || theArray->DrawMode() > GL_TRIANGLE_FAN
602 || anAttribs.IsNull())
604 return Handle(OpenGl_TriangleSet)();
607 OpenGl_Mat4 aNormalMatrix;
608 if (theTransform != NULL)
610 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
611 "Error: Failed to compute normal transformation matrix", NULL);
613 aNormalMatrix.Transpose();
616 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
618 aSet->Vertices.reserve (anAttribs->NbElements);
619 aSet->Normals.reserve (anAttribs->NbElements);
620 aSet->TexCrds.reserve (anAttribs->NbElements);
622 const size_t aVertFrom = aSet->Vertices.size();
624 Standard_Integer anAttribIndex = 0;
625 Standard_Size anAttribStride = 0;
626 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
628 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
629 if (anAttrib.DataType == Graphic3d_TOD_VEC2
630 || anAttrib.DataType == Graphic3d_TOD_VEC3
631 || anAttrib.DataType == Graphic3d_TOD_VEC4)
633 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
635 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
636 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
640 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
642 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
643 if (anAttrib.DataType == Graphic3d_TOD_VEC3
644 || anAttrib.DataType == Graphic3d_TOD_VEC4)
646 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
648 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
652 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
654 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
655 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
657 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
659 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
664 if (aSet->Normals.size() != aSet->Vertices.size())
666 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
668 aSet->Normals.push_back (BVH_Vec3f());
672 if (aSet->TexCrds.size() != aSet->Vertices.size())
674 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
676 aSet->TexCrds.push_back (BVH_Vec2f());
680 if (theTransform != NULL)
682 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
684 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
686 BVH_Vec4f aTransVertex = *theTransform *
687 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
689 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
691 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
693 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
695 BVH_Vec4f aTransNormal = aNormalMatrix *
696 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
698 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
702 if (!aBounds.IsNull())
704 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
706 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
708 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
711 return Handle(OpenGl_TriangleSet)();
714 aBoundStart += aVertNum;
719 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
721 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
724 return Handle(OpenGl_TriangleSet)();
729 if (aSet->Size() != 0)
737 // =======================================================================
738 // function : addRaytraceVertexIndices
739 // purpose : Adds vertex indices to ray-traced scene geometry
740 // =======================================================================
741 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
742 const Standard_Integer theMatID,
743 const Standard_Integer theCount,
744 const Standard_Integer theOffset,
745 const OpenGl_PrimitiveArray& theArray)
747 switch (theArray.DrawMode())
749 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
750 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
751 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
752 #if !defined(GL_ES_VERSION_2_0)
753 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
754 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
755 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
759 return Standard_False;
762 // =======================================================================
763 // function : addRaytraceTriangleArray
764 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
765 // =======================================================================
766 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
767 const Standard_Integer theMatID,
768 const Standard_Integer theCount,
769 const Standard_Integer theOffset,
770 const Handle(Graphic3d_IndexBuffer)& theIndices)
774 return Standard_True;
777 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
779 if (!theIndices.IsNull())
781 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
783 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
784 theIndices->Index (aVert + 1),
785 theIndices->Index (aVert + 2),
791 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
793 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
797 return Standard_True;
800 // =======================================================================
801 // function : addRaytraceTriangleFanArray
802 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
803 // =======================================================================
804 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
805 const Standard_Integer theMatID,
806 const Standard_Integer theCount,
807 const Standard_Integer theOffset,
808 const Handle(Graphic3d_IndexBuffer)& theIndices)
812 return Standard_True;
815 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
817 if (!theIndices.IsNull())
819 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
821 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
822 theIndices->Index (aVert + 1),
823 theIndices->Index (aVert + 2),
829 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
831 theSet.Elements.push_back (BVH_Vec4i (theOffset,
838 return Standard_True;
841 // =======================================================================
842 // function : addRaytraceTriangleStripArray
843 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
844 // =======================================================================
845 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
846 const Standard_Integer theMatID,
847 const Standard_Integer theCount,
848 const Standard_Integer theOffset,
849 const Handle(Graphic3d_IndexBuffer)& theIndices)
853 return Standard_True;
856 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
858 if (!theIndices.IsNull())
860 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
862 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
863 theIndices->Index (aVert + (aCW ? 0 : 1)),
864 theIndices->Index (aVert + 2),
870 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
872 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
873 aVert + (aCW ? 0 : 1),
879 return Standard_True;
882 // =======================================================================
883 // function : addRaytraceQuadrangleArray
884 // purpose : Adds OpenGL quad array to ray-traced scene geometry
885 // =======================================================================
886 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
887 const Standard_Integer theMatID,
888 const Standard_Integer theCount,
889 const Standard_Integer theOffset,
890 const Handle(Graphic3d_IndexBuffer)& theIndices)
894 return Standard_True;
897 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
899 if (!theIndices.IsNull())
901 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
903 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
904 theIndices->Index (aVert + 1),
905 theIndices->Index (aVert + 2),
907 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
908 theIndices->Index (aVert + 2),
909 theIndices->Index (aVert + 3),
915 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
917 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
919 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
924 return Standard_True;
927 // =======================================================================
928 // function : addRaytraceQuadrangleStripArray
929 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
930 // =======================================================================
931 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
932 const Standard_Integer theMatID,
933 const Standard_Integer theCount,
934 const Standard_Integer theOffset,
935 const Handle(Graphic3d_IndexBuffer)& theIndices)
939 return Standard_True;
942 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
944 if (!theIndices.IsNull())
946 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
948 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
949 theIndices->Index (aVert + 1),
950 theIndices->Index (aVert + 2),
953 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
954 theIndices->Index (aVert + 3),
955 theIndices->Index (aVert + 2),
961 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
963 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
968 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
975 return Standard_True;
978 // =======================================================================
979 // function : addRaytracePolygonArray
980 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
981 // =======================================================================
982 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
983 const Standard_Integer theMatID,
984 const Standard_Integer theCount,
985 const Standard_Integer theOffset,
986 const Handle(Graphic3d_IndexBuffer)& theIndices)
990 return Standard_True;
993 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
995 if (!theIndices.IsNull())
997 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
999 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
1000 theIndices->Index (aVert + 1),
1001 theIndices->Index (aVert + 2),
1007 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1009 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1016 return Standard_True;
1019 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1021 // =======================================================================
1022 // function : Source
1023 // purpose : Returns shader source combined with prefix
1024 // =======================================================================
1025 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1027 const TCollection_AsciiString aVersion = "#version 140";
1029 if (myPrefix.IsEmpty())
1031 return aVersion + "\n" + mySource;
1034 return aVersion + "\n" + myPrefix + "\n" + mySource;
1037 // =======================================================================
1038 // function : LoadFromFiles
1039 // purpose : Loads shader source from specified files
1040 // =======================================================================
1041 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1042 const TCollection_AsciiString& thePrefix)
1046 myPrefix = thePrefix;
1048 TCollection_AsciiString aMissingFiles;
1049 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1051 OSD_File aFile (theFileNames[anIndex]);
1054 aFile.Open (OSD_ReadOnly, OSD_Protection());
1056 if (!aFile.IsOpen())
1058 if (!aMissingFiles.IsEmpty())
1060 aMissingFiles += ", ";
1062 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1065 else if (!aMissingFiles.IsEmpty())
1071 TCollection_AsciiString aSource;
1072 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1073 if (!aSource.IsEmpty())
1075 mySource += TCollection_AsciiString ("\n") + aSource;
1080 if (!aMissingFiles.IsEmpty())
1082 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1083 return Standard_False;
1085 return Standard_True;
1088 // =======================================================================
1089 // function : LoadFromStrings
1091 // =======================================================================
1092 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1093 const TCollection_AsciiString& thePrefix)
1097 myPrefix = thePrefix;
1099 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1101 TCollection_AsciiString aSource = theStrings[anIndex];
1102 if (!aSource.IsEmpty())
1104 mySource += TCollection_AsciiString ("\n") + aSource;
1107 return Standard_True;
1110 // =======================================================================
1111 // function : generateShaderPrefix
1112 // purpose : Generates shader prefix based on current ray-tracing options
1113 // =======================================================================
1114 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1116 TCollection_AsciiString aPrefixString =
1117 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1118 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1120 if (myRaytraceParameters.TransparentShadows)
1122 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1125 // If OpenGL driver supports bindless textures and texturing
1126 // is actually used, activate texturing in ray-tracing mode
1127 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1129 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1130 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1133 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1135 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1137 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1139 // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
1140 if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1142 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
1143 TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
1147 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1149 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1152 switch (myRaytraceParameters.ToneMappingMethod)
1154 case Graphic3d_ToneMappingMethod_Disabled:
1156 case Graphic3d_ToneMappingMethod_Filmic:
1157 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1162 if (myRaytraceParameters.DepthOfField)
1164 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1167 return aPrefixString;
1170 // =======================================================================
1171 // function : safeFailBack
1172 // purpose : Performs safe exit when shaders initialization fails
1173 // =======================================================================
1174 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1175 const Handle(OpenGl_Context)& theGlContext)
1177 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1178 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1180 myRaytraceInitStatus = OpenGl_RT_FAIL;
1182 releaseRaytraceResources (theGlContext);
1184 return Standard_False;
1187 // =======================================================================
1188 // function : initShader
1189 // purpose : Creates new shader object with specified source
1190 // =======================================================================
1191 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1192 const ShaderSource& theSource,
1193 const Handle(OpenGl_Context)& theGlContext)
1195 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1197 if (!aShader->Create (theGlContext))
1199 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1200 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1202 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1203 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1205 aShader->Release (theGlContext.operator->());
1207 return Handle(OpenGl_ShaderObject)();
1210 if (!aShader->LoadSource (theGlContext, theSource.Source()))
1212 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1213 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1215 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1216 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1218 aShader->Release (theGlContext.operator->());
1220 return Handle(OpenGl_ShaderObject)();
1223 TCollection_AsciiString aBuildLog;
1225 if (!aShader->Compile (theGlContext))
1227 aShader->FetchInfoLog (theGlContext, aBuildLog);
1229 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1230 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1232 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1233 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1235 aShader->Release (theGlContext.operator->());
1237 #ifdef RAY_TRACE_PRINT_INFO
1238 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1241 return Handle(OpenGl_ShaderObject)();
1243 else if (theGlContext->caps->glslWarnings)
1245 aShader->FetchInfoLog (theGlContext, aBuildLog);
1247 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1249 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1250 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1252 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1253 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1256 #ifdef RAY_TRACE_PRINT_INFO
1257 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1264 // =======================================================================
1265 // function : initProgram
1266 // purpose : Creates GLSL program from the given shader objects
1267 // =======================================================================
1268 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1269 const Handle(OpenGl_ShaderObject)& theVertShader,
1270 const Handle(OpenGl_ShaderObject)& theFragShader)
1272 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1274 if (!aProgram->Create (theGlContext))
1276 theVertShader->Release (theGlContext.operator->());
1278 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1279 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1281 return Handle(OpenGl_ShaderProgram)();
1284 if (!aProgram->AttachShader (theGlContext, theVertShader)
1285 || !aProgram->AttachShader (theGlContext, theFragShader))
1287 theVertShader->Release (theGlContext.operator->());
1289 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1290 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1292 return Handle(OpenGl_ShaderProgram)();
1295 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1297 TCollection_AsciiString aLinkLog;
1299 if (!aProgram->Link (theGlContext))
1301 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1303 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1304 "Failed to link shader program:\n") + aLinkLog;
1306 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1307 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1309 return Handle(OpenGl_ShaderProgram)();
1311 else if (theGlContext->caps->glslWarnings)
1313 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1314 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1316 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1317 "Shader program was linked with following warnings:\n") + aLinkLog;
1319 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1320 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1327 // =======================================================================
1328 // function : initRaytraceResources
1329 // purpose : Initializes OpenGL/GLSL shader programs
1330 // =======================================================================
1331 Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1333 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1335 return Standard_False;
1338 Standard_Boolean aToRebuildShaders = Standard_False;
1340 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1342 myRaytraceInitStatus = OpenGl_RT_NONE;
1343 releaseRaytraceResources (theGlContext, Standard_True);
1344 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1347 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1349 if (!myIsRaytraceDataValid)
1351 return Standard_True;
1354 const Standard_Integer aRequiredStackSize =
1355 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1357 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1359 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1361 aToRebuildShaders = Standard_True;
1365 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1367 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1369 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1370 aToRebuildShaders = Standard_True;
1375 Standard_Integer aNbTilesX = 8;
1376 Standard_Integer aNbTilesY = 8;
1378 for (Standard_Integer anIdx = 0; aNbTilesX * aNbTilesY < myRenderParams.NbRayTracingTiles; ++anIdx)
1380 (anIdx % 2 == 0 ? aNbTilesX : aNbTilesY) <<= 1;
1383 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1384 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1385 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1386 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1387 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures
1388 || aNbTilesX != myRaytraceParameters.NbTilesX
1389 || aNbTilesY != myRaytraceParameters.NbTilesY)
1391 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1392 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1393 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1394 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1395 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1397 #ifdef RAY_TRACE_PRINT_INFO
1398 if (aNbTilesX != myRaytraceParameters.NbTilesX
1399 || aNbTilesY != myRaytraceParameters.NbTilesY)
1401 std::cout << "Number of tiles X: " << aNbTilesX << "\n";
1402 std::cout << "Number of tiles Y: " << aNbTilesY << "\n";
1406 myRaytraceParameters.NbTilesX = aNbTilesX;
1407 myRaytraceParameters.NbTilesY = aNbTilesY;
1409 aToRebuildShaders = Standard_True;
1412 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
1414 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1415 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1417 if (!theGlContext->HasRayTracingAdaptiveSampling())
1419 // disable the feature if it is not supported
1420 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1421 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1422 "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
1426 aToRebuildShaders = Standard_True;
1429 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1430 if (myRaytraceParameters.DepthOfField != toEnableDof)
1432 myRaytraceParameters.DepthOfField = toEnableDof;
1433 aToRebuildShaders = Standard_True;
1436 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1438 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1439 aToRebuildShaders = true;
1442 if (aToRebuildShaders)
1444 // Reject accumulated frames
1447 // Environment map should be updated
1448 myToUpdateEnvironmentMap = Standard_True;
1450 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1452 #ifdef RAY_TRACE_PRINT_INFO
1453 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1456 myRaytraceShaderSource.SetPrefix (aPrefixString);
1457 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1458 myOutImageShaderSource.SetPrefix (aPrefixString);
1460 if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1461 || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
1462 || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
1464 return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1467 TCollection_AsciiString aLog;
1469 if (!myRaytraceShader->Compile (theGlContext)
1470 || !myPostFSAAShader->Compile (theGlContext)
1471 || !myOutImageShader->Compile (theGlContext))
1473 #ifdef RAY_TRACE_PRINT_INFO
1474 myRaytraceShader->FetchInfoLog (theGlContext, aLog);
1476 if (!aLog.IsEmpty())
1478 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1481 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1484 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1485 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1486 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1488 if (!myRaytraceProgram->Link (theGlContext)
1489 || !myPostFSAAProgram->Link (theGlContext)
1490 || !myOutImageProgram->Link (theGlContext))
1492 #ifdef RAY_TRACE_PRINT_INFO
1493 myRaytraceProgram->FetchInfoLog (theGlContext, aLog);
1495 if (!aLog.IsEmpty())
1497 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1500 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1505 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1507 myAccumFrames = 0; // accumulation should be restarted
1509 if (!theGlContext->IsGlGreaterEqual (3, 1))
1511 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1513 else if (!theGlContext->arbTboRGB32)
1515 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1517 else if (!theGlContext->arbFBOBlit)
1519 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1522 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1524 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1525 if (myIsRaytraceDataValid)
1527 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1528 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1531 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1533 #ifdef RAY_TRACE_PRINT_INFO
1534 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1537 ShaderSource aBasicVertShaderSrc;
1539 if (!aShaderFolder.IsEmpty())
1541 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1542 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1544 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1549 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1550 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1555 if (!aShaderFolder.IsEmpty())
1557 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1558 aShaderFolder + "/PathtraceBase.fs",
1559 aShaderFolder + "/RaytraceRender.fs",
1561 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1563 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1568 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1569 Shaders_PathtraceBase_fs,
1570 Shaders_RaytraceRender_fs,
1572 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1575 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1576 if (aBasicVertShader.IsNull())
1578 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1581 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1582 if (myRaytraceShader.IsNull())
1584 aBasicVertShader->Release (theGlContext.operator->());
1585 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1588 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1589 if (myRaytraceProgram.IsNull())
1591 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1596 if (!aShaderFolder.IsEmpty())
1598 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1599 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1601 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1606 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1607 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1610 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1611 if (aBasicVertShader.IsNull())
1613 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1616 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1617 if (myPostFSAAShader.IsNull())
1619 aBasicVertShader->Release (theGlContext.operator->());
1620 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1623 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1624 if (myPostFSAAProgram.IsNull())
1626 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1631 if (!aShaderFolder.IsEmpty())
1633 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1634 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1636 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1641 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1642 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1645 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1646 if (aBasicVertShader.IsNull())
1648 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1651 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1652 if (myOutImageShader.IsNull())
1654 aBasicVertShader->Release (theGlContext.operator->());
1655 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1658 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
1659 if (myOutImageProgram.IsNull())
1661 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1666 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1668 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1670 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1671 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1673 theGlContext->BindProgram (aShaderProgram);
1675 aShaderProgram->SetSampler (theGlContext,
1676 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1677 aShaderProgram->SetSampler (theGlContext,
1678 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1679 aShaderProgram->SetSampler (theGlContext,
1680 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1681 aShaderProgram->SetSampler (theGlContext,
1682 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1683 aShaderProgram->SetSampler (theGlContext,
1684 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1685 aShaderProgram->SetSampler (theGlContext,
1686 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1687 aShaderProgram->SetSampler (theGlContext,
1688 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1689 aShaderProgram->SetSampler (theGlContext,
1690 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1691 aShaderProgram->SetSampler (theGlContext,
1692 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1693 aShaderProgram->SetSampler (theGlContext,
1694 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1695 aShaderProgram->SetSampler (theGlContext,
1696 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1700 aShaderProgram->SetSampler (theGlContext,
1701 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1705 aShaderProgram->SetSampler (theGlContext,
1706 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1709 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1710 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1712 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1713 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1714 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1715 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1716 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1717 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1718 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1719 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1720 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1721 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1722 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1723 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1724 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1725 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1726 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1727 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1728 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1729 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1730 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1731 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1733 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1734 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1735 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1736 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1737 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1738 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1739 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1740 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1742 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1743 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1744 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1745 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1746 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1747 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1749 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1750 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1752 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1753 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1754 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1755 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1756 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1757 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1758 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1759 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1760 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1761 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1763 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1764 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1765 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1766 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1768 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1769 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1770 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1771 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1773 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1774 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1775 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1776 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1778 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1779 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1780 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1781 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1783 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1784 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1787 theGlContext->BindProgram (myOutImageProgram);
1789 myOutImageProgram->SetSampler (theGlContext,
1790 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1792 myOutImageProgram->SetSampler (theGlContext,
1793 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1795 theGlContext->BindProgram (NULL);
1798 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1800 return myRaytraceInitStatus == OpenGl_RT_INIT;
1803 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1810 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1812 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1814 return Standard_True;
1817 // =======================================================================
1818 // function : nullifyResource
1819 // purpose : Releases OpenGL resource
1820 // =======================================================================
1822 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1824 if (!theResource.IsNull())
1826 theResource->Release (theGlContext.operator->());
1827 theResource.Nullify();
1831 // =======================================================================
1832 // function : releaseRaytraceResources
1833 // purpose : Releases OpenGL/GLSL shader programs
1834 // =======================================================================
1835 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1837 // release shader resources
1838 nullifyResource (theGlContext, myRaytraceShader);
1839 nullifyResource (theGlContext, myPostFSAAShader);
1841 nullifyResource (theGlContext, myRaytraceProgram);
1842 nullifyResource (theGlContext, myPostFSAAProgram);
1843 nullifyResource (theGlContext, myOutImageProgram);
1845 if (!theToRebuild) // complete release
1847 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1848 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1849 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1850 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1852 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1853 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1855 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1856 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1857 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1858 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1860 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1861 nullifyResource (theGlContext, mySceneMinPointTexture);
1862 nullifyResource (theGlContext, mySceneMaxPointTexture);
1864 nullifyResource (theGlContext, myGeometryVertexTexture);
1865 nullifyResource (theGlContext, myGeometryNormalTexture);
1866 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1867 nullifyResource (theGlContext, myGeometryTriangTexture);
1868 nullifyResource (theGlContext, mySceneTransformTexture);
1870 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1871 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1873 myRaytraceGeometry.ReleaseResources (theGlContext);
1875 if (myRaytraceScreenQuad.IsValid ())
1877 myRaytraceScreenQuad.Release (theGlContext.operator->());
1882 // =======================================================================
1883 // function : updateRaytraceBuffers
1884 // purpose : Updates auxiliary OpenGL frame buffers.
1885 // =======================================================================
1886 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1887 const Standard_Integer theSizeY,
1888 const Handle(OpenGl_Context)& theGlContext)
1890 // Auxiliary buffers are not used
1891 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1893 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1894 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1895 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1896 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1898 return Standard_True;
1901 if (myRaytraceParameters.AdaptiveScreenSampling)
1903 const Standard_Integer aSizeX = std::max (myRaytraceParameters.NbTilesX * 64, theSizeX);
1904 const Standard_Integer aSizeY = std::max (myRaytraceParameters.NbTilesY * 64, theSizeY);
1906 myRaytraceFBO1[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1907 myRaytraceFBO2[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1909 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1911 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1912 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1915 else // non-adaptive mode
1917 if (myRaytraceFBO1[0]->GetSizeX() != theSizeX
1918 || myRaytraceFBO1[0]->GetSizeY() != theSizeY)
1920 myAccumFrames = 0; // accumulation should be restarted
1923 myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1924 myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1926 // Init second set of buffers for stereographic rendering
1927 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1929 myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1930 myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1932 else if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1934 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1935 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1939 myTileSampler.SetSize (theSizeX, theSizeY);
1941 if (myRaytraceTileOffsetsTexture[0].IsNull()
1942 || myRaytraceTileOffsetsTexture[1].IsNull())
1944 myRaytraceOutputTexture[0] = new OpenGl_Texture();
1945 myRaytraceOutputTexture[1] = new OpenGl_Texture();
1947 myRaytraceTileOffsetsTexture[0] = new OpenGl_Texture();
1948 myRaytraceTileOffsetsTexture[1] = new OpenGl_Texture();
1949 myRaytraceVisualErrorTexture[0] = new OpenGl_Texture();
1950 myRaytraceVisualErrorTexture[1] = new OpenGl_Texture();
1953 if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
1954 || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
1958 // Due to limitations of OpenGL image load-store extension
1959 // atomic operations are supported only for single-channel
1960 // images, so we define GL_R32F image. It is used as array
1961 // of 6D floating point vectors:
1962 // 0 - R color channel
1963 // 1 - G color channel
1964 // 2 - B color channel
1965 // 3 - hit time transformed into OpenGL NDC space
1966 // 4 - luminance accumulated for odd samples only
1967 myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
1968 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1970 // workaround for some NVIDIA drivers
1971 myRaytraceVisualErrorTexture[0]->Release (theGlContext.operator->());
1972 myRaytraceTileOffsetsTexture[0]->Release (theGlContext.operator->());
1974 myRaytraceVisualErrorTexture[0]->Init (theGlContext,
1975 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1977 myRaytraceTileOffsetsTexture[0]->Init (theGlContext,
1978 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1981 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1983 if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
1984 || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
1986 myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
1987 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1989 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1990 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1992 myRaytraceVisualErrorTexture[1]->Init (theGlContext,
1993 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1995 myRaytraceTileOffsetsTexture[1]->Init (theGlContext,
1996 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
2001 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
2004 return Standard_True;
2007 // =======================================================================
2008 // function : updateCamera
2009 // purpose : Generates viewing rays for corners of screen quad
2010 // =======================================================================
2011 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
2012 const OpenGl_Mat4& theViewMapping,
2013 OpenGl_Vec3* theOrigins,
2014 OpenGl_Vec3* theDirects,
2015 OpenGl_Mat4& theViewPr,
2016 OpenGl_Mat4& theUnview)
2018 // compute view-projection matrix
2019 theViewPr = theViewMapping * theOrientation;
2021 // compute inverse view-projection matrix
2022 theViewPr.Inverted (theUnview);
2024 Standard_Integer aOriginIndex = 0;
2025 Standard_Integer aDirectIndex = 0;
2027 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2029 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2031 OpenGl_Vec4 aOrigin (GLfloat(aX),
2036 aOrigin = theUnview * aOrigin;
2038 aOrigin.x() = aOrigin.x() / aOrigin.w();
2039 aOrigin.y() = aOrigin.y() / aOrigin.w();
2040 aOrigin.z() = aOrigin.z() / aOrigin.w();
2042 OpenGl_Vec4 aDirect (GLfloat(aX),
2047 aDirect = theUnview * aDirect;
2049 aDirect.x() = aDirect.x() / aDirect.w();
2050 aDirect.y() = aDirect.y() / aDirect.w();
2051 aDirect.z() = aDirect.z() / aDirect.w();
2053 aDirect = aDirect - aOrigin;
2055 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2056 static_cast<GLfloat> (aOrigin.y()),
2057 static_cast<GLfloat> (aOrigin.z()));
2059 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2060 static_cast<GLfloat> (aDirect.y()),
2061 static_cast<GLfloat> (aDirect.z()));
2066 // =======================================================================
2067 // function : updatePerspCameraPT
2068 // purpose : Generates viewing rays (path tracing, perspective camera)
2069 // =======================================================================
2070 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
2071 const OpenGl_Mat4& theViewMapping,
2072 Graphic3d_Camera::Projection theProjection,
2073 OpenGl_Mat4& theViewPr,
2074 OpenGl_Mat4& theUnview,
2075 const int theWinSizeX,
2076 const int theWinSizeY)
2078 // compute view-projection matrix
2079 theViewPr = theViewMapping * theOrientation;
2081 // compute inverse view-projection matrix
2082 theViewPr.Inverted(theUnview);
2084 // get camera stereo params
2085 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2086 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2087 : static_cast<float> (myCamera->IOD());
2089 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2090 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2091 : static_cast<float> (myCamera->ZFocus());
2093 // get camera view vectors
2094 const gp_Pnt anOrig = myCamera->Eye();
2096 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2097 static_cast<float> (anOrig.Y()),
2098 static_cast<float> (anOrig.Z()));
2100 const gp_Dir aView = myCamera->Direction();
2102 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2103 static_cast<float> (aView.Y()),
2104 static_cast<float> (aView.Z()));
2106 const gp_Dir anUp = myCamera->Up();
2108 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2109 static_cast<float> (anUp.Y()),
2110 static_cast<float> (anUp.Z()));
2112 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2114 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2115 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2117 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2118 static_cast<float> (aScaleY));
2120 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2122 myEyeView = anEyeViewMono;
2124 else // stereo camera
2126 // compute z-focus point
2127 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2129 // compute stereo camera shift
2130 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2131 myEyeOrig += myEyeSide.Normalized() * aDx;
2133 // estimate new camera direction vector and correct its length
2134 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2135 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2139 // =======================================================================
2140 // function : uploadRaytraceData
2141 // purpose : Uploads ray-trace data to the GPU
2142 // =======================================================================
2143 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2145 if (!theGlContext->IsGlGreaterEqual (3, 1))
2147 #ifdef RAY_TRACE_PRINT_INFO
2148 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2150 return Standard_False;
2153 myAccumFrames = 0; // accumulation should be restarted
2155 /////////////////////////////////////////////////////////////////////////////
2156 // Prepare OpenGL textures
2158 if (theGlContext->arbTexBindless != NULL)
2160 // If OpenGL driver supports bindless textures we need
2161 // to get unique 64- bit handles for using on the GPU
2162 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2164 #ifdef RAY_TRACE_PRINT_INFO
2165 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2167 return Standard_False;
2171 /////////////////////////////////////////////////////////////////////////////
2172 // Create OpenGL BVH buffers
2174 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2176 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2177 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2178 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2179 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2181 if (!mySceneNodeInfoTexture->Create (theGlContext)
2182 || !mySceneMinPointTexture->Create (theGlContext)
2183 || !mySceneMaxPointTexture->Create (theGlContext)
2184 || !mySceneTransformTexture->Create (theGlContext))
2186 #ifdef RAY_TRACE_PRINT_INFO
2187 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2189 return Standard_False;
2193 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2195 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2196 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2197 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2198 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2200 if (!myGeometryVertexTexture->Create (theGlContext)
2201 || !myGeometryNormalTexture->Create (theGlContext)
2202 || !myGeometryTexCrdTexture->Create (theGlContext)
2203 || !myGeometryTriangTexture->Create (theGlContext))
2205 #ifdef RAY_TRACE_PRINT_INFO
2206 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2208 return Standard_False;
2212 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2214 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2216 if (!myRaytraceMaterialTexture->Create (theGlContext))
2218 #ifdef RAY_TRACE_PRINT_INFO
2219 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2221 return Standard_False;
2225 /////////////////////////////////////////////////////////////////////////////
2226 // Write transform buffer
2228 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2230 bool aResult = true;
2232 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2234 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2235 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2237 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2238 Standard_ASSERT_RETURN (aTransform != NULL,
2239 "OpenGl_TriangleSet does not contain transform", Standard_False);
2241 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2244 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2245 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2247 delete [] aNodeTransforms;
2249 /////////////////////////////////////////////////////////////////////////////
2250 // Write geometry and bottom-level BVH buffers
2252 Standard_Size aTotalVerticesNb = 0;
2253 Standard_Size aTotalElementsNb = 0;
2254 Standard_Size aTotalBVHNodesNb = 0;
2256 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2258 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2259 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2261 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2262 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2264 aTotalVerticesNb += aTriangleSet->Vertices.size();
2265 aTotalElementsNb += aTriangleSet->Elements.size();
2267 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2268 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2270 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2273 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2275 if (aTotalBVHNodesNb != 0)
2277 aResult &= mySceneNodeInfoTexture->Init (
2278 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2279 aResult &= mySceneMinPointTexture->Init (
2280 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2281 aResult &= mySceneMaxPointTexture->Init (
2282 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2287 #ifdef RAY_TRACE_PRINT_INFO
2288 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2290 return Standard_False;
2293 if (aTotalElementsNb != 0)
2295 aResult &= myGeometryTriangTexture->Init (
2296 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2299 if (aTotalVerticesNb != 0)
2301 aResult &= myGeometryVertexTexture->Init (
2302 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2303 aResult &= myGeometryNormalTexture->Init (
2304 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2305 aResult &= myGeometryTexCrdTexture->Init (
2306 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2311 #ifdef RAY_TRACE_PRINT_INFO
2312 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2314 return Standard_False;
2317 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2319 if (aBVH->Length() > 0)
2321 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2322 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2323 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2324 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2325 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2326 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2329 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2331 if (!aBVH->IsOuter (aNodeIdx))
2334 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2336 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2337 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2339 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2341 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2342 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2344 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2346 if (aBvhBuffersSize != 0)
2348 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2349 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2350 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2351 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2352 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2353 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2357 #ifdef RAY_TRACE_PRINT_INFO
2358 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2360 return Standard_False;
2364 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2366 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2367 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2369 if (!aTriangleSet->Vertices.empty())
2371 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2372 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2373 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2374 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2375 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2376 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2379 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2381 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2382 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2384 if (!aTriangleSet->Elements.empty())
2386 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2387 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2392 #ifdef RAY_TRACE_PRINT_INFO
2393 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2395 return Standard_False;
2399 /////////////////////////////////////////////////////////////////////////////
2400 // Write material buffer
2402 if (myRaytraceGeometry.Materials.size() != 0)
2404 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2405 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2409 #ifdef RAY_TRACE_PRINT_INFO
2410 std::cout << "Error: Failed to upload material buffer" << std::endl;
2412 return Standard_False;
2416 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2418 #ifdef RAY_TRACE_PRINT_INFO
2420 Standard_ShortReal aMemTrgUsed = 0.f;
2421 Standard_ShortReal aMemBvhUsed = 0.f;
2423 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2425 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2427 aMemTrgUsed += static_cast<Standard_ShortReal> (
2428 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2429 aMemTrgUsed += static_cast<Standard_ShortReal> (
2430 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2431 aMemTrgUsed += static_cast<Standard_ShortReal> (
2432 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2433 aMemTrgUsed += static_cast<Standard_ShortReal> (
2434 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2436 aMemBvhUsed += static_cast<Standard_ShortReal> (
2437 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2438 aMemBvhUsed += static_cast<Standard_ShortReal> (
2439 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2440 aMemBvhUsed += static_cast<Standard_ShortReal> (
2441 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2444 aMemBvhUsed += static_cast<Standard_ShortReal> (
2445 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2446 aMemBvhUsed += static_cast<Standard_ShortReal> (
2447 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2448 aMemBvhUsed += static_cast<Standard_ShortReal> (
2449 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2451 std::cout << "GPU Memory Used (Mb):\n"
2452 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2453 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2460 // =======================================================================
2461 // function : updateRaytraceLightSources
2462 // purpose : Updates 3D scene light sources for ray-tracing
2463 // =======================================================================
2464 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2466 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2467 myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2468 if (myShadingModel != Graphic3d_TOSM_UNLIT
2469 && !myLights.IsNull())
2471 const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
2472 myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
2474 // move positional light sources at the front of the list
2475 aLightSources.reserve (myLights->Extent());
2476 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2477 aLightIter.More(); aLightIter.Next())
2479 const Graphic3d_CLight& aLight = *aLightIter.Value();
2480 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2482 aLightSources.push_back (aLightIter.Value());
2486 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2487 aLightIter.More(); aLightIter.Next())
2489 if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2491 aLightSources.push_back (aLightIter.Value());
2496 // get number of 'real' (not ambient) light sources
2497 const size_t aNbLights = aLightSources.size();
2498 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2501 myRaytraceGeometry.Sources.resize (aNbLights);
2504 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2506 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2507 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2508 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2509 aLightColor.g() * aLight.Intensity(),
2510 aLightColor.b() * aLight.Intensity(),
2513 BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
2514 -aLight.PackedDirection().y(),
2515 -aLight.PackedDirection().z(),
2518 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2520 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2521 static_cast<float>(aLight.Position().Y()),
2522 static_cast<float>(aLight.Position().Z()),
2525 // store smoothing radius in W-component
2526 aEmission.w() = Max (aLight.Smoothness(), 0.f);
2530 // store cosine of smoothing angle in W-component
2531 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2534 if (aLight.IsHeadlight())
2536 aPosition = theInvModelView * aPosition;
2539 for (int aK = 0; aK < 4; ++aK)
2541 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2542 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2547 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2553 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2555 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2558 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2560 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2561 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2563 #ifdef RAY_TRACE_PRINT_INFO
2564 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2566 return Standard_False;
2569 myAccumFrames = 0; // accumulation should be restarted
2572 return Standard_True;
2575 // =======================================================================
2576 // function : setUniformState
2577 // purpose : Sets uniform state for the given ray-tracing shader program
2578 // =======================================================================
2579 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2580 const Standard_Integer theWinSizeX,
2581 const Standard_Integer theWinSizeY,
2582 Graphic3d_Camera::Projection theProjection,
2583 const Handle(OpenGl_Context)& theGlContext)
2585 // Get projection state
2586 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2588 OpenGl_Mat4 aViewPrjMat;
2589 OpenGl_Mat4 anUnviewMat;
2590 OpenGl_Vec3 aOrigins[4];
2591 OpenGl_Vec3 aDirects[4];
2593 if (myCamera->IsOrthographic()
2594 || !myRenderParams.IsGlobalIlluminationEnabled)
2596 updateCamera (myCamera->OrientationMatrixF(),
2597 aCntxProjectionState.Current(),
2605 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2606 aCntxProjectionState.Current(),
2614 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2616 : myPostFSAAProgram;
2618 if (theProgram.IsNull())
2620 return Standard_False;
2623 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2624 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2625 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2626 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2627 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2629 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2630 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2633 theProgram->SetUniform (theGlContext,
2634 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2635 theProgram->SetUniform (theGlContext,
2636 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2637 theProgram->SetUniform (theGlContext,
2638 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2639 theProgram->SetUniform (theGlContext,
2640 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2641 theProgram->SetUniform (theGlContext,
2642 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2643 theProgram->SetUniform (theGlContext,
2644 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2645 theProgram->SetUniform (theGlContext,
2646 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2647 theProgram->SetUniform (theGlContext,
2648 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2649 theProgram->SetUniform (theGlContext,
2650 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2651 theProgram->SetUniform (theGlContext,
2652 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2654 // Set screen dimensions
2655 myRaytraceProgram->SetUniform (theGlContext,
2656 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2657 myRaytraceProgram->SetUniform (theGlContext,
2658 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2660 // Set 3D scene parameters
2661 theProgram->SetUniform (theGlContext,
2662 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2663 theProgram->SetUniform (theGlContext,
2664 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2666 // Set light source parameters
2667 const Standard_Integer aLightSourceBufferSize =
2668 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2670 theProgram->SetUniform (theGlContext,
2671 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2673 // Set array of 64-bit texture handles
2674 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2676 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2678 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2679 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2682 // Set background colors (only gradient background supported)
2683 if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
2685 theProgram->SetUniform (theGlContext,
2686 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2687 theProgram->SetUniform (theGlContext,
2688 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2692 const OpenGl_Vec4& aBackColor = myBgColor;
2694 theProgram->SetUniform (theGlContext,
2695 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2696 theProgram->SetUniform (theGlContext,
2697 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2700 // Set environment map parameters
2701 const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2702 || myTextureEnv->IsEmpty()
2703 || !myTextureEnv->First()->IsValid();
2705 theProgram->SetUniform (theGlContext,
2706 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2708 theProgram->SetUniform (theGlContext,
2709 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2711 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2713 theProgram->SetUniform (theGlContext,
2714 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2716 theProgram->SetUniform (theGlContext,
2717 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2719 // Check whether we should restart accumulation for run-time parameters
2720 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2721 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2723 myAccumFrames = 0; // accumulation should be restarted
2725 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2726 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2729 else // RT parameters
2731 // Set ambient light source
2732 theProgram->SetUniform (theGlContext,
2733 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2735 // Enable/disable run-time ray-tracing effects
2736 theProgram->SetUniform (theGlContext,
2737 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2738 theProgram->SetUniform (theGlContext,
2739 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2742 return Standard_True;
2745 // =======================================================================
2746 // function : bindRaytraceTextures
2747 // purpose : Binds ray-trace textures to corresponding texture units
2748 // =======================================================================
2749 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2751 if (myRaytraceParameters.AdaptiveScreenSampling)
2753 #if !defined(GL_ES_VERSION_2_0)
2754 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
2755 myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2756 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
2757 myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2759 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageLft,
2760 myRaytraceVisualErrorTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2761 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageRgh,
2762 myRaytraceVisualErrorTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2763 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageLft,
2764 myRaytraceTileOffsetsTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2765 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageRgh,
2766 myRaytraceTileOffsetsTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2770 if (!myTextureEnv.IsNull()
2771 && !myTextureEnv->IsEmpty()
2772 && myTextureEnv->First()->IsValid())
2774 myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
2777 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2778 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2779 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2780 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2781 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2782 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2783 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2784 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2785 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2786 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2789 // =======================================================================
2790 // function : unbindRaytraceTextures
2791 // purpose : Unbinds ray-trace textures from corresponding texture units
2792 // =======================================================================
2793 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2795 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2796 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2797 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2798 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2799 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2800 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2801 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2802 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2803 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2804 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2806 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2809 // =======================================================================
2810 // function : runRaytraceShaders
2811 // purpose : Runs ray-tracing shader programs
2812 // =======================================================================
2813 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2814 const Standard_Integer theSizeY,
2815 Graphic3d_Camera::Projection theProjection,
2816 OpenGl_FrameBuffer* theReadDrawFbo,
2817 const Handle(OpenGl_Context)& theGlContext)
2819 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2821 aResult &= setUniformState (0,
2827 if (myRaytraceParameters.GlobalIllumination) // path tracing
2829 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2831 else // Whitted-style ray-tracing
2833 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2839 // =======================================================================
2840 // function : runRaytrace
2841 // purpose : Runs Whitted-style ray-tracing
2842 // =======================================================================
2843 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2844 const Standard_Integer theSizeY,
2845 Graphic3d_Camera::Projection theProjection,
2846 OpenGl_FrameBuffer* theReadDrawFbo,
2847 const Handle(OpenGl_Context)& theGlContext)
2849 Standard_Boolean aResult = Standard_True;
2851 bindRaytraceTextures (theGlContext);
2853 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2854 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2856 // Choose proper set of frame buffers for stereo rendering
2857 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2859 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2861 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2863 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2866 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2868 if (myRenderParams.IsAntialiasingEnabled)
2870 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2872 // bind ray-tracing output image as input
2873 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2875 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2877 aResult &= setUniformState (1 /* FSAA ID */,
2883 // Perform multi-pass adaptive FSAA using ping-pong technique.
2884 // We use 'FLIPTRI' sampling pattern changing for every pixel
2885 // (3 additional samples per pixel, the 1st sample is already
2886 // available from initial ray-traced image).
2887 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2889 GLfloat aOffsetX = 1.f / theSizeX;
2890 GLfloat aOffsetY = 1.f / theSizeY;
2908 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2909 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2910 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2911 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2912 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2913 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2915 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2916 ? myRaytraceFBO2[aFBOIdx]
2917 : myRaytraceFBO1[aFBOIdx];
2919 aFramebuffer->BindBuffer (theGlContext);
2921 // perform adaptive FSAA pass
2922 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2924 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2927 aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2928 aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2930 glEnable (GL_DEPTH_TEST);
2932 // Display filtered image
2933 theGlContext->BindProgram (myOutImageProgram);
2935 if (theReadDrawFbo != NULL)
2937 theReadDrawFbo->BindBuffer (theGlContext);
2941 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2944 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2945 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2947 // copy the output image with depth values
2948 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2950 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2951 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2954 unbindRaytraceTextures (theGlContext);
2956 theGlContext->BindProgram (NULL);
2961 // =======================================================================
2962 // function : runPathtrace
2963 // purpose : Runs path tracing shader
2964 // =======================================================================
2965 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2966 const Standard_Integer theSizeY,
2967 const Graphic3d_Camera::Projection theProjection,
2968 OpenGl_FrameBuffer* theReadDrawFbo,
2969 const Handle(OpenGl_Context)& theGlContext)
2971 Standard_Boolean aResult = Standard_True;
2973 if (myToUpdateEnvironmentMap) // check whether the map was changed
2975 myAccumFrames = myToUpdateEnvironmentMap = 0;
2978 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2979 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2982 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2983 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2988 // Choose proper set of frame buffers for stereo rendering
2989 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2991 if (myRaytraceParameters.AdaptiveScreenSampling)
2993 if (myAccumFrames == 0)
2995 myTileSampler.Reset(); // reset tile sampler to its initial state
2997 // Adaptive sampling is starting at the second frame
2998 myTileSampler.Upload (theGlContext,
2999 myRaytraceTileOffsetsTexture[aFBOIdx],
3000 myRaytraceParameters.NbTilesX,
3001 myRaytraceParameters.NbTilesY,
3006 bindRaytraceTextures (theGlContext);
3008 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
3009 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
3010 Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
3012 const Standard_Integer anImageId = (aFBOIdx != 0)
3013 ? OpenGl_RT_OutputImageRgh
3014 : OpenGl_RT_OutputImageLft;
3016 const Standard_Integer anErrorId = (aFBOIdx != 0)
3017 ? OpenGl_RT_VisualErrorImageRgh
3018 : OpenGl_RT_VisualErrorImageLft;
3020 const Standard_Integer anOffsetId = (aFBOIdx != 0)
3021 ? OpenGl_RT_TileOffsetsImageRgh
3022 : OpenGl_RT_TileOffsetsImageLft;
3024 aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3025 anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
3027 aDepthSourceFramebuffer = aRenderImageFramebuffer;
3029 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3031 aRenderImageFramebuffer->BindBuffer (theGlContext);
3033 if (myAccumFrames == 0)
3035 myRNG.SetSeed(); // start RNG from beginning
3038 // Clear adaptive screen sampling images
3039 if (myRaytraceParameters.AdaptiveScreenSampling)
3041 #if !defined(GL_ES_VERSION_2_0)
3042 if (myAccumFrames == 0 || (myAccumFrames == 1 && myCamera->IsStereo()))
3044 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
3047 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
3051 // Set frame accumulation weight
3052 myRaytraceProgram->SetUniform (theGlContext,
3053 myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
3055 // Set random number generator seed
3056 myRaytraceProgram->SetUniform (theGlContext,
3057 myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3059 // Set image uniforms for render program
3060 myRaytraceProgram->SetUniform (theGlContext,
3061 myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
3062 myRaytraceProgram->SetUniform (theGlContext,
3063 myUniformLocations[0][OpenGl_RT_uOffsetImage], anOffsetId);
3065 glDisable (GL_DEPTH_TEST);
3067 if (myRaytraceParameters.AdaptiveScreenSampling
3068 && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3072 myTileSampler.TileSize() * myRaytraceParameters.NbTilesX,
3073 myTileSampler.TileSize() * myRaytraceParameters.NbTilesY);
3076 // Generate for the given RNG seed
3077 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3079 if (myRaytraceParameters.AdaptiveScreenSampling
3080 && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3088 // Output accumulated path traced image
3089 theGlContext->BindProgram (myOutImageProgram);
3091 if (myRaytraceParameters.AdaptiveScreenSampling)
3093 // Set uniforms for display program
3094 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", anImageId);
3095 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
3096 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", anErrorId);
3097 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3100 if (myRaytraceParameters.GlobalIllumination)
3102 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3103 switch (myRaytraceParameters.ToneMappingMethod)
3105 case Graphic3d_ToneMappingMethod_Disabled:
3107 case Graphic3d_ToneMappingMethod_Filmic:
3108 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3113 if (theReadDrawFbo != NULL)
3115 theReadDrawFbo->BindBuffer (theGlContext);
3119 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3122 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3124 glEnable (GL_DEPTH_TEST);
3126 // Copy accumulated image with correct depth values
3127 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3129 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3131 if (myRaytraceParameters.AdaptiveScreenSampling)
3133 myRaytraceVisualErrorTexture[aFBOIdx]->Bind (theGlContext);
3135 // Download visual error map from the GPU and build
3136 // adjusted tile offsets for optimal image sampling
3137 myTileSampler.GrabVarianceMap (theGlContext);
3139 myTileSampler.Upload (theGlContext,
3140 myRaytraceTileOffsetsTexture[aFBOIdx],
3141 myRaytraceParameters.NbTilesX,
3142 myRaytraceParameters.NbTilesY,
3146 unbindRaytraceTextures (theGlContext);
3148 theGlContext->BindProgram (NULL);
3153 // =======================================================================
3154 // function : raytrace
3155 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3156 // =======================================================================
3157 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3158 const Standard_Integer theSizeY,
3159 Graphic3d_Camera::Projection theProjection,
3160 OpenGl_FrameBuffer* theReadDrawFbo,
3161 const Handle(OpenGl_Context)& theGlContext)
3163 if (!initRaytraceResources (theGlContext))
3165 return Standard_False;
3168 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3170 return Standard_False;
3173 OpenGl_Mat4 aLightSourceMatrix;
3175 // Get inversed model-view matrix for transforming lights
3176 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3178 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3180 return Standard_False;
3183 // Generate image using Whitted-style ray-tracing or path tracing
3184 if (myIsRaytraceDataValid)
3186 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3188 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3190 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3191 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3194 glDisable (GL_BLEND);
3196 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3204 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3205 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3208 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3210 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3211 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3214 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3217 return Standard_True;