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.
17 // On Windows, function TryEnterCriticalSection has appeared in Windows NT
18 // and is surrounded by #ifdef in MS VC++ 7.1 headers.
19 // Thus to use it we need to define appropriate macro saying that we will
20 // run on Windows NT 4.0 at least
21 #if defined(_WIN32) && !defined(_WIN32_WINNT)
22 #define _WIN32_WINNT 0x0501
28 #include <OpenGl_SceneGeometry.hxx>
30 #include <OpenGl_ArbTexBindless.hxx>
31 #include <OpenGl_PrimitiveArray.hxx>
32 #include <OpenGl_Structure.hxx>
33 #include <OSD_Timer.hxx>
34 #include <Standard_Assert.hxx>
36 //! Use this macro to output BVH profiling info
37 // #define RAY_TRACE_PRINT_INFO
41 //! Useful constant for null floating-point 4D vector.
42 static const BVH_Vec4f ZERO_VEC_4F;
45 // =======================================================================
46 // function : OpenGl_RaytraceMaterial
47 // purpose : Creates new default material
48 // =======================================================================
49 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial()
50 : Ambient (ZERO_VEC_4F),
51 Diffuse (ZERO_VEC_4F),
52 Specular (ZERO_VEC_4F),
53 Emission (ZERO_VEC_4F),
54 Reflection (ZERO_VEC_4F),
55 Refraction (ZERO_VEC_4F),
56 Transparency (ZERO_VEC_4F)
59 // =======================================================================
60 // function : OpenGl_RaytraceMaterial
61 // purpose : Creates new material with specified properties
62 // =======================================================================
63 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial (const BVH_Vec4f& theAmbient,
64 const BVH_Vec4f& theDiffuse,
65 const BVH_Vec4f& theSpecular)
66 : Ambient (theAmbient),
68 Specular (theSpecular),
69 Emission (ZERO_VEC_4F),
70 Reflection (ZERO_VEC_4F),
71 Refraction (ZERO_VEC_4F),
72 Transparency (ZERO_VEC_4F)
77 // =======================================================================
78 // function : OpenGl_RaytraceMaterial
79 // purpose : Creates new material with specified properties
80 // =======================================================================
81 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial (const BVH_Vec4f& theAmbient,
82 const BVH_Vec4f& theDiffuse,
83 const BVH_Vec4f& theSpecular,
84 const BVH_Vec4f& theEmission,
85 const BVH_Vec4f& theTranspar)
86 : Ambient (theAmbient),
88 Specular (theSpecular),
89 Emission (theEmission),
90 Reflection (ZERO_VEC_4F),
91 Refraction (ZERO_VEC_4F),
92 Transparency (theTranspar)
97 // =======================================================================
98 // function : OpenGl_RaytraceMaterial
99 // purpose : Creates new material with specified properties
100 // =======================================================================
101 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial (const BVH_Vec4f& theAmbient,
102 const BVH_Vec4f& theDiffuse,
103 const BVH_Vec4f& theSpecular,
104 const BVH_Vec4f& theEmission,
105 const BVH_Vec4f& theTranspar,
106 const BVH_Vec4f& theReflection,
107 const BVH_Vec4f& theRefraction)
108 : Ambient (theAmbient),
109 Diffuse (theDiffuse),
110 Specular (theSpecular),
111 Emission (theEmission),
112 Reflection (theReflection),
113 Refraction (theRefraction),
114 Transparency (theTranspar)
119 // =======================================================================
120 // function : OpenGl_LightSource
121 // purpose : Creates new light source
122 // =======================================================================
123 OpenGl_RaytraceLight::OpenGl_RaytraceLight (const BVH_Vec4f& theDiffuse,
124 const BVH_Vec4f& thePosition)
125 : Diffuse (theDiffuse),
126 Position (thePosition)
131 // =======================================================================
133 // purpose : Returns AABB of primitive set
134 // =======================================================================
135 OpenGl_TriangleSet::BVH_BoxNt OpenGl_TriangleSet::Box() const
137 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
138 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (Properties().operator->());
140 BVH_BoxNt aBox = BVH_PrimitiveSet<Standard_ShortReal, 3>::Box();
142 if (aTransform != NULL)
144 BVH_BoxNt aTransformedBox;
146 for (Standard_Integer aX = 0; aX <= 1; ++aX)
148 for (Standard_Integer aY = 0; aY <= 1; ++aY)
150 for (Standard_Integer aZ = 0; aZ <= 1; ++aZ)
152 BVH_Vec4f aCorner = aTransform->Transform() * BVH_Vec4f (
153 aX == 0 ? aBox.CornerMin().x() : aBox.CornerMax().x(),
154 aY == 0 ? aBox.CornerMin().y() : aBox.CornerMax().y(),
155 aZ == 0 ? aBox.CornerMin().z() : aBox.CornerMax().z(),
158 aTransformedBox.Add (reinterpret_cast<BVH_Vec3f&> (aCorner));
163 return aTransformedBox;
169 // =======================================================================
171 // purpose : Clears ray-tracing geometry
172 // =======================================================================
173 void OpenGl_RaytraceGeometry::Clear()
175 BVH_Geometry<Standard_ShortReal, 3>::BVH_Geometry::Clear();
177 std::vector<OpenGl_RaytraceLight,
178 NCollection_StdAllocator<OpenGl_RaytraceLight> > anEmptySources;
180 Sources.swap (anEmptySources);
182 std::vector<OpenGl_RaytraceMaterial,
183 NCollection_StdAllocator<OpenGl_RaytraceMaterial> > anEmptyMaterials;
185 Materials.swap (anEmptyMaterials);
190 struct OpenGL_BVHParallelBuilder
192 BVH_ObjectSet<Standard_ShortReal, 3>* Set;
194 OpenGL_BVHParallelBuilder (BVH_ObjectSet<Standard_ShortReal, 3>* theSet)
200 void operator() (const tbb::blocked_range<size_t>& theRange) const
202 for (size_t anObjectIdx = theRange.begin(); anObjectIdx != theRange.end(); ++anObjectIdx)
204 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
205 Set->Objects().ChangeValue (static_cast<Standard_Integer> (anObjectIdx)).operator->());
207 if (aTriangleSet != NULL)
217 // =======================================================================
218 // function : ProcessAcceleration
219 // purpose : Performs post-processing of high-level BVH
220 // =======================================================================
221 Standard_Boolean OpenGl_RaytraceGeometry::ProcessAcceleration()
223 #ifdef RAY_TRACE_PRINT_INFO
227 MarkDirty(); // force BVH rebuilding
229 #ifdef RAY_TRACE_PRINT_INFO
235 // If Intel TBB is available, perform the preliminary
236 // construction of bottom-level scene BVHs
237 tbb::parallel_for (tbb::blocked_range<size_t> (0, Size()),
238 OpenGL_BVHParallelBuilder (this));
241 myBottomLevelTreeDepth = 0;
243 for (Standard_Integer anObjectIdx = 0; anObjectIdx < Size(); ++anObjectIdx)
245 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
246 myObjects.ChangeValue (anObjectIdx).operator->());
248 Standard_ASSERT_RETURN (aTriangleSet != NULL,
249 "Error! Failed to get triangulation of OpenGL element", Standard_False);
251 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
252 "Error! Failed to update bottom-level BVH of OpenGL element", Standard_False);
254 myBottomLevelTreeDepth = Max (myBottomLevelTreeDepth, aTriangleSet->BVH()->Depth());
257 #ifdef RAY_TRACE_PRINT_INFO
260 std::cout << "Updating bottom-level BVHs (sec): " <<
261 aTimer.ElapsedTime() << std::endl;
264 #ifdef RAY_TRACE_PRINT_INFO
269 NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> > aBVH = BVH();
271 #ifdef RAY_TRACE_PRINT_INFO
274 std::cout << "Updating high-level BVH (sec): " <<
275 aTimer.ElapsedTime() << std::endl;
278 Standard_ASSERT_RETURN (!aBVH.IsNull(),
279 "Error! Failed to update high-level BVH of ray-tracing scene", Standard_False);
281 myHighLevelTreeDepth = aBVH->Depth();
283 Standard_Integer aVerticesOffset = 0;
284 Standard_Integer aElementsOffset = 0;
285 Standard_Integer aBVHNodesOffset = 0;
287 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
289 if (!aBVH->IsOuter (aNodeIdx))
292 Standard_ASSERT_RETURN (aBVH->BegPrimitive (aNodeIdx) == aBVH->EndPrimitive (aNodeIdx),
293 "Error! Invalid leaf node in high-level BVH (contains several objects)", Standard_False);
295 Standard_Integer anObjectIdx = aBVH->BegPrimitive (aNodeIdx);
297 Standard_ASSERT_RETURN (anObjectIdx < myObjects.Size(),
298 "Error! Invalid leaf node in high-level BVH (contains out-of-range object)", Standard_False);
300 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
301 myObjects.ChangeValue (anObjectIdx).operator->());
303 // Note: We overwrite node info record to store parameters
304 // of bottom-level BVH and triangulation of OpenGL element
306 aBVH->NodeInfoBuffer().at (aNodeIdx) = BVH_Vec4i (
307 anObjectIdx + 1 /* to keep leaf flag */, aBVHNodesOffset, aVerticesOffset, aElementsOffset);
309 aVerticesOffset += (int)aTriangleSet->Vertices.size();
310 aElementsOffset += (int)aTriangleSet->Elements.size();
311 aBVHNodesOffset += aTriangleSet->BVH()->Length();
314 return Standard_True;
317 // =======================================================================
318 // function : AccelerationOffset
319 // purpose : Returns offset of bottom-level BVH for given leaf node
320 // =======================================================================
321 Standard_Integer OpenGl_RaytraceGeometry::AccelerationOffset (Standard_Integer theNodeIdx)
323 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
325 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
326 return INVALID_OFFSET;
328 return aBVH->NodeInfoBuffer().at (theNodeIdx).y();
331 // =======================================================================
332 // function : VerticesOffset
333 // purpose : Returns offset of triangulation vertices for given leaf node
334 // =======================================================================
335 Standard_Integer OpenGl_RaytraceGeometry::VerticesOffset (Standard_Integer theNodeIdx)
337 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
339 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
340 return INVALID_OFFSET;
342 return aBVH->NodeInfoBuffer().at (theNodeIdx).z();
345 // =======================================================================
346 // function : ElementsOffset
347 // purpose : Returns offset of triangulation elements for given leaf node
348 // =======================================================================
349 Standard_Integer OpenGl_RaytraceGeometry::ElementsOffset (Standard_Integer theNodeIdx)
351 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
353 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
354 return INVALID_OFFSET;
356 return aBVH->NodeInfoBuffer().at (theNodeIdx).w();
359 // =======================================================================
360 // function : TriangleSet
361 // purpose : Returns triangulation data for given leaf node
362 // =======================================================================
363 OpenGl_TriangleSet* OpenGl_RaytraceGeometry::TriangleSet (Standard_Integer theNodeIdx)
365 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
367 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
370 if (aBVH->NodeInfoBuffer().at (theNodeIdx).x() > myObjects.Size())
373 return dynamic_cast<OpenGl_TriangleSet*> (myObjects.ChangeValue (
374 aBVH->NodeInfoBuffer().at (theNodeIdx).x() - 1).operator->());
377 // =======================================================================
378 // function : AcquireTextures
379 // purpose : Makes the OpenGL texture handles resident
380 // =======================================================================
381 Standard_Boolean OpenGl_RaytraceGeometry::AcquireTextures (const Handle(OpenGl_Context)& theContext) const
383 if (theContext->arbTexBindless == NULL)
385 return Standard_True;
388 #if !defined(GL_ES_VERSION_2_0)
389 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
391 theContext->arbTexBindless->glMakeTextureHandleResidentARB (myTextureHandles[anIdx]);
393 if (glGetError() != GL_NO_ERROR)
395 #ifdef RAY_TRACE_PRINT_INFO
396 std::cout << "Error: Failed to make OpenGL texture resident" << std::endl;
398 return Standard_False;
403 return Standard_True;
406 // =======================================================================
407 // function : ReleaseTextures
408 // purpose : Makes the OpenGL texture handles non-resident
409 // =======================================================================
410 Standard_Boolean OpenGl_RaytraceGeometry::ReleaseTextures (const Handle(OpenGl_Context)& theContext) const
412 if (theContext->arbTexBindless == NULL)
414 return Standard_True;
417 #if !defined(GL_ES_VERSION_2_0)
418 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
420 theContext->arbTexBindless->glMakeTextureHandleNonResidentARB (myTextureHandles[anIdx]);
422 if (glGetError() != GL_NO_ERROR)
424 #ifdef RAY_TRACE_PRINT_INFO
425 std::cout << "Error: Failed to make OpenGL texture non-resident" << std::endl;
427 return Standard_False;
432 return Standard_True;
435 // =======================================================================
436 // function : AddTexture
437 // purpose : Adds new OpenGL texture to the scene and returns its index
438 // =======================================================================
439 Standard_Integer OpenGl_RaytraceGeometry::AddTexture (const Handle(OpenGl_Texture)& theTexture)
441 NCollection_Vector<Handle (OpenGl_Texture)>::iterator anIter =
442 std::find (myTextures.begin(), myTextures.end(), theTexture);
444 if (anIter == myTextures.end())
446 if (myTextures.Size() >= MAX_TEX_NUMBER)
451 myTextures.Append (theTexture);
454 return static_cast<Standard_Integer> (anIter - myTextures.begin());
457 // =======================================================================
458 // function : UpdateTextureHandles
459 // purpose : Updates unique 64-bit texture handles to use in shaders
460 // =======================================================================
461 Standard_Boolean OpenGl_RaytraceGeometry::UpdateTextureHandles (const Handle(OpenGl_Context)& theContext)
463 if (theContext->arbTexBindless == NULL)
465 return Standard_False;
468 myTextureHandles.clear();
470 #if !defined(GL_ES_VERSION_2_0)
471 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
473 const GLuint64 aHandle = theContext->arbTexBindless->glGetTextureHandleARB (
474 myTextures.Value (anIdx)->TextureId());
476 if (glGetError() != GL_NO_ERROR)
478 #ifdef RAY_TRACE_PRINT_INFO
479 std::cout << "Error: Failed to get 64-bit handle of OpenGL texture" << std::endl;
481 return Standard_False;
484 myTextureHandles.push_back (aHandle);
488 return Standard_True;
491 namespace OpenGl_Raytrace
493 // =======================================================================
494 // function : IsRaytracedElement
495 // purpose : Checks to see if the element contains ray-trace geometry
496 // =======================================================================
497 Standard_Boolean IsRaytracedElement (const OpenGl_ElementNode* theNode)
499 OpenGl_PrimitiveArray* anArray = dynamic_cast<OpenGl_PrimitiveArray*> (theNode->elem);
500 return anArray != NULL
501 && anArray->DrawMode() >= GL_TRIANGLES;
504 // =======================================================================
505 // function : IsRaytracedElement
506 // purpose : Checks to see if the element contains ray-trace geometry
507 // =======================================================================
508 Standard_Boolean IsRaytracedElement (const OpenGl_Element* theElement)
510 const OpenGl_PrimitiveArray* anArray = dynamic_cast<const OpenGl_PrimitiveArray*> (theElement);
511 return anArray != NULL
512 && anArray->DrawMode() >= GL_TRIANGLES;
515 // =======================================================================
516 // function : IsRaytracedGroup
517 // purpose : Checks to see if the group contains ray-trace geometry
518 // =======================================================================
519 Standard_Boolean IsRaytracedGroup (const OpenGl_Group *theGroup)
521 const OpenGl_ElementNode* aNode;
522 for (aNode = theGroup->FirstNode(); aNode != NULL; aNode = aNode->next)
524 if (IsRaytracedElement (aNode))
526 return Standard_True;
529 return Standard_False;
532 // =======================================================================
533 // function : IsRaytracedStructure
534 // purpose : Checks to see if the structure contains ray-trace geometry
535 // =======================================================================
536 Standard_Boolean IsRaytracedStructure (const OpenGl_Structure* theStructure)
538 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups());
539 aGroupIter.More(); aGroupIter.Next())
541 if (aGroupIter.Value()->IsRaytracable())
542 return Standard_True;
544 for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures());
545 anIts.More(); anIts.Next())
547 if (IsRaytracedStructure (anIts.Value()))
548 return Standard_True;
550 return Standard_False;