1 // Created on: 2013-08-27
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2013 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_Workspace.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_FrameBuffer.hxx>
20 #include <OpenGl_PrimitiveArray.hxx>
21 #include <OpenGl_VertexBuffer.hxx>
22 #include <OpenGl_View.hxx>
23 #include <OSD_File.hxx>
24 #include <OSD_Protection.hxx>
26 using namespace OpenGl_Raytrace;
28 //! Use this macro to output ray-tracing debug info
29 // #define RAY_TRACE_PRINT_INFO
31 #ifdef RAY_TRACE_PRINT_INFO
32 #include <OSD_Timer.hxx>
35 // =======================================================================
36 // function : UpdateRaytraceGeometry
37 // purpose : Updates 3D scene geometry for ray tracing
38 // =======================================================================
39 Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (GeomUpdateMode theMode)
42 return Standard_False;
44 // Note: In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for modifications
45 // This is light-weight procedure performed for each frame
47 if (theMode == OpenGl_GUM_CHECK)
49 if (myLayersModificationStatus != myView->LayerList().ModificationState())
51 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
54 else if (theMode == OpenGl_GUM_PREPARE)
56 myRaytraceGeometry.ClearMaterials();
57 myArrayToTrianglesMap.clear();
59 myIsRaytraceDataValid = Standard_False;
62 // The set of processed structures (reflected to ray-tracing)
63 // This set is used to remove out-of-date records from the
64 // hash map of structures
65 std::set<const OpenGl_Structure*> anElements;
67 // Set of all currently visible and "raytracable" primitive arrays.
68 std::set<Standard_Size> anArrayIDs;
70 const OpenGl_LayerList& aList = myView->LayerList();
72 for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
74 const OpenGl_PriorityList& aPriorityList = anLayerIt.Value().PriorityList();
76 if (aPriorityList.NbStructures() == 0)
79 const OpenGl_ArrayOfStructure& aStructArray = aPriorityList.ArrayOfStructures();
81 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
83 OpenGl_SequenceOfStructure::Iterator aStructIt;
85 for (aStructIt.Init (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
87 const OpenGl_Structure* aStructure = aStructIt.Value();
89 if (theMode == OpenGl_GUM_CHECK)
91 if (CheckRaytraceStructure (aStructure))
93 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
96 else if (theMode == OpenGl_GUM_PREPARE)
98 if (!aStructure->IsRaytracable()
99 || !aStructure->IsVisible())
102 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
104 // OpenGL elements from group (extract primitives arrays)
105 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
107 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
109 if (aPrimArray != NULL)
111 // Collect all primitive arrays in scene.
112 anArrayIDs.insert (aPrimArray->GetUID());
117 else if (theMode == OpenGl_GUM_UPDATE)
119 if (!aStructure->IsRaytracable())
122 AddRaytraceStructure (aStructure, anElements);
128 if (theMode == OpenGl_GUM_PREPARE)
130 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
132 // Leave only unchanged objects in myRaytraceGeometry so only their transforms and materials will be updated
133 // Objects which not in myArrayToTrianglesMap will be built from scratch.
134 for (Standard_Integer anObjectIdx = 0; anObjectIdx < myRaytraceGeometry.Objects().Size(); ++anObjectIdx)
136 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
137 myRaytraceGeometry.Objects().ChangeValue (anObjectIdx).operator->());
139 // If primitive array of object not in "anArrays" set then it was hided or deleted.
140 // If primitive array present in "anArrays" set but we don't have associated object yet, then
141 // the object is new and still has to be built.
142 if ((aTriangleSet != NULL) && ((anArrayIDs.find (aTriangleSet->AssociatedPArrayID())) != anArrayIDs.end()))
144 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjectIdx));
146 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
150 myRaytraceGeometry.Objects() = anUnchangedObjects;
152 return UpdateRaytraceGeometry (OpenGl_GUM_UPDATE);
155 if (theMode == OpenGl_GUM_UPDATE)
157 // Actualize the hash map of structures -- remove out-of-date records
158 std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
160 while (anIter != myStructureStates.end())
162 if (anElements.find (anIter->first) == anElements.end())
164 myStructureStates.erase (anIter++);
172 // Actualize OpenGL layer list state
173 myLayersModificationStatus = myView->LayerList().ModificationState();
175 // Rebuild bottom-level and high-level BVHs
176 myRaytraceGeometry.ProcessAcceleration();
178 const Standard_ShortReal aMinRadius = Max (fabs (myRaytraceGeometry.Box().CornerMin().x()), Max (
179 fabs (myRaytraceGeometry.Box().CornerMin().y()), fabs (myRaytraceGeometry.Box().CornerMin().z())));
180 const Standard_ShortReal aMaxRadius = Max (fabs (myRaytraceGeometry.Box().CornerMax().x()), Max (
181 fabs (myRaytraceGeometry.Box().CornerMax().y()), fabs (myRaytraceGeometry.Box().CornerMax().z())));
183 myRaytraceSceneRadius = 2.f /* scale factor */ * Max (aMinRadius, aMaxRadius);
185 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
187 myRaytraceSceneEpsilon = Max (1e-6f, 1e-4f * sqrtf (
188 aSize.x() * aSize.x() + aSize.y() * aSize.y() + aSize.z() * aSize.z()));
190 return UploadRaytraceData();
193 return Standard_True;
196 // =======================================================================
197 // function : CheckRaytraceStructure
198 // purpose : Checks to see if the structure is modified
199 // =======================================================================
200 Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
202 if (!theStructure->IsRaytracable())
204 // Checks to see if all ray-tracable elements were
205 // removed from the structure
206 if (theStructure->ModificationState() > 0)
208 theStructure->ResetModificationState();
209 return Standard_True;
212 return Standard_False;
215 std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
217 if (aStructState != myStructureStates.end())
218 return aStructState->second != theStructure->ModificationState();
220 return Standard_True;
223 // =======================================================================
224 // function : BuildTexTransform
225 // purpose : Constructs texture transformation matrix
226 // =======================================================================
227 void BuildTexTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
229 theMatrix.InitIdentity();
232 const Graphic3d_Vec2& aScale = theParams->Scale();
234 theMatrix.ChangeValue (0, 0) *= aScale.x();
235 theMatrix.ChangeValue (1, 0) *= aScale.x();
236 theMatrix.ChangeValue (2, 0) *= aScale.x();
237 theMatrix.ChangeValue (3, 0) *= aScale.x();
239 theMatrix.ChangeValue (0, 1) *= aScale.y();
240 theMatrix.ChangeValue (1, 1) *= aScale.y();
241 theMatrix.ChangeValue (2, 1) *= aScale.y();
242 theMatrix.ChangeValue (3, 1) *= aScale.y();
245 const Graphic3d_Vec2 aTrans = -theParams->Translation();
247 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
248 theMatrix.GetValue (0, 1) * aTrans.y();
250 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
251 theMatrix.GetValue (1, 1) * aTrans.y();
253 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
254 theMatrix.GetValue (2, 1) * aTrans.y();
257 const Standard_ShortReal aSin = std::sin (
258 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
259 const Standard_ShortReal aCos = std::cos (
260 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
262 BVH_Mat4f aRotationMat;
263 aRotationMat.SetValue (0, 0, aCos);
264 aRotationMat.SetValue (1, 1, aCos);
265 aRotationMat.SetValue (0, 1, -aSin);
266 aRotationMat.SetValue (1, 0, aSin);
268 theMatrix = theMatrix * aRotationMat;
271 // =======================================================================
272 // function : CreateMaterial
273 // purpose : Creates ray-tracing material properties
274 // =======================================================================
275 Standard_Boolean OpenGl_Workspace::CreateMaterial (const OpenGl_AspectFace* theAspect, OpenGl_RaytraceMaterial& theMaterial)
277 const OPENGL_SURF_PROP& aProperties = theAspect->IntFront();
279 const Standard_ShortReal* aSrcAmbient =
280 aProperties.isphysic ? aProperties.ambcol.rgb : aProperties.matcol.rgb;
282 theMaterial.Ambient = BVH_Vec4f (aSrcAmbient[0] * aProperties.amb,
283 aSrcAmbient[1] * aProperties.amb,
284 aSrcAmbient[2] * aProperties.amb,
287 const Standard_ShortReal* aSrcDiffuse =
288 aProperties.isphysic ? aProperties.difcol.rgb : aProperties.matcol.rgb;
290 theMaterial.Diffuse = BVH_Vec4f (aSrcDiffuse[0] * aProperties.diff,
291 aSrcDiffuse[1] * aProperties.diff,
292 aSrcDiffuse[2] * aProperties.diff,
293 -1.f /* no texture */);
295 theMaterial.Specular = BVH_Vec4f (
296 (aProperties.isphysic ? aProperties.speccol.rgb[0] : 1.f) * aProperties.spec,
297 (aProperties.isphysic ? aProperties.speccol.rgb[1] : 1.f) * aProperties.spec,
298 (aProperties.isphysic ? aProperties.speccol.rgb[2] : 1.f) * aProperties.spec,
301 const Standard_ShortReal* aSrcEmission =
302 aProperties.isphysic ? aProperties.emscol.rgb : aProperties.matcol.rgb;
304 theMaterial.Emission = BVH_Vec4f (aSrcEmission[0] * aProperties.emsv,
305 aSrcEmission[1] * aProperties.emsv,
306 aSrcEmission[2] * aProperties.emsv,
309 // Note: Here we use sub-linear transparency function
310 // to produce realistic-looking transparency effect
311 theMaterial.Transparency = BVH_Vec4f (powf (aProperties.trans, 0.75f),
312 1.f - aProperties.trans,
313 aProperties.index == 0 ? 1.f : aProperties.index,
314 aProperties.index == 0 ? 1.f : 1.f / aProperties.index);
316 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
317 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
318 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
320 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
322 theMaterial.Reflection = BVH_Vec4f (
323 aProperties.speccol.rgb[0] * aProperties.spec * aReflectionScale,
324 aProperties.speccol.rgb[1] * aProperties.spec * aReflectionScale,
325 aProperties.speccol.rgb[2] * aProperties.spec * aReflectionScale,
328 if (theAspect->DoTextureMap())
330 if (myGlContext->arbTexBindless != NULL)
332 BuildTexTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
333 theMaterial.Diffuse.w() = static_cast<Standard_ShortReal> (
334 myRaytraceGeometry.AddTexture (theAspect->TextureRes (myGlContext)));
336 else if (!myIsRaytraceWarnTextures)
338 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
339 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
340 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
341 "Textures will be ignored.");
342 myIsRaytraceWarnTextures = Standard_True;
346 return Standard_True;
349 // =======================================================================
350 // function : AddRaytraceStructure
351 // purpose : Adds OpenGL structure to ray-traced scene geometry
352 // =======================================================================
353 Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure, std::set<const OpenGl_Structure*>& theElements)
355 theElements.insert (theStructure);
357 if (!theStructure->IsVisible())
359 myStructureStates[theStructure] = theStructure->ModificationState();
360 return Standard_True;
363 // Get structure material
364 Standard_Integer aStructMatID = -1;
366 if (theStructure->AspectFace() != NULL)
368 aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
370 OpenGl_RaytraceMaterial aStructMaterial;
371 CreateMaterial (theStructure->AspectFace(), aStructMaterial);
373 myRaytraceGeometry.Materials.push_back (aStructMaterial);
376 Standard_ShortReal aStructTransformArr[16];
377 Standard_ShortReal* aStructTransform = NULL;
378 if (theStructure->Transformation()->mat != NULL)
380 aStructTransform = aStructTransformArr;
381 for (Standard_Integer i = 0; i < 4; ++i)
383 for (Standard_Integer j = 0; j < 4; ++j)
385 aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
390 AddRaytraceGroups (theStructure, aStructMatID, aStructTransform);
392 // Process all connected OpenGL structures
393 for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
395 if (anIts.Value()->IsRaytracable())
396 AddRaytraceGroups (anIts.Value(), aStructMatID, aStructTransform);
399 myStructureStates[theStructure] = theStructure->ModificationState();
400 return Standard_True;
403 // =======================================================================
404 // function : AddRaytraceGroups
405 // purpose : Adds OpenGL groups to ray-traced scene geometry
406 // =======================================================================
407 Standard_Boolean OpenGl_Workspace::AddRaytraceGroups (const OpenGl_Structure* theStructure,
408 const Standard_Integer theStructMatId,
409 const Standard_ShortReal* theTransform)
411 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
413 // Get group material
414 Standard_Integer aGroupMatID = -1;
415 if (aGroupIter.Value()->AspectFace() != NULL)
417 aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
419 OpenGl_RaytraceMaterial aGroupMaterial;
420 CreateMaterial (aGroupIter.Value()->AspectFace(), aGroupMaterial);
422 myRaytraceGeometry.Materials.push_back (aGroupMaterial);
425 Standard_Integer aMatID = aGroupMatID < 0 ? theStructMatId : aGroupMatID;
429 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
431 myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
434 // Add OpenGL elements from group (extract primitives arrays and aspects)
435 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
437 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
438 if (anAspect != NULL)
440 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
442 OpenGl_RaytraceMaterial aMaterial;
443 CreateMaterial (anAspect, aMaterial);
445 myRaytraceGeometry.Materials.push_back (aMaterial);
449 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
451 if (aPrimArray != NULL)
453 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
455 if (aSetIter != myArrayToTrianglesMap.end())
457 OpenGl_TriangleSet* aSet = aSetIter->second;
459 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
461 if (theTransform != NULL)
463 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
466 aSet->SetProperties (aTransform);
468 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
470 aSet->SetMaterialIndex (aMatID);
475 NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
476 AddRaytracePrimitiveArray (aPrimArray, aMatID, 0);
480 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
482 if (theTransform != NULL)
484 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
487 aSet->SetProperties (aTransform);
489 myRaytraceGeometry.Objects().Append (aSet);
497 return Standard_True;
500 // =======================================================================
501 // function : AddRaytracePrimitiveArray
502 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
503 // =======================================================================
504 OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
505 Standard_Integer theMatID,
506 const OpenGl_Mat4* theTransform)
508 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
509 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
510 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
511 if (theArray->DrawMode() < GL_TRIANGLES
512 #if !defined(GL_ES_VERSION_2_0)
513 || theArray->DrawMode() > GL_POLYGON
515 || theArray->DrawMode() > GL_TRIANGLE_FAN
517 || anAttribs.IsNull())
522 #ifdef RAY_TRACE_PRINT_INFO
523 switch (theArray->DrawMode())
525 case GL_TRIANGLES: std::cout << "\tAdding GL_TRIANGLES\n"; break;
526 case GL_TRIANGLE_FAN: std::cout << "\tAdding GL_TRIANGLE_FAN\n"; break;
527 case GL_TRIANGLE_STRIP: std::cout << "\tAdding GL_TRIANGLE_STRIP\n"; break;
528 #if !defined(GL_ES_VERSION_2_0)
529 case GL_QUADS: std::cout << "\tAdding GL_QUADS\n"; break;
530 case GL_QUAD_STRIP: std::cout << "\tAdding GL_QUAD_STRIP\n"; break;
531 case GL_POLYGON: std::cout << "\tAdding GL_POLYGON\n"; break;
536 OpenGl_Mat4 aNormalMatrix;
538 if (theTransform != NULL)
540 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
541 "Error: Failed to compute normal transformation matrix", NULL);
543 aNormalMatrix.Transpose();
546 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
548 aSet->Vertices.reserve (anAttribs->NbElements);
549 aSet->Normals .reserve (anAttribs->NbElements);
550 aSet->TexCrds .reserve (anAttribs->NbElements);
552 const size_t aVertFrom = aSet->Vertices.size();
553 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
555 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
556 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
557 if (anAttrib.Id == Graphic3d_TOA_POS)
559 if (anAttrib.DataType == Graphic3d_TOD_VEC3
560 || anAttrib.DataType == Graphic3d_TOD_VEC4)
562 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
564 aSet->Vertices.push_back (
565 *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
568 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
570 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
572 const Graphic3d_Vec2& aVert = *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset);
573 aSet->Vertices.push_back (BVH_Vec3f (aVert.x(), aVert.y(), 0.0f));
577 else if (anAttrib.Id == Graphic3d_TOA_NORM)
579 if (anAttrib.DataType == Graphic3d_TOD_VEC3
580 || anAttrib.DataType == Graphic3d_TOD_VEC4)
582 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
584 aSet->Normals.push_back (
585 *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
589 else if (anAttrib.Id == Graphic3d_TOA_UV)
591 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
593 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
595 aSet->TexCrds.push_back (
596 *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset));
602 if (aSet->Normals.size() != aSet->Vertices.size())
604 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
606 aSet->Normals.push_back (BVH_Vec3f());
610 if (aSet->TexCrds.size() != aSet->Vertices.size())
612 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
614 aSet->TexCrds.push_back (BVH_Vec2f());
618 if (theTransform != NULL)
620 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
622 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
624 BVH_Vec4f aTransVertex =
625 *theTransform * BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
627 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
629 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
631 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
633 BVH_Vec4f aTransNormal =
634 aNormalMatrix * BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
636 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
640 if (!aBounds.IsNull())
642 #ifdef RAY_TRACE_PRINT_INFO
643 std::cout << "\tNumber of bounds = " << aBounds->NbBounds << std::endl;
646 Standard_Integer aBoundStart = 0;
647 for (Standard_Integer aBound = 0; aBound < aBounds->NbBounds; ++aBound)
649 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
651 #ifdef RAY_TRACE_PRINT_INFO
652 std::cout << "\tAdding indices from bound " << aBound << ": " <<
653 aBoundStart << " .. " << aVertNum << std::endl;
656 if (!AddRaytraceVertexIndices (*aSet, *theArray, aBoundStart, aVertNum, theMatID))
662 aBoundStart += aVertNum;
667 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
669 #ifdef RAY_TRACE_PRINT_INFO
670 std::cout << "\tAdding indices from array: " << aVertNum << std::endl;
673 if (!AddRaytraceVertexIndices (*aSet, *theArray, 0, aVertNum, theMatID))
681 if (aSet->Size() != 0)
687 // =======================================================================
688 // function : AddRaytraceVertexIndices
689 // purpose : Adds vertex indices to ray-traced scene geometry
690 // =======================================================================
691 Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
692 const OpenGl_PrimitiveArray& theArray,
693 Standard_Integer theOffset,
694 Standard_Integer theCount,
695 Standard_Integer theMatID)
697 switch (theArray.DrawMode())
699 case GL_TRIANGLES: return AddRaytraceTriangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
700 case GL_TRIANGLE_FAN: return AddRaytraceTriangleFanArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
701 case GL_TRIANGLE_STRIP: return AddRaytraceTriangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
702 #if !defined(GL_ES_VERSION_2_0)
703 case GL_QUADS: return AddRaytraceQuadrangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
704 case GL_QUAD_STRIP: return AddRaytraceQuadrangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
705 case GL_POLYGON: return AddRaytracePolygonArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
708 return Standard_False;
711 // =======================================================================
712 // function : AddRaytraceTriangleArray
713 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
714 // =======================================================================
715 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
716 const Handle(Graphic3d_IndexBuffer)& theIndices,
717 Standard_Integer theOffset,
718 Standard_Integer theCount,
719 Standard_Integer theMatID)
722 return Standard_True;
724 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
726 if (!theIndices.IsNull())
728 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
730 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
731 theIndices->Index (aVert + 1),
732 theIndices->Index (aVert + 2),
738 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
740 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
745 return Standard_True;
748 // =======================================================================
749 // function : AddRaytraceTriangleFanArray
750 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
751 // =======================================================================
752 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
753 const Handle(Graphic3d_IndexBuffer)& theIndices,
754 Standard_Integer theOffset,
755 Standard_Integer theCount,
756 Standard_Integer theMatID)
759 return Standard_True;
761 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
763 if (!theIndices.IsNull())
765 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
767 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
768 theIndices->Index (aVert + 1),
769 theIndices->Index (aVert + 2),
775 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
777 theSet.Elements.push_back (BVH_Vec4i (theOffset,
784 return Standard_True;
787 // =======================================================================
788 // function : AddRaytraceTriangleStripArray
789 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
790 // =======================================================================
791 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
792 const Handle(Graphic3d_IndexBuffer)& theIndices,
793 Standard_Integer theOffset,
794 Standard_Integer theCount,
795 Standard_Integer theMatID)
798 return Standard_True;
800 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
802 if (!theIndices.IsNull())
804 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
806 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
807 theIndices->Index (aVert + aCW ? 0 : 1),
808 theIndices->Index (aVert + 2),
814 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
816 theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
823 return Standard_True;
826 // =======================================================================
827 // function : AddRaytraceQuadrangleArray
828 // purpose : Adds OpenGL quad array to ray-traced scene geometry
829 // =======================================================================
830 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
831 const Handle(Graphic3d_IndexBuffer)& theIndices,
832 Standard_Integer theOffset,
833 Standard_Integer theCount,
834 Standard_Integer theMatID)
837 return Standard_True;
839 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
841 if (!theIndices.IsNull())
843 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
845 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
846 theIndices->Index (aVert + 1),
847 theIndices->Index (aVert + 2),
849 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
850 theIndices->Index (aVert + 2),
851 theIndices->Index (aVert + 3),
857 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
859 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
861 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
866 return Standard_True;
869 // =======================================================================
870 // function : AddRaytraceQuadrangleStripArray
871 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
872 // =======================================================================
873 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
874 const Handle(Graphic3d_IndexBuffer)& theIndices,
875 Standard_Integer theOffset,
876 Standard_Integer theCount,
877 Standard_Integer theMatID)
880 return Standard_True;
882 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
884 if (!theIndices.IsNull())
886 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
888 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
889 theIndices->Index (aVert + 1),
890 theIndices->Index (aVert + 2),
893 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
894 theIndices->Index (aVert + 3),
895 theIndices->Index (aVert + 2),
901 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
903 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
908 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
915 return Standard_True;
918 // =======================================================================
919 // function : AddRaytracePolygonArray
920 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
921 // =======================================================================
922 Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet& theSet,
923 const Handle(Graphic3d_IndexBuffer)& theIndices,
924 Standard_Integer theOffset,
925 Standard_Integer theCount,
926 Standard_Integer theMatID)
929 return Standard_True;
931 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
933 if (!theIndices.IsNull())
935 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
937 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
938 theIndices->Index (aVert + 1),
939 theIndices->Index (aVert + 2),
945 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
947 theSet.Elements.push_back (BVH_Vec4i (theOffset,
954 return Standard_True;
957 // =======================================================================
958 // function : UpdateRaytraceLightSources
959 // purpose : Updates 3D scene light sources for ray-tracing
960 // =======================================================================
961 Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const OpenGl_Mat4& theInvModelView)
963 myRaytraceGeometry.Sources.clear();
965 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
967 for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
969 const OpenGl_Light& aLight = anItl.Value();
971 if (aLight.Type == Visual3d_TOLS_AMBIENT)
973 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
980 BVH_Vec4f aDiffuse (aLight.Color.r(),
985 BVH_Vec4f aPosition (-aLight.Direction.x(),
986 -aLight.Direction.y(),
987 -aLight.Direction.z(),
990 if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
992 aPosition = BVH_Vec4f (aLight.Position.x(),
998 if (aLight.IsHeadlight)
1000 aPosition = theInvModelView * aPosition;
1003 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
1006 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
1008 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
1010 if (!myRaytraceLightSrcTexture->Create (myGlContext))
1012 #ifdef RAY_TRACE_PRINT_INFO
1013 std::cout << "Error: Failed to create light source buffer" << std::endl;
1015 return Standard_False;
1019 if (myRaytraceGeometry.Sources.size() != 0)
1021 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
1022 if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
1024 #ifdef RAY_TRACE_PRINT_INFO
1025 std::cout << "Error: Failed to upload light source buffer" << std::endl;
1027 return Standard_False;
1031 return Standard_True;
1034 // =======================================================================
1035 // function : UpdateRaytraceEnvironmentMap
1036 // purpose : Updates environment map for ray-tracing
1037 // =======================================================================
1038 Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
1040 if (myView.IsNull())
1041 return Standard_False;
1043 if (myViewModificationStatus == myView->ModificationState())
1044 return Standard_True;
1046 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
1048 const Handle(OpenGl_ShaderProgram)& aProgram =
1049 anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
1051 if (!aProgram.IsNull())
1053 myGlContext->BindProgram (aProgram);
1055 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
1057 myView->TextureEnv()->Bind (
1058 myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
1060 aProgram->SetUniform (myGlContext,
1061 myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 1);
1065 aProgram->SetUniform (myGlContext,
1066 myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 0);
1071 myGlContext->BindProgram (NULL);
1072 myViewModificationStatus = myView->ModificationState();
1073 return Standard_True;
1076 // =======================================================================
1077 // function : Source
1078 // purpose : Returns shader source combined with prefix
1079 // =======================================================================
1080 TCollection_AsciiString OpenGl_Workspace::ShaderSource::Source() const
1082 static const TCollection_AsciiString aVersion = "#version 140";
1084 if (myPrefix.IsEmpty())
1086 return aVersion + "\n" + mySource;
1089 return aVersion + "\n" + myPrefix + "\n" + mySource;
1092 // =======================================================================
1094 // purpose : Loads shader source from specified files
1095 // =======================================================================
1096 void OpenGl_Workspace::ShaderSource::Load (
1097 const TCollection_AsciiString* theFileNames, const Standard_Integer theCount)
1101 for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
1103 OSD_File aFile (theFileNames[anIndex]);
1105 Standard_ASSERT_RETURN (aFile.Exists(),
1106 "Error: Failed to find shader source file", /* none */);
1108 aFile.Open (OSD_ReadOnly, OSD_Protection());
1110 TCollection_AsciiString aSource;
1112 Standard_ASSERT_RETURN (aFile.IsOpen(),
1113 "Error: Failed to open shader source file", /* none */);
1115 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1117 if (!aSource.IsEmpty())
1119 mySource += TCollection_AsciiString ("\n") + aSource;
1126 // =======================================================================
1127 // function : LoadShader
1128 // purpose : Creates new shader object with specified source
1129 // =======================================================================
1130 Handle(OpenGl_ShaderObject) OpenGl_Workspace::LoadShader (const ShaderSource& theSource, GLenum theType)
1132 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1134 if (!aShader->Create (myGlContext))
1136 const TCollection_ExtendedString aMessage = "Error: Failed to create shader object";
1138 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1139 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1141 aShader->Release (myGlContext.operator->());
1143 return Handle(OpenGl_ShaderObject)();
1146 if (!aShader->LoadSource (myGlContext, theSource.Source()))
1148 const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1150 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1151 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1153 aShader->Release (myGlContext.operator->());
1155 return Handle(OpenGl_ShaderObject)();
1158 TCollection_AsciiString aBuildLog;
1160 if (!aShader->Compile (myGlContext))
1162 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1164 const TCollection_ExtendedString aMessage =
1165 TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1167 #ifdef RAY_TRACE_PRINT_INFO
1168 std::cout << aBuildLog << std::endl;
1171 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1172 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1175 aShader->Release (myGlContext.operator->());
1177 return Handle(OpenGl_ShaderObject)();
1180 #ifdef RAY_TRACE_PRINT_INFO
1181 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1183 if (!aBuildLog.IsEmpty())
1185 std::cout << aBuildLog << std::endl;
1189 std::cout << "Info: shader build log is empty" << std::endl;
1197 // =======================================================================
1198 // function : SafeFailBack
1199 // purpose : Performs safe exit when shaders initialization fails
1200 // =======================================================================
1201 Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
1203 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1204 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
1206 myComputeInitStatus = OpenGl_RT_FAIL;
1208 ReleaseRaytraceResources();
1210 return Standard_False;
1213 // =======================================================================
1214 // function : GenerateShaderPrefix
1215 // purpose : Generates shader prefix based on current ray-tracing options
1216 // =======================================================================
1217 TCollection_AsciiString OpenGl_Workspace::GenerateShaderPrefix()
1219 TCollection_AsciiString aPrefixString =
1220 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1221 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1223 if (myRaytraceParameters.TransparentShadows)
1225 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1228 // If OpenGL driver supports bindless textures
1229 // activate texturing in ray-tracing mode
1230 if (myGlContext->arbTexBindless != NULL)
1232 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1233 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1236 return aPrefixString;
1239 // =======================================================================
1240 // function : InitRaytraceResources
1241 // purpose : Initializes OpenGL/GLSL shader programs
1242 // =======================================================================
1243 Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
1245 Standard_Boolean aToRebuildShaders = Standard_False;
1247 if (myComputeInitStatus == OpenGl_RT_INIT)
1249 if (!myIsRaytraceDataValid)
1250 return Standard_True;
1252 const Standard_Integer aRequiredStackSize =
1253 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
1255 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1257 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1259 aToRebuildShaders = Standard_True;
1263 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1265 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1267 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1268 aToRebuildShaders = Standard_True;
1273 if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1275 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1276 aToRebuildShaders = Standard_True;
1279 if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1281 myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1282 aToRebuildShaders = Standard_True;
1285 if (aToRebuildShaders)
1287 #ifdef RAY_TRACE_PRINT_INFO
1288 std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
1291 // Change state to force update all uniforms
1292 ++myViewModificationStatus;
1294 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1296 #ifdef RAY_TRACE_PRINT_INFO
1297 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1300 myRaytraceShaderSource.SetPrefix (aPrefixString);
1301 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1303 if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1304 || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1306 return Standard_False;
1309 if (!myRaytraceShader->Compile (myGlContext)
1310 || !myPostFSAAShader->Compile (myGlContext))
1312 return Standard_False;
1315 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1316 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1317 if (!myRaytraceProgram->Link (myGlContext)
1318 || !myPostFSAAProgram->Link (myGlContext))
1320 return Standard_False;
1325 if (myComputeInitStatus == OpenGl_RT_NONE)
1327 if (!myGlContext->IsGlGreaterEqual (3, 1))
1329 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1330 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1331 "Ray-tracing requires OpenGL 3.1 and higher");
1332 return Standard_False;
1334 else if (!myGlContext->arbTboRGB32)
1336 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1337 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1338 "Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension");
1339 return Standard_False;
1342 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1344 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1346 if (aFolder.IsEmpty())
1348 const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1350 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1351 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1353 return Standard_False;
1356 if (myIsRaytraceDataValid)
1358 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1359 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1362 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1364 #ifdef RAY_TRACE_PRINT_INFO
1365 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1369 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1370 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1372 if (aBasicVertShader.IsNull())
1374 return SafeFailBack ("Failed to set vertex shader source");
1377 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
1379 myRaytraceShaderSource.Load (aFiles, 2);
1381 myRaytraceShaderSource.SetPrefix (aPrefixString);
1383 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
1385 if (myRaytraceShader.IsNull())
1387 aBasicVertShader->Release (myGlContext.operator->());
1389 return SafeFailBack ("Failed to set ray-trace fragment shader source");
1392 myRaytraceProgram = new OpenGl_ShaderProgram;
1394 if (!myRaytraceProgram->Create (myGlContext))
1396 aBasicVertShader->Release (myGlContext.operator->());
1398 return SafeFailBack ("Failed to create ray-trace shader program");
1401 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1402 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1404 aBasicVertShader->Release (myGlContext.operator->());
1406 return SafeFailBack ("Failed to attach ray-trace shader objects");
1409 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1410 if (!myRaytraceProgram->Link (myGlContext))
1412 TCollection_AsciiString aLinkLog;
1414 if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1416 #ifdef RAY_TRACE_PRINT_INFO
1417 std::cout << aLinkLog << std::endl;
1421 return SafeFailBack ("Failed to link ray-trace shader program");
1426 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1427 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1429 if (aBasicVertShader.IsNull())
1431 return SafeFailBack ("Failed to set vertex shader source");
1434 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
1436 myPostFSAAShaderSource.Load (aFiles, 2);
1438 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1440 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
1442 if (myPostFSAAShader.IsNull())
1444 aBasicVertShader->Release (myGlContext.operator->());
1446 return SafeFailBack ("Failed to set FSAA fragment shader source");
1449 myPostFSAAProgram = new OpenGl_ShaderProgram;
1451 if (!myPostFSAAProgram->Create (myGlContext))
1453 aBasicVertShader->Release (myGlContext.operator->());
1455 return SafeFailBack ("Failed to create FSAA shader program");
1458 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1459 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1461 aBasicVertShader->Release (myGlContext.operator->());
1463 return SafeFailBack ("Failed to attach FSAA shader objects");
1466 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1467 if (!myPostFSAAProgram->Link (myGlContext))
1469 TCollection_AsciiString aLinkLog;
1471 if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1473 #ifdef RAY_TRACE_PRINT_INFO
1474 std::cout << aLinkLog << std::endl;
1478 return SafeFailBack ("Failed to link FSAA shader program");
1483 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1485 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1487 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1488 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1490 myGlContext->BindProgram (aShaderProgram);
1492 aShaderProgram->SetSampler (myGlContext,
1493 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1494 aShaderProgram->SetSampler (myGlContext,
1495 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1496 aShaderProgram->SetSampler (myGlContext,
1497 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1498 aShaderProgram->SetSampler (myGlContext,
1499 "uObjectMinPointTexture", OpenGl_RT_ObjectMinPointTexture);
1500 aShaderProgram->SetSampler (myGlContext,
1501 "uObjectMaxPointTexture", OpenGl_RT_ObjectMaxPointTexture);
1502 aShaderProgram->SetSampler (myGlContext,
1503 "uObjectNodeInfoTexture", OpenGl_RT_ObjectNodeInfoTexture);
1504 aShaderProgram->SetSampler (myGlContext,
1505 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1506 aShaderProgram->SetSampler (myGlContext,
1507 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1508 aShaderProgram->SetSampler (myGlContext,
1509 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1510 aShaderProgram->SetSampler (myGlContext,
1511 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1512 aShaderProgram->SetSampler (myGlContext,
1513 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1514 aShaderProgram->SetSampler (myGlContext,
1515 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1516 aShaderProgram->SetSampler (myGlContext,
1517 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1518 aShaderProgram->SetSampler (myGlContext,
1519 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1521 aShaderProgram->SetSampler (myGlContext,
1522 "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1523 aShaderProgram->SetSampler (myGlContext,
1524 "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1528 aShaderProgram->SetSampler (myGlContext,
1529 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1532 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1533 aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
1535 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1536 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1537 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1538 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1539 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1540 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1541 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1542 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1543 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1544 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1545 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1546 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1547 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1548 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1549 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1550 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
1551 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1552 aShaderProgram->GetUniformLocation (myGlContext, "uUnviewMat");
1554 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1555 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1556 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1557 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1558 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1559 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1560 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1561 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1563 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1564 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1565 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1566 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1567 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1568 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
1569 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1570 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeX");
1571 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1572 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeY");
1574 myUniformLocations[anIndex][OpenGl_RT_uTextures] =
1575 aShaderProgram->GetUniformLocation (myGlContext, "uTextureSamplers");
1577 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1578 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1579 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1580 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1581 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnable] =
1582 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
1585 myGlContext->BindProgram (NULL);
1588 if (myComputeInitStatus != OpenGl_RT_NONE)
1590 return myComputeInitStatus == OpenGl_RT_INIT;
1593 if (myRaytraceFBO1.IsNull())
1595 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1598 if (myRaytraceFBO2.IsNull())
1600 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1603 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1610 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
1612 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1614 return Standard_True;
1617 // =======================================================================
1618 // function : NullifyResource
1620 // =======================================================================
1621 inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1622 Handle(OpenGl_Resource)& theResource)
1624 if (!theResource.IsNull())
1626 theResource->Release (theContext.operator->());
1627 theResource.Nullify();
1631 // =======================================================================
1632 // function : ReleaseRaytraceResources
1633 // purpose : Releases OpenGL/GLSL shader programs
1634 // =======================================================================
1635 void OpenGl_Workspace::ReleaseRaytraceResources()
1637 NullifyResource (myGlContext, myOpenGlFBO);
1638 NullifyResource (myGlContext, myRaytraceFBO1);
1639 NullifyResource (myGlContext, myRaytraceFBO2);
1641 NullifyResource (myGlContext, myRaytraceShader);
1642 NullifyResource (myGlContext, myPostFSAAShader);
1644 NullifyResource (myGlContext, myRaytraceProgram);
1645 NullifyResource (myGlContext, myPostFSAAProgram);
1647 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1648 NullifyResource (myGlContext, mySceneMinPointTexture);
1649 NullifyResource (myGlContext, mySceneMaxPointTexture);
1651 NullifyResource (myGlContext, myObjectNodeInfoTexture);
1652 NullifyResource (myGlContext, myObjectMinPointTexture);
1653 NullifyResource (myGlContext, myObjectMaxPointTexture);
1655 NullifyResource (myGlContext, myGeometryVertexTexture);
1656 NullifyResource (myGlContext, myGeometryNormalTexture);
1657 NullifyResource (myGlContext, myGeometryTexCrdTexture);
1658 NullifyResource (myGlContext, myGeometryTriangTexture);
1659 NullifyResource (myGlContext, mySceneTransformTexture);
1661 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1662 NullifyResource (myGlContext, myRaytraceMaterialTexture);
1664 if (myRaytraceScreenQuad.IsValid())
1665 myRaytraceScreenQuad.Release (myGlContext.operator->());
1668 // =======================================================================
1669 // function : UploadRaytraceData
1670 // purpose : Uploads ray-trace data to the GPU
1671 // =======================================================================
1672 Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1674 if (!myGlContext->IsGlGreaterEqual (3, 1))
1676 #ifdef RAY_TRACE_PRINT_INFO
1677 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1679 return Standard_False;
1682 /////////////////////////////////////////////////////////////////////////////
1683 // Prepare OpenGL textures
1685 if (myGlContext->arbTexBindless != NULL)
1687 // If OpenGL driver supports bindless textures we need
1688 // to get unique 64- bit handles for using on the GPU
1689 if (!myRaytraceGeometry.UpdateTextureHandles (myGlContext))
1691 #ifdef RAY_TRACE_PRINT_INFO
1692 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1694 return Standard_False;
1698 /////////////////////////////////////////////////////////////////////////////
1699 // Create OpenGL texture buffers
1701 if (mySceneNodeInfoTexture.IsNull()) // create hight-level BVH buffers
1703 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1704 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1705 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
1706 mySceneTransformTexture = new OpenGl_TextureBufferArb;
1708 if (!mySceneNodeInfoTexture->Create (myGlContext)
1709 || !mySceneMinPointTexture->Create (myGlContext)
1710 || !mySceneMaxPointTexture->Create (myGlContext)
1711 || !mySceneTransformTexture->Create (myGlContext))
1713 #ifdef RAY_TRACE_PRINT_INFO
1714 std::cout << "Error: Failed to create buffers for high-level scene BVH" << std::endl;
1716 return Standard_False;
1720 if (myObjectNodeInfoTexture.IsNull()) // create bottom-level BVH buffers
1722 myObjectNodeInfoTexture = new OpenGl_TextureBufferArb;
1723 myObjectMinPointTexture = new OpenGl_TextureBufferArb;
1724 myObjectMaxPointTexture = new OpenGl_TextureBufferArb;
1726 if (!myObjectNodeInfoTexture->Create (myGlContext)
1727 || !myObjectMinPointTexture->Create (myGlContext)
1728 || !myObjectMaxPointTexture->Create (myGlContext))
1730 #ifdef RAY_TRACE_PRINT_INFO
1731 std::cout << "Error: Failed to create buffers for bottom-level scene BVH" << std::endl;
1733 return Standard_False;
1737 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
1739 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1740 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1741 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1742 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1744 if (!myGeometryVertexTexture->Create (myGlContext)
1745 || !myGeometryNormalTexture->Create (myGlContext)
1746 || !myGeometryTexCrdTexture->Create (myGlContext)
1747 || !myGeometryTriangTexture->Create (myGlContext))
1749 #ifdef RAY_TRACE_PRINT_INFO
1750 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1752 return Standard_False;
1756 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1758 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1760 if (!myRaytraceMaterialTexture->Create (myGlContext))
1762 #ifdef RAY_TRACE_PRINT_INFO
1763 std::cout << "Error: Failed to create buffers for material data" << std::endl;
1765 return Standard_False;
1769 /////////////////////////////////////////////////////////////////////////////
1770 // Write top-level BVH buffers
1772 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
1774 bool aResult = true;
1775 if (!aBVH->NodeInfoBuffer().empty())
1777 aResult &= mySceneNodeInfoTexture->Init (myGlContext, 4, GLsizei (aBVH->NodeInfoBuffer().size()),
1778 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1779 aResult &= mySceneMinPointTexture->Init (myGlContext, 3, GLsizei (aBVH->MinPointBuffer().size()),
1780 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1781 aResult &= mySceneMaxPointTexture->Init (myGlContext, 3, GLsizei (aBVH->MaxPointBuffer().size()),
1782 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1786 #ifdef RAY_TRACE_PRINT_INFO
1787 std::cout << "Error: Failed to upload buffers for high-level scene BVH" << std::endl;
1789 return Standard_False;
1792 /////////////////////////////////////////////////////////////////////////////
1793 // Write transform buffer
1795 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1797 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1799 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1800 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1802 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1803 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1805 Standard_ASSERT_RETURN (aTransform != NULL,
1806 "OpenGl_TriangleSet does not contain transform", Standard_False);
1808 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1811 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1812 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1814 delete [] aNodeTransforms;
1816 /////////////////////////////////////////////////////////////////////////////
1817 // Write geometry and bottom-level BVH buffers
1819 Standard_Size aTotalVerticesNb = 0;
1820 Standard_Size aTotalElementsNb = 0;
1821 Standard_Size aTotalBVHNodesNb = 0;
1823 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1825 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1826 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1828 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1829 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1831 aTotalVerticesNb += aTriangleSet->Vertices.size();
1832 aTotalElementsNb += aTriangleSet->Elements.size();
1834 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1835 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
1837 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1840 if (aTotalBVHNodesNb != 0)
1842 aResult &= myObjectNodeInfoTexture->Init (
1843 myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1844 aResult &= myObjectMinPointTexture->Init (
1845 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1846 aResult &= myObjectMaxPointTexture->Init (
1847 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1852 #ifdef RAY_TRACE_PRINT_INFO
1853 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1855 return Standard_False;
1858 if (aTotalElementsNb != 0)
1860 aResult &= myGeometryTriangTexture->Init (
1861 myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
1864 if (aTotalVerticesNb != 0)
1866 aResult &= myGeometryVertexTexture->Init (
1867 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1868 aResult &= myGeometryNormalTexture->Init (
1869 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1870 aResult &= myGeometryTexCrdTexture->Init (
1871 myGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1876 #ifdef RAY_TRACE_PRINT_INFO
1877 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1879 return Standard_False;
1882 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1884 if (!aBVH->IsOuter (aNodeIdx))
1887 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
1889 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1890 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1892 const Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
1894 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1895 "Error: Failed to get offset for bottom-level BVH", Standard_False);
1897 const size_t aBVHBuffserSize = aTriangleSet->BVH()->NodeInfoBuffer().size();
1899 if (aBVHBuffserSize != 0)
1901 aResult &= myObjectNodeInfoTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1902 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1903 aResult &= myObjectMinPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1904 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1905 aResult &= myObjectMaxPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1906 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
1909 #ifdef RAY_TRACE_PRINT_INFO
1910 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1912 return Standard_False;
1916 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
1918 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1919 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
1921 if (!aTriangleSet->Vertices.empty())
1923 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1924 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1925 aResult &= myGeometryTexCrdTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->TexCrds.size()),
1926 reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
1927 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1928 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
1931 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
1933 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1934 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
1936 if (!aTriangleSet->Elements.empty())
1938 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1939 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
1944 #ifdef RAY_TRACE_PRINT_INFO
1945 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
1947 return Standard_False;
1951 /////////////////////////////////////////////////////////////////////////////
1952 // Write material buffer
1954 if (myRaytraceGeometry.Materials.size() != 0)
1956 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4,
1957 GLsizei (myRaytraceGeometry.Materials.size() * 11), myRaytraceGeometry.Materials.front().Packed());
1961 #ifdef RAY_TRACE_PRINT_INFO
1962 std::cout << "Error: Failed to upload material buffer" << std::endl;
1964 return Standard_False;
1968 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
1970 #ifdef RAY_TRACE_PRINT_INFO
1972 Standard_ShortReal aMemUsed = 0.f;
1974 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1976 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1977 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
1979 aMemUsed += static_cast<Standard_ShortReal> (
1980 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
1981 aMemUsed += static_cast<Standard_ShortReal> (
1982 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
1983 aMemUsed += static_cast<Standard_ShortReal> (
1984 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
1985 aMemUsed += static_cast<Standard_ShortReal> (
1986 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
1988 aMemUsed += static_cast<Standard_ShortReal> (
1989 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1990 aMemUsed += static_cast<Standard_ShortReal> (
1991 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1992 aMemUsed += static_cast<Standard_ShortReal> (
1993 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1996 aMemUsed += static_cast<Standard_ShortReal> (
1997 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1998 aMemUsed += static_cast<Standard_ShortReal> (
1999 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2000 aMemUsed += static_cast<Standard_ShortReal> (
2001 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2003 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
2010 // =======================================================================
2011 // function : ResizeRaytraceBuffers
2012 // purpose : Resizes OpenGL frame buffers
2013 // =======================================================================
2014 Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
2015 const Standard_Integer theSizeY)
2017 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
2018 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
2020 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
2021 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
2024 return Standard_True;
2027 // =======================================================================
2028 // function : UpdateCamera
2029 // purpose : Generates viewing rays for corners of screen quad
2030 // =======================================================================
2031 void OpenGl_Workspace::UpdateCamera (const OpenGl_Mat4& theOrientation,
2032 const OpenGl_Mat4& theViewMapping,
2033 OpenGl_Vec3 theOrigins[4],
2034 OpenGl_Vec3 theDirects[4],
2035 OpenGl_Mat4& theInvModelProj)
2037 // compute inverse model-view-projection matrix
2038 (theViewMapping * theOrientation).Inverted (theInvModelProj);
2040 Standard_Integer aOriginIndex = 0;
2041 Standard_Integer aDirectIndex = 0;
2043 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2045 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2047 OpenGl_Vec4 aOrigin (GLfloat(aX),
2052 aOrigin = theInvModelProj * aOrigin;
2054 aOrigin.x() = aOrigin.x() / aOrigin.w();
2055 aOrigin.y() = aOrigin.y() / aOrigin.w();
2056 aOrigin.z() = aOrigin.z() / aOrigin.w();
2058 OpenGl_Vec4 aDirect (GLfloat(aX),
2063 aDirect = theInvModelProj * aDirect;
2065 aDirect.x() = aDirect.x() / aDirect.w();
2066 aDirect.y() = aDirect.y() / aDirect.w();
2067 aDirect.z() = aDirect.z() / aDirect.w();
2069 aDirect = aDirect - aOrigin;
2071 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
2072 aDirect.y() * aDirect.y() +
2073 aDirect.z() * aDirect.z());
2075 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2076 static_cast<GLfloat> (aOrigin.y()),
2077 static_cast<GLfloat> (aOrigin.z()));
2079 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
2080 static_cast<GLfloat> (aDirect.y() * aInvLen),
2081 static_cast<GLfloat> (aDirect.z() * aInvLen));
2086 // =======================================================================
2087 // function : SetUniformState
2088 // purpose : Sets uniform state for the given ray-tracing shader program
2089 // =======================================================================
2090 Standard_Boolean OpenGl_Workspace::SetUniformState (const Graphic3d_CView& theCView,
2091 const Standard_Integer theSizeX,
2092 const Standard_Integer theSizeY,
2093 const OpenGl_Vec3* theOrigins,
2094 const OpenGl_Vec3* theDirects,
2095 const OpenGl_Mat4& theUnviewMat,
2096 const Standard_Integer theProgramIndex,
2097 Handle(OpenGl_ShaderProgram)& theRaytraceProgram)
2099 if (theRaytraceProgram.IsNull())
2101 return Standard_False;
2104 Standard_Integer aLightSourceBufferSize =
2105 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2107 Standard_Boolean aResult = Standard_True;
2110 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2111 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLB], theOrigins[0]);
2112 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2113 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRB], theOrigins[1]);
2114 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2115 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLT], theOrigins[2]);
2116 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2117 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRT], theOrigins[3]);
2118 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2119 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLB], theDirects[0]);
2120 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2121 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRB], theDirects[1]);
2122 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2123 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLT], theDirects[2]);
2124 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2125 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRT], theDirects[3]);
2126 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2127 myUniformLocations[theProgramIndex][OpenGl_RT_uUnviewMat], theUnviewMat);
2130 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2131 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeX], theSizeX);
2132 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2133 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeY], theSizeY);
2135 // Set scene parameters
2136 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2137 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2138 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2139 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2140 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2141 myUniformLocations[theProgramIndex][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2142 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2143 myUniformLocations[theProgramIndex][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2145 // Set rendering options
2146 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2147 myUniformLocations[theProgramIndex][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
2148 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2149 myUniformLocations[theProgramIndex][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
2151 // Set array of 64-bit texture handles
2152 if (myGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2154 aResult &= theRaytraceProgram->SetUniform (myGlContext, "uTextureSamplers",
2155 static_cast<GLsizei> (myRaytraceGeometry.TextureHandles().size()), &myRaytraceGeometry.TextureHandles()[0]);
2160 #ifdef RAY_TRACE_PRINT_INFO
2161 std::cout << "Info: Not all uniforms were detected (for program " << theProgramIndex << ")" << std::endl;
2168 // =======================================================================
2169 // function : RunRaytraceShaders
2170 // purpose : Runs ray-tracing shader programs
2171 // =======================================================================
2172 Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
2173 const Standard_Integer theSizeX,
2174 const Standard_Integer theSizeY,
2175 const OpenGl_Vec3 theOrigins[4],
2176 const OpenGl_Vec3 theDirects[4],
2177 const OpenGl_Mat4& theUnviewMat,
2178 OpenGl_FrameBuffer* theFrameBuffer)
2180 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2181 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2182 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2183 myObjectMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
2184 myObjectMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
2185 myObjectNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
2186 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2187 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2188 myGeometryTexCrdTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2189 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2190 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2191 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2192 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2194 myOpenGlFBO->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2195 myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2197 if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
2199 myRaytraceFBO1->BindBuffer (myGlContext);
2201 glDisable (GL_BLEND);
2204 myGlContext->BindProgram (myRaytraceProgram);
2206 SetUniformState (theCView,
2212 0, // ID of RT program
2215 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2217 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2218 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2220 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2222 if (!theCView.RenderParams.IsAntialiasingEnabled)
2224 myGlContext->BindProgram (NULL);
2226 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2227 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2228 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2229 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2230 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2231 myObjectMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
2232 myObjectMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
2233 myObjectNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
2234 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2235 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2236 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2237 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2238 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2239 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2240 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2242 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2244 return Standard_True;
2247 myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2249 myGlContext->BindProgram (myPostFSAAProgram);
2251 SetUniformState (theCView,
2257 1, // ID of FSAA program
2260 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2261 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2263 // Perform multi-pass adaptive FSAA using ping-pong technique.
2264 // We use 'FLIPTRI' sampling pattern changing for every pixel
2265 // (3 additional samples per pixel, the 1st sample is already
2266 // available from initial ray-traced image).
2267 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2269 GLfloat aOffsetX = 1.f / theSizeX;
2270 GLfloat aOffsetY = 1.f / theSizeY;
2288 myPostFSAAProgram->SetUniform (myGlContext,
2289 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2290 myPostFSAAProgram->SetUniform (myGlContext,
2291 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2292 myPostFSAAProgram->SetUniform (myGlContext,
2293 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2295 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
2297 if (anIt == 3) // disable FBO on last iteration
2299 glEnable (GL_BLEND);
2301 if (theFrameBuffer != NULL)
2302 theFrameBuffer->BindBuffer (myGlContext);
2306 aFramebuffer->BindBuffer (myGlContext);
2309 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2311 if (anIt != 3) // set input for the next pass
2313 aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2314 aFramebuffer->UnbindBuffer (myGlContext);
2318 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2320 myGlContext->BindProgram (NULL);
2321 myRaytraceFBO1->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2322 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2323 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2324 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2325 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2326 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2327 myObjectMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
2328 myObjectMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
2329 myObjectNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
2330 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2331 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2332 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2333 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2334 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2335 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2336 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2338 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2340 return Standard_True;
2343 // =======================================================================
2344 // function : Raytrace
2345 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2346 // =======================================================================
2347 Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
2348 const Standard_Integer theSizeX,
2349 const Standard_Integer theSizeY,
2350 const Standard_Boolean theToSwap,
2351 const Aspect_CLayer2d& theCOverLayer,
2352 const Aspect_CLayer2d& theCUnderLayer,
2353 OpenGl_FrameBuffer* theFrameBuffer)
2355 if (!InitRaytraceResources (theCView))
2356 return Standard_False;
2358 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
2359 return Standard_False;
2361 if (!UpdateRaytraceEnvironmentMap())
2362 return Standard_False;
2364 // Get model-view and projection matrices
2365 OpenGl_Mat4 aOrientationMatrix;
2366 OpenGl_Mat4 aViewMappingMatrix;
2368 myView->GetMatrices (aOrientationMatrix,
2369 aViewMappingMatrix);
2371 OpenGl_Mat4 aInvOrientationMatrix;
2372 aOrientationMatrix.Inverted (aInvOrientationMatrix);
2374 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
2375 return Standard_False;
2377 OpenGl_Vec3 aOrigins[4];
2378 OpenGl_Vec3 aDirects[4];
2379 OpenGl_Mat4 anUnviewMat;
2381 UpdateCamera (aOrientationMatrix,
2387 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2388 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
2390 glDisable (GL_DEPTH_TEST);
2392 if (theFrameBuffer != NULL)
2394 theFrameBuffer->BindBuffer (myGlContext);
2397 if (NamedStatus & OPENGL_NS_WHITEBACK)
2399 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2403 glClearColor (myBgColor.rgb[0],
2409 glClear (GL_COLOR_BUFFER_BIT);
2411 myView->DrawBackground (*this);
2413 myView->RedrawLayer2d (myPrintContext, this, theCView, theCUnderLayer);
2415 myGlContext->WorldViewState.Push();
2416 myGlContext->ProjectionState.Push();
2418 myGlContext->WorldViewState.SetIdentity();
2419 myGlContext->ProjectionState.SetIdentity();
2421 myGlContext->ApplyProjectionMatrix();
2422 myGlContext->ApplyWorldViewMatrix();
2424 glEnable (GL_BLEND);
2425 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
2427 // Generate ray-traced image
2428 if (myIsRaytraceDataValid)
2430 myRaytraceScreenQuad.Bind (myGlContext);
2432 if (!myRaytraceGeometry.AcquireTextures (myGlContext))
2434 const TCollection_ExtendedString aMessage = "Error: Failed to acquire OpenGL image textures";
2436 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2437 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2440 RunRaytraceShaders (theCView,
2448 if (!myRaytraceGeometry.ReleaseTextures (myGlContext))
2450 const TCollection_ExtendedString aMessage = "Error: Failed to release OpenGL image textures";
2452 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2453 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2456 myRaytraceScreenQuad.Unbind (myGlContext);
2459 if (!wasBlendingEnabled)
2460 glDisable (GL_BLEND);
2462 if (wasDepthTestEnabled)
2463 glEnable (GL_DEPTH_TEST);
2465 myGlContext->WorldViewState.Pop();
2466 myGlContext->ProjectionState.Pop();
2468 myGlContext->ApplyProjectionMatrix();
2471 myView->RedrawTrihedron (this);
2474 const int aMode = 0;
2475 DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
2476 myView->RedrawLayer2d (myPrintContext, this, theCView, theCOverLayer);
2477 DisplayCallback (theCView, aMode);
2482 GetGlContext()->SwapBuffers();
2483 myBackBufferRestored = Standard_False;
2490 return Standard_True;
2493 IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2494 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2496 // =======================================================================
2497 // function : CanRender
2499 // =======================================================================
2500 Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2502 Standard_Boolean aPrevFilterResult = Standard_True;
2503 if (!myPrevRenderFilter.IsNull())
2505 aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2507 return aPrevFilterResult &&
2508 !OpenGl_Raytrace::IsRaytracedElement (theElement);