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