0025376: Inconsistence between function and derivatives evaluation in Extrema_GlobOpt...
[occt.git] / src / OpenGl / OpenGl_Workspace_Raytrace.cxx
CommitLineData
e276548b 1// Created on: 2013-08-27
2// Created by: Denis BOGOLEPOV
3// Copyright (c) 2013 OPEN CASCADE SAS
4//
973c2be1 5// This file is part of Open CASCADE Technology software library.
e276548b 6//
d5f74e42 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
973c2be1 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.
e276548b 12//
973c2be1 13// Alternatively, this file may be used under the terms of Open CASCADE
14// commercial license or contractual agreement.
e276548b 15
b7cd4ba7 16#include <OpenGl_Workspace.hxx>
17
fc73a202 18#include <NCollection_Mat4.hxx>
19#include <OpenGl_ArbFBO.hxx>
20#include <OpenGl_FrameBuffer.hxx>
b7cd4ba7 21#include <OpenGl_PrimitiveArray.hxx>
e276548b 22#include <OpenGl_Texture.hxx>
fc73a202 23#include <OpenGl_VertexBuffer.hxx>
e276548b 24#include <OpenGl_View.hxx>
fc73a202 25#include <OSD_File.hxx>
26#include <OSD_Protection.hxx>
265d4508 27#include <Standard_Assert.hxx>
e276548b 28
29using namespace OpenGl_Raytrace;
30
31//! Use this macro to output ray-tracing debug info
fc73a202 32// #define RAY_TRACE_PRINT_INFO
e276548b 33
34#ifdef RAY_TRACE_PRINT_INFO
35 #include <OSD_Timer.hxx>
36#endif
37
e276548b 38// =======================================================================
39// function : MatVecMult
40// purpose : Multiples 4x4 matrix by 4D vector
41// =======================================================================
265d4508 42template<typename T>
43BVH_Vec4f MatVecMult (const T m[16], const BVH_Vec4f& v)
e276548b 44{
265d4508 45 return BVH_Vec4f (
e276548b 46 static_cast<float> (m[ 0] * v.x() + m[ 4] * v.y() +
47 m[ 8] * v.z() + m[12] * v.w()),
48 static_cast<float> (m[ 1] * v.x() + m[ 5] * v.y() +
49 m[ 9] * v.z() + m[13] * v.w()),
50 static_cast<float> (m[ 2] * v.x() + m[ 6] * v.y() +
51 m[10] * v.z() + m[14] * v.w()),
52 static_cast<float> (m[ 3] * v.x() + m[ 7] * v.y() +
53 m[11] * v.z() + m[15] * v.w()));
54}
55
56// =======================================================================
e276548b 57// function : UpdateRaytraceGeometry
58// purpose : Updates 3D scene geometry for ray tracing
59// =======================================================================
84c71f29 60Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (GeomUpdateMode theMode)
e276548b 61{
62 if (myView.IsNull())
63 return Standard_False;
64
84c71f29 65 // Note: In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for modifications
e276548b 66 // This is light-weight procedure performed for each frame
67
84c71f29 68 if (theMode == OpenGl_GUM_CHECK)
e276548b 69 {
84c71f29 70 if (myLayersModificationStatus != myView->LayerList().ModificationState())
71 {
72 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
73 }
74 }
75 else if (theMode == OpenGl_GUM_PREPARE)
76 {
77 myRaytraceGeometry.ClearMaterials();
78 myArrayToTrianglesMap.clear();
e276548b 79
80 myIsRaytraceDataValid = Standard_False;
81 }
e276548b 82
83 // The set of processed structures (reflected to ray-tracing)
84 // This set is used to remove out-of-date records from the
85 // hash map of structures
86 std::set<const OpenGl_Structure*> anElements;
87
84c71f29 88 // Set of all currently visible and "raytracable" primitive arrays.
8d3f219f 89 std::set<Standard_Size> anArrayIDs;
84c71f29 90
e276548b 91 const OpenGl_LayerList& aList = myView->LayerList();
92
93 for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
94 {
c5751993 95 const OpenGl_PriorityList& aPriorityList = anLayerIt.Value().PriorityList();
e276548b 96
97 if (aPriorityList.NbStructures() == 0)
98 continue;
99
100 const OpenGl_ArrayOfStructure& aStructArray = aPriorityList.ArrayOfStructures();
101
68333c8f 102 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
e276548b 103 {
104 OpenGl_SequenceOfStructure::Iterator aStructIt;
105
106 for (aStructIt.Init (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
107 {
108 const OpenGl_Structure* aStructure = aStructIt.Value();
109
84c71f29 110 if (theMode == OpenGl_GUM_CHECK)
e276548b 111 {
112 if (CheckRaytraceStructure (aStructure))
113 {
84c71f29 114 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
e276548b 115 }
84c71f29 116 }
117 else if (theMode == OpenGl_GUM_PREPARE)
118 {
119 if (!aStructure->IsRaytracable()
120 || !aStructure->IsVisible())
121 continue;
122
123 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
124 {
125 // OpenGL elements from group (extract primitives arrays)
126 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
127 {
128 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
129
130 if (aPrimArray != NULL)
131 {
132 // Collect all primitive arrays in scene.
8d3f219f 133 anArrayIDs.insert (aPrimArray->GetUID());
84c71f29 134 }
135 }
136 }
137 }
138 else if (theMode == OpenGl_GUM_UPDATE)
e276548b 139 {
140 if (!aStructure->IsRaytracable())
141 continue;
142
0717ddc1 143 AddRaytraceStructure (aStructure, anElements);
e276548b 144 }
145 }
146 }
147 }
148
84c71f29 149 if (theMode == OpenGl_GUM_PREPARE)
150 {
151 BVH_ObjectSet<Standard_ShortReal, 4>::BVH_ObjectList anUnchangedObjects;
152
153 // Leave only unchanged objects in myRaytraceGeometry so only their transforms and materials will be updated
154 // Objects which not in myArrayToTrianglesMap will be built from scratch.
155 for (Standard_Integer anObjectIdx = 0; anObjectIdx < myRaytraceGeometry.Objects().Size(); ++anObjectIdx)
156 {
157 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
158 myRaytraceGeometry.Objects().ChangeValue (anObjectIdx).operator->());
159
160 // If primitive array of object not in "anArrays" set then it was hided or deleted.
161 // If primitive array present in "anArrays" set but we don't have associated object yet, then
162 // the object is new and still has to be built.
8d3f219f 163 if ((aTriangleSet != NULL) && ((anArrayIDs.find (aTriangleSet->AssociatedPArrayID())) != anArrayIDs.end()))
84c71f29 164 {
165 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjectIdx));
166
8d3f219f 167 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
84c71f29 168 }
169 }
170
171 myRaytraceGeometry.Objects() = anUnchangedObjects;
172
173 return UpdateRaytraceGeometry (OpenGl_GUM_UPDATE);
174 }
175
176 if (theMode == OpenGl_GUM_UPDATE)
e276548b 177 {
178 // Actualize the hash map of structures -- remove out-of-date records
179 std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
180
181 while (anIter != myStructureStates.end())
182 {
183 if (anElements.find (anIter->first) == anElements.end())
184 {
185 myStructureStates.erase (anIter++);
186 }
187 else
188 {
189 ++anIter;
190 }
191 }
192
193 // Actualize OpenGL layer list state
194 myLayersModificationStatus = myView->LayerList().ModificationState();
195
265d4508 196 // Rebuild bottom-level and high-level BVHs
197 myRaytraceGeometry.ProcessAcceleration();
e276548b 198
265d4508 199 const Standard_ShortReal aMinRadius = Max (fabs (myRaytraceGeometry.Box().CornerMin().x()), Max (
200 fabs (myRaytraceGeometry.Box().CornerMin().y()), fabs (myRaytraceGeometry.Box().CornerMin().z())));
201 const Standard_ShortReal aMaxRadius = Max (fabs (myRaytraceGeometry.Box().CornerMax().x()), Max (
202 fabs (myRaytraceGeometry.Box().CornerMax().y()), fabs (myRaytraceGeometry.Box().CornerMax().z())));
e276548b 203
265d4508 204 myRaytraceSceneRadius = 2.f /* scale factor */ * Max (aMinRadius, aMaxRadius);
e276548b 205
fc73a202 206 const BVH_Vec4f aSize = myRaytraceGeometry.Box().Size();
e276548b 207
a89742cf 208 myRaytraceSceneEpsilon = Max (1e-6f, 1e-4f * sqrtf (
fc73a202 209 aSize.x() * aSize.x() + aSize.y() * aSize.y() + aSize.z() * aSize.z()));
210
211 return UploadRaytraceData();
e276548b 212 }
213
e276548b 214 return Standard_True;
215}
216
217// =======================================================================
218// function : CheckRaytraceStructure
265d4508 219// purpose : Checks to see if the structure is modified
e276548b 220// =======================================================================
221Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
222{
223 if (!theStructure->IsRaytracable())
224 {
225 // Checks to see if all ray-tracable elements were
226 // removed from the structure
227 if (theStructure->ModificationState() > 0)
228 {
229 theStructure->ResetModificationState();
230 return Standard_True;
231 }
232
233 return Standard_False;
234 }
235
236 std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
237
238 if (aStructState != myStructureStates.end())
239 return aStructState->second != theStructure->ModificationState();
240
241 return Standard_True;
242}
243
244// =======================================================================
245// function : CreateMaterial
246// purpose : Creates ray-tracing material properties
247// =======================================================================
265d4508 248void CreateMaterial (const OPENGL_SURF_PROP& theProp, OpenGl_RaytraceMaterial& theMaterial)
e276548b 249{
64c759f8 250 const float* aSrcAmb = theProp.isphysic ? theProp.ambcol.rgb : theProp.matcol.rgb;
265d4508 251 theMaterial.Ambient = BVH_Vec4f (aSrcAmb[0] * theProp.amb,
252 aSrcAmb[1] * theProp.amb,
253 aSrcAmb[2] * theProp.amb,
254 1.0f);
64c759f8 255
256 const float* aSrcDif = theProp.isphysic ? theProp.difcol.rgb : theProp.matcol.rgb;
265d4508 257 theMaterial.Diffuse = BVH_Vec4f (aSrcDif[0] * theProp.diff,
258 aSrcDif[1] * theProp.diff,
259 aSrcDif[2] * theProp.diff,
260 1.0f);
64c759f8 261
262 const float aDefSpecCol[4] = {1.0f, 1.0f, 1.0f, 1.0f};
263 const float* aSrcSpe = theProp.isphysic ? theProp.speccol.rgb : aDefSpecCol;
265d4508 264 theMaterial.Specular = BVH_Vec4f (aSrcSpe[0] * theProp.spec,
265 aSrcSpe[1] * theProp.spec,
266 aSrcSpe[2] * theProp.spec,
267 theProp.shine);
e276548b 268
64c759f8 269 const float* aSrcEms = theProp.isphysic ? theProp.emscol.rgb : theProp.matcol.rgb;
265d4508 270 theMaterial.Emission = BVH_Vec4f (aSrcEms[0] * theProp.emsv,
271 aSrcEms[1] * theProp.emsv,
272 aSrcEms[2] * theProp.emsv,
273 1.0f);
e276548b 274
275 // Note: Here we use sub-linear transparency function
276 // to produce realistic-looking transparency effect
265d4508 277 theMaterial.Transparency = BVH_Vec4f (powf (theProp.trans, 0.75f),
278 1.f - theProp.trans,
dc9ef964 279 theProp.index == 0 ? 1.f : theProp.index,
280 theProp.index == 0 ? 1.f : 1.f / theProp.index);
e276548b 281
282 const float aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
283 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
284 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
285
286 const float aReflectionScale = 0.75f / aMaxRefl;
287
fc73a202 288 theMaterial.Reflection = BVH_Vec4f (theProp.speccol.rgb[0] * theProp.spec * aReflectionScale,
289 theProp.speccol.rgb[1] * theProp.spec * aReflectionScale,
290 theProp.speccol.rgb[2] * theProp.spec * aReflectionScale,
291 0.f);
e276548b 292}
293
294// =======================================================================
295// function : AddRaytraceStructure
296// purpose : Adds OpenGL structure to ray-traced scene geometry
297// =======================================================================
0717ddc1 298Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure, std::set<const OpenGl_Structure*>& theElements)
e276548b 299{
e276548b 300 theElements.insert (theStructure);
301
302 if (!theStructure->IsVisible())
303 {
304 myStructureStates[theStructure] = theStructure->ModificationState();
305 return Standard_True;
306 }
307
308 // Get structure material
68333c8f 309 Standard_Integer aStructMatID = -1;
e276548b 310
311 if (theStructure->AspectFace() != NULL)
312 {
265d4508 313 aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 314
315 OpenGl_RaytraceMaterial aStructMaterial;
316 CreateMaterial (theStructure->AspectFace()->IntFront(), aStructMaterial);
317
265d4508 318 myRaytraceGeometry.Materials.push_back (aStructMaterial);
e276548b 319 }
320
0717ddc1 321 Standard_ShortReal aStructTransformArr[16];
322 Standard_ShortReal* aStructTransform = NULL;
323 if (theStructure->Transformation()->mat != NULL)
324 {
325 aStructTransform = aStructTransformArr;
326 for (Standard_Integer i = 0; i < 4; ++i)
327 {
328 for (Standard_Integer j = 0; j < 4; ++j)
329 {
330 aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
331 }
332 }
333 }
334
335 AddRaytraceGroups (theStructure, aStructMatID, aStructTransform);
336
337 // Process all connected OpenGL structures
338 for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
339 {
340 if (anIts.Value()->IsRaytracable())
341 AddRaytraceGroups (anIts.Value(), aStructMatID, aStructTransform);
342 }
343
344 myStructureStates[theStructure] = theStructure->ModificationState();
345 return Standard_True;
346}
347
348// =======================================================================
349// function : AddRaytraceGroups
350// purpose : Adds OpenGL groups to ray-traced scene geometry
351// =======================================================================
352Standard_Boolean OpenGl_Workspace::AddRaytraceGroups (const OpenGl_Structure* theStructure,
353 const Standard_Integer theStructMatId,
354 const Standard_ShortReal* theTransform)
355{
b64d84be 356 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
e276548b 357 {
358 // Get group material
68333c8f 359 Standard_Integer aGroupMatID = -1;
b64d84be 360 if (aGroupIter.Value()->AspectFace() != NULL)
e276548b 361 {
265d4508 362 aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 363
364 OpenGl_RaytraceMaterial aGroupMaterial;
b64d84be 365 CreateMaterial (aGroupIter.Value()->AspectFace()->IntFront(), aGroupMaterial);
e276548b 366
265d4508 367 myRaytraceGeometry.Materials.push_back (aGroupMaterial);
e276548b 368 }
369
0717ddc1 370 Standard_Integer aMatID = aGroupMatID < 0 ? theStructMatId : aGroupMatID;
e276548b 371
265d4508 372 if (aMatID < 0)
e276548b 373 {
265d4508 374 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 375
265d4508 376 myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
e276548b 377 }
378
265d4508 379 // Add OpenGL elements from group (extract primitives arrays and aspects)
b64d84be 380 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
e276548b 381 {
5322131b 382 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
383 if (anAspect != NULL)
e276548b 384 {
5322131b 385 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 386
5322131b 387 OpenGl_RaytraceMaterial aMaterial;
388 CreateMaterial (anAspect->IntFront(), aMaterial);
e276548b 389
5322131b 390 myRaytraceGeometry.Materials.push_back (aMaterial);
e276548b 391 }
5322131b 392 else
e276548b 393 {
394 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
84c71f29 395
e276548b 396 if (aPrimArray != NULL)
397 {
8d3f219f 398 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
399
84c71f29 400 if (aSetIter != myArrayToTrianglesMap.end())
401 {
402 OpenGl_TriangleSet* aSet = aSetIter->second;
403
404 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
405
406 if (theTransform != NULL)
407 {
408 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
409 }
410
411 aSet->SetProperties (aTransform);
412
413 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID )
414 {
415 aSet->SetMaterialIndex (aMatID);
416 }
417 }
418 else
419 {
420 NCollection_Handle<BVH_Object<Standard_ShortReal, 4> > aSet =
421 AddRaytracePrimitiveArray (aPrimArray, aMatID, 0);
265d4508 422
84c71f29 423 if (!aSet.IsNull())
424 {
425 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
426
427 if (theTransform != NULL)
428 {
429 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
430 }
431
432 aSet->SetProperties (aTransform);
433
434 myRaytraceGeometry.Objects().Append (aSet);
435 }
436 }
e276548b 437 }
438 }
439 }
e276548b 440 }
441
e276548b 442 return Standard_True;
443}
444
445// =======================================================================
446// function : AddRaytracePrimitiveArray
447// purpose : Adds OpenGL primitive array to ray-traced scene geometry
448// =======================================================================
871fa103 449OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
450 Standard_Integer theMatID,
451 const Standard_ShortReal* theTransform)
e276548b 452{
871fa103 453 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
454 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
455 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
456 if (theArray->DrawMode() < GL_TRIANGLES
ca3c13d1 457 #if !defined(GL_ES_VERSION_2_0)
871fa103 458 || theArray->DrawMode() > GL_POLYGON
ca3c13d1 459 #else
460 || theArray->DrawMode() > GL_TRIANGLE_FAN
461 #endif
871fa103 462 || anAttribs.IsNull())
e276548b 463 {
265d4508 464 return NULL;
e276548b 465 }
466
e276548b 467#ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 468 switch (theArray->DrawMode())
e276548b 469 {
871fa103 470 case GL_TRIANGLES: std::cout << "\tAdding GL_TRIANGLES\n"; break;
871fa103 471 case GL_TRIANGLE_FAN: std::cout << "\tAdding GL_TRIANGLE_FAN\n"; break;
472 case GL_TRIANGLE_STRIP: std::cout << "\tAdding GL_TRIANGLE_STRIP\n"; break;
ca3c13d1 473 #if !defined(GL_ES_VERSION_2_0)
474 case GL_QUADS: std::cout << "\tAdding GL_QUADS\n"; break;
871fa103 475 case GL_QUAD_STRIP: std::cout << "\tAdding GL_QUAD_STRIP\n"; break;
ca3c13d1 476 case GL_POLYGON: std::cout << "\tAdding GL_POLYGON\n"; break;
477 #endif
e276548b 478 }
479#endif
480
8d3f219f 481 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
e276548b 482 {
871fa103 483 aSet->Vertices.reserve (anAttribs->NbElements);
484 aSet->Normals .reserve (anAttribs->NbElements);
485 const size_t aVertFrom = aSet->Vertices.size();
486 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
265d4508 487 {
871fa103 488 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
489 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
490 if (anAttrib.Id == Graphic3d_TOA_POS)
491 {
492 if (anAttrib.DataType == Graphic3d_TOD_VEC3
493 || anAttrib.DataType == Graphic3d_TOD_VEC4)
494 {
495 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
496 {
497 const Graphic3d_Vec3& aVert = *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset);
498 aSet->Vertices.push_back (BVH_Vec4f (aVert.x(), aVert.y(), aVert.z(), 1.0f));
499 }
500 }
501 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
502 {
503 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
504 {
505 const Graphic3d_Vec2& aVert = *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset);
506 aSet->Vertices.push_back (BVH_Vec4f (aVert.x(), aVert.y(), 0.0f, 1.0f));
507 }
508 }
509 }
510 else if (anAttrib.Id == Graphic3d_TOA_NORM)
511 {
512 if (anAttrib.DataType == Graphic3d_TOD_VEC3
513 || anAttrib.DataType == Graphic3d_TOD_VEC4)
514 {
515 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
516 {
517 const Graphic3d_Vec3& aNorm = *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset);
518 aSet->Normals.push_back (BVH_Vec4f (aNorm.x(), aNorm.y(), aNorm.z(), 0.0f));
519 }
520 }
521 }
265d4508 522 }
e276548b 523
871fa103 524 if (aSet->Normals.size() != aSet->Vertices.size())
265d4508 525 {
871fa103 526 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
265d4508 527 {
871fa103 528 aSet->Normals.push_back (BVH_Vec4f());
265d4508 529 }
871fa103 530 }
e276548b 531
871fa103 532 if (theTransform)
533 {
534 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
535 {
536 BVH_Vec4f& aVertex = aSet->Vertices[aVertIter];
537 aVertex = MatVecMult (theTransform, aVertex);
538 }
539 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
540 {
541 BVH_Vec4f& aNorm = aSet->Normals[aVertIter];
542 aNorm = MatVecMult (theTransform, aNorm);
543 }
e276548b 544 }
545
871fa103 546 if (!aBounds.IsNull())
265d4508 547 {
548 #ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 549 std::cout << "\tNumber of bounds = " << aBounds->NbBounds << std::endl;
265d4508 550 #endif
e276548b 551
265d4508 552 Standard_Integer aBoundStart = 0;
871fa103 553 for (Standard_Integer aBound = 0; aBound < aBounds->NbBounds; ++aBound)
265d4508 554 {
871fa103 555 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
e276548b 556
265d4508 557 #ifdef RAY_TRACE_PRINT_INFO
558 std::cout << "\tAdding indices from bound " << aBound << ": " <<
559 aBoundStart << " .. " << aVertNum << std::endl;
560 #endif
561
871fa103 562 if (!AddRaytraceVertexIndices (*aSet, *theArray, aBoundStart, aVertNum, theMatID))
265d4508 563 {
564 delete aSet;
565 return NULL;
566 }
567
568 aBoundStart += aVertNum;
569 }
570 }
571 else
e276548b 572 {
871fa103 573 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
e276548b 574
265d4508 575 #ifdef RAY_TRACE_PRINT_INFO
576 std::cout << "\tAdding indices from array: " << aVertNum << std::endl;
577 #endif
e276548b 578
871fa103 579 if (!AddRaytraceVertexIndices (*aSet, *theArray, 0, aVertNum, theMatID))
e276548b 580 {
265d4508 581 delete aSet;
582 return NULL;
e276548b 583 }
e276548b 584 }
585 }
e276548b 586
265d4508 587 if (aSet->Size() != 0)
588 aSet->MarkDirty();
e276548b 589
265d4508 590 return aSet;
e276548b 591}
592
593// =======================================================================
594// function : AddRaytraceVertexIndices
595// purpose : Adds vertex indices to ray-traced scene geometry
596// =======================================================================
871fa103 597Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
598 const OpenGl_PrimitiveArray& theArray,
599 Standard_Integer theOffset,
600 Standard_Integer theCount,
601 Standard_Integer theMatID)
e276548b 602{
871fa103 603 switch (theArray.DrawMode())
e276548b 604 {
871fa103 605 case GL_TRIANGLES: return AddRaytraceTriangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
871fa103 606 case GL_TRIANGLE_FAN: return AddRaytraceTriangleFanArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
607 case GL_TRIANGLE_STRIP: return AddRaytraceTriangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
ca3c13d1 608 #if !defined(GL_ES_VERSION_2_0)
609 case GL_QUADS: return AddRaytraceQuadrangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
871fa103 610 case GL_QUAD_STRIP: return AddRaytraceQuadrangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
611 case GL_POLYGON: return AddRaytracePolygonArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
ca3c13d1 612 #endif
e276548b 613 }
871fa103 614 return Standard_False;
e276548b 615}
616
617// =======================================================================
618// function : AddRaytraceTriangleArray
619// purpose : Adds OpenGL triangle array to ray-traced scene geometry
620// =======================================================================
871fa103 621Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
622 const Handle(Graphic3d_IndexBuffer)& theIndices,
623 Standard_Integer theOffset,
624 Standard_Integer theCount,
625 Standard_Integer theMatID)
e276548b 626{
265d4508 627 if (theCount < 3)
e276548b 628 return Standard_True;
629
871fa103 630 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
265d4508 631
871fa103 632 if (!theIndices.IsNull())
e276548b 633 {
265d4508 634 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 635 {
871fa103 636 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
637 theIndices->Index (aVert + 1),
638 theIndices->Index (aVert + 2),
639 theMatID));
e276548b 640 }
641 }
642 else
643 {
265d4508 644 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 645 {
871fa103 646 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
647 theMatID));
e276548b 648 }
649 }
650
651 return Standard_True;
652}
653
654// =======================================================================
655// function : AddRaytraceTriangleFanArray
656// purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
657// =======================================================================
871fa103 658Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
659 const Handle(Graphic3d_IndexBuffer)& theIndices,
660 Standard_Integer theOffset,
661 Standard_Integer theCount,
662 Standard_Integer theMatID)
e276548b 663{
265d4508 664 if (theCount < 3)
e276548b 665 return Standard_True;
666
871fa103 667 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 668
871fa103 669 if (!theIndices.IsNull())
e276548b 670 {
265d4508 671 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 672 {
871fa103 673 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
674 theIndices->Index (aVert + 1),
675 theIndices->Index (aVert + 2),
676 theMatID));
e276548b 677 }
678 }
679 else
680 {
265d4508 681 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 682 {
871fa103 683 theSet.Elements.push_back (BVH_Vec4i (theOffset,
684 aVert + 1,
685 aVert + 2,
686 theMatID));
e276548b 687 }
688 }
689
690 return Standard_True;
691}
692
693// =======================================================================
694// function : AddRaytraceTriangleStripArray
695// purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
696// =======================================================================
871fa103 697Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
698 const Handle(Graphic3d_IndexBuffer)& theIndices,
699 Standard_Integer theOffset,
700 Standard_Integer theCount,
701 Standard_Integer theMatID)
e276548b 702{
265d4508 703 if (theCount < 3)
e276548b 704 return Standard_True;
705
871fa103 706 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 707
871fa103 708 if (!theIndices.IsNull())
e276548b 709 {
265d4508 710 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 711 {
871fa103 712 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
713 theIndices->Index (aVert + aCW ? 0 : 1),
714 theIndices->Index (aVert + 2),
715 theMatID));
e276548b 716 }
717 }
718 else
719 {
265d4508 720 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 721 {
871fa103 722 theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
723 aVert + aCW ? 0 : 1,
724 aVert + 2,
725 theMatID));
e276548b 726 }
727 }
728
729 return Standard_True;
730}
731
732// =======================================================================
733// function : AddRaytraceQuadrangleArray
734// purpose : Adds OpenGL quad array to ray-traced scene geometry
735// =======================================================================
871fa103 736Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
737 const Handle(Graphic3d_IndexBuffer)& theIndices,
738 Standard_Integer theOffset,
739 Standard_Integer theCount,
740 Standard_Integer theMatID)
e276548b 741{
265d4508 742 if (theCount < 4)
e276548b 743 return Standard_True;
744
871fa103 745 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
265d4508 746
871fa103 747 if (!theIndices.IsNull())
e276548b 748 {
265d4508 749 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 750 {
871fa103 751 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
752 theIndices->Index (aVert + 1),
753 theIndices->Index (aVert + 2),
754 theMatID));
755 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
756 theIndices->Index (aVert + 2),
757 theIndices->Index (aVert + 3),
758 theMatID));
e276548b 759 }
760 }
761 else
762 {
265d4508 763 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 764 {
871fa103 765 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
766 theMatID));
767 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
768 theMatID));
e276548b 769 }
770 }
771
772 return Standard_True;
773}
774
775// =======================================================================
776// function : AddRaytraceQuadrangleStripArray
777// purpose : Adds OpenGL quad strip array to ray-traced scene geometry
778// =======================================================================
871fa103 779Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
780 const Handle(Graphic3d_IndexBuffer)& theIndices,
781 Standard_Integer theOffset,
782 Standard_Integer theCount,
783 Standard_Integer theMatID)
e276548b 784{
265d4508 785 if (theCount < 4)
e276548b 786 return Standard_True;
787
871fa103 788 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
265d4508 789
871fa103 790 if (!theIndices.IsNull())
e276548b 791 {
265d4508 792 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 793 {
871fa103 794 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
795 theIndices->Index (aVert + 1),
796 theIndices->Index (aVert + 2),
797 theMatID));
798
799 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
800 theIndices->Index (aVert + 3),
801 theIndices->Index (aVert + 2),
802 theMatID));
e276548b 803 }
804 }
805 else
806 {
265d4508 807 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 808 {
871fa103 809 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
810 aVert + 1,
811 aVert + 2,
812 theMatID));
813
814 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
815 aVert + 3,
816 aVert + 2,
817 theMatID));
e276548b 818 }
819 }
820
821 return Standard_True;
822}
823
824// =======================================================================
825// function : AddRaytracePolygonArray
826// purpose : Adds OpenGL polygon array to ray-traced scene geometry
827// =======================================================================
871fa103 828Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet& theSet,
829 const Handle(Graphic3d_IndexBuffer)& theIndices,
830 Standard_Integer theOffset,
831 Standard_Integer theCount,
832 Standard_Integer theMatID)
e276548b 833{
265d4508 834 if (theCount < 3)
e276548b 835 return Standard_True;
836
871fa103 837 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 838
871fa103 839 if (!theIndices.IsNull())
e276548b 840 {
265d4508 841 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 842 {
871fa103 843 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
844 theIndices->Index (aVert + 1),
845 theIndices->Index (aVert + 2),
846 theMatID));
e276548b 847 }
848 }
849 else
850 {
265d4508 851 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 852 {
871fa103 853 theSet.Elements.push_back (BVH_Vec4i (theOffset,
854 aVert + 1,
855 aVert + 2,
856 theMatID));
e276548b 857 }
858 }
859
860 return Standard_True;
861}
862
863// =======================================================================
864// function : UpdateRaytraceLightSources
865// purpose : Updates 3D scene light sources for ray-tracing
866// =======================================================================
867Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const GLdouble theInvModelView[16])
868{
265d4508 869 myRaytraceGeometry.Sources.clear();
e276548b 870
fc73a202 871 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
265d4508 872
873 for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
e276548b 874 {
12381341 875 const OpenGl_Light& aLight = anItl.Value();
265d4508 876
12381341 877 if (aLight.Type == Visual3d_TOLS_AMBIENT)
e276548b 878 {
fc73a202 879 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
880 aLight.Color.g(),
881 aLight.Color.b(),
882 0.0f);
e276548b 883 continue;
884 }
885
265d4508 886 BVH_Vec4f aDiffuse (aLight.Color.r(),
887 aLight.Color.g(),
888 aLight.Color.b(),
889 1.0f);
890
891 BVH_Vec4f aPosition (-aLight.Direction.x(),
892 -aLight.Direction.y(),
893 -aLight.Direction.z(),
894 0.0f);
895
12381341 896 if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
e276548b 897 {
265d4508 898 aPosition = BVH_Vec4f (aLight.Position.x(),
899 aLight.Position.y(),
900 aLight.Position.z(),
901 1.0f);
e276548b 902 }
265d4508 903
12381341 904 if (aLight.IsHeadlight)
e276548b 905 aPosition = MatVecMult (theInvModelView, aPosition);
e276548b 906
fc73a202 907
265d4508 908 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
e276548b 909 }
910
fc73a202 911 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
e276548b 912 {
fc73a202 913 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
e276548b 914
fc73a202 915 if (!myRaytraceLightSrcTexture->Create (myGlContext))
916 {
e276548b 917#ifdef RAY_TRACE_PRINT_INFO
fc73a202 918 std::cout << "Error: Failed to create light source buffer" << std::endl;
e276548b 919#endif
fc73a202 920 return Standard_False;
921 }
e276548b 922 }
fc73a202 923
924 if (myRaytraceGeometry.Sources.size() != 0)
e276548b 925 {
fc73a202 926 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
5cff985a 927 if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
fc73a202 928 {
929#ifdef RAY_TRACE_PRINT_INFO
930 std::cout << "Error: Failed to upload light source buffer" << std::endl;
e276548b 931#endif
fc73a202 932 return Standard_False;
933 }
934 }
e276548b 935
936 return Standard_True;
937}
938
939// =======================================================================
fc73a202 940// function : UpdateRaytraceEnvironmentMap
941// purpose : Updates environment map for ray-tracing
e276548b 942// =======================================================================
fc73a202 943Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
e276548b 944{
fc73a202 945 if (myView.IsNull())
e276548b 946 return Standard_False;
e276548b 947
fc73a202 948 if (myViewModificationStatus == myView->ModificationState())
949 return Standard_True;
e276548b 950
fc73a202 951 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
e276548b 952 {
fc73a202 953 const Handle(OpenGl_ShaderProgram)& aProgram =
954 anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
e276548b 955
fc73a202 956 if (!aProgram.IsNull())
e276548b 957 {
7d3e64ef 958 myGlContext->BindProgram (aProgram);
e276548b 959
fc73a202 960 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
e276548b 961 {
fc73a202 962 myView->TextureEnv()->Bind (
963 myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
964
84c71f29 965 aProgram->SetUniform (myGlContext,
966 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 1);
e276548b 967 }
968 else
969 {
84c71f29 970 aProgram->SetUniform (myGlContext,
971 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 0);
e276548b 972 }
fc73a202 973 }
e276548b 974 }
975
7d3e64ef 976 myGlContext->BindProgram (NULL);
fc73a202 977 myViewModificationStatus = myView->ModificationState();
e276548b 978 return Standard_True;
979}
980
981// =======================================================================
fc73a202 982// function : Source
983// purpose : Returns shader source combined with prefix
e276548b 984// =======================================================================
fc73a202 985TCollection_AsciiString OpenGl_Workspace::ShaderSource::Source() const
e276548b 986{
fc73a202 987 static const TCollection_AsciiString aVersion = "#version 140";
e276548b 988
fc73a202 989 if (myPrefix.IsEmpty())
e276548b 990 {
fc73a202 991 return aVersion + "\n" + mySource;
e276548b 992 }
993
fc73a202 994 return aVersion + "\n" + myPrefix + "\n" + mySource;
e276548b 995}
996
997// =======================================================================
fc73a202 998// function : Load
999// purpose : Loads shader source from specified files
e276548b 1000// =======================================================================
fc73a202 1001void OpenGl_Workspace::ShaderSource::Load (
1002 const TCollection_AsciiString* theFileNames, const Standard_Integer theCount)
e276548b 1003{
fc73a202 1004 mySource.Clear();
e276548b 1005
fc73a202 1006 for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
1007 {
1008 OSD_File aFile (theFileNames[anIndex]);
e276548b 1009
fc73a202 1010 Standard_ASSERT_RETURN (aFile.Exists(),
1011 "Error: Failed to find shader source file", /* none */);
e276548b 1012
fc73a202 1013 aFile.Open (OSD_ReadOnly, OSD_Protection());
265d4508 1014
fc73a202 1015 TCollection_AsciiString aSource;
265d4508 1016
fc73a202 1017 Standard_ASSERT_RETURN (aFile.IsOpen(),
1018 "Error: Failed to open shader source file", /* none */);
e276548b 1019
fc73a202 1020 aFile.Read (aSource, (Standard_Integer) aFile.Size());
e276548b 1021
fc73a202 1022 if (!aSource.IsEmpty())
1023 {
1024 mySource += TCollection_AsciiString ("\n") + aSource;
1025 }
68333c8f 1026
fc73a202 1027 aFile.Close();
68333c8f 1028 }
e276548b 1029}
1030
1031// =======================================================================
fc73a202 1032// function : LoadShader
1033// purpose : Creates new shader object with specified source
e276548b 1034// =======================================================================
fc73a202 1035Handle(OpenGl_ShaderObject) OpenGl_Workspace::LoadShader (const ShaderSource& theSource, GLenum theType)
e276548b 1036{
fc73a202 1037 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
e276548b 1038
fc73a202 1039 if (!aShader->Create (myGlContext))
e276548b 1040 {
fc73a202 1041 const TCollection_ExtendedString aMessage = "Error: Failed to create shader object";
1042
1043 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1044 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
e276548b 1045
fc73a202 1046 aShader->Release (myGlContext.operator->());
e276548b 1047
fc73a202 1048 return Handle(OpenGl_ShaderObject)();
e276548b 1049 }
5322131b 1050
fc73a202 1051 if (!aShader->LoadSource (myGlContext, theSource.Source()))
1052 {
1053 const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1054
1055 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1056 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
e276548b 1057
fc73a202 1058 aShader->Release (myGlContext.operator->());
e276548b 1059
fc73a202 1060 return Handle(OpenGl_ShaderObject)();
1061 }
e276548b 1062
fc73a202 1063 TCollection_AsciiString aBuildLog;
e276548b 1064
fc73a202 1065 if (!aShader->Compile (myGlContext))
e276548b 1066 {
fc73a202 1067 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1068 {
1069 const TCollection_ExtendedString aMessage =
1070 TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1071
e276548b 1072#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1073 std::cout << aBuildLog << std::endl;
e276548b 1074#endif
e276548b 1075
fc73a202 1076 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1077 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1078 }
1079
1080 aShader->Release (myGlContext.operator->());
1081
1082 return Handle(OpenGl_ShaderObject)();
1083 }
68333c8f 1084
e276548b 1085#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1086 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1087 {
1088 if (!aBuildLog.IsEmpty())
1089 {
1090 std::cout << aBuildLog << std::endl;
1091 }
1092 else
1093 {
1094 std::cout << "Info: shader build log is empty" << std::endl;
1095 }
1096 }
e276548b 1097#endif
e276548b 1098
fc73a202 1099 return aShader;
e276548b 1100}
1101
1102// =======================================================================
fc73a202 1103// function : SafeFailBack
1104// purpose : Performs safe exit when shaders initialization fails
e276548b 1105// =======================================================================
fc73a202 1106Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
e276548b 1107{
fc73a202 1108 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1109 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
265d4508 1110
fc73a202 1111 myComputeInitStatus = OpenGl_RT_FAIL;
265d4508 1112
fc73a202 1113 ReleaseRaytraceResources();
1114
1115 return Standard_False;
1116}
e276548b 1117
fc73a202 1118// =======================================================================
1119// function : InitRaytraceResources
1120// purpose : Initializes OpenGL/GLSL shader programs
1121// =======================================================================
bc8c79bb 1122Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
fc73a202 1123{
1124 Standard_Boolean aToRebuildShaders = Standard_False;
e276548b 1125
fc73a202 1126 if (myComputeInitStatus == OpenGl_RT_INIT)
1127 {
1128 if (!myIsRaytraceDataValid)
1129 return Standard_True;
e276548b 1130
fc73a202 1131 const Standard_Integer aRequiredStackSize =
1132 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
e276548b 1133
bc8c79bb 1134 if (myRaytraceParameters.StackSize < aRequiredStackSize)
fc73a202 1135 {
bc8c79bb 1136 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
e276548b 1137
fc73a202 1138 aToRebuildShaders = Standard_True;
1139 }
1140 else
1141 {
bc8c79bb 1142 if (aRequiredStackSize < myRaytraceParameters.StackSize)
fc73a202 1143 {
bc8c79bb 1144 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
fc73a202 1145 {
bc8c79bb 1146 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
fc73a202 1147 aToRebuildShaders = Standard_True;
1148 }
1149 }
1150 }
e276548b 1151
bc8c79bb 1152 if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.TraceDepth)
1153 {
1154 myRaytraceParameters.TraceDepth = theCView.RenderParams.RaytracingDepth;
1155 aToRebuildShaders = Standard_True;
1156 }
1157
1158 if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1159 {
1160 myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1161 aToRebuildShaders = Standard_True;
1162 }
1163
fc73a202 1164 if (aToRebuildShaders)
1165 {
e276548b 1166#ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 1167 std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
e276548b 1168#endif
e276548b 1169
bc8c79bb 1170 // Change state to force update all uniforms
84c71f29 1171 ++myViewModificationStatus;
1172
bc8c79bb 1173 TCollection_AsciiString aPrefixString =
1174 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1175 TCollection_AsciiString ("#define TRACE_DEPTH ") + TCollection_AsciiString (myRaytraceParameters.TraceDepth);
1176
1177 if (myRaytraceParameters.TransparentShadows)
1178 {
1179 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1180 }
1181
1182#ifdef RAY_TRACE_PRINT_INFO
1183 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1184#endif
265d4508 1185
bc8c79bb 1186 myRaytraceShaderSource.SetPrefix (aPrefixString);
1187 myPostFSAAShaderSource.SetPrefix (aPrefixString);
265d4508 1188
fc73a202 1189 if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1190 || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1191 {
1192 return Standard_False;
1193 }
265d4508 1194
fc73a202 1195 if (!myRaytraceShader->Compile (myGlContext)
1196 || !myPostFSAAShader->Compile (myGlContext))
1197 {
1198 return Standard_False;
1199 }
1200
7d3e64ef 1201 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1202 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1203 if (!myRaytraceProgram->Link (myGlContext)
1204 || !myPostFSAAProgram->Link (myGlContext))
1205 {
1206 return Standard_False;
1207 }
1208 }
e276548b 1209 }
1210
fc73a202 1211 if (myComputeInitStatus == OpenGl_RT_NONE)
1212 {
1213 if (!myGlContext->IsGlGreaterEqual (3, 1))
1214 {
1215 const TCollection_ExtendedString aMessage = "Ray-tracing requires OpenGL 3.1 and higher";
265d4508 1216
fc73a202 1217 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1218 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
265d4508 1219
fc73a202 1220 return Standard_False;
1221 }
5322131b 1222
bc8c79bb 1223 myRaytraceParameters.TraceDepth = theCView.RenderParams.RaytracingDepth;
1224
fc73a202 1225 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
265d4508 1226
fc73a202 1227 if (aFolder.IsEmpty())
1228 {
1229 const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1230
1231 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1232 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1233
1234 return Standard_False;
1235 }
265d4508 1236
fc73a202 1237 if (myIsRaytraceDataValid)
1238 {
bc8c79bb 1239 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
fc73a202 1240 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1241 }
265d4508 1242
bc8c79bb 1243 TCollection_AsciiString aPrefixString =
1244 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1245 TCollection_AsciiString ("#define TRACE_DEPTH ") + TCollection_AsciiString (myRaytraceParameters.TraceDepth);
1246
1247 if (myRaytraceParameters.TransparentShadows)
1248 {
1249 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1250 }
1251
1252#ifdef RAY_TRACE_PRINT_INFO
1253 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1254#endif
1255
fc73a202 1256 {
1257 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1258 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1259
fc73a202 1260 if (aBasicVertShader.IsNull())
1261 {
1262 return SafeFailBack ("Failed to set vertex shader source");
1263 }
265d4508 1264
fc73a202 1265 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
265d4508 1266
fc73a202 1267 myRaytraceShaderSource.Load (aFiles, 2);
e276548b 1268
bc8c79bb 1269 myRaytraceShaderSource.SetPrefix (aPrefixString);
265d4508 1270
fc73a202 1271 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
265d4508 1272
fc73a202 1273 if (myRaytraceShader.IsNull())
1274 {
1275 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1276
fc73a202 1277 return SafeFailBack ("Failed to set ray-trace fragment shader source");
1278 }
265d4508 1279
fc73a202 1280 myRaytraceProgram = new OpenGl_ShaderProgram;
5322131b 1281
fc73a202 1282 if (!myRaytraceProgram->Create (myGlContext))
1283 {
1284 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1285
fc73a202 1286 return SafeFailBack ("Failed to create ray-trace shader program");
1287 }
265d4508 1288
fc73a202 1289 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1290 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1291 {
1292 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1293
fc73a202 1294 return SafeFailBack ("Failed to attach ray-trace shader objects");
1295 }
265d4508 1296
7d3e64ef 1297 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1298 if (!myRaytraceProgram->Link (myGlContext))
1299 {
1300 TCollection_AsciiString aLinkLog;
e276548b 1301
fc73a202 1302 if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1303 {
1304 #ifdef RAY_TRACE_PRINT_INFO
1305 std::cout << aLinkLog << std::endl;
1306 #endif
1307 }
265d4508 1308
fc73a202 1309 return SafeFailBack ("Failed to link ray-trace shader program");
1310 }
1311 }
265d4508 1312
fc73a202 1313 {
1314 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1315 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1316
fc73a202 1317 if (aBasicVertShader.IsNull())
1318 {
1319 return SafeFailBack ("Failed to set vertex shader source");
1320 }
265d4508 1321
fc73a202 1322 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
265d4508 1323
fc73a202 1324 myPostFSAAShaderSource.Load (aFiles, 2);
265d4508 1325
bc8c79bb 1326 myPostFSAAShaderSource.SetPrefix (aPrefixString);
fc73a202 1327
1328 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
265d4508 1329
fc73a202 1330 if (myPostFSAAShader.IsNull())
1331 {
1332 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1333
fc73a202 1334 return SafeFailBack ("Failed to set FSAA fragment shader source");
1335 }
265d4508 1336
fc73a202 1337 myPostFSAAProgram = new OpenGl_ShaderProgram;
265d4508 1338
fc73a202 1339 if (!myPostFSAAProgram->Create (myGlContext))
1340 {
1341 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1342
fc73a202 1343 return SafeFailBack ("Failed to create FSAA shader program");
1344 }
1345
1346 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1347 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1348 {
1349 aBasicVertShader->Release (myGlContext.operator->());
1350
1351 return SafeFailBack ("Failed to attach FSAA shader objects");
1352 }
1353
7d3e64ef 1354 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1355 if (!myPostFSAAProgram->Link (myGlContext))
1356 {
1357 TCollection_AsciiString aLinkLog;
1358
1359 if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1360 {
1361 #ifdef RAY_TRACE_PRINT_INFO
1362 std::cout << aLinkLog << std::endl;
1363 #endif
1364 }
1365
1366 return SafeFailBack ("Failed to link FSAA shader program");
1367 }
e276548b 1368 }
fc73a202 1369 }
e276548b 1370
fc73a202 1371 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1372 {
1373 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
e276548b 1374 {
fc73a202 1375 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1376 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1377
7d3e64ef 1378 myGlContext->BindProgram (aShaderProgram);
fc73a202 1379
1380 aShaderProgram->SetSampler (myGlContext,
1381 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1382 aShaderProgram->SetSampler (myGlContext,
1383 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1384 aShaderProgram->SetSampler (myGlContext,
1385 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1386 aShaderProgram->SetSampler (myGlContext,
1387 "uObjectMinPointTexture", OpenGl_RT_ObjectMinPointTexture);
1388 aShaderProgram->SetSampler (myGlContext,
1389 "uObjectMaxPointTexture", OpenGl_RT_ObjectMaxPointTexture);
1390 aShaderProgram->SetSampler (myGlContext,
1391 "uObjectNodeInfoTexture", OpenGl_RT_ObjectNodeInfoTexture);
1392 aShaderProgram->SetSampler (myGlContext,
1393 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1394 aShaderProgram->SetSampler (myGlContext,
1395 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1396 aShaderProgram->SetSampler (myGlContext,
1397 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1398 aShaderProgram->SetSampler (myGlContext,
1399 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1400 aShaderProgram->SetSampler (myGlContext,
1401 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
84c71f29 1402 aShaderProgram->SetSampler (myGlContext,
1403 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1404 aShaderProgram->SetSampler (myGlContext,
1405 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
fc73a202 1406
a89742cf 1407 aShaderProgram->SetSampler (myGlContext,
1408 "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1409 aShaderProgram->SetSampler (myGlContext,
1410 "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1411
fc73a202 1412 if (anIndex == 1)
1413 {
1414 aShaderProgram->SetSampler (myGlContext,
1415 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1416 }
265d4508 1417
fc73a202 1418 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
7d3e64ef 1419 aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
fc73a202 1420
1421 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1422 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1423 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1424 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1425 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1426 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1427 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1428 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1429 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1430 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1431 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1432 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1433 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1434 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1435 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1436 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
a89742cf 1437 myUniformLocations[anIndex][OpenGl_RT_uInvModelProj] =
1438 aShaderProgram->GetUniformLocation (myGlContext, "uInvModelProj");
fc73a202 1439
1440 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1441 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1442 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1443 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1444
1445 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1446 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1447 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1448 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1449
1450 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1451 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1452 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1453 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1454
1455 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1456 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1457 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1458 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1459 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1460 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
84c71f29 1461
1462 myUniformLocations[anIndex][OpenGl_RT_uEnvironmentEnable] =
1463 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
fc73a202 1464 }
265d4508 1465
7d3e64ef 1466 myGlContext->BindProgram (NULL);
fc73a202 1467 }
265d4508 1468
fc73a202 1469 if (myComputeInitStatus != OpenGl_RT_NONE)
1470 {
1471 return myComputeInitStatus == OpenGl_RT_INIT;
1472 }
265d4508 1473
fc73a202 1474 if (myRaytraceFBO1.IsNull())
1475 {
1476 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1477 }
265d4508 1478
fc73a202 1479 if (myRaytraceFBO2.IsNull())
1480 {
1481 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1482 }
265d4508 1483
fc73a202 1484 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1485 -1.f, 1.f, 0.f,
1486 1.f, 1.f, 0.f,
1487 1.f, 1.f, 0.f,
1488 1.f, -1.f, 0.f,
1489 -1.f, -1.f, 0.f };
265d4508 1490
fc73a202 1491 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
265d4508 1492
fc73a202 1493 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
ca3c13d1 1494
fc73a202 1495 return Standard_True;
1496}
265d4508 1497
fc73a202 1498// =======================================================================
1499// function : NullifyResource
1500// purpose :
1501// =======================================================================
1502inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1503 Handle(OpenGl_Resource)& theResource)
1504{
1505 if (!theResource.IsNull())
1506 {
1507 theResource->Release (theContext.operator->());
1508 theResource.Nullify();
1509 }
1510}
265d4508 1511
fc73a202 1512// =======================================================================
1513// function : ReleaseRaytraceResources
1514// purpose : Releases OpenGL/GLSL shader programs
1515// =======================================================================
1516void OpenGl_Workspace::ReleaseRaytraceResources()
1517{
a89742cf 1518 NullifyResource (myGlContext, myOpenGlFBO);
fc73a202 1519 NullifyResource (myGlContext, myRaytraceFBO1);
1520 NullifyResource (myGlContext, myRaytraceFBO2);
265d4508 1521
fc73a202 1522 NullifyResource (myGlContext, myRaytraceShader);
1523 NullifyResource (myGlContext, myPostFSAAShader);
265d4508 1524
fc73a202 1525 NullifyResource (myGlContext, myRaytraceProgram);
1526 NullifyResource (myGlContext, myPostFSAAProgram);
265d4508 1527
fc73a202 1528 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1529 NullifyResource (myGlContext, mySceneMinPointTexture);
1530 NullifyResource (myGlContext, mySceneMaxPointTexture);
265d4508 1531
fc73a202 1532 NullifyResource (myGlContext, myObjectNodeInfoTexture);
1533 NullifyResource (myGlContext, myObjectMinPointTexture);
1534 NullifyResource (myGlContext, myObjectMaxPointTexture);
265d4508 1535
fc73a202 1536 NullifyResource (myGlContext, myGeometryVertexTexture);
1537 NullifyResource (myGlContext, myGeometryNormalTexture);
1538 NullifyResource (myGlContext, myGeometryTriangTexture);
bc8c79bb 1539 NullifyResource (myGlContext, mySceneTransformTexture);
265d4508 1540
fc73a202 1541 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1542 NullifyResource (myGlContext, myRaytraceMaterialTexture);
265d4508 1543
fc73a202 1544 if (myRaytraceScreenQuad.IsValid())
1545 myRaytraceScreenQuad.Release (myGlContext.operator->());
1546}
265d4508 1547
fc73a202 1548// =======================================================================
1549// function : UploadRaytraceData
1550// purpose : Uploads ray-trace data to the GPU
1551// =======================================================================
1552Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1553{
1554 if (!myGlContext->IsGlGreaterEqual (3, 1))
1555 {
265d4508 1556#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1557 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
265d4508 1558#endif
fc73a202 1559 return Standard_False;
e276548b 1560 }
1561
265d4508 1562 /////////////////////////////////////////////////////////////////////////////
fc73a202 1563 // Create OpenGL texture buffers
265d4508 1564
fc73a202 1565 if (mySceneNodeInfoTexture.IsNull()) // create hight-level BVH buffers
e276548b 1566 {
fc73a202 1567 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1568 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1569 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
84c71f29 1570 mySceneTransformTexture = new OpenGl_TextureBufferArb;
265d4508 1571
fc73a202 1572 if (!mySceneNodeInfoTexture->Create (myGlContext)
84c71f29 1573 || !mySceneMinPointTexture->Create (myGlContext)
1574 || !mySceneMaxPointTexture->Create (myGlContext)
1575 || !mySceneTransformTexture->Create (myGlContext))
e276548b 1576 {
fc73a202 1577#ifdef RAY_TRACE_PRINT_INFO
1578 std::cout << "Error: Failed to create buffers for high-level scene BVH" << std::endl;
1579#endif
e276548b 1580 return Standard_False;
1581 }
1582 }
1583
fc73a202 1584 if (myObjectNodeInfoTexture.IsNull()) // create bottom-level BVH buffers
265d4508 1585 {
fc73a202 1586 myObjectNodeInfoTexture = new OpenGl_TextureBufferArb;
1587 myObjectMinPointTexture = new OpenGl_TextureBufferArb;
1588 myObjectMaxPointTexture = new OpenGl_TextureBufferArb;
e276548b 1589
fc73a202 1590 if (!myObjectNodeInfoTexture->Create (myGlContext)
1591 || !myObjectMinPointTexture->Create (myGlContext)
1592 || !myObjectMaxPointTexture->Create (myGlContext))
1593 {
e276548b 1594#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1595 std::cout << "Error: Failed to create buffers for bottom-level scene BVH" << std::endl;
1596#endif
1597 return Standard_False;
1598 }
1599 }
5322131b 1600
fc73a202 1601 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
265d4508 1602 {
fc73a202 1603 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1604 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1605 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
e276548b 1606
fc73a202 1607 if (!myGeometryVertexTexture->Create (myGlContext)
1608 || !myGeometryNormalTexture->Create (myGlContext)
1609 || !myGeometryTriangTexture->Create (myGlContext))
1610 {
1611#ifdef RAY_TRACE_PRINT_INFO
1612 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1613#endif
1614 return Standard_False;
1615 }
265d4508 1616 }
5322131b 1617
fc73a202 1618 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1619 {
1620 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
e276548b 1621
fc73a202 1622 if (!myRaytraceMaterialTexture->Create (myGlContext))
1623 {
1624#ifdef RAY_TRACE_PRINT_INFO
1625 std::cout << "Error: Failed to create buffers for material data" << std::endl;
e276548b 1626#endif
fc73a202 1627 return Standard_False;
1628 }
1629 }
e276548b 1630
fc73a202 1631 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 1632 // Write top-level BVH buffers
e276548b 1633
fc73a202 1634 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 4> >& aBVH = myRaytraceGeometry.BVH();
e276548b 1635
fc73a202 1636 bool aResult = true;
fc73a202 1637 if (!aBVH->NodeInfoBuffer().empty())
1638 {
5cff985a 1639 aResult &= mySceneNodeInfoTexture->Init (myGlContext, 4, GLsizei (aBVH->NodeInfoBuffer().size()),
1640 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1641 aResult &= mySceneMinPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MinPointBuffer().size()),
1642 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1643 aResult &= mySceneMaxPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MaxPointBuffer().size()),
1644 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
fc73a202 1645 }
fc73a202 1646 if (!aResult)
1647 {
1648#ifdef RAY_TRACE_PRINT_INFO
1649 std::cout << "Error: Failed to upload buffers for high-level scene BVH" << std::endl;
1650#endif
e276548b 1651 return Standard_False;
1652 }
1653
84c71f29 1654 /////////////////////////////////////////////////////////////////////////////
1655 // Write transform buffer
1656
1657 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1658 BVH_Mat4f anIdentity;
1659
1660 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1661 {
1662 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1663 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1664
1665 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1666 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1667
1668 Standard_ASSERT_RETURN (aTransform != NULL,
1669 "OpenGl_TriangleSet does not contain transform", Standard_False);
1670
1671 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1672
1673 }
1674
1675 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1676 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1677
1678 delete[] aNodeTransforms;
1679
1680 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 1681 // Write geometry and bottom-level BVH buffers
84c71f29 1682
fc73a202 1683 Standard_Size aTotalVerticesNb = 0;
1684 Standard_Size aTotalElementsNb = 0;
1685 Standard_Size aTotalBVHNodesNb = 0;
265d4508 1686
fc73a202 1687 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1688 {
1689 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1690 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
265d4508 1691
fc73a202 1692 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1693 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1694
1695 aTotalVerticesNb += aTriangleSet->Vertices.size();
1696 aTotalElementsNb += aTriangleSet->Elements.size();
e276548b 1697
fc73a202 1698 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1699 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
265d4508 1700
fc73a202 1701 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1702 }
e276548b 1703
fc73a202 1704 if (aTotalBVHNodesNb != 0)
e276548b 1705 {
5cff985a 1706 aResult &= myObjectNodeInfoTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1707 aResult &= myObjectMinPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1708 aResult &= myObjectMaxPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1709 }
265d4508 1710
fc73a202 1711 if (!aResult)
1712 {
1713#ifdef RAY_TRACE_PRINT_INFO
1714 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1715#endif
1716 return Standard_False;
1717 }
e276548b 1718
fc73a202 1719 if (aTotalElementsNb != 0)
1720 {
5cff985a 1721 aResult &= myGeometryTriangTexture->Init (myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
fc73a202 1722 }
265d4508 1723
fc73a202 1724 if (aTotalVerticesNb != 0)
1725 {
5cff985a 1726 aResult &= myGeometryVertexTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1727 aResult &= myGeometryNormalTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1728 }
265d4508 1729
fc73a202 1730 if (!aResult)
1731 {
1732#ifdef RAY_TRACE_PRINT_INFO
1733 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1734#endif
1735 return Standard_False;
1736 }
265d4508 1737
fc73a202 1738 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1739 {
1740 if (!aBVH->IsOuter (aNodeIdx))
1741 continue;
265d4508 1742
fc73a202 1743 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
e276548b 1744
fc73a202 1745 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1746 "Error: Failed to get triangulation of OpenGL element", Standard_False);
e276548b 1747
fc73a202 1748 const Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
e276548b 1749
fc73a202 1750 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1751 "Error: Failed to get offset for bottom-level BVH", Standard_False);
e276548b 1752
fc73a202 1753 const size_t aBVHBuffserSize = aTriangleSet->BVH()->NodeInfoBuffer().size();
265d4508 1754
fc73a202 1755 if (aBVHBuffserSize != 0)
1756 {
5cff985a 1757 aResult &= myObjectNodeInfoTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1758 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1759 aResult &= myObjectMinPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1760 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1761 aResult &= myObjectMaxPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1762 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
fc73a202 1763 if (!aResult)
e276548b 1764 {
fc73a202 1765#ifdef RAY_TRACE_PRINT_INFO
1766 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1767#endif
e276548b 1768 return Standard_False;
1769 }
1770 }
1771
fc73a202 1772 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
265d4508 1773
fc73a202 1774 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1775 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
265d4508 1776
fc73a202 1777 if (!aTriangleSet->Vertices.empty())
1778 {
5cff985a 1779 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1780 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1781 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1782 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
fc73a202 1783 }
e276548b 1784
fc73a202 1785 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
265d4508 1786
fc73a202 1787 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1788 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
e276548b 1789
fc73a202 1790 if (!aTriangleSet->Elements.empty())
e276548b 1791 {
5cff985a 1792 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1793 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
e276548b 1794 }
265d4508 1795
fc73a202 1796 if (!aResult)
1797 {
1798#ifdef RAY_TRACE_PRINT_INFO
1799 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
e276548b 1800#endif
fc73a202 1801 return Standard_False;
1802 }
e276548b 1803 }
e276548b 1804
fc73a202 1805 if (myRaytraceGeometry.Materials.size() != 0)
1806 {
1807 const GLfloat* aDataPtr = myRaytraceGeometry.Materials.front().Packed();
5cff985a 1808 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Materials.size() * 7), aDataPtr);
fc73a202 1809 if (!aResult)
1810 {
1811#ifdef RAY_TRACE_PRINT_INFO
1812 std::cout << "Error: Failed to upload material buffer" << std::endl;
1813#endif
1814 return Standard_False;
1815 }
1816 }
e276548b 1817
fc73a202 1818 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
e276548b 1819
fc73a202 1820#ifdef RAY_TRACE_PRINT_INFO
e276548b 1821
fc73a202 1822 Standard_ShortReal aMemUsed = 0.f;
e276548b 1823
fc73a202 1824 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1825 {
1826 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1827 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
e276548b 1828
fc73a202 1829 aMemUsed += static_cast<Standard_ShortReal> (
1830 aTriangleSet->Vertices.size() * sizeof (BVH_Vec4f));
1831 aMemUsed += static_cast<Standard_ShortReal> (
1832 aTriangleSet->Normals.size() * sizeof (BVH_Vec4f));
1833 aMemUsed += static_cast<Standard_ShortReal> (
1834 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
e276548b 1835
fc73a202 1836 aMemUsed += static_cast<Standard_ShortReal> (
1837 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1838 aMemUsed += static_cast<Standard_ShortReal> (
1839 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1840 aMemUsed += static_cast<Standard_ShortReal> (
1841 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
1842 }
e276548b 1843
fc73a202 1844 aMemUsed += static_cast<Standard_ShortReal> (
1845 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1846 aMemUsed += static_cast<Standard_ShortReal> (
1847 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1848 aMemUsed += static_cast<Standard_ShortReal> (
1849 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
e276548b 1850
fc73a202 1851 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
e276548b 1852
fc73a202 1853#endif
e276548b 1854
fc73a202 1855 return aResult;
1856}
e276548b 1857
fc73a202 1858// =======================================================================
1859// function : ResizeRaytraceBuffers
1860// purpose : Resizes OpenGL frame buffers
1861// =======================================================================
1862Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1863 const Standard_Integer theSizeY)
1864{
1865 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1866 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1867 {
1868 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1869 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1870 }
e276548b 1871
fc73a202 1872 return Standard_True;
e276548b 1873}
1874
1875// =======================================================================
fc73a202 1876// function : UpdateCamera
1877// purpose : Generates viewing rays for corners of screen quad
e276548b 1878// =======================================================================
fc73a202 1879void OpenGl_Workspace::UpdateCamera (const NCollection_Mat4<GLdouble>& theOrientation,
1880 const NCollection_Mat4<GLdouble>& theViewMapping,
1881 OpenGl_Vec3 theOrigins[4],
a89742cf 1882 OpenGl_Vec3 theDirects[4],
1883 NCollection_Mat4<GLdouble>& theInvModelProj)
e276548b 1884{
bc8c79bb 1885 // compute inverse model-view-projection matrix
a89742cf 1886 (theViewMapping * theOrientation).Inverted (theInvModelProj);
fc73a202 1887
68333c8f 1888 Standard_Integer aOriginIndex = 0;
1889 Standard_Integer aDirectIndex = 0;
e276548b 1890
fc73a202 1891 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
e276548b 1892 {
fc73a202 1893 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
e276548b 1894 {
fc73a202 1895 OpenGl_Vec4d aOrigin (GLdouble(aX),
1896 GLdouble(aY),
1897 -1.0,
1898 1.0);
1899
a89742cf 1900 aOrigin = theInvModelProj * aOrigin;
e276548b 1901
b5ac8292 1902 aOrigin.x() = aOrigin.x() / aOrigin.w();
1903 aOrigin.y() = aOrigin.y() / aOrigin.w();
1904 aOrigin.z() = aOrigin.z() / aOrigin.w();
e276548b 1905
fc73a202 1906 OpenGl_Vec4d aDirect (GLdouble(aX),
1907 GLdouble(aY),
1908 1.0,
1909 1.0);
1910
a89742cf 1911 aDirect = theInvModelProj * aDirect;
e276548b 1912
b5ac8292 1913 aDirect.x() = aDirect.x() / aDirect.w();
1914 aDirect.y() = aDirect.y() / aDirect.w();
1915 aDirect.z() = aDirect.z() / aDirect.w();
b5ac8292 1916
1917 aDirect = aDirect - aOrigin;
e276548b 1918
fc73a202 1919 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
e276548b 1920 aDirect.y() * aDirect.y() +
1921 aDirect.z() * aDirect.z());
1922
fc73a202 1923 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1924 static_cast<GLfloat> (aOrigin.y()),
1925 static_cast<GLfloat> (aOrigin.z()));
1926
1927 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
1928 static_cast<GLfloat> (aDirect.y() * aInvLen),
1929 static_cast<GLfloat> (aDirect.z() * aInvLen));
1930 }
1931 }
1932}
1933
1934// =======================================================================
1935// function : RunRaytraceShaders
1936// purpose : Runs ray-tracing shader programs
1937// =======================================================================
1938Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
1939 const Standard_Integer theSizeX,
1940 const Standard_Integer theSizeY,
1941 const OpenGl_Vec3 theOrigins[4],
1942 const OpenGl_Vec3 theDirects[4],
a89742cf 1943 const OpenGl_Matrix& theInvModelProj,
fc73a202 1944 OpenGl_FrameBuffer* theFrameBuffer)
1945{
1946 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
1947 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
1948 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
1949 myObjectMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
1950 myObjectMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
1951 myObjectNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
1952 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
1953 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
1954 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
a89742cf 1955 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
fc73a202 1956 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
1957 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
a89742cf 1958
1959 myOpenGlFBO->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
1960 myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
fc73a202 1961
bc8c79bb 1962 if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
fc73a202 1963 {
1964 myRaytraceFBO1->BindBuffer (myGlContext);
1965
1966 glDisable (GL_BLEND);
1967 }
1968
7d3e64ef 1969 myGlContext->BindProgram (myRaytraceProgram);
fc73a202 1970
1971 Standard_Integer aLightSourceBufferSize =
1972 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
1973
1974 myRaytraceProgram->SetUniform (myGlContext,
1975 myUniformLocations[0][OpenGl_RT_uOriginLB], theOrigins[0]);
1976 myRaytraceProgram->SetUniform (myGlContext,
1977 myUniformLocations[0][OpenGl_RT_uOriginRB], theOrigins[1]);
1978 myRaytraceProgram->SetUniform (myGlContext,
1979 myUniformLocations[0][OpenGl_RT_uOriginLT], theOrigins[2]);
1980 myRaytraceProgram->SetUniform (myGlContext,
1981 myUniformLocations[0][OpenGl_RT_uOriginRT], theOrigins[3]);
1982 myRaytraceProgram->SetUniform (myGlContext,
1983 myUniformLocations[0][OpenGl_RT_uDirectLB], theDirects[0]);
1984 myRaytraceProgram->SetUniform (myGlContext,
1985 myUniformLocations[0][OpenGl_RT_uDirectRB], theDirects[1]);
1986 myRaytraceProgram->SetUniform (myGlContext,
1987 myUniformLocations[0][OpenGl_RT_uDirectLT], theDirects[2]);
1988 myRaytraceProgram->SetUniform (myGlContext,
1989 myUniformLocations[0][OpenGl_RT_uDirectRT], theDirects[3]);
1990 myRaytraceProgram->SetUniform (myGlContext,
a89742cf 1991 myUniformLocations[0][OpenGl_RT_uInvModelProj], theInvModelProj);
1992 myRaytraceProgram->SetUniform (myGlContext,
fc73a202 1993 myUniformLocations[0][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
1994 myRaytraceProgram->SetUniform (myGlContext,
1995 myUniformLocations[0][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
1996 myRaytraceProgram->SetUniform (myGlContext,
1997 myUniformLocations[0][OpenGl_RT_uLightCount], aLightSourceBufferSize);
1998 myRaytraceProgram->SetUniform (myGlContext,
1999 myUniformLocations[0][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2000 myRaytraceProgram->SetUniform (myGlContext,
bc8c79bb 2001 myUniformLocations[0][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
fc73a202 2002 myRaytraceProgram->SetUniform (myGlContext,
bc8c79bb 2003 myUniformLocations[0][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
fc73a202 2004
7d3e64ef 2005 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 2006 {
7d3e64ef 2007 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
fc73a202 2008 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2009 }
7d3e64ef 2010 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 2011
bc8c79bb 2012 if (!theCView.RenderParams.IsAntialiasingEnabled)
fc73a202 2013 {
7d3e64ef 2014 myGlContext->BindProgram (NULL);
fc73a202 2015
a89742cf 2016 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2017 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2018 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2019 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2020 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2021 myObjectMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
2022 myObjectMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
2023 myObjectNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
2024 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2025 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2026 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2027 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2028 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2029 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2030
2031 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2032
fc73a202 2033 return Standard_True;
2034 }
2035
945c3529 2036 myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2037
7d3e64ef 2038 myGlContext->BindProgram (myPostFSAAProgram);
fc73a202 2039
2040 myPostFSAAProgram->SetUniform (myGlContext,
2041 myUniformLocations[1][OpenGl_RT_uOriginLB], theOrigins[0]);
2042 myPostFSAAProgram->SetUniform (myGlContext,
2043 myUniformLocations[1][OpenGl_RT_uOriginRB], theOrigins[1]);
2044 myPostFSAAProgram->SetUniform (myGlContext,
2045 myUniformLocations[1][OpenGl_RT_uOriginLT], theOrigins[2]);
2046 myPostFSAAProgram->SetUniform (myGlContext,
2047 myUniformLocations[1][OpenGl_RT_uOriginRT], theOrigins[3]);
2048 myPostFSAAProgram->SetUniform (myGlContext,
2049 myUniformLocations[1][OpenGl_RT_uDirectLB], theDirects[0]);
2050 myPostFSAAProgram->SetUniform (myGlContext,
2051 myUniformLocations[1][OpenGl_RT_uDirectRB], theDirects[1]);
2052 myPostFSAAProgram->SetUniform (myGlContext,
2053 myUniformLocations[1][OpenGl_RT_uDirectLT], theDirects[2]);
2054 myPostFSAAProgram->SetUniform (myGlContext,
2055 myUniformLocations[1][OpenGl_RT_uDirectRT], theDirects[3]);
a89742cf 2056 myRaytraceProgram->SetUniform (myGlContext,
2057 myUniformLocations[1][OpenGl_RT_uInvModelProj], theInvModelProj);
fc73a202 2058 myPostFSAAProgram->SetUniform (myGlContext,
2059 myUniformLocations[1][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2060 myPostFSAAProgram->SetUniform (myGlContext,
2061 myUniformLocations[1][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2062 myPostFSAAProgram->SetUniform (myGlContext,
2063 myUniformLocations[1][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2064 myPostFSAAProgram->SetUniform (myGlContext,
2065 myUniformLocations[1][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2066 myPostFSAAProgram->SetUniform (myGlContext,
bc8c79bb 2067 myUniformLocations[1][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
fc73a202 2068 myPostFSAAProgram->SetUniform (myGlContext,
bc8c79bb 2069 myUniformLocations[1][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
fc73a202 2070
2071 const Standard_ShortReal aMaxOffset = 0.559017f;
2072 const Standard_ShortReal aMinOffset = 0.186339f;
2073
7d3e64ef 2074 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2075 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
fc73a202 2076
2077 // Perform multi-pass adaptive FSAA using ping-pong technique
84c71f29 2078 // rotated grid AA always uses 4 samples
fc73a202 2079 for (Standard_Integer anIt = 0; anIt < 4; ++anIt)
2080 {
2081 GLfloat aOffsetX = 1.f / theSizeX;
2082 GLfloat aOffsetY = 1.f / theSizeY;
2083
2084 if (anIt < 2)
2085 {
2086 aOffsetX *= anIt < 1 ? aMinOffset : -aMaxOffset;
2087 aOffsetY *= anIt < 1 ? aMaxOffset : aMinOffset;
2088 }
2089 else
2090 {
2091 aOffsetX *= anIt > 2 ? aMaxOffset : -aMinOffset;
2092 aOffsetY *= anIt > 2 ? -aMinOffset : -aMaxOffset;
2093 }
2094
2095 myPostFSAAProgram->SetUniform (myGlContext,
2096 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 2);
2097 myPostFSAAProgram->SetUniform (myGlContext,
2098 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2099 myPostFSAAProgram->SetUniform (myGlContext,
2100 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2101
2102 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO1 : myRaytraceFBO2;
2103
2104 if (anIt == 3) // disable FBO on last iteration
2105 {
2106 glEnable (GL_BLEND);
2107
2108 if (theFrameBuffer != NULL)
2109 theFrameBuffer->BindBuffer (myGlContext);
2110 }
2111 else
2112 {
2113 aFramebuffer->BindBuffer (myGlContext);
2114 }
2115
2116 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
e276548b 2117
fc73a202 2118 if (anIt != 3) // set input for the next pass
2119 {
945c3529 2120 aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2121 aFramebuffer->UnbindBuffer (myGlContext);
e276548b 2122 }
2123 }
fc73a202 2124
7d3e64ef 2125 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 2126
7d3e64ef 2127 myGlContext->BindProgram (NULL);
a89742cf 2128 myRaytraceFBO1->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2129 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2130 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2131 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2132 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2133 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2134 myObjectMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
2135 myObjectMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
2136 myObjectNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
2137 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2138 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2139 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2140 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2141 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2142 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2143
2144 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
fc73a202 2145
2146 return Standard_True;
e276548b 2147}
2148
2149// =======================================================================
2150// function : Raytrace
fc73a202 2151// purpose : Redraws the window using OpenGL/GLSL ray-tracing
e276548b 2152// =======================================================================
2153Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
68333c8f 2154 const Standard_Integer theSizeX,
2155 const Standard_Integer theSizeY,
fc73a202 2156 const Standard_Boolean theToSwap,
a89742cf 2157 const Aspect_CLayer2d& theCOverLayer,
2158 const Aspect_CLayer2d& theCUnderLayer,
fc73a202 2159 OpenGl_FrameBuffer* theFrameBuffer)
e276548b 2160{
bc8c79bb 2161 if (!InitRaytraceResources (theCView))
e276548b 2162 return Standard_False;
2163
fc73a202 2164 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
e276548b 2165 return Standard_False;
2166
fc73a202 2167 if (!UpdateRaytraceEnvironmentMap())
e276548b 2168 return Standard_False;
2169
2170 // Get model-view and projection matrices
2171 TColStd_Array2OfReal theOrientation (0, 3, 0, 3);
2172 TColStd_Array2OfReal theViewMapping (0, 3, 0, 3);
2173
b5ac8292 2174 myView->GetMatrices (theOrientation, theViewMapping);
e276548b 2175
fc73a202 2176 NCollection_Mat4<GLdouble> aOrientationMatrix;
2177 NCollection_Mat4<GLdouble> aViewMappingMatrix;
e276548b 2178
68333c8f 2179 for (Standard_Integer j = 0; j < 4; ++j)
fc73a202 2180 {
68333c8f 2181 for (Standard_Integer i = 0; i < 4; ++i)
e276548b 2182 {
2183 aOrientationMatrix [4 * j + i] = theOrientation (i, j);
2184 aViewMappingMatrix [4 * j + i] = theViewMapping (i, j);
2185 }
fc73a202 2186 }
2187
2188 NCollection_Mat4<GLdouble> aInvOrientationMatrix;
2189 aOrientationMatrix.Inverted (aInvOrientationMatrix);
e276548b 2190
fc73a202 2191 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
e276548b 2192 return Standard_False;
2193
fc73a202 2194 OpenGl_Vec3 aOrigins[4];
2195 OpenGl_Vec3 aDirects[4];
a89742cf 2196 NCollection_Mat4<GLdouble> anInvModelProj;
e276548b 2197
fc73a202 2198 UpdateCamera (aOrientationMatrix,
2199 aViewMappingMatrix,
2200 aOrigins,
a89742cf 2201 aDirects,
2202 anInvModelProj);
2203
2204 OpenGl_Matrix anInvModelProjMatrix;
2205 for (Standard_Integer j = 0; j < 4; ++j)
2206 {
2207 for (Standard_Integer i = 0; i < 4; ++i)
2208 {
2209 anInvModelProjMatrix.mat[j][i] = static_cast<GLfloat>(anInvModelProj.GetValue(i,j));
2210 }
2211 }
e276548b 2212
84c71f29 2213 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2214 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
e276548b 2215
2216 glDisable (GL_DEPTH_TEST);
2217
a89742cf 2218 if (theFrameBuffer != NULL)
2219 {
2220 theFrameBuffer->BindBuffer (myGlContext);
2221 }
2222
e276548b 2223 if (NamedStatus & OPENGL_NS_WHITEBACK)
2224 {
2225 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2226 }
2227 else
2228 {
2229 glClearColor (myBgColor.rgb[0],
2230 myBgColor.rgb[1],
2231 myBgColor.rgb[2],
2232 1.0f);
2233 }
2234
2235 glClear (GL_COLOR_BUFFER_BIT);
2236
fc73a202 2237 myView->DrawBackground (*this);
e276548b 2238
a89742cf 2239 myView->RedrawLayer2d (myPrintContext, theCView, theCUnderLayer);
2240
ca3c13d1 2241#if !defined(GL_ES_VERSION_2_0)
fc73a202 2242 // Generate ray-traced image
e276548b 2243 glMatrixMode (GL_PROJECTION);
a89742cf 2244 glPushMatrix();
e276548b 2245 glLoadIdentity();
2246
2247 glMatrixMode (GL_MODELVIEW);
a89742cf 2248 glPushMatrix();
e276548b 2249 glLoadIdentity();
ca3c13d1 2250#endif
e276548b 2251
fc73a202 2252 glEnable (GL_BLEND);
2253 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
e276548b 2254
2255 if (myIsRaytraceDataValid)
2256 {
fc73a202 2257 myRaytraceScreenQuad.Bind (myGlContext);
2258
2259 RunRaytraceShaders (theCView,
2260 theSizeX,
2261 theSizeY,
2262 aOrigins,
2263 aDirects,
a89742cf 2264 anInvModelProjMatrix,
fc73a202 2265 theFrameBuffer);
2266
2267 myRaytraceScreenQuad.Unbind (myGlContext);
e276548b 2268 }
2269
84c71f29 2270 if (!wasBlendingEnabled)
2271 glDisable (GL_BLEND);
fc73a202 2272
84c71f29 2273 if (wasDepthTestEnabled)
2274 glEnable (GL_DEPTH_TEST);
e276548b 2275
ca3c13d1 2276#if !defined(GL_ES_VERSION_2_0)
a89742cf 2277 glMatrixMode (GL_PROJECTION);
2278 glPopMatrix();
2279 glMatrixMode (GL_MODELVIEW);
2280 glPopMatrix();
ca3c13d1 2281#endif
a89742cf 2282
2283 // Redraw trihedron
2284 myView->RedrawTrihedron (this);
2285
2286 // Redraw overlay
2287 const int aMode = 0;
2288 DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
2289 myView->RedrawLayer2d (myPrintContext, theCView, theCOverLayer);
2290 DisplayCallback (theCView, aMode);
2291
e276548b 2292 // Swap the buffers
2293 if (theToSwap)
2294 {
2295 GetGlContext()->SwapBuffers();
2296 myBackBufferRestored = Standard_False;
2297 }
2298 else
fc73a202 2299 {
e276548b 2300 glFlush();
fc73a202 2301 }
e276548b 2302
2303 return Standard_True;
2304}
a89742cf 2305
2306IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2307IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2308
2309// =======================================================================
2310// function : CanRender
2311// purpose :
2312// =======================================================================
2313Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2314{
2315 Standard_Boolean aPrevFilterResult = Standard_True;
2316 if (!myPrevRenderFilter.IsNull())
2317 {
2318 aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2319 }
2320 return aPrevFilterResult &&
2321 !OpenGl_Raytrace::IsRaytracedElement (theElement);
2322}