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