c618c299d99144ed1abcac5e6abaa20a0b86003b
[occt.git] / src / OpenGl / OpenGl_SceneGeometry.cxx
1 // Created on: 2013-08-27
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2013 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
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.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #ifdef HAVE_TBB
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
23   #endif
24
25   #include <tbb/tbb.h>
26 #endif
27
28 #include <OpenGl_SceneGeometry.hxx>
29
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>
35
36 //! Use this macro to output BVH profiling info
37 // #define RAY_TRACE_PRINT_INFO
38
39 namespace
40 {
41   //! Useful constant for null floating-point 4D vector.
42   static const BVH_Vec4f ZERO_VEC_4F;
43 }
44
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)
57 { }
58
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),
67   Diffuse      (theDiffuse),
68   Specular     (theSpecular),
69   Emission     (ZERO_VEC_4F),
70   Reflection   (ZERO_VEC_4F),
71   Refraction   (ZERO_VEC_4F),
72   Transparency (ZERO_VEC_4F)
73 {
74   //
75 }
76
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),
87   Diffuse      (theDiffuse),
88   Specular     (theSpecular),
89   Emission     (theEmission),
90   Reflection   (ZERO_VEC_4F),
91   Refraction   (ZERO_VEC_4F),
92   Transparency (theTranspar)
93 {
94   //
95 }
96
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)
115 {
116   //
117 }
118
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)
127 {
128   //
129 }
130
131 // =======================================================================
132 // function : Box
133 // purpose  : Returns AABB of primitive set
134 // =======================================================================
135 OpenGl_TriangleSet::BVH_BoxNt OpenGl_TriangleSet::Box() const
136 {
137   const BVH_Transform<Standard_ShortReal, 4>* aTransform =
138     dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (Properties().operator->());
139
140   BVH_BoxNt aBox = BVH_PrimitiveSet<Standard_ShortReal, 3>::Box();
141
142   if (aTransform != NULL)
143   {
144     BVH_BoxNt aTransformedBox;
145
146     for (Standard_Integer aX = 0; aX <= 1; ++aX)
147     {
148       for (Standard_Integer aY = 0; aY <= 1; ++aY)
149       {
150         for (Standard_Integer aZ = 0; aZ <= 1; ++aZ)
151         {
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(),
156             1.f);
157
158           aTransformedBox.Add (reinterpret_cast<BVH_Vec3f&> (aCorner));
159         }
160       }
161     }
162
163     return aTransformedBox;
164   }
165
166   return aBox;
167 }
168
169 // =======================================================================
170 // function : Clear
171 // purpose  : Clears ray-tracing geometry
172 // =======================================================================
173 void OpenGl_RaytraceGeometry::Clear()
174 {
175   BVH_Geometry<Standard_ShortReal, 3>::BVH_Geometry::Clear();
176
177   std::vector<OpenGl_RaytraceLight,
178     NCollection_StdAllocator<OpenGl_RaytraceLight> > anEmptySources;
179
180   Sources.swap (anEmptySources);
181
182   std::vector<OpenGl_RaytraceMaterial,
183     NCollection_StdAllocator<OpenGl_RaytraceMaterial> > anEmptyMaterials;
184
185   Materials.swap (anEmptyMaterials);
186 }
187
188 #ifdef HAVE_TBB
189
190 struct OpenGL_BVHParallelBuilder
191 {
192   BVH_ObjectSet<Standard_ShortReal, 3>* Set;
193
194   OpenGL_BVHParallelBuilder (BVH_ObjectSet<Standard_ShortReal, 3>* theSet)
195     : Set (theSet)
196   {
197     //
198   }
199
200   void operator() (const tbb::blocked_range<size_t>& theRange) const
201   {
202     for (size_t anObjectIdx = theRange.begin(); anObjectIdx != theRange.end(); ++anObjectIdx)
203     {
204       OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
205         Set->Objects().ChangeValue (static_cast<Standard_Integer> (anObjectIdx)).operator->());
206
207       if (aTriangleSet != NULL)
208       {
209         aTriangleSet->BVH();
210       }
211     }
212   }
213 };
214
215 #endif
216
217 // =======================================================================
218 // function : ProcessAcceleration
219 // purpose  : Performs post-processing of high-level BVH
220 // =======================================================================
221 Standard_Boolean OpenGl_RaytraceGeometry::ProcessAcceleration()
222 {
223 #ifdef RAY_TRACE_PRINT_INFO
224     OSD_Timer aTimer;
225 #endif
226
227   MarkDirty(); // force BVH rebuilding
228
229 #ifdef RAY_TRACE_PRINT_INFO
230   aTimer.Reset();
231   aTimer.Start();
232 #endif
233
234 #ifdef HAVE_TBB
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));
239 #endif
240
241   myBottomLevelTreeDepth = 0;
242
243   for (Standard_Integer anObjectIdx = 0; anObjectIdx < Size(); ++anObjectIdx)
244   {
245     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
246       myObjects.ChangeValue (anObjectIdx).operator->());
247
248     Standard_ASSERT_RETURN (aTriangleSet != NULL,
249       "Error! Failed to get triangulation of OpenGL element", Standard_False);
250
251     Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
252       "Error! Failed to update bottom-level BVH of OpenGL element", Standard_False);
253
254     myBottomLevelTreeDepth = Max (myBottomLevelTreeDepth, aTriangleSet->BVH()->Depth());
255   }
256
257 #ifdef RAY_TRACE_PRINT_INFO
258   aTimer.Stop();
259
260   std::cout << "Updating bottom-level BVHs (sec): " <<
261     aTimer.ElapsedTime() << std::endl;
262 #endif
263
264 #ifdef RAY_TRACE_PRINT_INFO
265   aTimer.Reset();
266   aTimer.Start();
267 #endif
268
269   NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> > aBVH = BVH();
270
271 #ifdef RAY_TRACE_PRINT_INFO
272   aTimer.Stop();
273
274   std::cout << "Updating high-level BVH (sec): " <<
275     aTimer.ElapsedTime() << std::endl;
276 #endif
277
278   Standard_ASSERT_RETURN (!aBVH.IsNull(),
279     "Error! Failed to update high-level BVH of ray-tracing scene", Standard_False);
280
281   myHighLevelTreeDepth = aBVH->Depth();
282
283   Standard_Integer aVerticesOffset = 0;
284   Standard_Integer aElementsOffset = 0;
285   Standard_Integer aBVHNodesOffset = 0;
286
287   for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
288   {
289     if (!aBVH->IsOuter (aNodeIdx))
290       continue;
291
292     Standard_ASSERT_RETURN (aBVH->BegPrimitive (aNodeIdx) == aBVH->EndPrimitive (aNodeIdx),
293       "Error! Invalid leaf node in high-level BVH (contains several objects)", Standard_False);
294
295     Standard_Integer anObjectIdx = aBVH->BegPrimitive (aNodeIdx);
296
297     Standard_ASSERT_RETURN (anObjectIdx < myObjects.Size(),
298       "Error! Invalid leaf node in high-level BVH (contains out-of-range object)", Standard_False);
299
300     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
301       myObjects.ChangeValue (anObjectIdx).operator->());
302
303     // Note: We overwrite node info record to store parameters
304     // of bottom-level BVH and triangulation of OpenGL element
305
306     aBVH->NodeInfoBuffer().at (aNodeIdx) = BVH_Vec4i (
307       anObjectIdx + 1 /* to keep leaf flag */, aBVHNodesOffset, aVerticesOffset, aElementsOffset);
308
309     aVerticesOffset += (int)aTriangleSet->Vertices.size();
310     aElementsOffset += (int)aTriangleSet->Elements.size();
311     aBVHNodesOffset += aTriangleSet->BVH()->Length();
312   }
313
314   return Standard_True;
315 }
316
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)
322 {
323   const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
324
325   if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
326     return INVALID_OFFSET;
327
328   return aBVH->NodeInfoBuffer().at (theNodeIdx).y();
329 }
330
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)
336 {
337   const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
338
339   if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
340     return INVALID_OFFSET;
341
342   return aBVH->NodeInfoBuffer().at (theNodeIdx).z();
343 }
344
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)
350 {
351   const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
352
353   if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
354     return INVALID_OFFSET;
355
356   return aBVH->NodeInfoBuffer().at (theNodeIdx).w();
357 }
358
359 // =======================================================================
360 // function : TriangleSet
361 // purpose  : Returns triangulation data for given leaf node
362 // =======================================================================
363 OpenGl_TriangleSet* OpenGl_RaytraceGeometry::TriangleSet (Standard_Integer theNodeIdx)
364 {
365   const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = BVH();
366
367   if (theNodeIdx >= aBVH->Length() || !aBVH->IsOuter (theNodeIdx))
368     return NULL;
369
370   if (aBVH->NodeInfoBuffer().at (theNodeIdx).x() > myObjects.Size())
371     return NULL;
372
373   return dynamic_cast<OpenGl_TriangleSet*> (myObjects.ChangeValue (
374     aBVH->NodeInfoBuffer().at (theNodeIdx).x() - 1).operator->());
375 }
376
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
382 {
383   if (theContext->arbTexBindless == NULL)
384   {
385     return Standard_True;
386   }
387
388 #if !defined(GL_ES_VERSION_2_0)
389   for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
390   {
391     theContext->arbTexBindless->glMakeTextureHandleResidentARB (myTextureHandles[anIdx]);
392
393     if (glGetError() != GL_NO_ERROR)
394     {
395 #ifdef RAY_TRACE_PRINT_INFO
396       std::cout << "Error: Failed to make OpenGL texture resident" << std::endl;
397 #endif
398       return Standard_False;
399     }
400   }
401 #endif
402
403   return Standard_True;
404 }
405
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
411 {
412   if (theContext->arbTexBindless == NULL)
413   {
414     return Standard_True;
415   }
416
417 #if !defined(GL_ES_VERSION_2_0)
418   for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
419   {
420     theContext->arbTexBindless->glMakeTextureHandleNonResidentARB (myTextureHandles[anIdx]);
421
422     if (glGetError() != GL_NO_ERROR)
423     {
424 #ifdef RAY_TRACE_PRINT_INFO
425       std::cout << "Error: Failed to make OpenGL texture non-resident" << std::endl;
426 #endif
427       return Standard_False;
428     }
429   }
430 #endif
431
432   return Standard_True;
433 }
434
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)
440 {
441   NCollection_Vector<Handle (OpenGl_Texture)>::iterator anIter =
442     std::find (myTextures.begin(), myTextures.end(), theTexture);
443
444   if (anIter == myTextures.end())
445   {
446     if (myTextures.Size() >= MAX_TEX_NUMBER)
447     {
448       return -1;
449     }
450
451     myTextures.Append (theTexture);
452   }
453
454   return static_cast<Standard_Integer> (anIter - myTextures.begin());
455 }
456
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)
462 {
463   if (theContext->arbTexBindless == NULL)
464   {
465     return Standard_False;
466   }
467
468   myTextureHandles.clear();
469
470 #if !defined(GL_ES_VERSION_2_0)
471   for (Standard_Integer anIdx = 0; anIdx < myTextures.Size(); ++anIdx)
472   {
473     const GLuint64 aHandle = theContext->arbTexBindless->glGetTextureHandleARB (
474       myTextures.Value (anIdx)->TextureId());
475
476     if (glGetError() != GL_NO_ERROR)
477     {
478 #ifdef RAY_TRACE_PRINT_INFO
479       std::cout << "Error: Failed to get 64-bit handle of OpenGL texture" << std::endl;
480 #endif
481       return Standard_False;
482     }
483
484     myTextureHandles.push_back (aHandle);
485   }
486 #endif
487
488   return Standard_True;
489 }
490
491 namespace OpenGl_Raytrace
492 {
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)
498   {
499     OpenGl_PrimitiveArray* anArray = dynamic_cast<OpenGl_PrimitiveArray*> (theNode->elem);
500     return anArray != NULL
501         && anArray->DrawMode() >= GL_TRIANGLES;
502   }
503
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)
509   {
510     const OpenGl_PrimitiveArray* anArray = dynamic_cast<const OpenGl_PrimitiveArray*> (theElement);
511     return anArray != NULL
512         && anArray->DrawMode() >= GL_TRIANGLES;
513   }
514
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)
520   {
521     const OpenGl_ElementNode* aNode;
522     for (aNode = theGroup->FirstNode(); aNode != NULL; aNode = aNode->next)
523     {
524       if (IsRaytracedElement (aNode))
525       {
526         return Standard_True;
527       }
528     }
529     return Standard_False;
530   }
531
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)
537   {
538     for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups());
539          aGroupIter.More(); aGroupIter.Next())
540     {
541       if (aGroupIter.Value()->IsRaytracable())
542         return Standard_True;
543     }
544     for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures());
545          anIts.More(); anIts.Next())
546     {
547       if (IsRaytracedStructure (anIts.Value()))
548         return Standard_True;
549     }
550     return Standard_False;
551   }
552 }