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 (aCorner.xyz());
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 NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> > aBVH = aTriangleSet->BVH();
266 // correct data array of bottom-level BVH to set special flag for outer
267 // nodes in order to distinguish them from outer nodes of top-level BVH
268 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
270 if (aBVH->IsOuter (aNodeIdx))
272 aBVH->NodeInfoBuffer()[aNodeIdx].x() = -1;
276 myBottomLevelTreeDepth = Max (myBottomLevelTreeDepth, aTriangleSet->BVH()->Depth());
279 #ifdef RAY_TRACE_PRINT_INFO
282 std::cout << "Updating bottom-level BVHs (sec): " <<
283 aTimer.ElapsedTime() << std::endl;
286 #ifdef RAY_TRACE_PRINT_INFO
291 NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> > aBVH = BVH();
293 #ifdef RAY_TRACE_PRINT_INFO
296 std::cout << "Updating high-level BVH (sec): " <<
297 aTimer.ElapsedTime() << std::endl;
300 Standard_ASSERT_RETURN (!aBVH.IsNull(),
301 "Error! Failed to update high-level BVH of ray-tracing scene", Standard_False);
303 myHighLevelTreeDepth = aBVH->Depth();
305 Standard_Integer aVerticesOffset = 0;
306 Standard_Integer aElementsOffset = 0;
307 Standard_Integer aBVHNodesOffset = BVH()->Length();
309 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
311 if (!aBVH->IsOuter (aNodeIdx))
314 Standard_ASSERT_RETURN (aBVH->BegPrimitive (aNodeIdx) == aBVH->EndPrimitive (aNodeIdx),
315 "Error! Invalid leaf node in high-level BVH (contains several objects)", Standard_False);
317 Standard_Integer anObjectIdx = aBVH->BegPrimitive (aNodeIdx);
319 Standard_ASSERT_RETURN (anObjectIdx < myObjects.Size(),
320 "Error! Invalid leaf node in high-level BVH (contains out-of-range object)", Standard_False);
322 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
323 myObjects.ChangeValue (anObjectIdx).operator->());
325 // Note: We overwrite node info record to store parameters
326 // of bottom-level BVH and triangulation of OpenGL element
328 aBVH->NodeInfoBuffer().at (aNodeIdx) = BVH_Vec4i (
329 anObjectIdx + 1 /* to keep leaf flag */, aBVHNodesOffset, aVerticesOffset, aElementsOffset);
331 aVerticesOffset += (int)aTriangleSet->Vertices.size();
332 aElementsOffset += (int)aTriangleSet->Elements.size();
333 aBVHNodesOffset += aTriangleSet->BVH()->Length();
336 return Standard_True;
339 // =======================================================================
340 // function : AccelerationOffset
341 // purpose : Returns offset of bottom-level BVH for given leaf node
342 // =======================================================================
343 Standard_Integer OpenGl_RaytraceGeometry::AccelerationOffset (Standard_Integer theNodeIdx)
345 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
347 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
348 return INVALID_OFFSET;
350 return aBVH->NodeInfoBuffer().at (theNodeIdx).y();
353 // =======================================================================
354 // function : VerticesOffset
355 // purpose : Returns offset of triangulation vertices for given leaf node
356 // =======================================================================
357 Standard_Integer OpenGl_RaytraceGeometry::VerticesOffset (Standard_Integer theNodeIdx)
359 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
361 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
362 return INVALID_OFFSET;
364 return aBVH->NodeInfoBuffer().at (theNodeIdx).z();
367 // =======================================================================
368 // function : ElementsOffset
369 // purpose : Returns offset of triangulation elements for given leaf node
370 // =======================================================================
371 Standard_Integer OpenGl_RaytraceGeometry::ElementsOffset (Standard_Integer theNodeIdx)
373 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
375 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
376 return INVALID_OFFSET;
378 return aBVH->NodeInfoBuffer().at (theNodeIdx).w();
381 // =======================================================================
382 // function : TriangleSet
383 // purpose : Returns triangulation data for given leaf node
384 // =======================================================================
385 OpenGl_TriangleSet* OpenGl_RaytraceGeometry::TriangleSet (Standard_Integer theNodeIdx)
387 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
389 if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
392 if (aBVH->NodeInfoBuffer().at (theNodeIdx).x() > myObjects.Size())
395 return dynamic_cast<OpenGl_TriangleSet*> (myObjects.ChangeValue (
396 aBVH->NodeInfoBuffer().at (theNodeIdx).x() - 1).operator->());
399 // =======================================================================
400 // function : AcquireTextures
401 // purpose : Makes the OpenGL texture handles resident
402 // =======================================================================
403 Standard_Boolean OpenGl_RaytraceGeometry::AcquireTextures (const Handle(OpenGl_Context)& theContext) const
405 if (theContext->arbTexBindless == NULL)
407 return Standard_True;
410 #if !defined(GL_ES_VERSION_2_0)
411 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
413 theContext->arbTexBindless->glMakeTextureHandleResidentARB (myTextureHandles[anIdx]);
415 if (glGetError() != GL_NO_ERROR)
417 #ifdef RAY_TRACE_PRINT_INFO
418 std::cout << "Error: Failed to make OpenGL texture resident" << std::endl;
420 return Standard_False;
425 return Standard_True;
428 // =======================================================================
429 // function : ReleaseTextures
430 // purpose : Makes the OpenGL texture handles non-resident
431 // =======================================================================
432 Standard_Boolean OpenGl_RaytraceGeometry::ReleaseTextures (const Handle(OpenGl_Context)& theContext) const
434 if (theContext->arbTexBindless == NULL)
436 return Standard_True;
439 #if !defined(GL_ES_VERSION_2_0)
440 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
442 theContext->arbTexBindless->glMakeTextureHandleNonResidentARB (myTextureHandles[anIdx]);
444 if (glGetError() != GL_NO_ERROR)
446 #ifdef RAY_TRACE_PRINT_INFO
447 std::cout << "Error: Failed to make OpenGL texture non-resident" << std::endl;
449 return Standard_False;
454 return Standard_True;
457 // =======================================================================
458 // function : AddTexture
459 // purpose : Adds new OpenGL texture to the scene and returns its index
460 // =======================================================================
461 Standard_Integer OpenGl_RaytraceGeometry::AddTexture (const Handle(OpenGl_Texture)& theTexture)
463 NCollection_Vector<Handle (OpenGl_Texture)>::iterator anIter =
464 std::find (myTextures.begin(), myTextures.end(), theTexture);
466 if (anIter == myTextures.end())
468 if (myTextures.Size() >= MAX_TEX_NUMBER)
473 myTextures.Append (theTexture);
476 return static_cast<Standard_Integer> (anIter - myTextures.begin());
479 // =======================================================================
480 // function : UpdateTextureHandles
481 // purpose : Updates unique 64-bit texture handles to use in shaders
482 // =======================================================================
483 Standard_Boolean OpenGl_RaytraceGeometry::UpdateTextureHandles (const Handle(OpenGl_Context)& theContext)
485 if (theContext->arbTexBindless == NULL)
487 return Standard_False;
490 if (myTextureSampler.IsNull())
492 myTextureSampler = new OpenGl_Sampler();
493 myTextureSampler->Init (*theContext.operator->());
494 myTextureSampler->SetParameter (*theContext.operator->(), GL_TEXTURE_MIN_FILTER, GL_LINEAR);
495 myTextureSampler->SetParameter (*theContext.operator->(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
496 myTextureSampler->SetParameter (*theContext.operator->(), GL_TEXTURE_WRAP_S, GL_REPEAT);
497 myTextureSampler->SetParameter (*theContext.operator->(), GL_TEXTURE_WRAP_T, GL_REPEAT);
500 myTextureHandles.clear();
502 #if !defined(GL_ES_VERSION_2_0)
503 for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
505 const GLuint64 aHandle = theContext->arbTexBindless->glGetTextureSamplerHandleARB (
506 myTextures.Value (anIdx)->TextureId(), myTextureSampler->SamplerID());
508 if (glGetError() != GL_NO_ERROR)
510 #ifdef RAY_TRACE_PRINT_INFO
511 std::cout << "Error: Failed to get 64-bit handle of OpenGL texture" << std::endl;
513 return Standard_False;
516 myTextureHandles.push_back (aHandle);
520 return Standard_True;
523 namespace OpenGl_Raytrace
525 // =======================================================================
526 // function : IsRaytracedElement
527 // purpose : Checks to see if the element contains ray-trace geometry
528 // =======================================================================
529 Standard_Boolean IsRaytracedElement (const OpenGl_ElementNode* theNode)
531 OpenGl_PrimitiveArray* anArray = dynamic_cast<OpenGl_PrimitiveArray*> (theNode->elem);
532 return anArray != NULL
533 && anArray->DrawMode() >= GL_TRIANGLES;
536 // =======================================================================
537 // function : IsRaytracedElement
538 // purpose : Checks to see if the element contains ray-trace geometry
539 // =======================================================================
540 Standard_Boolean IsRaytracedElement (const OpenGl_Element* theElement)
542 const OpenGl_PrimitiveArray* anArray = dynamic_cast<const OpenGl_PrimitiveArray*> (theElement);
543 return anArray != NULL
544 && anArray->DrawMode() >= GL_TRIANGLES;
547 // =======================================================================
548 // function : IsRaytracedGroup
549 // purpose : Checks to see if the group contains ray-trace geometry
550 // =======================================================================
551 Standard_Boolean IsRaytracedGroup (const OpenGl_Group* theGroup)
553 for (const OpenGl_ElementNode* aNode = theGroup->FirstNode(); aNode != NULL; aNode = aNode->next)
555 if (IsRaytracedElement (aNode))
557 return Standard_True;
560 return Standard_False;
563 // =======================================================================
564 // function : IsRaytracedStructure
565 // purpose : Checks to see if the structure contains ray-trace geometry
566 // =======================================================================
567 Standard_Boolean IsRaytracedStructure (const OpenGl_Structure* theStructure)
569 for (OpenGl_Structure::GroupIterator anIter (theStructure->DrawGroups()); anIter.More(); anIter.Next())
571 if (anIter.Value()->IsRaytracable())
573 return Standard_True;
576 return Standard_False;