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 <NCollection_Mat4.hxx>
17 #include <OpenGl_ArbFBO.hxx>
18 #include <OpenGl_FrameBuffer.hxx>
19 #include <OpenGl_Texture.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_View.hxx>
22 #include <OpenGl_Workspace.hxx>
23 #include <OSD_File.hxx>
24 #include <OSD_Protection.hxx>
25 #include <Standard_Assert.hxx>
27 using namespace OpenGl_Raytrace;
29 //! Use this macro to output ray-tracing debug info
30 // #define RAY_TRACE_PRINT_INFO
32 #ifdef RAY_TRACE_PRINT_INFO
33 #include <OSD_Timer.hxx>
36 // =======================================================================
37 // function : MatVecMult
38 // purpose : Multiples 4x4 matrix by 4D vector
39 // =======================================================================
41 BVH_Vec4f MatVecMult (const T m[16], const BVH_Vec4f& v)
44 static_cast<float> (m[ 0] * v.x() + m[ 4] * v.y() +
45 m[ 8] * v.z() + m[12] * v.w()),
46 static_cast<float> (m[ 1] * v.x() + m[ 5] * v.y() +
47 m[ 9] * v.z() + m[13] * v.w()),
48 static_cast<float> (m[ 2] * v.x() + m[ 6] * v.y() +
49 m[10] * v.z() + m[14] * v.w()),
50 static_cast<float> (m[ 3] * v.x() + m[ 7] * v.y() +
51 m[11] * v.z() + m[15] * v.w()));
54 // =======================================================================
55 // function : UpdateRaytraceGeometry
56 // purpose : Updates 3D scene geometry for ray tracing
57 // =======================================================================
58 Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (GeomUpdateMode theMode)
61 return Standard_False;
63 // Note: In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for modifications
64 // This is light-weight procedure performed for each frame
66 if (theMode == OpenGl_GUM_CHECK)
68 if (myLayersModificationStatus != myView->LayerList().ModificationState())
70 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
73 else if (theMode == OpenGl_GUM_PREPARE)
75 myRaytraceGeometry.ClearMaterials();
76 myArrayToTrianglesMap.clear();
78 myIsRaytraceDataValid = Standard_False;
81 // The set of processed structures (reflected to ray-tracing)
82 // This set is used to remove out-of-date records from the
83 // hash map of structures
84 std::set<const OpenGl_Structure*> anElements;
86 // Set of all currently visible and "raytracable" primitive arrays.
87 std::set<const OpenGl_PrimitiveArray*> anArrays;
89 const OpenGl_LayerList& aList = myView->LayerList();
91 for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
93 const OpenGl_PriorityList& aPriorityList = anLayerIt.Value().PriorityList();
95 if (aPriorityList.NbStructures() == 0)
98 const OpenGl_ArrayOfStructure& aStructArray = aPriorityList.ArrayOfStructures();
100 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
102 OpenGl_SequenceOfStructure::Iterator aStructIt;
104 for (aStructIt.Init (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
106 Standard_ShortReal* aTransform (NULL);
108 const OpenGl_Structure* aStructure = aStructIt.Value();
110 if (theMode == OpenGl_GUM_CHECK)
112 if (CheckRaytraceStructure (aStructure))
114 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
117 else if (theMode == OpenGl_GUM_PREPARE)
119 if (!aStructure->IsRaytracable()
120 || !aStructure->IsVisible())
123 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
125 // OpenGL elements from group (extract primitives arrays)
126 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
128 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
130 if (aPrimArray != NULL)
132 // Collect all primitive arrays in scene.
133 anArrays.insert (aPrimArray);
138 else if (theMode == OpenGl_GUM_UPDATE)
140 if (!aStructure->IsRaytracable())
143 if (aStructure->Transformation()->mat != NULL)
145 if (aTransform == NULL)
146 aTransform = new Standard_ShortReal[16];
148 for (Standard_Integer i = 0; i < 4; ++i)
149 for (Standard_Integer j = 0; j < 4; ++j)
151 aTransform[j * 4 + i] = aStructure->Transformation()->mat[i][j];
155 AddRaytraceStructure (aStructure, aTransform, anElements);
158 delete [] aTransform;
163 if (theMode == OpenGl_GUM_PREPARE)
165 BVH_ObjectSet<Standard_ShortReal, 4>::BVH_ObjectList anUnchangedObjects;
167 // Leave only unchanged objects in myRaytraceGeometry so only their transforms and materials will be updated
168 // Objects which not in myArrayToTrianglesMap will be built from scratch.
169 for (Standard_Integer anObjectIdx = 0; anObjectIdx < myRaytraceGeometry.Objects().Size(); ++anObjectIdx)
171 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
172 myRaytraceGeometry.Objects().ChangeValue (anObjectIdx).operator->());
174 // If primitive array of object not in "anArrays" set then it was hided or deleted.
175 // If primitive array present in "anArrays" set but we don't have associated object yet, then
176 // the object is new and still has to be built.
177 if ((aTriangleSet != NULL) && ((anArrays.find (aTriangleSet->AssociatedPArray())) != anArrays.end()))
179 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjectIdx));
181 myArrayToTrianglesMap[aTriangleSet->AssociatedPArray()] = aTriangleSet;
185 myRaytraceGeometry.Objects() = anUnchangedObjects;
187 return UpdateRaytraceGeometry (OpenGl_GUM_UPDATE);
190 if (theMode == OpenGl_GUM_UPDATE)
192 // Actualize the hash map of structures -- remove out-of-date records
193 std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
195 while (anIter != myStructureStates.end())
197 if (anElements.find (anIter->first) == anElements.end())
199 myStructureStates.erase (anIter++);
207 // Actualize OpenGL layer list state
208 myLayersModificationStatus = myView->LayerList().ModificationState();
210 // Rebuild bottom-level and high-level BVHs
211 myRaytraceGeometry.ProcessAcceleration();
213 const Standard_ShortReal aMinRadius = Max (fabs (myRaytraceGeometry.Box().CornerMin().x()), Max (
214 fabs (myRaytraceGeometry.Box().CornerMin().y()), fabs (myRaytraceGeometry.Box().CornerMin().z())));
215 const Standard_ShortReal aMaxRadius = Max (fabs (myRaytraceGeometry.Box().CornerMax().x()), Max (
216 fabs (myRaytraceGeometry.Box().CornerMax().y()), fabs (myRaytraceGeometry.Box().CornerMax().z())));
218 myRaytraceSceneRadius = 2.f /* scale factor */ * Max (aMinRadius, aMaxRadius);
220 const BVH_Vec4f aSize = myRaytraceGeometry.Box().Size();
222 myRaytraceSceneEpsilon = Max (1e-4f, 1e-4f * sqrtf (
223 aSize.x() * aSize.x() + aSize.y() * aSize.y() + aSize.z() * aSize.z()));
225 return UploadRaytraceData();
228 return Standard_True;
231 // =======================================================================
232 // function : CheckRaytraceStructure
233 // purpose : Checks to see if the structure is modified
234 // =======================================================================
235 Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
237 if (!theStructure->IsRaytracable())
239 // Checks to see if all ray-tracable elements were
240 // removed from the structure
241 if (theStructure->ModificationState() > 0)
243 theStructure->ResetModificationState();
244 return Standard_True;
247 return Standard_False;
250 std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
252 if (aStructState != myStructureStates.end())
253 return aStructState->second != theStructure->ModificationState();
255 return Standard_True;
258 // =======================================================================
259 // function : CreateMaterial
260 // purpose : Creates ray-tracing material properties
261 // =======================================================================
262 void CreateMaterial (const OPENGL_SURF_PROP& theProp, OpenGl_RaytraceMaterial& theMaterial)
264 const float* aSrcAmb = theProp.isphysic ? theProp.ambcol.rgb : theProp.matcol.rgb;
265 theMaterial.Ambient = BVH_Vec4f (aSrcAmb[0] * theProp.amb,
266 aSrcAmb[1] * theProp.amb,
267 aSrcAmb[2] * theProp.amb,
270 const float* aSrcDif = theProp.isphysic ? theProp.difcol.rgb : theProp.matcol.rgb;
271 theMaterial.Diffuse = BVH_Vec4f (aSrcDif[0] * theProp.diff,
272 aSrcDif[1] * theProp.diff,
273 aSrcDif[2] * theProp.diff,
276 const float aDefSpecCol[4] = {1.0f, 1.0f, 1.0f, 1.0f};
277 const float* aSrcSpe = theProp.isphysic ? theProp.speccol.rgb : aDefSpecCol;
278 theMaterial.Specular = BVH_Vec4f (aSrcSpe[0] * theProp.spec,
279 aSrcSpe[1] * theProp.spec,
280 aSrcSpe[2] * theProp.spec,
283 const float* aSrcEms = theProp.isphysic ? theProp.emscol.rgb : theProp.matcol.rgb;
284 theMaterial.Emission = BVH_Vec4f (aSrcEms[0] * theProp.emsv,
285 aSrcEms[1] * theProp.emsv,
286 aSrcEms[2] * theProp.emsv,
289 // Note: Here we use sub-linear transparency function
290 // to produce realistic-looking transparency effect
291 theMaterial.Transparency = BVH_Vec4f (powf (theProp.trans, 0.75f),
296 const float aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
297 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
298 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
300 const float aReflectionScale = 0.75f / aMaxRefl;
302 theMaterial.Reflection = BVH_Vec4f (theProp.speccol.rgb[0] * theProp.spec * aReflectionScale,
303 theProp.speccol.rgb[1] * theProp.spec * aReflectionScale,
304 theProp.speccol.rgb[2] * theProp.spec * aReflectionScale,
308 // =======================================================================
309 // function : AddRaytraceStructure
310 // purpose : Adds OpenGL structure to ray-traced scene geometry
311 // =======================================================================
312 Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure,
313 const Standard_ShortReal* theTransform, std::set<const OpenGl_Structure*>& theElements)
315 theElements.insert (theStructure);
317 if (!theStructure->IsVisible())
319 myStructureStates[theStructure] = theStructure->ModificationState();
320 return Standard_True;
323 // Get structure material
324 Standard_Integer aStructMatID = -1;
326 if (theStructure->AspectFace() != NULL)
328 aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
330 OpenGl_RaytraceMaterial aStructMaterial;
331 CreateMaterial (theStructure->AspectFace()->IntFront(), aStructMaterial);
333 myRaytraceGeometry.Materials.push_back (aStructMaterial);
336 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
338 // Get group material
339 Standard_Integer aGroupMatID = -1;
340 if (aGroupIter.Value()->AspectFace() != NULL)
342 aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
344 OpenGl_RaytraceMaterial aGroupMaterial;
345 CreateMaterial (aGroupIter.Value()->AspectFace()->IntFront(), aGroupMaterial);
347 myRaytraceGeometry.Materials.push_back (aGroupMaterial);
350 Standard_Integer aMatID = aGroupMatID < 0 ? aStructMatID : aGroupMatID;
354 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
356 myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
359 // Add OpenGL elements from group (extract primitives arrays and aspects)
360 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
362 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
363 if (anAspect != NULL)
365 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
367 OpenGl_RaytraceMaterial aMaterial;
368 CreateMaterial (anAspect->IntFront(), aMaterial);
370 myRaytraceGeometry.Materials.push_back (aMaterial);
374 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
376 std::map<const OpenGl_PrimitiveArray*, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray);
378 if (aPrimArray != NULL)
380 if (aSetIter != myArrayToTrianglesMap.end())
382 OpenGl_TriangleSet* aSet = aSetIter->second;
384 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
386 if (theTransform != NULL)
388 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
391 aSet->SetProperties (aTransform);
393 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID )
395 aSet->SetMaterialIndex (aMatID);
400 NCollection_Handle<BVH_Object<Standard_ShortReal, 4> > aSet =
401 AddRaytracePrimitiveArray (aPrimArray, aMatID, 0);
405 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
407 if (theTransform != NULL)
409 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
412 aSet->SetProperties (aTransform);
414 myRaytraceGeometry.Objects().Append (aSet);
422 Standard_ShortReal* aTransform = NULL;
424 // Process all connected OpenGL structures
425 for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
427 if (anIts.Value()->Transformation()->mat != NULL)
429 if (aTransform == NULL)
430 aTransform = new Standard_ShortReal[16];
432 for (Standard_Integer i = 0; i < 4; ++i)
433 for (Standard_Integer j = 0; j < 4; ++j)
435 aTransform[j * 4 + i] =
436 anIts.Value()->Transformation()->mat[i][j];
440 if (anIts.Value()->IsRaytracable())
441 AddRaytraceStructure (anIts.Value(), aTransform != NULL ? aTransform : theTransform, theElements);
446 myStructureStates[theStructure] = theStructure->ModificationState();
448 return Standard_True;
451 // =======================================================================
452 // function : AddRaytracePrimitiveArray
453 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
454 // =======================================================================
455 OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (
456 const OpenGl_PrimitiveArray* theArray, Standard_Integer theMatID, const Standard_ShortReal* theTransform)
458 CALL_DEF_PARRAY* aPArray = theArray->PArray();
460 if (aPArray->type != TelPolygonsArrayType &&
461 aPArray->type != TelTrianglesArrayType &&
462 aPArray->type != TelQuadranglesArrayType &&
463 aPArray->type != TelTriangleFansArrayType &&
464 aPArray->type != TelTriangleStripsArrayType &&
465 aPArray->type != TelQuadrangleStripsArrayType)
470 if (aPArray->vertices == NULL)
473 #ifdef RAY_TRACE_PRINT_INFO
474 switch (aPArray->type)
476 case TelPolygonsArrayType:
477 std::cout << "\tAdding TelPolygonsArrayType" << std::endl; break;
478 case TelTrianglesArrayType:
479 std::cout << "\tAdding TelTrianglesArrayType" << std::endl; break;
480 case TelQuadranglesArrayType:
481 std::cout << "\tAdding TelQuadranglesArrayType" << std::endl; break;
482 case TelTriangleFansArrayType:
483 std::cout << "\tAdding TelTriangleFansArrayType" << std::endl; break;
484 case TelTriangleStripsArrayType:
485 std::cout << "\tAdding TelTriangleStripsArrayType" << std::endl; break;
486 case TelQuadrangleStripsArrayType:
487 std::cout << "\tAdding TelQuadrangleStripsArrayType" << std::endl; break;
491 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray);
494 aSet->Vertices.reserve (aPArray->num_vertexs);
496 for (Standard_Integer aVert = 0; aVert < aPArray->num_vertexs; ++aVert)
498 BVH_Vec4f aVertex (aPArray->vertices[aVert].xyz[0],
499 aPArray->vertices[aVert].xyz[1],
500 aPArray->vertices[aVert].xyz[2],
503 aVertex = MatVecMult (theTransform, aVertex);
505 aSet->Vertices.push_back (aVertex);
508 aSet->Normals.reserve (aPArray->num_vertexs);
510 for (Standard_Integer aNorm = 0; aNorm < aPArray->num_vertexs; ++aNorm)
514 // Note: In case of absence of normals, the
515 // renderer uses generated geometric normals
517 if (aPArray->vnormals != NULL)
519 aNormal = BVH_Vec4f (aPArray->vnormals[aNorm].xyz[0],
520 aPArray->vnormals[aNorm].xyz[1],
521 aPArray->vnormals[aNorm].xyz[2],
525 aNormal = MatVecMult (theTransform, aNormal);
528 aSet->Normals.push_back (aNormal);
531 if (aPArray->num_bounds > 0)
533 #ifdef RAY_TRACE_PRINT_INFO
534 std::cout << "\tNumber of bounds = " << aPArray->num_bounds << std::endl;
537 Standard_Integer aBoundStart = 0;
539 for (Standard_Integer aBound = 0; aBound < aPArray->num_bounds; ++aBound)
541 const Standard_Integer aVertNum = aPArray->bounds[aBound];
543 #ifdef RAY_TRACE_PRINT_INFO
544 std::cout << "\tAdding indices from bound " << aBound << ": " <<
545 aBoundStart << " .. " << aVertNum << std::endl;
548 if (!AddRaytraceVertexIndices (aSet, aPArray, aBoundStart, aVertNum, theMatID))
554 aBoundStart += aVertNum;
559 const Standard_Integer aVertNum = aPArray->num_edges > 0 ? aPArray->num_edges : aPArray->num_vertexs;
561 #ifdef RAY_TRACE_PRINT_INFO
562 std::cout << "\tAdding indices from array: " << aVertNum << std::endl;
565 if (!AddRaytraceVertexIndices (aSet, aPArray, 0, aVertNum, theMatID))
573 if (aSet->Size() != 0)
579 // =======================================================================
580 // function : AddRaytraceVertexIndices
581 // purpose : Adds vertex indices to ray-traced scene geometry
582 // =======================================================================
583 Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (OpenGl_TriangleSet* theSet,
584 const CALL_DEF_PARRAY* theArray, Standard_Integer theOffset, Standard_Integer theCount, Standard_Integer theMatID)
586 switch (theArray->type)
588 case TelTrianglesArrayType:
589 return AddRaytraceTriangleArray (theSet, theArray, theOffset, theCount, theMatID);
591 case TelQuadranglesArrayType:
592 return AddRaytraceQuadrangleArray (theSet, theArray, theOffset, theCount, theMatID);
594 case TelTriangleFansArrayType:
595 return AddRaytraceTriangleFanArray (theSet, theArray, theOffset, theCount, theMatID);
597 case TelTriangleStripsArrayType:
598 return AddRaytraceTriangleStripArray (theSet, theArray, theOffset, theCount, theMatID);
600 case TelQuadrangleStripsArrayType:
601 return AddRaytraceQuadrangleStripArray (theSet, theArray, theOffset, theCount, theMatID);
604 return AddRaytracePolygonArray (theSet, theArray, theOffset, theCount, theMatID);
608 // =======================================================================
609 // function : AddRaytraceTriangleArray
610 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
611 // =======================================================================
612 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet* theSet,
613 const CALL_DEF_PARRAY* theArray, Standard_Integer theOffset, Standard_Integer theCount, Standard_Integer theMatID)
616 return Standard_True;
618 theSet->Elements.reserve (theSet->Elements.size() + theCount / 3);
620 if (theArray->num_edges > 0)
622 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
624 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[aVert + 0],
625 theArray->edges[aVert + 1],
626 theArray->edges[aVert + 2],
632 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
634 theSet->Elements.push_back (BVH_Vec4i (aVert + 0,
641 return Standard_True;
644 // =======================================================================
645 // function : AddRaytraceTriangleFanArray
646 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
647 // =======================================================================
648 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet* theSet,
649 const CALL_DEF_PARRAY* theArray, Standard_Integer theOffset, Standard_Integer theCount, Standard_Integer theMatID)
652 return Standard_True;
654 theSet->Elements.reserve (theSet->Elements.size() + theCount - 2);
656 if (theArray->num_edges > 0)
658 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
660 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[theOffset],
661 theArray->edges[aVert + 1],
662 theArray->edges[aVert + 2],
668 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
670 theSet->Elements.push_back (BVH_Vec4i (theOffset,
677 return Standard_True;
680 // =======================================================================
681 // function : AddRaytraceTriangleStripArray
682 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
683 // =======================================================================
684 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet* theSet,
685 const CALL_DEF_PARRAY* theArray, Standard_Integer theOffset, Standard_Integer theCount, Standard_Integer theMatID)
688 return Standard_True;
690 theSet->Elements.reserve (theSet->Elements.size() + theCount - 2);
692 if (theArray->num_edges > 0)
694 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
696 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[aVert + aCW ? 1 : 0],
697 theArray->edges[aVert + aCW ? 0 : 1],
698 theArray->edges[aVert + 2],
704 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
706 theSet->Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
713 return Standard_True;
716 // =======================================================================
717 // function : AddRaytraceQuadrangleArray
718 // purpose : Adds OpenGL quad array to ray-traced scene geometry
719 // =======================================================================
720 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet* theSet,
721 const CALL_DEF_PARRAY* theArray, Standard_Integer theOffset, Standard_Integer theCount, Standard_Integer theMatID)
724 return Standard_True;
726 theSet->Elements.reserve (theSet->Elements.size() + theCount / 2);
728 if (theArray->num_edges > 0)
730 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
732 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[aVert + 0],
733 theArray->edges[aVert + 1],
734 theArray->edges[aVert + 2],
737 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[aVert + 0],
738 theArray->edges[aVert + 2],
739 theArray->edges[aVert + 3],
745 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
747 theSet->Elements.push_back (BVH_Vec4i (aVert + 0,
752 theSet->Elements.push_back (BVH_Vec4i (aVert + 0,
759 return Standard_True;
762 // =======================================================================
763 // function : AddRaytraceQuadrangleStripArray
764 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
765 // =======================================================================
766 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet* theSet,
767 const CALL_DEF_PARRAY* theArray, Standard_Integer theOffset, Standard_Integer theCount, Standard_Integer theMatID)
770 return Standard_True;
772 theSet->Elements.reserve (theSet->Elements.size() + 2 * theCount - 6);
774 if (theArray->num_edges > 0)
776 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
778 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[aVert + 0],
779 theArray->edges[aVert + 1],
780 theArray->edges[aVert + 2],
783 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[aVert + 1],
784 theArray->edges[aVert + 3],
785 theArray->edges[aVert + 2],
791 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
793 theSet->Elements.push_back (BVH_Vec4i (aVert + 0,
798 theSet->Elements.push_back (BVH_Vec4i (aVert + 1,
805 return Standard_True;
808 // =======================================================================
809 // function : AddRaytracePolygonArray
810 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
811 // =======================================================================
812 Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet* theSet,
813 const CALL_DEF_PARRAY* theArray, Standard_Integer theOffset, Standard_Integer theCount, Standard_Integer theMatID)
816 return Standard_True;
818 theSet->Elements.reserve (theSet->Elements.size() + theCount - 2);
820 if (theArray->num_edges > 0)
822 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
824 theSet->Elements.push_back (BVH_Vec4i (theArray->edges[theOffset],
825 theArray->edges[aVert + 1],
826 theArray->edges[aVert + 2],
832 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
834 theSet->Elements.push_back (BVH_Vec4i (theOffset,
841 return Standard_True;
844 // =======================================================================
845 // function : UpdateRaytraceLightSources
846 // purpose : Updates 3D scene light sources for ray-tracing
847 // =======================================================================
848 Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const GLdouble theInvModelView[16])
850 myRaytraceGeometry.Sources.clear();
852 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
854 for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
856 const OpenGl_Light& aLight = anItl.Value();
858 if (aLight.Type == Visual3d_TOLS_AMBIENT)
860 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
867 BVH_Vec4f aDiffuse (aLight.Color.r(),
872 BVH_Vec4f aPosition (-aLight.Direction.x(),
873 -aLight.Direction.y(),
874 -aLight.Direction.z(),
877 if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
879 aPosition = BVH_Vec4f (aLight.Position.x(),
885 if (aLight.IsHeadlight)
886 aPosition = MatVecMult (theInvModelView, aPosition);
889 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
892 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
894 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
896 if (!myRaytraceLightSrcTexture->Create (myGlContext))
898 #ifdef RAY_TRACE_PRINT_INFO
899 std::cout << "Error: Failed to create light source buffer" << std::endl;
901 return Standard_False;
905 if (myRaytraceGeometry.Sources.size() != 0)
907 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
908 if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
910 #ifdef RAY_TRACE_PRINT_INFO
911 std::cout << "Error: Failed to upload light source buffer" << std::endl;
913 return Standard_False;
917 return Standard_True;
920 // =======================================================================
921 // function : UpdateRaytraceEnvironmentMap
922 // purpose : Updates environment map for ray-tracing
923 // =======================================================================
924 Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
927 return Standard_False;
929 if (myViewModificationStatus == myView->ModificationState())
930 return Standard_True;
932 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
934 const Handle(OpenGl_ShaderProgram)& aProgram =
935 anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
937 if (!aProgram.IsNull())
939 aProgram->Bind (myGlContext);
941 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
943 myView->TextureEnv()->Bind (
944 myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
946 aProgram->SetUniform (myGlContext,
947 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 1);
951 aProgram->SetUniform (myGlContext,
952 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 0);
957 OpenGl_ShaderProgram::Unbind (myGlContext);
959 myViewModificationStatus = myView->ModificationState();
961 return Standard_True;
964 // =======================================================================
966 // purpose : Returns shader source combined with prefix
967 // =======================================================================
968 TCollection_AsciiString OpenGl_Workspace::ShaderSource::Source() const
970 static const TCollection_AsciiString aVersion = "#version 140";
972 if (myPrefix.IsEmpty())
974 return aVersion + "\n" + mySource;
977 return aVersion + "\n" + myPrefix + "\n" + mySource;
980 // =======================================================================
982 // purpose : Loads shader source from specified files
983 // =======================================================================
984 void OpenGl_Workspace::ShaderSource::Load (
985 const TCollection_AsciiString* theFileNames, const Standard_Integer theCount)
989 for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
991 OSD_File aFile (theFileNames[anIndex]);
993 Standard_ASSERT_RETURN (aFile.Exists(),
994 "Error: Failed to find shader source file", /* none */);
996 aFile.Open (OSD_ReadOnly, OSD_Protection());
998 TCollection_AsciiString aSource;
1000 Standard_ASSERT_RETURN (aFile.IsOpen(),
1001 "Error: Failed to open shader source file", /* none */);
1003 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1005 if (!aSource.IsEmpty())
1007 mySource += TCollection_AsciiString ("\n") + aSource;
1014 // =======================================================================
1015 // function : LoadShader
1016 // purpose : Creates new shader object with specified source
1017 // =======================================================================
1018 Handle(OpenGl_ShaderObject) OpenGl_Workspace::LoadShader (const ShaderSource& theSource, GLenum theType)
1020 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1022 if (!aShader->Create (myGlContext))
1024 const TCollection_ExtendedString aMessage = "Error: Failed to create shader object";
1026 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1027 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1029 aShader->Release (myGlContext.operator->());
1031 return Handle(OpenGl_ShaderObject)();
1034 if (!aShader->LoadSource (myGlContext, theSource.Source()))
1036 const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1038 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1039 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1041 aShader->Release (myGlContext.operator->());
1043 return Handle(OpenGl_ShaderObject)();
1046 TCollection_AsciiString aBuildLog;
1048 if (!aShader->Compile (myGlContext))
1050 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1052 const TCollection_ExtendedString aMessage =
1053 TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1055 #ifdef RAY_TRACE_PRINT_INFO
1056 std::cout << aBuildLog << std::endl;
1059 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1060 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1063 aShader->Release (myGlContext.operator->());
1065 return Handle(OpenGl_ShaderObject)();
1068 #ifdef RAY_TRACE_PRINT_INFO
1069 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1071 if (!aBuildLog.IsEmpty())
1073 std::cout << aBuildLog << std::endl;
1077 std::cout << "Info: shader build log is empty" << std::endl;
1085 // =======================================================================
1086 // function : SafeFailBack
1087 // purpose : Performs safe exit when shaders initialization fails
1088 // =======================================================================
1089 Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
1091 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1092 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
1094 myComputeInitStatus = OpenGl_RT_FAIL;
1096 ReleaseRaytraceResources();
1098 return Standard_False;
1101 // =======================================================================
1102 // function : InitRaytraceResources
1103 // purpose : Initializes OpenGL/GLSL shader programs
1104 // =======================================================================
1105 Standard_Boolean OpenGl_Workspace::InitRaytraceResources()
1107 Standard_Boolean aToRebuildShaders = Standard_False;
1109 if (myComputeInitStatus == OpenGl_RT_INIT)
1111 if (!myIsRaytraceDataValid)
1112 return Standard_True;
1114 const Standard_Integer aRequiredStackSize =
1115 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
1117 if (myTraversalStackSize < aRequiredStackSize)
1119 myTraversalStackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1121 aToRebuildShaders = Standard_True;
1125 if (aRequiredStackSize < myTraversalStackSize)
1127 if (myTraversalStackSize > THE_DEFAULT_STACK_SIZE)
1129 myTraversalStackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1131 aToRebuildShaders = Standard_True;
1136 if (aToRebuildShaders)
1138 #ifdef RAY_TRACE_PRINT_INFO
1139 std::cout << "Info: Rebuild shaders with stack size: " << myTraversalStackSize << std::endl;
1142 // Change state to force update all uniforms.
1143 ++myViewModificationStatus;
1145 TCollection_AsciiString aStackSizeStr =
1146 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myTraversalStackSize);
1148 myRaytraceShaderSource.SetPrefix (aStackSizeStr);
1149 myPostFSAAShaderSource.SetPrefix (aStackSizeStr);
1151 if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1152 || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1154 return Standard_False;
1157 if (!myRaytraceShader->Compile (myGlContext)
1158 || !myPostFSAAShader->Compile (myGlContext))
1160 return Standard_False;
1163 if (!myRaytraceProgram->Link (myGlContext)
1164 || !myPostFSAAProgram->Link (myGlContext))
1166 return Standard_False;
1171 if (myComputeInitStatus == OpenGl_RT_NONE)
1173 if (!myGlContext->IsGlGreaterEqual (3, 1))
1175 const TCollection_ExtendedString aMessage = "Ray-tracing requires OpenGL 3.1 and higher";
1177 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1178 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1180 return Standard_False;
1183 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1185 if (aFolder.IsEmpty())
1187 const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1189 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1190 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1192 return Standard_False;
1195 if (myIsRaytraceDataValid)
1197 myTraversalStackSize = Max (THE_DEFAULT_STACK_SIZE,
1198 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1202 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1203 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1205 if (aBasicVertShader.IsNull())
1207 return SafeFailBack ("Failed to set vertex shader source");
1210 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
1212 myRaytraceShaderSource.Load (aFiles, 2);
1214 TCollection_AsciiString aStackSizeStr =
1215 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myTraversalStackSize);
1217 myRaytraceShaderSource.SetPrefix (aStackSizeStr);
1219 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
1221 if (myRaytraceShader.IsNull())
1223 aBasicVertShader->Release (myGlContext.operator->());
1225 return SafeFailBack ("Failed to set ray-trace fragment shader source");
1228 myRaytraceProgram = new OpenGl_ShaderProgram;
1230 if (!myRaytraceProgram->Create (myGlContext))
1232 aBasicVertShader->Release (myGlContext.operator->());
1234 return SafeFailBack ("Failed to create ray-trace shader program");
1237 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1238 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1240 aBasicVertShader->Release (myGlContext.operator->());
1242 return SafeFailBack ("Failed to attach ray-trace shader objects");
1245 if (!myRaytraceProgram->Link (myGlContext))
1247 TCollection_AsciiString aLinkLog;
1249 if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1251 #ifdef RAY_TRACE_PRINT_INFO
1252 std::cout << aLinkLog << std::endl;
1256 return SafeFailBack ("Failed to link ray-trace shader program");
1261 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1262 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1264 if (aBasicVertShader.IsNull())
1266 return SafeFailBack ("Failed to set vertex shader source");
1269 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
1271 myPostFSAAShaderSource.Load (aFiles, 2);
1273 TCollection_AsciiString aStackSizeStr =
1274 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myTraversalStackSize);
1276 myPostFSAAShaderSource.SetPrefix (aStackSizeStr);
1278 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
1280 if (myPostFSAAShader.IsNull())
1282 aBasicVertShader->Release (myGlContext.operator->());
1284 return SafeFailBack ("Failed to set FSAA fragment shader source");
1287 myPostFSAAProgram = new OpenGl_ShaderProgram;
1289 if (!myPostFSAAProgram->Create (myGlContext))
1291 aBasicVertShader->Release (myGlContext.operator->());
1293 return SafeFailBack ("Failed to create FSAA shader program");
1296 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1297 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1299 aBasicVertShader->Release (myGlContext.operator->());
1301 return SafeFailBack ("Failed to attach FSAA shader objects");
1304 if (!myPostFSAAProgram->Link (myGlContext))
1306 TCollection_AsciiString aLinkLog;
1308 if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1310 #ifdef RAY_TRACE_PRINT_INFO
1311 std::cout << aLinkLog << std::endl;
1315 return SafeFailBack ("Failed to link FSAA shader program");
1320 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1322 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1324 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1325 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1327 aShaderProgram->Bind (myGlContext);
1329 aShaderProgram->SetSampler (myGlContext,
1330 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1331 aShaderProgram->SetSampler (myGlContext,
1332 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1333 aShaderProgram->SetSampler (myGlContext,
1334 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1335 aShaderProgram->SetSampler (myGlContext,
1336 "uObjectMinPointTexture", OpenGl_RT_ObjectMinPointTexture);
1337 aShaderProgram->SetSampler (myGlContext,
1338 "uObjectMaxPointTexture", OpenGl_RT_ObjectMaxPointTexture);
1339 aShaderProgram->SetSampler (myGlContext,
1340 "uObjectNodeInfoTexture", OpenGl_RT_ObjectNodeInfoTexture);
1341 aShaderProgram->SetSampler (myGlContext,
1342 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1343 aShaderProgram->SetSampler (myGlContext,
1344 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1345 aShaderProgram->SetSampler (myGlContext,
1346 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1347 aShaderProgram->SetSampler (myGlContext,
1348 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1349 aShaderProgram->SetSampler (myGlContext,
1350 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1351 aShaderProgram->SetSampler (myGlContext,
1352 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1353 aShaderProgram->SetSampler (myGlContext,
1354 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1358 aShaderProgram->SetSampler (myGlContext,
1359 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1362 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1363 aShaderProgram->GetAttributeLocation (myGlContext, "aPosition");
1365 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1366 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1367 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1368 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1369 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1370 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1371 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1372 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1373 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1374 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1375 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1376 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1377 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1378 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1379 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1380 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
1382 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1383 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1384 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1385 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1387 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1388 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1389 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1390 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1392 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1393 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1394 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1395 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1397 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1398 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1399 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1400 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1401 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1402 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
1404 myUniformLocations[anIndex][OpenGl_RT_uEnvironmentEnable] =
1405 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
1408 OpenGl_ShaderProgram::Unbind (myGlContext);
1411 if (myComputeInitStatus != OpenGl_RT_NONE)
1413 return myComputeInitStatus == OpenGl_RT_INIT;
1416 if (myRaytraceFBO1.IsNull())
1418 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1421 if (myRaytraceFBO2.IsNull())
1423 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1426 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1433 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
1435 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1437 return Standard_True;
1440 // =======================================================================
1441 // function : NullifyResource
1443 // =======================================================================
1444 inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1445 Handle(OpenGl_Resource)& theResource)
1447 if (!theResource.IsNull())
1449 theResource->Release (theContext.operator->());
1450 theResource.Nullify();
1454 // =======================================================================
1455 // function : ReleaseRaytraceResources
1456 // purpose : Releases OpenGL/GLSL shader programs
1457 // =======================================================================
1458 void OpenGl_Workspace::ReleaseRaytraceResources()
1460 NullifyResource (myGlContext, myRaytraceFBO1);
1461 NullifyResource (myGlContext, myRaytraceFBO2);
1463 NullifyResource (myGlContext, myRaytraceShader);
1464 NullifyResource (myGlContext, myPostFSAAShader);
1466 NullifyResource (myGlContext, myRaytraceProgram);
1467 NullifyResource (myGlContext, myPostFSAAProgram);
1469 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1470 NullifyResource (myGlContext, mySceneMinPointTexture);
1471 NullifyResource (myGlContext, mySceneMaxPointTexture);
1473 NullifyResource (myGlContext, mySceneTransformTexture);
1475 NullifyResource (myGlContext, myObjectNodeInfoTexture);
1476 NullifyResource (myGlContext, myObjectMinPointTexture);
1477 NullifyResource (myGlContext, myObjectMaxPointTexture);
1479 NullifyResource (myGlContext, myGeometryVertexTexture);
1480 NullifyResource (myGlContext, myGeometryNormalTexture);
1481 NullifyResource (myGlContext, myGeometryTriangTexture);
1483 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1484 NullifyResource (myGlContext, myRaytraceMaterialTexture);
1486 if (myRaytraceScreenQuad.IsValid())
1487 myRaytraceScreenQuad.Release (myGlContext.operator->());
1490 // =======================================================================
1491 // function : UploadRaytraceData
1492 // purpose : Uploads ray-trace data to the GPU
1493 // =======================================================================
1494 Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1496 if (!myGlContext->IsGlGreaterEqual (3, 1))
1498 #ifdef RAY_TRACE_PRINT_INFO
1499 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1501 return Standard_False;
1504 /////////////////////////////////////////////////////////////////////////////
1505 // Create OpenGL texture buffers
1507 if (mySceneNodeInfoTexture.IsNull()) // create hight-level BVH buffers
1509 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1510 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1511 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
1512 mySceneTransformTexture = new OpenGl_TextureBufferArb;
1514 if (!mySceneNodeInfoTexture->Create (myGlContext)
1515 || !mySceneMinPointTexture->Create (myGlContext)
1516 || !mySceneMaxPointTexture->Create (myGlContext)
1517 || !mySceneTransformTexture->Create (myGlContext))
1519 #ifdef RAY_TRACE_PRINT_INFO
1520 std::cout << "Error: Failed to create buffers for high-level scene BVH" << std::endl;
1522 return Standard_False;
1526 if (myObjectNodeInfoTexture.IsNull()) // create bottom-level BVH buffers
1528 myObjectNodeInfoTexture = new OpenGl_TextureBufferArb;
1529 myObjectMinPointTexture = new OpenGl_TextureBufferArb;
1530 myObjectMaxPointTexture = new OpenGl_TextureBufferArb;
1532 if (!myObjectNodeInfoTexture->Create (myGlContext)
1533 || !myObjectMinPointTexture->Create (myGlContext)
1534 || !myObjectMaxPointTexture->Create (myGlContext))
1536 #ifdef RAY_TRACE_PRINT_INFO
1537 std::cout << "Error: Failed to create buffers for bottom-level scene BVH" << std::endl;
1539 return Standard_False;
1543 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
1545 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1546 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1547 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1549 if (!myGeometryVertexTexture->Create (myGlContext)
1550 || !myGeometryNormalTexture->Create (myGlContext)
1551 || !myGeometryTriangTexture->Create (myGlContext))
1553 #ifdef RAY_TRACE_PRINT_INFO
1554 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1556 return Standard_False;
1560 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1562 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1564 if (!myRaytraceMaterialTexture->Create (myGlContext))
1566 #ifdef RAY_TRACE_PRINT_INFO
1567 std::cout << "Error: Failed to create buffers for material data" << std::endl;
1569 return Standard_False;
1573 /////////////////////////////////////////////////////////////////////////////
1574 // Write OpenGL texture buffers
1576 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 4> >& aBVH = myRaytraceGeometry.BVH();
1578 bool aResult = true;
1579 if (!aBVH->NodeInfoBuffer().empty())
1581 aResult &= mySceneNodeInfoTexture->Init (myGlContext, 4, GLsizei (aBVH->NodeInfoBuffer().size()),
1582 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1583 aResult &= mySceneMinPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MinPointBuffer().size()),
1584 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1585 aResult &= mySceneMaxPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MaxPointBuffer().size()),
1586 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1590 #ifdef RAY_TRACE_PRINT_INFO
1591 std::cout << "Error: Failed to upload buffers for high-level scene BVH" << std::endl;
1593 return Standard_False;
1596 /////////////////////////////////////////////////////////////////////////////
1597 // Write transform buffer
1599 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1600 BVH_Mat4f anIdentity;
1602 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1604 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1605 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1607 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1608 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1610 Standard_ASSERT_RETURN (aTransform != NULL,
1611 "OpenGl_TriangleSet does not contain transform", Standard_False);
1613 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1617 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1618 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1620 delete[] aNodeTransforms;
1622 /////////////////////////////////////////////////////////////////////////////
1624 Standard_Size aTotalVerticesNb = 0;
1625 Standard_Size aTotalElementsNb = 0;
1626 Standard_Size aTotalBVHNodesNb = 0;
1628 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1630 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1631 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1633 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1634 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1636 aTotalVerticesNb += aTriangleSet->Vertices.size();
1637 aTotalElementsNb += aTriangleSet->Elements.size();
1639 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1640 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
1642 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1645 if (aTotalBVHNodesNb != 0)
1647 aResult &= myObjectNodeInfoTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1648 aResult &= myObjectMinPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1649 aResult &= myObjectMaxPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1654 #ifdef RAY_TRACE_PRINT_INFO
1655 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1657 return Standard_False;
1660 if (aTotalElementsNb != 0)
1662 aResult &= myGeometryTriangTexture->Init (myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
1665 if (aTotalVerticesNb != 0)
1667 aResult &= myGeometryVertexTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1668 aResult &= myGeometryNormalTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1673 #ifdef RAY_TRACE_PRINT_INFO
1674 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1676 return Standard_False;
1679 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1681 if (!aBVH->IsOuter (aNodeIdx))
1684 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
1686 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1687 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1689 const Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
1691 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1692 "Error: Failed to get offset for bottom-level BVH", Standard_False);
1694 const size_t aBVHBuffserSize = aTriangleSet->BVH()->NodeInfoBuffer().size();
1696 if (aBVHBuffserSize != 0)
1698 aResult &= myObjectNodeInfoTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1699 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1700 aResult &= myObjectMinPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1701 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1702 aResult &= myObjectMaxPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1703 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
1706 #ifdef RAY_TRACE_PRINT_INFO
1707 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1709 return Standard_False;
1713 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
1715 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1716 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
1718 if (!aTriangleSet->Vertices.empty())
1720 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1721 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1722 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1723 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
1726 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
1728 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1729 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
1731 if (!aTriangleSet->Elements.empty())
1733 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1734 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
1739 #ifdef RAY_TRACE_PRINT_INFO
1740 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
1742 return Standard_False;
1746 if (myRaytraceGeometry.Materials.size() != 0)
1748 const GLfloat* aDataPtr = myRaytraceGeometry.Materials.front().Packed();
1749 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Materials.size() * 7), aDataPtr);
1752 #ifdef RAY_TRACE_PRINT_INFO
1753 std::cout << "Error: Failed to upload material buffer" << std::endl;
1755 return Standard_False;
1759 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
1761 #ifdef RAY_TRACE_PRINT_INFO
1763 Standard_ShortReal aMemUsed = 0.f;
1765 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1767 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1768 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
1770 aMemUsed += static_cast<Standard_ShortReal> (
1771 aTriangleSet->Vertices.size() * sizeof (BVH_Vec4f));
1772 aMemUsed += static_cast<Standard_ShortReal> (
1773 aTriangleSet->Normals.size() * sizeof (BVH_Vec4f));
1774 aMemUsed += static_cast<Standard_ShortReal> (
1775 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
1777 aMemUsed += static_cast<Standard_ShortReal> (
1778 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1779 aMemUsed += static_cast<Standard_ShortReal> (
1780 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1781 aMemUsed += static_cast<Standard_ShortReal> (
1782 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
1785 aMemUsed += static_cast<Standard_ShortReal> (
1786 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1787 aMemUsed += static_cast<Standard_ShortReal> (
1788 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1789 aMemUsed += static_cast<Standard_ShortReal> (
1790 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
1792 aMemUsed += static_cast<Standard_ShortReal> (
1793 aTransformsNb * sizeof (BVH_Vec4f) * 4);
1795 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
1802 // =======================================================================
1803 // function : ResizeRaytraceBuffers
1804 // purpose : Resizes OpenGL frame buffers
1805 // =======================================================================
1806 Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1807 const Standard_Integer theSizeY)
1809 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1810 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1812 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1813 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1816 return Standard_True;
1819 // =======================================================================
1820 // function : UpdateCamera
1821 // purpose : Generates viewing rays for corners of screen quad
1822 // =======================================================================
1823 void OpenGl_Workspace::UpdateCamera (const NCollection_Mat4<GLdouble>& theOrientation,
1824 const NCollection_Mat4<GLdouble>& theViewMapping,
1825 OpenGl_Vec3 theOrigins[4],
1826 OpenGl_Vec3 theDirects[4])
1828 NCollection_Mat4<GLdouble> aInvModelProj;
1830 // compute invserse model-view-projection matrix
1831 (theViewMapping * theOrientation).Inverted (aInvModelProj);
1833 Standard_Integer aOriginIndex = 0;
1834 Standard_Integer aDirectIndex = 0;
1836 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1838 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1840 OpenGl_Vec4d aOrigin (GLdouble(aX),
1845 aOrigin = aInvModelProj * aOrigin;
1847 aOrigin.x() = aOrigin.x() / aOrigin.w();
1848 aOrigin.y() = aOrigin.y() / aOrigin.w();
1849 aOrigin.z() = aOrigin.z() / aOrigin.w();
1851 OpenGl_Vec4d aDirect (GLdouble(aX),
1856 aDirect = aInvModelProj * aDirect;
1858 aDirect.x() = aDirect.x() / aDirect.w();
1859 aDirect.y() = aDirect.y() / aDirect.w();
1860 aDirect.z() = aDirect.z() / aDirect.w();
1862 aDirect = aDirect - aOrigin;
1864 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
1865 aDirect.y() * aDirect.y() +
1866 aDirect.z() * aDirect.z());
1868 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1869 static_cast<GLfloat> (aOrigin.y()),
1870 static_cast<GLfloat> (aOrigin.z()));
1872 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
1873 static_cast<GLfloat> (aDirect.y() * aInvLen),
1874 static_cast<GLfloat> (aDirect.z() * aInvLen));
1879 // =======================================================================
1880 // function : RunRaytraceShaders
1881 // purpose : Runs ray-tracing shader programs
1882 // =======================================================================
1883 Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
1884 const Standard_Integer theSizeX,
1885 const Standard_Integer theSizeY,
1886 const OpenGl_Vec3 theOrigins[4],
1887 const OpenGl_Vec3 theDirects[4],
1888 OpenGl_FrameBuffer* theFrameBuffer)
1890 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
1891 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
1892 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
1893 myObjectMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
1894 myObjectMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
1895 myObjectNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
1896 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
1897 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
1898 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
1899 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
1900 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
1901 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
1903 if (theCView.IsAntialiasingEnabled) // render source image to FBO
1905 myRaytraceFBO1->BindBuffer (myGlContext);
1907 glDisable (GL_BLEND);
1910 myRaytraceProgram->Bind (myGlContext);
1912 Standard_Integer aLightSourceBufferSize =
1913 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
1915 myRaytraceProgram->SetUniform (myGlContext,
1916 myUniformLocations[0][OpenGl_RT_uOriginLB], theOrigins[0]);
1917 myRaytraceProgram->SetUniform (myGlContext,
1918 myUniformLocations[0][OpenGl_RT_uOriginRB], theOrigins[1]);
1919 myRaytraceProgram->SetUniform (myGlContext,
1920 myUniformLocations[0][OpenGl_RT_uOriginLT], theOrigins[2]);
1921 myRaytraceProgram->SetUniform (myGlContext,
1922 myUniformLocations[0][OpenGl_RT_uOriginRT], theOrigins[3]);
1923 myRaytraceProgram->SetUniform (myGlContext,
1924 myUniformLocations[0][OpenGl_RT_uDirectLB], theDirects[0]);
1925 myRaytraceProgram->SetUniform (myGlContext,
1926 myUniformLocations[0][OpenGl_RT_uDirectRB], theDirects[1]);
1927 myRaytraceProgram->SetUniform (myGlContext,
1928 myUniformLocations[0][OpenGl_RT_uDirectLT], theDirects[2]);
1929 myRaytraceProgram->SetUniform (myGlContext,
1930 myUniformLocations[0][OpenGl_RT_uDirectRT], theDirects[3]);
1931 myRaytraceProgram->SetUniform (myGlContext,
1932 myUniformLocations[0][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
1933 myRaytraceProgram->SetUniform (myGlContext,
1934 myUniformLocations[0][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
1935 myRaytraceProgram->SetUniform (myGlContext,
1936 myUniformLocations[0][OpenGl_RT_uLightCount], aLightSourceBufferSize);
1937 myRaytraceProgram->SetUniform (myGlContext,
1938 myUniformLocations[0][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
1939 myRaytraceProgram->SetUniform (myGlContext,
1940 myUniformLocations[0][OpenGl_RT_uShadEnabled], theCView.IsShadowsEnabled);
1941 myRaytraceProgram->SetUniform (myGlContext,
1942 myUniformLocations[0][OpenGl_RT_uReflEnabled], theCView.IsReflectionsEnabled);
1944 myGlContext->core20fwd->glEnableVertexAttribArray (
1945 myUniformLocations[0][OpenGl_RT_aPosition]);
1947 myGlContext->core20fwd->glVertexAttribPointer (
1948 myUniformLocations[0][OpenGl_RT_aPosition], 3, GL_FLOAT, GL_FALSE, 0, NULL);
1950 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
1952 myGlContext->core20fwd->glDisableVertexAttribArray (
1953 myUniformLocations[0][OpenGl_RT_aPosition]);
1955 if (!theCView.IsAntialiasingEnabled)
1957 myRaytraceProgram->Unbind (myGlContext);
1959 return Standard_True;
1962 myGlContext->core20fwd->glActiveTexture (
1963 GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture); // texture unit for FBO texture
1965 myRaytraceFBO1->BindTexture (myGlContext);
1967 myPostFSAAProgram->Bind (myGlContext);
1969 myPostFSAAProgram->SetUniform (myGlContext,
1970 myUniformLocations[1][OpenGl_RT_uOriginLB], theOrigins[0]);
1971 myPostFSAAProgram->SetUniform (myGlContext,
1972 myUniformLocations[1][OpenGl_RT_uOriginRB], theOrigins[1]);
1973 myPostFSAAProgram->SetUniform (myGlContext,
1974 myUniformLocations[1][OpenGl_RT_uOriginLT], theOrigins[2]);
1975 myPostFSAAProgram->SetUniform (myGlContext,
1976 myUniformLocations[1][OpenGl_RT_uOriginRT], theOrigins[3]);
1977 myPostFSAAProgram->SetUniform (myGlContext,
1978 myUniformLocations[1][OpenGl_RT_uDirectLB], theDirects[0]);
1979 myPostFSAAProgram->SetUniform (myGlContext,
1980 myUniformLocations[1][OpenGl_RT_uDirectRB], theDirects[1]);
1981 myPostFSAAProgram->SetUniform (myGlContext,
1982 myUniformLocations[1][OpenGl_RT_uDirectLT], theDirects[2]);
1983 myPostFSAAProgram->SetUniform (myGlContext,
1984 myUniformLocations[1][OpenGl_RT_uDirectRT], theDirects[3]);
1985 myPostFSAAProgram->SetUniform (myGlContext,
1986 myUniformLocations[1][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
1987 myPostFSAAProgram->SetUniform (myGlContext,
1988 myUniformLocations[1][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
1989 myPostFSAAProgram->SetUniform (myGlContext,
1990 myUniformLocations[1][OpenGl_RT_uLightCount], aLightSourceBufferSize);
1991 myPostFSAAProgram->SetUniform (myGlContext,
1992 myUniformLocations[1][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
1993 myPostFSAAProgram->SetUniform (myGlContext,
1994 myUniformLocations[1][OpenGl_RT_uShadEnabled], theCView.IsShadowsEnabled);
1995 myPostFSAAProgram->SetUniform (myGlContext,
1996 myUniformLocations[1][OpenGl_RT_uReflEnabled], theCView.IsReflectionsEnabled);
1998 const Standard_ShortReal aMaxOffset = 0.559017f;
1999 const Standard_ShortReal aMinOffset = 0.186339f;
2001 myGlContext->core20fwd->glEnableVertexAttribArray (
2002 myUniformLocations[1][OpenGl_RT_aPosition]);
2004 myGlContext->core20fwd->glVertexAttribPointer (
2005 myUniformLocations[1][OpenGl_RT_aPosition], 3, GL_FLOAT, GL_FALSE, 0, NULL);
2007 // Perform multi-pass adaptive FSAA using ping-pong technique
2008 // rotated grid AA always uses 4 samples
2009 for (Standard_Integer anIt = 0; anIt < 4; ++anIt)
2011 GLfloat aOffsetX = 1.f / theSizeX;
2012 GLfloat aOffsetY = 1.f / theSizeY;
2016 aOffsetX *= anIt < 1 ? aMinOffset : -aMaxOffset;
2017 aOffsetY *= anIt < 1 ? aMaxOffset : aMinOffset;
2021 aOffsetX *= anIt > 2 ? aMaxOffset : -aMinOffset;
2022 aOffsetY *= anIt > 2 ? -aMinOffset : -aMaxOffset;
2025 myPostFSAAProgram->SetUniform (myGlContext,
2026 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 2);
2027 myPostFSAAProgram->SetUniform (myGlContext,
2028 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2029 myPostFSAAProgram->SetUniform (myGlContext,
2030 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2032 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO1 : myRaytraceFBO2;
2034 if (anIt == 3) // disable FBO on last iteration
2036 glEnable (GL_BLEND);
2038 if (theFrameBuffer != NULL)
2039 theFrameBuffer->BindBuffer (myGlContext);
2043 aFramebuffer->BindBuffer (myGlContext);
2046 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2048 if (anIt != 3) // set input for the next pass
2050 aFramebuffer->BindTexture (myGlContext);
2051 aFramebuffer->UnbindBuffer (myGlContext);
2055 myGlContext->core20fwd->glDisableVertexAttribArray (
2056 myUniformLocations[1][OpenGl_RT_aPosition]);
2058 myPostFSAAProgram->Unbind (myGlContext);
2060 return Standard_True;
2063 // =======================================================================
2064 // function : Raytrace
2065 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2066 // =======================================================================
2067 Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
2068 const Standard_Integer theSizeX,
2069 const Standard_Integer theSizeY,
2070 const Standard_Boolean theToSwap,
2071 OpenGl_FrameBuffer* theFrameBuffer)
2073 if (!UpdateRaytraceGeometry (OpenGl_GUM_CHECK))
2074 return Standard_False;
2076 if (!InitRaytraceResources())
2077 return Standard_False;
2079 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
2080 return Standard_False;
2082 if (!UpdateRaytraceEnvironmentMap())
2083 return Standard_False;
2085 // Get model-view and projection matrices
2086 TColStd_Array2OfReal theOrientation (0, 3, 0, 3);
2087 TColStd_Array2OfReal theViewMapping (0, 3, 0, 3);
2089 myView->GetMatrices (theOrientation, theViewMapping);
2091 NCollection_Mat4<GLdouble> aOrientationMatrix;
2092 NCollection_Mat4<GLdouble> aViewMappingMatrix;
2094 for (Standard_Integer j = 0; j < 4; ++j)
2096 for (Standard_Integer i = 0; i < 4; ++i)
2098 aOrientationMatrix [4 * j + i] = theOrientation (i, j);
2099 aViewMappingMatrix [4 * j + i] = theViewMapping (i, j);
2103 NCollection_Mat4<GLdouble> aInvOrientationMatrix;
2104 aOrientationMatrix.Inverted (aInvOrientationMatrix);
2106 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
2107 return Standard_False;
2109 OpenGl_Vec3 aOrigins[4];
2110 OpenGl_Vec3 aDirects[4];
2112 UpdateCamera (aOrientationMatrix,
2117 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2118 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
2120 glDisable (GL_DEPTH_TEST);
2122 if (NamedStatus & OPENGL_NS_WHITEBACK)
2124 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2128 glClearColor (myBgColor.rgb[0],
2134 glClear (GL_COLOR_BUFFER_BIT);
2136 if (theFrameBuffer != NULL)
2137 theFrameBuffer->BindBuffer (myGlContext);
2139 myView->DrawBackground (*this);
2141 // Generate ray-traced image
2142 glMatrixMode (GL_PROJECTION);
2145 glMatrixMode (GL_MODELVIEW);
2148 glEnable (GL_BLEND);
2149 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
2151 if (myIsRaytraceDataValid)
2153 myRaytraceScreenQuad.Bind (myGlContext);
2155 RunRaytraceShaders (theCView,
2162 myRaytraceScreenQuad.Unbind (myGlContext);
2165 if (!wasBlendingEnabled)
2166 glDisable (GL_BLEND);
2168 if (wasDepthTestEnabled)
2169 glEnable (GL_DEPTH_TEST);
2174 GetGlContext()->SwapBuffers();
2175 myBackBufferRestored = Standard_False;
2182 return Standard_True;