0024887: Visualization - revise and extend Raytracing controls
[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
dc9ef964 222 myRaytraceSceneEpsilon = Max (1e-7f, 1e-4f * sqrtf (
fc73a202 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,
dc9ef964 293 theProp.index == 0 ? 1.f : theProp.index,
294 theProp.index == 0 ? 1.f : 1.f / theProp.index);
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// =======================================================================
871fa103 455OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
456 Standard_Integer theMatID,
457 const Standard_ShortReal* theTransform)
e276548b 458{
871fa103 459 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
460 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
461 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
462 if (theArray->DrawMode() < GL_TRIANGLES
463 || theArray->DrawMode() > GL_POLYGON
464 || anAttribs.IsNull())
e276548b 465 {
265d4508 466 return NULL;
e276548b 467 }
468
e276548b 469#ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 470 switch (theArray->DrawMode())
e276548b 471 {
871fa103 472 case GL_POLYGON: std::cout << "\tAdding GL_POLYGON\n"; break;
473 case GL_TRIANGLES: std::cout << "\tAdding GL_TRIANGLES\n"; break;
474 case GL_QUADS: std::cout << "\tAdding GL_QUADS\n"; break;
475 case GL_TRIANGLE_FAN: std::cout << "\tAdding GL_TRIANGLE_FAN\n"; break;
476 case GL_TRIANGLE_STRIP: std::cout << "\tAdding GL_TRIANGLE_STRIP\n"; break;
477 case GL_QUAD_STRIP: std::cout << "\tAdding GL_QUAD_STRIP\n"; break;
e276548b 478 }
479#endif
480
84c71f29 481 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray);
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);
606 case GL_QUADS: return AddRaytraceQuadrangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
607 case GL_TRIANGLE_FAN: return AddRaytraceTriangleFanArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
608 case GL_TRIANGLE_STRIP: return AddRaytraceTriangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
609 case GL_QUAD_STRIP: return AddRaytraceQuadrangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
610 case GL_POLYGON: return AddRaytracePolygonArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
e276548b 611 }
871fa103 612 return Standard_False;
e276548b 613}
614
615// =======================================================================
616// function : AddRaytraceTriangleArray
617// purpose : Adds OpenGL triangle array to ray-traced scene geometry
618// =======================================================================
871fa103 619Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
620 const Handle(Graphic3d_IndexBuffer)& theIndices,
621 Standard_Integer theOffset,
622 Standard_Integer theCount,
623 Standard_Integer theMatID)
e276548b 624{
265d4508 625 if (theCount < 3)
e276548b 626 return Standard_True;
627
871fa103 628 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
265d4508 629
871fa103 630 if (!theIndices.IsNull())
e276548b 631 {
265d4508 632 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 633 {
871fa103 634 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
635 theIndices->Index (aVert + 1),
636 theIndices->Index (aVert + 2),
637 theMatID));
e276548b 638 }
639 }
640 else
641 {
265d4508 642 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 643 {
871fa103 644 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
645 theMatID));
e276548b 646 }
647 }
648
649 return Standard_True;
650}
651
652// =======================================================================
653// function : AddRaytraceTriangleFanArray
654// purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
655// =======================================================================
871fa103 656Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
657 const Handle(Graphic3d_IndexBuffer)& theIndices,
658 Standard_Integer theOffset,
659 Standard_Integer theCount,
660 Standard_Integer theMatID)
e276548b 661{
265d4508 662 if (theCount < 3)
e276548b 663 return Standard_True;
664
871fa103 665 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 666
871fa103 667 if (!theIndices.IsNull())
e276548b 668 {
265d4508 669 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 670 {
871fa103 671 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
672 theIndices->Index (aVert + 1),
673 theIndices->Index (aVert + 2),
674 theMatID));
e276548b 675 }
676 }
677 else
678 {
265d4508 679 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 680 {
871fa103 681 theSet.Elements.push_back (BVH_Vec4i (theOffset,
682 aVert + 1,
683 aVert + 2,
684 theMatID));
e276548b 685 }
686 }
687
688 return Standard_True;
689}
690
691// =======================================================================
692// function : AddRaytraceTriangleStripArray
693// purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
694// =======================================================================
871fa103 695Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
696 const Handle(Graphic3d_IndexBuffer)& theIndices,
697 Standard_Integer theOffset,
698 Standard_Integer theCount,
699 Standard_Integer theMatID)
e276548b 700{
265d4508 701 if (theCount < 3)
e276548b 702 return Standard_True;
703
871fa103 704 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 705
871fa103 706 if (!theIndices.IsNull())
e276548b 707 {
265d4508 708 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 709 {
871fa103 710 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
711 theIndices->Index (aVert + aCW ? 0 : 1),
712 theIndices->Index (aVert + 2),
713 theMatID));
e276548b 714 }
715 }
716 else
717 {
265d4508 718 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 719 {
871fa103 720 theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
721 aVert + aCW ? 0 : 1,
722 aVert + 2,
723 theMatID));
e276548b 724 }
725 }
726
727 return Standard_True;
728}
729
730// =======================================================================
731// function : AddRaytraceQuadrangleArray
732// purpose : Adds OpenGL quad array to ray-traced scene geometry
733// =======================================================================
871fa103 734Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
735 const Handle(Graphic3d_IndexBuffer)& theIndices,
736 Standard_Integer theOffset,
737 Standard_Integer theCount,
738 Standard_Integer theMatID)
e276548b 739{
265d4508 740 if (theCount < 4)
e276548b 741 return Standard_True;
742
871fa103 743 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
265d4508 744
871fa103 745 if (!theIndices.IsNull())
e276548b 746 {
265d4508 747 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 748 {
871fa103 749 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
750 theIndices->Index (aVert + 1),
751 theIndices->Index (aVert + 2),
752 theMatID));
753 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
754 theIndices->Index (aVert + 2),
755 theIndices->Index (aVert + 3),
756 theMatID));
e276548b 757 }
758 }
759 else
760 {
265d4508 761 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 762 {
871fa103 763 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
764 theMatID));
765 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
766 theMatID));
e276548b 767 }
768 }
769
770 return Standard_True;
771}
772
773// =======================================================================
774// function : AddRaytraceQuadrangleStripArray
775// purpose : Adds OpenGL quad strip array to ray-traced scene geometry
776// =======================================================================
871fa103 777Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
778 const Handle(Graphic3d_IndexBuffer)& theIndices,
779 Standard_Integer theOffset,
780 Standard_Integer theCount,
781 Standard_Integer theMatID)
e276548b 782{
265d4508 783 if (theCount < 4)
e276548b 784 return Standard_True;
785
871fa103 786 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
265d4508 787
871fa103 788 if (!theIndices.IsNull())
e276548b 789 {
265d4508 790 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 791 {
871fa103 792 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
793 theIndices->Index (aVert + 1),
794 theIndices->Index (aVert + 2),
795 theMatID));
796
797 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
798 theIndices->Index (aVert + 3),
799 theIndices->Index (aVert + 2),
800 theMatID));
e276548b 801 }
802 }
803 else
804 {
265d4508 805 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 806 {
871fa103 807 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
808 aVert + 1,
809 aVert + 2,
810 theMatID));
811
812 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
813 aVert + 3,
814 aVert + 2,
815 theMatID));
e276548b 816 }
817 }
818
819 return Standard_True;
820}
821
822// =======================================================================
823// function : AddRaytracePolygonArray
824// purpose : Adds OpenGL polygon array to ray-traced scene geometry
825// =======================================================================
871fa103 826Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet& theSet,
827 const Handle(Graphic3d_IndexBuffer)& theIndices,
828 Standard_Integer theOffset,
829 Standard_Integer theCount,
830 Standard_Integer theMatID)
e276548b 831{
265d4508 832 if (theCount < 3)
e276548b 833 return Standard_True;
834
871fa103 835 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 836
871fa103 837 if (!theIndices.IsNull())
e276548b 838 {
265d4508 839 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 840 {
871fa103 841 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
842 theIndices->Index (aVert + 1),
843 theIndices->Index (aVert + 2),
844 theMatID));
e276548b 845 }
846 }
847 else
848 {
265d4508 849 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 850 {
871fa103 851 theSet.Elements.push_back (BVH_Vec4i (theOffset,
852 aVert + 1,
853 aVert + 2,
854 theMatID));
e276548b 855 }
856 }
857
858 return Standard_True;
859}
860
861// =======================================================================
862// function : UpdateRaytraceLightSources
863// purpose : Updates 3D scene light sources for ray-tracing
864// =======================================================================
865Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const GLdouble theInvModelView[16])
866{
265d4508 867 myRaytraceGeometry.Sources.clear();
e276548b 868
fc73a202 869 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
265d4508 870
871 for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
e276548b 872 {
12381341 873 const OpenGl_Light& aLight = anItl.Value();
265d4508 874
12381341 875 if (aLight.Type == Visual3d_TOLS_AMBIENT)
e276548b 876 {
fc73a202 877 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
878 aLight.Color.g(),
879 aLight.Color.b(),
880 0.0f);
e276548b 881 continue;
882 }
883
265d4508 884 BVH_Vec4f aDiffuse (aLight.Color.r(),
885 aLight.Color.g(),
886 aLight.Color.b(),
887 1.0f);
888
889 BVH_Vec4f aPosition (-aLight.Direction.x(),
890 -aLight.Direction.y(),
891 -aLight.Direction.z(),
892 0.0f);
893
12381341 894 if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
e276548b 895 {
265d4508 896 aPosition = BVH_Vec4f (aLight.Position.x(),
897 aLight.Position.y(),
898 aLight.Position.z(),
899 1.0f);
e276548b 900 }
265d4508 901
12381341 902 if (aLight.IsHeadlight)
e276548b 903 aPosition = MatVecMult (theInvModelView, aPosition);
e276548b 904
fc73a202 905
265d4508 906 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
e276548b 907 }
908
fc73a202 909 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
e276548b 910 {
fc73a202 911 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
e276548b 912
fc73a202 913 if (!myRaytraceLightSrcTexture->Create (myGlContext))
914 {
e276548b 915#ifdef RAY_TRACE_PRINT_INFO
fc73a202 916 std::cout << "Error: Failed to create light source buffer" << std::endl;
e276548b 917#endif
fc73a202 918 return Standard_False;
919 }
e276548b 920 }
fc73a202 921
922 if (myRaytraceGeometry.Sources.size() != 0)
e276548b 923 {
fc73a202 924 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
5cff985a 925 if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
fc73a202 926 {
927#ifdef RAY_TRACE_PRINT_INFO
928 std::cout << "Error: Failed to upload light source buffer" << std::endl;
e276548b 929#endif
fc73a202 930 return Standard_False;
931 }
932 }
e276548b 933
934 return Standard_True;
935}
936
937// =======================================================================
fc73a202 938// function : UpdateRaytraceEnvironmentMap
939// purpose : Updates environment map for ray-tracing
e276548b 940// =======================================================================
fc73a202 941Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
e276548b 942{
fc73a202 943 if (myView.IsNull())
e276548b 944 return Standard_False;
e276548b 945
fc73a202 946 if (myViewModificationStatus == myView->ModificationState())
947 return Standard_True;
e276548b 948
fc73a202 949 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
e276548b 950 {
fc73a202 951 const Handle(OpenGl_ShaderProgram)& aProgram =
952 anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
e276548b 953
fc73a202 954 if (!aProgram.IsNull())
e276548b 955 {
fc73a202 956 aProgram->Bind (myGlContext);
e276548b 957
fc73a202 958 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
e276548b 959 {
fc73a202 960 myView->TextureEnv()->Bind (
961 myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
962
84c71f29 963 aProgram->SetUniform (myGlContext,
964 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 1);
e276548b 965 }
966 else
967 {
84c71f29 968 aProgram->SetUniform (myGlContext,
969 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 0);
e276548b 970 }
fc73a202 971 }
e276548b 972 }
973
fc73a202 974 OpenGl_ShaderProgram::Unbind (myGlContext);
e276548b 975
fc73a202 976 myViewModificationStatus = myView->ModificationState();
e276548b 977
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
1201 if (!myRaytraceProgram->Link (myGlContext)
1202 || !myPostFSAAProgram->Link (myGlContext))
1203 {
1204 return Standard_False;
1205 }
1206 }
e276548b 1207 }
1208
fc73a202 1209 if (myComputeInitStatus == OpenGl_RT_NONE)
1210 {
1211 if (!myGlContext->IsGlGreaterEqual (3, 1))
1212 {
1213 const TCollection_ExtendedString aMessage = "Ray-tracing requires OpenGL 3.1 and higher";
265d4508 1214
fc73a202 1215 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1216 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
265d4508 1217
fc73a202 1218 return Standard_False;
1219 }
5322131b 1220
bc8c79bb 1221 myRaytraceParameters.TraceDepth = theCView.RenderParams.RaytracingDepth;
1222
fc73a202 1223 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
265d4508 1224
fc73a202 1225 if (aFolder.IsEmpty())
1226 {
1227 const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1228
1229 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1230 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1231
1232 return Standard_False;
1233 }
265d4508 1234
fc73a202 1235 if (myIsRaytraceDataValid)
1236 {
bc8c79bb 1237 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
fc73a202 1238 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1239 }
265d4508 1240
bc8c79bb 1241 TCollection_AsciiString aPrefixString =
1242 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1243 TCollection_AsciiString ("#define TRACE_DEPTH ") + TCollection_AsciiString (myRaytraceParameters.TraceDepth);
1244
1245 if (myRaytraceParameters.TransparentShadows)
1246 {
1247 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1248 }
1249
1250#ifdef RAY_TRACE_PRINT_INFO
1251 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1252#endif
1253
fc73a202 1254 {
1255 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1256 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1257
fc73a202 1258 if (aBasicVertShader.IsNull())
1259 {
1260 return SafeFailBack ("Failed to set vertex shader source");
1261 }
265d4508 1262
fc73a202 1263 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
265d4508 1264
fc73a202 1265 myRaytraceShaderSource.Load (aFiles, 2);
e276548b 1266
bc8c79bb 1267 myRaytraceShaderSource.SetPrefix (aPrefixString);
265d4508 1268
fc73a202 1269 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
265d4508 1270
fc73a202 1271 if (myRaytraceShader.IsNull())
1272 {
1273 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1274
fc73a202 1275 return SafeFailBack ("Failed to set ray-trace fragment shader source");
1276 }
265d4508 1277
fc73a202 1278 myRaytraceProgram = new OpenGl_ShaderProgram;
5322131b 1279
fc73a202 1280 if (!myRaytraceProgram->Create (myGlContext))
1281 {
1282 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1283
fc73a202 1284 return SafeFailBack ("Failed to create ray-trace shader program");
1285 }
265d4508 1286
fc73a202 1287 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1288 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1289 {
1290 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1291
fc73a202 1292 return SafeFailBack ("Failed to attach ray-trace shader objects");
1293 }
265d4508 1294
fc73a202 1295 if (!myRaytraceProgram->Link (myGlContext))
1296 {
1297 TCollection_AsciiString aLinkLog;
e276548b 1298
fc73a202 1299 if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1300 {
1301 #ifdef RAY_TRACE_PRINT_INFO
1302 std::cout << aLinkLog << std::endl;
1303 #endif
1304 }
265d4508 1305
fc73a202 1306 return SafeFailBack ("Failed to link ray-trace shader program");
1307 }
1308 }
265d4508 1309
fc73a202 1310 {
1311 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1312 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1313
fc73a202 1314 if (aBasicVertShader.IsNull())
1315 {
1316 return SafeFailBack ("Failed to set vertex shader source");
1317 }
265d4508 1318
fc73a202 1319 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
265d4508 1320
fc73a202 1321 myPostFSAAShaderSource.Load (aFiles, 2);
265d4508 1322
bc8c79bb 1323 myPostFSAAShaderSource.SetPrefix (aPrefixString);
fc73a202 1324
1325 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
265d4508 1326
fc73a202 1327 if (myPostFSAAShader.IsNull())
1328 {
1329 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1330
fc73a202 1331 return SafeFailBack ("Failed to set FSAA fragment shader source");
1332 }
265d4508 1333
fc73a202 1334 myPostFSAAProgram = new OpenGl_ShaderProgram;
265d4508 1335
fc73a202 1336 if (!myPostFSAAProgram->Create (myGlContext))
1337 {
1338 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1339
fc73a202 1340 return SafeFailBack ("Failed to create FSAA shader program");
1341 }
1342
1343 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1344 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1345 {
1346 aBasicVertShader->Release (myGlContext.operator->());
1347
1348 return SafeFailBack ("Failed to attach FSAA shader objects");
1349 }
1350
1351 if (!myPostFSAAProgram->Link (myGlContext))
1352 {
1353 TCollection_AsciiString aLinkLog;
1354
1355 if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1356 {
1357 #ifdef RAY_TRACE_PRINT_INFO
1358 std::cout << aLinkLog << std::endl;
1359 #endif
1360 }
1361
1362 return SafeFailBack ("Failed to link FSAA shader program");
1363 }
e276548b 1364 }
fc73a202 1365 }
e276548b 1366
fc73a202 1367 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1368 {
1369 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
e276548b 1370 {
fc73a202 1371 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1372 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1373
1374 aShaderProgram->Bind (myGlContext);
1375
1376 aShaderProgram->SetSampler (myGlContext,
1377 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1378 aShaderProgram->SetSampler (myGlContext,
1379 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1380 aShaderProgram->SetSampler (myGlContext,
1381 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1382 aShaderProgram->SetSampler (myGlContext,
1383 "uObjectMinPointTexture", OpenGl_RT_ObjectMinPointTexture);
1384 aShaderProgram->SetSampler (myGlContext,
1385 "uObjectMaxPointTexture", OpenGl_RT_ObjectMaxPointTexture);
1386 aShaderProgram->SetSampler (myGlContext,
1387 "uObjectNodeInfoTexture", OpenGl_RT_ObjectNodeInfoTexture);
1388 aShaderProgram->SetSampler (myGlContext,
1389 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1390 aShaderProgram->SetSampler (myGlContext,
1391 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1392 aShaderProgram->SetSampler (myGlContext,
1393 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1394 aShaderProgram->SetSampler (myGlContext,
1395 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1396 aShaderProgram->SetSampler (myGlContext,
1397 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
84c71f29 1398 aShaderProgram->SetSampler (myGlContext,
1399 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1400 aShaderProgram->SetSampler (myGlContext,
1401 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
fc73a202 1402
1403 if (anIndex == 1)
1404 {
1405 aShaderProgram->SetSampler (myGlContext,
1406 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1407 }
265d4508 1408
fc73a202 1409 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1410 aShaderProgram->GetAttributeLocation (myGlContext, "aPosition");
1411
1412 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1413 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1414 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1415 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1416 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1417 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1418 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1419 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1420 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1421 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1422 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1423 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1424 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1425 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1426 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1427 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
1428
1429 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1430 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1431 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1432 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1433
1434 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1435 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1436 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1437 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1438
1439 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1440 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1441 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1442 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1443
1444 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1445 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1446 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1447 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1448 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1449 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
84c71f29 1450
1451 myUniformLocations[anIndex][OpenGl_RT_uEnvironmentEnable] =
1452 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
fc73a202 1453 }
265d4508 1454
fc73a202 1455 OpenGl_ShaderProgram::Unbind (myGlContext);
1456 }
265d4508 1457
fc73a202 1458 if (myComputeInitStatus != OpenGl_RT_NONE)
1459 {
1460 return myComputeInitStatus == OpenGl_RT_INIT;
1461 }
265d4508 1462
fc73a202 1463 if (myRaytraceFBO1.IsNull())
1464 {
1465 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1466 }
265d4508 1467
fc73a202 1468 if (myRaytraceFBO2.IsNull())
1469 {
1470 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1471 }
265d4508 1472
fc73a202 1473 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1474 -1.f, 1.f, 0.f,
1475 1.f, 1.f, 0.f,
1476 1.f, 1.f, 0.f,
1477 1.f, -1.f, 0.f,
1478 -1.f, -1.f, 0.f };
265d4508 1479
fc73a202 1480 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
265d4508 1481
fc73a202 1482 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1483
1484 return Standard_True;
1485}
265d4508 1486
fc73a202 1487// =======================================================================
1488// function : NullifyResource
1489// purpose :
1490// =======================================================================
1491inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1492 Handle(OpenGl_Resource)& theResource)
1493{
1494 if (!theResource.IsNull())
1495 {
1496 theResource->Release (theContext.operator->());
1497 theResource.Nullify();
1498 }
1499}
265d4508 1500
fc73a202 1501// =======================================================================
1502// function : ReleaseRaytraceResources
1503// purpose : Releases OpenGL/GLSL shader programs
1504// =======================================================================
1505void OpenGl_Workspace::ReleaseRaytraceResources()
1506{
1507 NullifyResource (myGlContext, myRaytraceFBO1);
1508 NullifyResource (myGlContext, myRaytraceFBO2);
265d4508 1509
fc73a202 1510 NullifyResource (myGlContext, myRaytraceShader);
1511 NullifyResource (myGlContext, myPostFSAAShader);
265d4508 1512
fc73a202 1513 NullifyResource (myGlContext, myRaytraceProgram);
1514 NullifyResource (myGlContext, myPostFSAAProgram);
265d4508 1515
fc73a202 1516 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1517 NullifyResource (myGlContext, mySceneMinPointTexture);
1518 NullifyResource (myGlContext, mySceneMaxPointTexture);
265d4508 1519
fc73a202 1520 NullifyResource (myGlContext, myObjectNodeInfoTexture);
1521 NullifyResource (myGlContext, myObjectMinPointTexture);
1522 NullifyResource (myGlContext, myObjectMaxPointTexture);
265d4508 1523
fc73a202 1524 NullifyResource (myGlContext, myGeometryVertexTexture);
1525 NullifyResource (myGlContext, myGeometryNormalTexture);
1526 NullifyResource (myGlContext, myGeometryTriangTexture);
bc8c79bb 1527 NullifyResource (myGlContext, mySceneTransformTexture);
265d4508 1528
fc73a202 1529 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1530 NullifyResource (myGlContext, myRaytraceMaterialTexture);
265d4508 1531
fc73a202 1532 if (myRaytraceScreenQuad.IsValid())
1533 myRaytraceScreenQuad.Release (myGlContext.operator->());
1534}
265d4508 1535
fc73a202 1536// =======================================================================
1537// function : UploadRaytraceData
1538// purpose : Uploads ray-trace data to the GPU
1539// =======================================================================
1540Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1541{
1542 if (!myGlContext->IsGlGreaterEqual (3, 1))
1543 {
265d4508 1544#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1545 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
265d4508 1546#endif
fc73a202 1547 return Standard_False;
e276548b 1548 }
1549
265d4508 1550 /////////////////////////////////////////////////////////////////////////////
fc73a202 1551 // Create OpenGL texture buffers
265d4508 1552
fc73a202 1553 if (mySceneNodeInfoTexture.IsNull()) // create hight-level BVH buffers
e276548b 1554 {
fc73a202 1555 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1556 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1557 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
84c71f29 1558 mySceneTransformTexture = new OpenGl_TextureBufferArb;
265d4508 1559
fc73a202 1560 if (!mySceneNodeInfoTexture->Create (myGlContext)
84c71f29 1561 || !mySceneMinPointTexture->Create (myGlContext)
1562 || !mySceneMaxPointTexture->Create (myGlContext)
1563 || !mySceneTransformTexture->Create (myGlContext))
e276548b 1564 {
fc73a202 1565#ifdef RAY_TRACE_PRINT_INFO
1566 std::cout << "Error: Failed to create buffers for high-level scene BVH" << std::endl;
1567#endif
e276548b 1568 return Standard_False;
1569 }
1570 }
1571
fc73a202 1572 if (myObjectNodeInfoTexture.IsNull()) // create bottom-level BVH buffers
265d4508 1573 {
fc73a202 1574 myObjectNodeInfoTexture = new OpenGl_TextureBufferArb;
1575 myObjectMinPointTexture = new OpenGl_TextureBufferArb;
1576 myObjectMaxPointTexture = new OpenGl_TextureBufferArb;
e276548b 1577
fc73a202 1578 if (!myObjectNodeInfoTexture->Create (myGlContext)
1579 || !myObjectMinPointTexture->Create (myGlContext)
1580 || !myObjectMaxPointTexture->Create (myGlContext))
1581 {
e276548b 1582#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1583 std::cout << "Error: Failed to create buffers for bottom-level scene BVH" << std::endl;
1584#endif
1585 return Standard_False;
1586 }
1587 }
5322131b 1588
fc73a202 1589 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
265d4508 1590 {
fc73a202 1591 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1592 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1593 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
e276548b 1594
fc73a202 1595 if (!myGeometryVertexTexture->Create (myGlContext)
1596 || !myGeometryNormalTexture->Create (myGlContext)
1597 || !myGeometryTriangTexture->Create (myGlContext))
1598 {
1599#ifdef RAY_TRACE_PRINT_INFO
1600 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1601#endif
1602 return Standard_False;
1603 }
265d4508 1604 }
5322131b 1605
fc73a202 1606 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1607 {
1608 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
e276548b 1609
fc73a202 1610 if (!myRaytraceMaterialTexture->Create (myGlContext))
1611 {
1612#ifdef RAY_TRACE_PRINT_INFO
1613 std::cout << "Error: Failed to create buffers for material data" << std::endl;
e276548b 1614#endif
fc73a202 1615 return Standard_False;
1616 }
1617 }
e276548b 1618
fc73a202 1619 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 1620 // Write top-level BVH buffers
e276548b 1621
fc73a202 1622 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 4> >& aBVH = myRaytraceGeometry.BVH();
e276548b 1623
fc73a202 1624 bool aResult = true;
fc73a202 1625 if (!aBVH->NodeInfoBuffer().empty())
1626 {
5cff985a 1627 aResult &= mySceneNodeInfoTexture->Init (myGlContext, 4, GLsizei (aBVH->NodeInfoBuffer().size()),
1628 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1629 aResult &= mySceneMinPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MinPointBuffer().size()),
1630 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1631 aResult &= mySceneMaxPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MaxPointBuffer().size()),
1632 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
fc73a202 1633 }
fc73a202 1634 if (!aResult)
1635 {
1636#ifdef RAY_TRACE_PRINT_INFO
1637 std::cout << "Error: Failed to upload buffers for high-level scene BVH" << std::endl;
1638#endif
e276548b 1639 return Standard_False;
1640 }
1641
84c71f29 1642 /////////////////////////////////////////////////////////////////////////////
1643 // Write transform buffer
1644
1645 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1646 BVH_Mat4f anIdentity;
1647
1648 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1649 {
1650 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1651 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1652
1653 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1654 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1655
1656 Standard_ASSERT_RETURN (aTransform != NULL,
1657 "OpenGl_TriangleSet does not contain transform", Standard_False);
1658
1659 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1660
1661 }
1662
1663 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1664 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1665
1666 delete[] aNodeTransforms;
1667
1668 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 1669 // Write geometry and bottom-level BVH buffers
84c71f29 1670
fc73a202 1671 Standard_Size aTotalVerticesNb = 0;
1672 Standard_Size aTotalElementsNb = 0;
1673 Standard_Size aTotalBVHNodesNb = 0;
265d4508 1674
fc73a202 1675 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1676 {
1677 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1678 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
265d4508 1679
fc73a202 1680 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1681 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1682
1683 aTotalVerticesNb += aTriangleSet->Vertices.size();
1684 aTotalElementsNb += aTriangleSet->Elements.size();
e276548b 1685
fc73a202 1686 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1687 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
265d4508 1688
fc73a202 1689 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1690 }
e276548b 1691
fc73a202 1692 if (aTotalBVHNodesNb != 0)
e276548b 1693 {
5cff985a 1694 aResult &= myObjectNodeInfoTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1695 aResult &= myObjectMinPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1696 aResult &= myObjectMaxPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1697 }
265d4508 1698
fc73a202 1699 if (!aResult)
1700 {
1701#ifdef RAY_TRACE_PRINT_INFO
1702 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1703#endif
1704 return Standard_False;
1705 }
e276548b 1706
fc73a202 1707 if (aTotalElementsNb != 0)
1708 {
5cff985a 1709 aResult &= myGeometryTriangTexture->Init (myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
fc73a202 1710 }
265d4508 1711
fc73a202 1712 if (aTotalVerticesNb != 0)
1713 {
5cff985a 1714 aResult &= myGeometryVertexTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1715 aResult &= myGeometryNormalTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1716 }
265d4508 1717
fc73a202 1718 if (!aResult)
1719 {
1720#ifdef RAY_TRACE_PRINT_INFO
1721 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1722#endif
1723 return Standard_False;
1724 }
265d4508 1725
fc73a202 1726 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1727 {
1728 if (!aBVH->IsOuter (aNodeIdx))
1729 continue;
265d4508 1730
fc73a202 1731 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
e276548b 1732
fc73a202 1733 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1734 "Error: Failed to get triangulation of OpenGL element", Standard_False);
e276548b 1735
fc73a202 1736 const Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
e276548b 1737
fc73a202 1738 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1739 "Error: Failed to get offset for bottom-level BVH", Standard_False);
e276548b 1740
fc73a202 1741 const size_t aBVHBuffserSize = aTriangleSet->BVH()->NodeInfoBuffer().size();
265d4508 1742
fc73a202 1743 if (aBVHBuffserSize != 0)
1744 {
5cff985a 1745 aResult &= myObjectNodeInfoTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1746 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1747 aResult &= myObjectMinPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1748 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1749 aResult &= myObjectMaxPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1750 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
fc73a202 1751 if (!aResult)
e276548b 1752 {
fc73a202 1753#ifdef RAY_TRACE_PRINT_INFO
1754 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1755#endif
e276548b 1756 return Standard_False;
1757 }
1758 }
1759
fc73a202 1760 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
265d4508 1761
fc73a202 1762 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1763 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
265d4508 1764
fc73a202 1765 if (!aTriangleSet->Vertices.empty())
1766 {
5cff985a 1767 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1768 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1769 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1770 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
fc73a202 1771 }
e276548b 1772
fc73a202 1773 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
265d4508 1774
fc73a202 1775 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1776 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
e276548b 1777
fc73a202 1778 if (!aTriangleSet->Elements.empty())
e276548b 1779 {
5cff985a 1780 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1781 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
e276548b 1782 }
265d4508 1783
fc73a202 1784 if (!aResult)
1785 {
1786#ifdef RAY_TRACE_PRINT_INFO
1787 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
e276548b 1788#endif
fc73a202 1789 return Standard_False;
1790 }
e276548b 1791 }
e276548b 1792
fc73a202 1793 if (myRaytraceGeometry.Materials.size() != 0)
1794 {
1795 const GLfloat* aDataPtr = myRaytraceGeometry.Materials.front().Packed();
5cff985a 1796 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Materials.size() * 7), aDataPtr);
fc73a202 1797 if (!aResult)
1798 {
1799#ifdef RAY_TRACE_PRINT_INFO
1800 std::cout << "Error: Failed to upload material buffer" << std::endl;
1801#endif
1802 return Standard_False;
1803 }
1804 }
e276548b 1805
fc73a202 1806 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
e276548b 1807
fc73a202 1808#ifdef RAY_TRACE_PRINT_INFO
e276548b 1809
fc73a202 1810 Standard_ShortReal aMemUsed = 0.f;
e276548b 1811
fc73a202 1812 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1813 {
1814 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1815 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
e276548b 1816
fc73a202 1817 aMemUsed += static_cast<Standard_ShortReal> (
1818 aTriangleSet->Vertices.size() * sizeof (BVH_Vec4f));
1819 aMemUsed += static_cast<Standard_ShortReal> (
1820 aTriangleSet->Normals.size() * sizeof (BVH_Vec4f));
1821 aMemUsed += static_cast<Standard_ShortReal> (
1822 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
e276548b 1823
fc73a202 1824 aMemUsed += static_cast<Standard_ShortReal> (
1825 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1826 aMemUsed += static_cast<Standard_ShortReal> (
1827 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1828 aMemUsed += static_cast<Standard_ShortReal> (
1829 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
1830 }
e276548b 1831
fc73a202 1832 aMemUsed += static_cast<Standard_ShortReal> (
1833 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1834 aMemUsed += static_cast<Standard_ShortReal> (
1835 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1836 aMemUsed += static_cast<Standard_ShortReal> (
1837 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
e276548b 1838
fc73a202 1839 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
e276548b 1840
fc73a202 1841#endif
e276548b 1842
fc73a202 1843 return aResult;
1844}
e276548b 1845
fc73a202 1846// =======================================================================
1847// function : ResizeRaytraceBuffers
1848// purpose : Resizes OpenGL frame buffers
1849// =======================================================================
1850Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1851 const Standard_Integer theSizeY)
1852{
1853 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1854 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1855 {
1856 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1857 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1858 }
e276548b 1859
fc73a202 1860 return Standard_True;
e276548b 1861}
1862
1863// =======================================================================
fc73a202 1864// function : UpdateCamera
1865// purpose : Generates viewing rays for corners of screen quad
e276548b 1866// =======================================================================
fc73a202 1867void OpenGl_Workspace::UpdateCamera (const NCollection_Mat4<GLdouble>& theOrientation,
1868 const NCollection_Mat4<GLdouble>& theViewMapping,
1869 OpenGl_Vec3 theOrigins[4],
1870 OpenGl_Vec3 theDirects[4])
e276548b 1871{
fc73a202 1872 NCollection_Mat4<GLdouble> aInvModelProj;
1873
bc8c79bb 1874 // compute inverse model-view-projection matrix
fc73a202 1875 (theViewMapping * theOrientation).Inverted (aInvModelProj);
1876
68333c8f 1877 Standard_Integer aOriginIndex = 0;
1878 Standard_Integer aDirectIndex = 0;
e276548b 1879
fc73a202 1880 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
e276548b 1881 {
fc73a202 1882 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
e276548b 1883 {
fc73a202 1884 OpenGl_Vec4d aOrigin (GLdouble(aX),
1885 GLdouble(aY),
1886 -1.0,
1887 1.0);
1888
1889 aOrigin = aInvModelProj * aOrigin;
e276548b 1890
b5ac8292 1891 aOrigin.x() = aOrigin.x() / aOrigin.w();
1892 aOrigin.y() = aOrigin.y() / aOrigin.w();
1893 aOrigin.z() = aOrigin.z() / aOrigin.w();
e276548b 1894
fc73a202 1895 OpenGl_Vec4d aDirect (GLdouble(aX),
1896 GLdouble(aY),
1897 1.0,
1898 1.0);
1899
1900 aDirect = aInvModelProj * aDirect;
e276548b 1901
b5ac8292 1902 aDirect.x() = aDirect.x() / aDirect.w();
1903 aDirect.y() = aDirect.y() / aDirect.w();
1904 aDirect.z() = aDirect.z() / aDirect.w();
b5ac8292 1905
1906 aDirect = aDirect - aOrigin;
e276548b 1907
fc73a202 1908 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
e276548b 1909 aDirect.y() * aDirect.y() +
1910 aDirect.z() * aDirect.z());
1911
fc73a202 1912 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1913 static_cast<GLfloat> (aOrigin.y()),
1914 static_cast<GLfloat> (aOrigin.z()));
1915
1916 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
1917 static_cast<GLfloat> (aDirect.y() * aInvLen),
1918 static_cast<GLfloat> (aDirect.z() * aInvLen));
1919 }
1920 }
1921}
1922
1923// =======================================================================
1924// function : RunRaytraceShaders
1925// purpose : Runs ray-tracing shader programs
1926// =======================================================================
1927Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
1928 const Standard_Integer theSizeX,
1929 const Standard_Integer theSizeY,
1930 const OpenGl_Vec3 theOrigins[4],
1931 const OpenGl_Vec3 theDirects[4],
1932 OpenGl_FrameBuffer* theFrameBuffer)
1933{
1934 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
1935 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
1936 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
1937 myObjectMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
1938 myObjectMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
1939 myObjectNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
1940 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
1941 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
1942 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
1943 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
1944 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
84c71f29 1945 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
fc73a202 1946
bc8c79bb 1947 if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
fc73a202 1948 {
1949 myRaytraceFBO1->BindBuffer (myGlContext);
1950
1951 glDisable (GL_BLEND);
1952 }
1953
1954 myRaytraceProgram->Bind (myGlContext);
1955
1956 Standard_Integer aLightSourceBufferSize =
1957 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
1958
1959 myRaytraceProgram->SetUniform (myGlContext,
1960 myUniformLocations[0][OpenGl_RT_uOriginLB], theOrigins[0]);
1961 myRaytraceProgram->SetUniform (myGlContext,
1962 myUniformLocations[0][OpenGl_RT_uOriginRB], theOrigins[1]);
1963 myRaytraceProgram->SetUniform (myGlContext,
1964 myUniformLocations[0][OpenGl_RT_uOriginLT], theOrigins[2]);
1965 myRaytraceProgram->SetUniform (myGlContext,
1966 myUniformLocations[0][OpenGl_RT_uOriginRT], theOrigins[3]);
1967 myRaytraceProgram->SetUniform (myGlContext,
1968 myUniformLocations[0][OpenGl_RT_uDirectLB], theDirects[0]);
1969 myRaytraceProgram->SetUniform (myGlContext,
1970 myUniformLocations[0][OpenGl_RT_uDirectRB], theDirects[1]);
1971 myRaytraceProgram->SetUniform (myGlContext,
1972 myUniformLocations[0][OpenGl_RT_uDirectLT], theDirects[2]);
1973 myRaytraceProgram->SetUniform (myGlContext,
1974 myUniformLocations[0][OpenGl_RT_uDirectRT], theDirects[3]);
1975 myRaytraceProgram->SetUniform (myGlContext,
1976 myUniformLocations[0][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
1977 myRaytraceProgram->SetUniform (myGlContext,
1978 myUniformLocations[0][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
1979 myRaytraceProgram->SetUniform (myGlContext,
1980 myUniformLocations[0][OpenGl_RT_uLightCount], aLightSourceBufferSize);
1981 myRaytraceProgram->SetUniform (myGlContext,
1982 myUniformLocations[0][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
1983 myRaytraceProgram->SetUniform (myGlContext,
bc8c79bb 1984 myUniformLocations[0][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
fc73a202 1985 myRaytraceProgram->SetUniform (myGlContext,
bc8c79bb 1986 myUniformLocations[0][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
fc73a202 1987
1988 myGlContext->core20fwd->glEnableVertexAttribArray (
1989 myUniformLocations[0][OpenGl_RT_aPosition]);
1990 {
1991 myGlContext->core20fwd->glVertexAttribPointer (
1992 myUniformLocations[0][OpenGl_RT_aPosition], 3, GL_FLOAT, GL_FALSE, 0, NULL);
1993
1994 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
1995 }
1996 myGlContext->core20fwd->glDisableVertexAttribArray (
1997 myUniformLocations[0][OpenGl_RT_aPosition]);
1998
bc8c79bb 1999 if (!theCView.RenderParams.IsAntialiasingEnabled)
fc73a202 2000 {
2001 myRaytraceProgram->Unbind (myGlContext);
2002
2003 return Standard_True;
2004 }
2005
945c3529 2006 myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2007
2008 myPostFSAAProgram->Bind (myGlContext);
2009
2010 myPostFSAAProgram->SetUniform (myGlContext,
2011 myUniformLocations[1][OpenGl_RT_uOriginLB], theOrigins[0]);
2012 myPostFSAAProgram->SetUniform (myGlContext,
2013 myUniformLocations[1][OpenGl_RT_uOriginRB], theOrigins[1]);
2014 myPostFSAAProgram->SetUniform (myGlContext,
2015 myUniformLocations[1][OpenGl_RT_uOriginLT], theOrigins[2]);
2016 myPostFSAAProgram->SetUniform (myGlContext,
2017 myUniformLocations[1][OpenGl_RT_uOriginRT], theOrigins[3]);
2018 myPostFSAAProgram->SetUniform (myGlContext,
2019 myUniformLocations[1][OpenGl_RT_uDirectLB], theDirects[0]);
2020 myPostFSAAProgram->SetUniform (myGlContext,
2021 myUniformLocations[1][OpenGl_RT_uDirectRB], theDirects[1]);
2022 myPostFSAAProgram->SetUniform (myGlContext,
2023 myUniformLocations[1][OpenGl_RT_uDirectLT], theDirects[2]);
2024 myPostFSAAProgram->SetUniform (myGlContext,
2025 myUniformLocations[1][OpenGl_RT_uDirectRT], theDirects[3]);
2026 myPostFSAAProgram->SetUniform (myGlContext,
2027 myUniformLocations[1][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2028 myPostFSAAProgram->SetUniform (myGlContext,
2029 myUniformLocations[1][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2030 myPostFSAAProgram->SetUniform (myGlContext,
2031 myUniformLocations[1][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2032 myPostFSAAProgram->SetUniform (myGlContext,
2033 myUniformLocations[1][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2034 myPostFSAAProgram->SetUniform (myGlContext,
bc8c79bb 2035 myUniformLocations[1][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
fc73a202 2036 myPostFSAAProgram->SetUniform (myGlContext,
bc8c79bb 2037 myUniformLocations[1][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
fc73a202 2038
2039 const Standard_ShortReal aMaxOffset = 0.559017f;
2040 const Standard_ShortReal aMinOffset = 0.186339f;
2041
2042 myGlContext->core20fwd->glEnableVertexAttribArray (
2043 myUniformLocations[1][OpenGl_RT_aPosition]);
2044
2045 myGlContext->core20fwd->glVertexAttribPointer (
2046 myUniformLocations[1][OpenGl_RT_aPosition], 3, GL_FLOAT, GL_FALSE, 0, NULL);
2047
2048 // Perform multi-pass adaptive FSAA using ping-pong technique
84c71f29 2049 // rotated grid AA always uses 4 samples
fc73a202 2050 for (Standard_Integer anIt = 0; anIt < 4; ++anIt)
2051 {
2052 GLfloat aOffsetX = 1.f / theSizeX;
2053 GLfloat aOffsetY = 1.f / theSizeY;
2054
2055 if (anIt < 2)
2056 {
2057 aOffsetX *= anIt < 1 ? aMinOffset : -aMaxOffset;
2058 aOffsetY *= anIt < 1 ? aMaxOffset : aMinOffset;
2059 }
2060 else
2061 {
2062 aOffsetX *= anIt > 2 ? aMaxOffset : -aMinOffset;
2063 aOffsetY *= anIt > 2 ? -aMinOffset : -aMaxOffset;
2064 }
2065
2066 myPostFSAAProgram->SetUniform (myGlContext,
2067 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 2);
2068 myPostFSAAProgram->SetUniform (myGlContext,
2069 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2070 myPostFSAAProgram->SetUniform (myGlContext,
2071 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2072
2073 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO1 : myRaytraceFBO2;
2074
2075 if (anIt == 3) // disable FBO on last iteration
2076 {
2077 glEnable (GL_BLEND);
2078
2079 if (theFrameBuffer != NULL)
2080 theFrameBuffer->BindBuffer (myGlContext);
2081 }
2082 else
2083 {
2084 aFramebuffer->BindBuffer (myGlContext);
2085 }
2086
2087 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
e276548b 2088
fc73a202 2089 if (anIt != 3) // set input for the next pass
2090 {
945c3529 2091 aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2092 aFramebuffer->UnbindBuffer (myGlContext);
e276548b 2093 }
2094 }
fc73a202 2095
2096 myGlContext->core20fwd->glDisableVertexAttribArray (
2097 myUniformLocations[1][OpenGl_RT_aPosition]);
2098
2099 myPostFSAAProgram->Unbind (myGlContext);
2100
2101 return Standard_True;
e276548b 2102}
2103
2104// =======================================================================
2105// function : Raytrace
fc73a202 2106// purpose : Redraws the window using OpenGL/GLSL ray-tracing
e276548b 2107// =======================================================================
2108Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
68333c8f 2109 const Standard_Integer theSizeX,
2110 const Standard_Integer theSizeY,
fc73a202 2111 const Standard_Boolean theToSwap,
2112 OpenGl_FrameBuffer* theFrameBuffer)
e276548b 2113{
84c71f29 2114 if (!UpdateRaytraceGeometry (OpenGl_GUM_CHECK))
e276548b 2115 return Standard_False;
2116
bc8c79bb 2117 if (!InitRaytraceResources (theCView))
e276548b 2118 return Standard_False;
2119
fc73a202 2120 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
e276548b 2121 return Standard_False;
2122
fc73a202 2123 if (!UpdateRaytraceEnvironmentMap())
e276548b 2124 return Standard_False;
2125
2126 // Get model-view and projection matrices
2127 TColStd_Array2OfReal theOrientation (0, 3, 0, 3);
2128 TColStd_Array2OfReal theViewMapping (0, 3, 0, 3);
2129
b5ac8292 2130 myView->GetMatrices (theOrientation, theViewMapping);
e276548b 2131
fc73a202 2132 NCollection_Mat4<GLdouble> aOrientationMatrix;
2133 NCollection_Mat4<GLdouble> aViewMappingMatrix;
e276548b 2134
68333c8f 2135 for (Standard_Integer j = 0; j < 4; ++j)
fc73a202 2136 {
68333c8f 2137 for (Standard_Integer i = 0; i < 4; ++i)
e276548b 2138 {
2139 aOrientationMatrix [4 * j + i] = theOrientation (i, j);
2140 aViewMappingMatrix [4 * j + i] = theViewMapping (i, j);
2141 }
fc73a202 2142 }
2143
2144 NCollection_Mat4<GLdouble> aInvOrientationMatrix;
2145 aOrientationMatrix.Inverted (aInvOrientationMatrix);
e276548b 2146
fc73a202 2147 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
e276548b 2148 return Standard_False;
2149
fc73a202 2150 OpenGl_Vec3 aOrigins[4];
2151 OpenGl_Vec3 aDirects[4];
e276548b 2152
fc73a202 2153 UpdateCamera (aOrientationMatrix,
2154 aViewMappingMatrix,
2155 aOrigins,
2156 aDirects);
e276548b 2157
84c71f29 2158 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2159 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
e276548b 2160
2161 glDisable (GL_DEPTH_TEST);
2162
2163 if (NamedStatus & OPENGL_NS_WHITEBACK)
2164 {
2165 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2166 }
2167 else
2168 {
2169 glClearColor (myBgColor.rgb[0],
2170 myBgColor.rgb[1],
2171 myBgColor.rgb[2],
2172 1.0f);
2173 }
2174
2175 glClear (GL_COLOR_BUFFER_BIT);
2176
fc73a202 2177 if (theFrameBuffer != NULL)
2178 theFrameBuffer->BindBuffer (myGlContext);
e276548b 2179
fc73a202 2180 myView->DrawBackground (*this);
e276548b 2181
fc73a202 2182 // Generate ray-traced image
e276548b 2183 glMatrixMode (GL_PROJECTION);
2184 glLoadIdentity();
2185
2186 glMatrixMode (GL_MODELVIEW);
2187 glLoadIdentity();
2188
fc73a202 2189 glEnable (GL_BLEND);
2190 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
e276548b 2191
2192 if (myIsRaytraceDataValid)
2193 {
fc73a202 2194 myRaytraceScreenQuad.Bind (myGlContext);
2195
2196 RunRaytraceShaders (theCView,
2197 theSizeX,
2198 theSizeY,
2199 aOrigins,
2200 aDirects,
2201 theFrameBuffer);
2202
2203 myRaytraceScreenQuad.Unbind (myGlContext);
e276548b 2204 }
2205
84c71f29 2206 if (!wasBlendingEnabled)
2207 glDisable (GL_BLEND);
fc73a202 2208
84c71f29 2209 if (wasDepthTestEnabled)
2210 glEnable (GL_DEPTH_TEST);
e276548b 2211
2212 // Swap the buffers
2213 if (theToSwap)
2214 {
2215 GetGlContext()->SwapBuffers();
2216 myBackBufferRestored = Standard_False;
2217 }
2218 else
fc73a202 2219 {
e276548b 2220 glFlush();
fc73a202 2221 }
e276548b 2222
2223 return Standard_True;
2224}