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 <OSD_Timer.hxx>
17 #include <OSD_Parallel.hxx>
18 #include <Standard_Assert.hxx>
19 #include <OpenGl_ArbTexBindless.hxx>
20 #include <OpenGl_PrimitiveArray.hxx>
21 #include <OpenGl_SceneGeometry.hxx>
22 #include <OpenGl_Structure.hxx>
23 #include <Graphic3d_GraphicDriver.hxx>
25 //! Use this macro to output BVH profiling info
26 // #define RAY_TRACE_PRINT_INFO
30 //! Useful constant for null floating-point 4D vector.
31 static const BVH_Vec4f ZERO_VEC_4F;
34 // =======================================================================
35 // function : OpenGl_RaytraceMaterial
36 // purpose : Creates new default material
37 // =======================================================================
38 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial()
39 : Ambient (ZERO_VEC_4F),
40 Diffuse (ZERO_VEC_4F),
41 Specular (ZERO_VEC_4F),
42 Emission (ZERO_VEC_4F),
43 Reflection (ZERO_VEC_4F),
44 Refraction (ZERO_VEC_4F),
45 Transparency (ZERO_VEC_4F)
48 // =======================================================================
49 // function : OpenGl_RaytraceMaterial
50 // purpose : Creates new material with specified properties
51 // =======================================================================
52 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial (const BVH_Vec4f& theAmbient,
53 const BVH_Vec4f& theDiffuse,
54 const BVH_Vec4f& theSpecular)
55 : Ambient (theAmbient),
57 Specular (theSpecular),
58 Emission (ZERO_VEC_4F),
59 Reflection (ZERO_VEC_4F),
60 Refraction (ZERO_VEC_4F),
61 Transparency (ZERO_VEC_4F)
66 // =======================================================================
67 // function : OpenGl_RaytraceMaterial
68 // purpose : Creates new material with specified properties
69 // =======================================================================
70 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial (const BVH_Vec4f& theAmbient,
71 const BVH_Vec4f& theDiffuse,
72 const BVH_Vec4f& theSpecular,
73 const BVH_Vec4f& theEmission,
74 const BVH_Vec4f& theTranspar)
75 : Ambient (theAmbient),
77 Specular (theSpecular),
78 Emission (theEmission),
79 Reflection (ZERO_VEC_4F),
80 Refraction (ZERO_VEC_4F),
81 Transparency (theTranspar)
86 // =======================================================================
87 // function : OpenGl_RaytraceMaterial
88 // purpose : Creates new material with specified properties
89 // =======================================================================
90 OpenGl_RaytraceMaterial::OpenGl_RaytraceMaterial (const BVH_Vec4f& theAmbient,
91 const BVH_Vec4f& theDiffuse,
92 const BVH_Vec4f& theSpecular,
93 const BVH_Vec4f& theEmission,
94 const BVH_Vec4f& theTranspar,
95 const BVH_Vec4f& theReflection,
96 const BVH_Vec4f& theRefraction)
97 : Ambient (theAmbient),
99 Specular (theSpecular),
100 Emission (theEmission),
101 Reflection (theReflection),
102 Refraction (theRefraction),
103 Transparency (theTranspar)
108 // =======================================================================
109 // function : OpenGl_LightSource
110 // purpose : Creates new light source
111 // =======================================================================
112 OpenGl_RaytraceLight::OpenGl_RaytraceLight (const BVH_Vec4f& theDiffuse,
113 const BVH_Vec4f& thePosition)
114 : Diffuse (theDiffuse),
115 Position (thePosition)
120 // =======================================================================
122 // purpose : Returns centroid position along the given axis
123 // =======================================================================
124 Standard_ShortReal OpenGl_TriangleSet::Center (
125 const Standard_Integer theIndex, const Standard_Integer theAxis) const
127 // Note: Experiments show that the use of the box centroid (instead
128 // of the triangle centroid) increases render performance up to 12%
130 const BVH_Vec4i& aTriangle = Elements[theIndex];
132 const Standard_ShortReal aVertex0 =
133 BVH::VecComp<Standard_ShortReal, 3>::Get (Vertices[aTriangle.x()], theAxis);
134 const Standard_ShortReal aVertex1 =
135 BVH::VecComp<Standard_ShortReal, 3>::Get (Vertices[aTriangle.y()], theAxis);
136 const Standard_ShortReal aVertex2 =
137 BVH::VecComp<Standard_ShortReal, 3>::Get (Vertices[aTriangle.z()], theAxis);
139 return (Min (Min (aVertex0, aVertex1), aVertex2) +
140 Max (Max (aVertex0, aVertex1), aVertex2)) * 0.5f;
143 // =======================================================================
145 // purpose : Returns AABB of primitive set
146 // =======================================================================
147 OpenGl_TriangleSet::BVH_BoxNt OpenGl_TriangleSet::Box() const
149 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
150 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (Properties().operator->());
152 BVH_BoxNt aBox = BVH_PrimitiveSet<Standard_ShortReal, 3>::Box();
154 if (aTransform != NULL)
156 BVH_BoxNt aTransformedBox;
158 for (Standard_Integer aX = 0; aX <= 1; ++aX)
160 for (Standard_Integer aY = 0; aY <= 1; ++aY)
162 for (Standard_Integer aZ = 0; aZ <= 1; ++aZ)
164 BVH_Vec4f aCorner = aTransform->Transform() * BVH_Vec4f (
165 aX == 0 ? aBox.CornerMin().x() : aBox.CornerMax().x(),
166 aY == 0 ? aBox.CornerMin().y() : aBox.CornerMax().y(),
167 aZ == 0 ? aBox.CornerMin().z() : aBox.CornerMax().z(),
170 aTransformedBox.Add (reinterpret_cast<BVH_Vec3f&> (aCorner));
175 return aTransformedBox;
181 // =======================================================================
182 // function : OpenGl_TriangleSet
183 // purpose : Creates new OpenGL element triangulation
184 // =======================================================================
185 OpenGl_TriangleSet::OpenGl_TriangleSet (const Standard_Size theArrayID)
186 : BVH_Triangulation<Standard_ShortReal, 3>(),
187 myArrayID (theArrayID)
189 myBuilder = new BVH_BinnedBuilder<Standard_ShortReal, 3 /* dim */, 48 /* bins */>
190 (5 /* leaf size */, 32 /* max height */, Standard_False, OSD_Parallel::NbLogicalProcessors() + 1 /* threads */);
193 // =======================================================================
195 // purpose : Clears ray-tracing geometry
196 // =======================================================================
197 void OpenGl_RaytraceGeometry::Clear()
199 BVH_Geometry<Standard_ShortReal, 3>::BVH_Geometry::Clear();
201 std::vector<OpenGl_RaytraceLight,
202 NCollection_StdAllocator<OpenGl_RaytraceLight> > anEmptySources;
204 Sources.swap (anEmptySources);
206 std::vector<OpenGl_RaytraceMaterial,
207 NCollection_StdAllocator<OpenGl_RaytraceMaterial> > anEmptyMaterials;
209 Materials.swap (anEmptyMaterials);
212 struct OpenGL_BVHParallelBuilder
214 BVH_ObjectSet<Standard_ShortReal, 3>* Set;
216 OpenGL_BVHParallelBuilder (BVH_ObjectSet<Standard_ShortReal, 3>* theSet)
222 void operator() (const Standard_Integer theObjectIdx) const
224 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
225 Set->Objects().ChangeValue (static_cast<Standard_Integer> (theObjectIdx)).operator->());
227 if (aTriangleSet != NULL)
232 // =======================================================================
233 // function : ProcessAcceleration
234 // purpose : Performs post-processing of high-level BVH
235 // =======================================================================
236 Standard_Boolean OpenGl_RaytraceGeometry::ProcessAcceleration()
238 #ifdef RAY_TRACE_PRINT_INFO
242 MarkDirty(); // force BVH rebuilding
244 #ifdef RAY_TRACE_PRINT_INFO
249 OSD_Parallel::For(0, Size(), OpenGL_BVHParallelBuilder(this));
251 myBottomLevelTreeDepth = 0;
253 for (Standard_Integer anObjectIdx = 0; anObjectIdx < Size(); ++anObjectIdx)
255 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
256 myObjects.ChangeValue (anObjectIdx).operator->());
258 Standard_ASSERT_RETURN (aTriangleSet != NULL,
259 "Error! Failed to get triangulation of OpenGL element", Standard_False);
261 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
262 "Error! Failed to update bottom-level BVH of OpenGL element", Standard_False);
264 myBottomLevelTreeDepth = Max (myBottomLevelTreeDepth, aTriangleSet->BVH()->Depth());
267 #ifdef RAY_TRACE_PRINT_INFO
270 std::cout << "Updating bottom-level BVHs (sec): " <<
271 aTimer.ElapsedTime() << std::endl;
274 #ifdef RAY_TRACE_PRINT_INFO
279 NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> > aBVH = BVH();
281 #ifdef RAY_TRACE_PRINT_INFO
284 std::cout << "Updating high-level BVH (sec): " <<
285 aTimer.ElapsedTime() << std::endl;
288 Standard_ASSERT_RETURN (!aBVH.IsNull(),
289 "Error! Failed to update high-level BVH of ray-tracing scene", Standard_False);
291 myHighLevelTreeDepth = aBVH->Depth();
293 Standard_Integer aVerticesOffset = 0;
294 Standard_Integer aElementsOffset = 0;
295 Standard_Integer aBVHNodesOffset = BVH()->Length();
297 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
299 if (!aBVH->IsOuter (aNodeIdx))
302 Standard_ASSERT_RETURN (aBVH->BegPrimitive (aNodeIdx) == aBVH->EndPrimitive (aNodeIdx),
303 "Error! Invalid leaf node in high-level BVH (contains several objects)", Standard_False);
305 Standard_Integer anObjectIdx = aBVH->BegPrimitive (aNodeIdx);
307 Standard_ASSERT_RETURN (anObjectIdx < myObjects.Size(),
308 "Error! Invalid leaf node in high-level BVH (contains out-of-range object)", Standard_False);
310 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
311 myObjects.ChangeValue (anObjectIdx).operator->());
313 // Note: We overwrite node info record to store parameters
314 // of bottom-level BVH and triangulation of OpenGL element
316 aBVH->NodeInfoBuffer().at (aNodeIdx) = BVH_Vec4i (
317 anObjectIdx + 1 /* to keep leaf flag */, aBVHNodesOffset, aVerticesOffset, aElementsOffset);
319 aVerticesOffset += (int)aTriangleSet->Vertices.size();
320 aElementsOffset += (int)aTriangleSet->Elements.size();
321 aBVHNodesOffset += aTriangleSet->BVH()->Length();
324 return Standard_True;
327 // =======================================================================
328 // function : AccelerationOffset
329 // purpose : Returns offset of bottom-level BVH for given leaf node
330 // =======================================================================
331 Standard_Integer OpenGl_RaytraceGeometry::AccelerationOffset (Standard_Integer theNodeIdx)
333 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
335 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
336 return INVALID_OFFSET;
338 return aBVH->NodeInfoBuffer().at (theNodeIdx).y();
341 // =======================================================================
342 // function : VerticesOffset
343 // purpose : Returns offset of triangulation vertices for given leaf node
344 // =======================================================================
345 Standard_Integer OpenGl_RaytraceGeometry::VerticesOffset (Standard_Integer theNodeIdx)
347 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
349 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
350 return INVALID_OFFSET;
352 return aBVH->NodeInfoBuffer().at (theNodeIdx).z();
355 // =======================================================================
356 // function : ElementsOffset
357 // purpose : Returns offset of triangulation elements for given leaf node
358 // =======================================================================
359 Standard_Integer OpenGl_RaytraceGeometry::ElementsOffset (Standard_Integer theNodeIdx)
361 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
363 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
364 return INVALID_OFFSET;
366 return aBVH->NodeInfoBuffer().at (theNodeIdx).w();
369 // =======================================================================
370 // function : TriangleSet
371 // purpose : Returns triangulation data for given leaf node
372 // =======================================================================
373 OpenGl_TriangleSet* OpenGl_RaytraceGeometry::TriangleSet (Standard_Integer theNodeIdx)
375 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
377 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
380 if (aBVH->NodeInfoBuffer().at (theNodeIdx).x() > myObjects.Size())
383 return dynamic_cast<OpenGl_TriangleSet*> (myObjects.ChangeValue (
384 aBVH->NodeInfoBuffer().at (theNodeIdx).x() - 1).operator->());
387 // =======================================================================
388 // function : AcquireTextures
389 // purpose : Makes the OpenGL texture handles resident
390 // =======================================================================
391 Standard_Boolean OpenGl_RaytraceGeometry::AcquireTextures (const Handle(OpenGl_Context)& theContext) const
393 if (theContext->arbTexBindless == NULL)
395 return Standard_True;
398 #if !defined(GL_ES_VERSION_2_0)
399 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
401 theContext->arbTexBindless->glMakeTextureHandleResidentARB (myTextureHandles[anIdx]);
403 if (glGetError() != GL_NO_ERROR)
405 #ifdef RAY_TRACE_PRINT_INFO
406 std::cout << "Error: Failed to make OpenGL texture resident" << std::endl;
408 return Standard_False;
413 return Standard_True;
416 // =======================================================================
417 // function : ReleaseTextures
418 // purpose : Makes the OpenGL texture handles non-resident
419 // =======================================================================
420 Standard_Boolean OpenGl_RaytraceGeometry::ReleaseTextures (const Handle(OpenGl_Context)& theContext) const
422 if (theContext->arbTexBindless == NULL)
424 return Standard_True;
427 #if !defined(GL_ES_VERSION_2_0)
428 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
430 theContext->arbTexBindless->glMakeTextureHandleNonResidentARB (myTextureHandles[anIdx]);
432 if (glGetError() != GL_NO_ERROR)
434 #ifdef RAY_TRACE_PRINT_INFO
435 std::cout << "Error: Failed to make OpenGL texture non-resident" << std::endl;
437 return Standard_False;
442 return Standard_True;
445 // =======================================================================
446 // function : AddTexture
447 // purpose : Adds new OpenGL texture to the scene and returns its index
448 // =======================================================================
449 Standard_Integer OpenGl_RaytraceGeometry::AddTexture (const Handle(OpenGl_Texture)& theTexture)
451 NCollection_Vector<Handle (OpenGl_Texture)>::iterator anIter =
452 std::find (myTextures.begin(), myTextures.end(), theTexture);
454 if (anIter == myTextures.end())
456 if (myTextures.Size() >= MAX_TEX_NUMBER)
461 myTextures.Append (theTexture);
464 return static_cast<Standard_Integer> (anIter - myTextures.begin());
467 // =======================================================================
468 // function : UpdateTextureHandles
469 // purpose : Updates unique 64-bit texture handles to use in shaders
470 // =======================================================================
471 Standard_Boolean OpenGl_RaytraceGeometry::UpdateTextureHandles (const Handle(OpenGl_Context)& theContext)
473 if (theContext->arbTexBindless == NULL)
475 return Standard_False;
478 myTextureHandles.clear();
480 #if !defined(GL_ES_VERSION_2_0)
481 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
483 const GLuint64 aHandle = theContext->arbTexBindless->glGetTextureHandleARB (
484 myTextures.Value (anIdx)->TextureId());
486 if (glGetError() != GL_NO_ERROR)
488 #ifdef RAY_TRACE_PRINT_INFO
489 std::cout << "Error: Failed to get 64-bit handle of OpenGL texture" << std::endl;
491 return Standard_False;
494 myTextureHandles.push_back (aHandle);
498 return Standard_True;
501 namespace OpenGl_Raytrace
503 // =======================================================================
504 // function : IsRaytracedElement
505 // purpose : Checks to see if the element contains ray-trace geometry
506 // =======================================================================
507 Standard_Boolean IsRaytracedElement (const OpenGl_ElementNode* theNode)
509 OpenGl_PrimitiveArray* anArray = dynamic_cast<OpenGl_PrimitiveArray*> (theNode->elem);
510 return anArray != NULL
511 && anArray->DrawMode() >= GL_TRIANGLES;
514 // =======================================================================
515 // function : IsRaytracedElement
516 // purpose : Checks to see if the element contains ray-trace geometry
517 // =======================================================================
518 Standard_Boolean IsRaytracedElement (const OpenGl_Element* theElement)
520 const OpenGl_PrimitiveArray* anArray = dynamic_cast<const OpenGl_PrimitiveArray*> (theElement);
521 return anArray != NULL
522 && anArray->DrawMode() >= GL_TRIANGLES;
525 // =======================================================================
526 // function : IsRaytracedGroup
527 // purpose : Checks to see if the group contains ray-trace geometry
528 // =======================================================================
529 Standard_Boolean IsRaytracedGroup (const OpenGl_Group* theGroup)
531 for (const OpenGl_ElementNode* aNode = theGroup->FirstNode(); aNode != NULL; aNode = aNode->next)
533 if (IsRaytracedElement (aNode))
535 return Standard_True;
538 return Standard_False;
541 // =======================================================================
542 // function : IsRaytracedStructure
543 // purpose : Checks to see if the structure contains ray-trace geometry
544 // =======================================================================
545 Standard_Boolean IsRaytracedStructure (const OpenGl_Structure* theStructure)
547 for (OpenGl_Structure::GroupIterator anIter (theStructure->DrawGroups()); anIter.More(); anIter.Next())
549 if (anIter.Value()->IsRaytracable())
551 return Standard_True;
554 return Standard_False;