0025951: Exception in intersection operation.
[occt.git] / src / OpenGl / OpenGl_Workspace_Raytrace.cxx
CommitLineData
e276548b 1// Created on: 2013-08-27
2// Created by: Denis BOGOLEPOV
3// Copyright (c) 2013 OPEN CASCADE SAS
4//
973c2be1 5// This file is part of Open CASCADE Technology software library.
e276548b 6//
d5f74e42 7// This library is free software; you can redistribute it and/or modify it under
8// the terms of the GNU Lesser General Public License version 2.1 as published
973c2be1 9// by the Free Software Foundation, with special exception defined in the file
10// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11// distribution for complete text of the license and disclaimer of any warranty.
e276548b 12//
973c2be1 13// Alternatively, this file may be used under the terms of Open CASCADE
14// commercial license or contractual agreement.
e276548b 15
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 {
fc73a202 1139 const TCollection_ExtendedString aMessage = "Error: Failed to create shader object";
1140
1141 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1142 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
e276548b 1143
fc73a202 1144 aShader->Release (myGlContext.operator->());
e276548b 1145
fc73a202 1146 return Handle(OpenGl_ShaderObject)();
e276548b 1147 }
5322131b 1148
fc73a202 1149 if (!aShader->LoadSource (myGlContext, theSource.Source()))
1150 {
1151 const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1152
1153 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1154 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
e276548b 1155
fc73a202 1156 aShader->Release (myGlContext.operator->());
e276548b 1157
fc73a202 1158 return Handle(OpenGl_ShaderObject)();
1159 }
e276548b 1160
fc73a202 1161 TCollection_AsciiString aBuildLog;
e276548b 1162
fc73a202 1163 if (!aShader->Compile (myGlContext))
e276548b 1164 {
fc73a202 1165 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1166 {
1167 const TCollection_ExtendedString aMessage =
1168 TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1169
e276548b 1170#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1171 std::cout << aBuildLog << std::endl;
e276548b 1172#endif
e276548b 1173
fc73a202 1174 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1175 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1176 }
1177
1178 aShader->Release (myGlContext.operator->());
1179
1180 return Handle(OpenGl_ShaderObject)();
1181 }
68333c8f 1182
e276548b 1183#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1184 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1185 {
1186 if (!aBuildLog.IsEmpty())
1187 {
1188 std::cout << aBuildLog << std::endl;
1189 }
1190 else
1191 {
1192 std::cout << "Info: shader build log is empty" << std::endl;
1193 }
1194 }
e276548b 1195#endif
e276548b 1196
fc73a202 1197 return aShader;
e276548b 1198}
1199
1200// =======================================================================
fc73a202 1201// function : SafeFailBack
1202// purpose : Performs safe exit when shaders initialization fails
e276548b 1203// =======================================================================
fc73a202 1204Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
e276548b 1205{
fc73a202 1206 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1207 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
265d4508 1208
fc73a202 1209 myComputeInitStatus = OpenGl_RT_FAIL;
265d4508 1210
fc73a202 1211 ReleaseRaytraceResources();
1212
1213 return Standard_False;
1214}
e276548b 1215
fc73a202 1216// =======================================================================
25ef750e 1217// function : GenerateShaderPrefix
1218// purpose : Generates shader prefix based on current ray-tracing options
1219// =======================================================================
1220TCollection_AsciiString OpenGl_Workspace::GenerateShaderPrefix()
1221{
1222 TCollection_AsciiString aPrefixString =
1223 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1224 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1225
1226 if (myRaytraceParameters.TransparentShadows)
1227 {
1228 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1229 }
1230
1231 // If OpenGL driver supports bindless textures
1232 // activate texturing in ray-tracing mode
1233 if (myGlContext->arbTexBindless != NULL)
1234 {
1235 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1236 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1237 }
1238
1239 return aPrefixString;
1240}
1241
1242// =======================================================================
fc73a202 1243// function : InitRaytraceResources
1244// purpose : Initializes OpenGL/GLSL shader programs
1245// =======================================================================
bc8c79bb 1246Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
fc73a202 1247{
1248 Standard_Boolean aToRebuildShaders = Standard_False;
e276548b 1249
fc73a202 1250 if (myComputeInitStatus == OpenGl_RT_INIT)
1251 {
1252 if (!myIsRaytraceDataValid)
1253 return Standard_True;
e276548b 1254
fc73a202 1255 const Standard_Integer aRequiredStackSize =
1256 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
e276548b 1257
bc8c79bb 1258 if (myRaytraceParameters.StackSize < aRequiredStackSize)
fc73a202 1259 {
bc8c79bb 1260 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
e276548b 1261
fc73a202 1262 aToRebuildShaders = Standard_True;
1263 }
1264 else
1265 {
bc8c79bb 1266 if (aRequiredStackSize < myRaytraceParameters.StackSize)
fc73a202 1267 {
bc8c79bb 1268 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
fc73a202 1269 {
bc8c79bb 1270 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
fc73a202 1271 aToRebuildShaders = Standard_True;
1272 }
1273 }
1274 }
e276548b 1275
25ef750e 1276 if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
bc8c79bb 1277 {
25ef750e 1278 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
bc8c79bb 1279 aToRebuildShaders = Standard_True;
1280 }
1281
1282 if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1283 {
1284 myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1285 aToRebuildShaders = Standard_True;
1286 }
1287
fc73a202 1288 if (aToRebuildShaders)
1289 {
e276548b 1290#ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 1291 std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
e276548b 1292#endif
e276548b 1293
bc8c79bb 1294 // Change state to force update all uniforms
84c71f29 1295 ++myViewModificationStatus;
1296
25ef750e 1297 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
bc8c79bb 1298
1299#ifdef RAY_TRACE_PRINT_INFO
1300 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1301#endif
265d4508 1302
bc8c79bb 1303 myRaytraceShaderSource.SetPrefix (aPrefixString);
1304 myPostFSAAShaderSource.SetPrefix (aPrefixString);
265d4508 1305
fc73a202 1306 if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1307 || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1308 {
1309 return Standard_False;
1310 }
265d4508 1311
fc73a202 1312 if (!myRaytraceShader->Compile (myGlContext)
1313 || !myPostFSAAShader->Compile (myGlContext))
1314 {
1315 return Standard_False;
1316 }
1317
7d3e64ef 1318 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1319 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1320 if (!myRaytraceProgram->Link (myGlContext)
1321 || !myPostFSAAProgram->Link (myGlContext))
1322 {
1323 return Standard_False;
1324 }
1325 }
e276548b 1326 }
1327
fc73a202 1328 if (myComputeInitStatus == OpenGl_RT_NONE)
1329 {
1330 if (!myGlContext->IsGlGreaterEqual (3, 1))
1331 {
fc73a202 1332 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
25ef750e 1333 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1334 "Ray-tracing requires OpenGL 3.1 and higher");
1335 return Standard_False;
1336 }
1337 else if (!myGlContext->arbTboRGB32)
1338 {
1339 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1340 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1341 "Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension");
fc73a202 1342 return Standard_False;
1343 }
5322131b 1344
25ef750e 1345 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
bc8c79bb 1346
fc73a202 1347 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
265d4508 1348
fc73a202 1349 if (aFolder.IsEmpty())
1350 {
1351 const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1352
1353 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1354 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1355
1356 return Standard_False;
1357 }
265d4508 1358
fc73a202 1359 if (myIsRaytraceDataValid)
1360 {
bc8c79bb 1361 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
fc73a202 1362 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1363 }
265d4508 1364
25ef750e 1365 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
bc8c79bb 1366
1367#ifdef RAY_TRACE_PRINT_INFO
1368 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1369#endif
1370
fc73a202 1371 {
1372 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1373 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1374
fc73a202 1375 if (aBasicVertShader.IsNull())
1376 {
1377 return SafeFailBack ("Failed to set vertex shader source");
1378 }
265d4508 1379
fc73a202 1380 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
265d4508 1381
fc73a202 1382 myRaytraceShaderSource.Load (aFiles, 2);
e276548b 1383
bc8c79bb 1384 myRaytraceShaderSource.SetPrefix (aPrefixString);
265d4508 1385
fc73a202 1386 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
265d4508 1387
fc73a202 1388 if (myRaytraceShader.IsNull())
1389 {
1390 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1391
fc73a202 1392 return SafeFailBack ("Failed to set ray-trace fragment shader source");
1393 }
265d4508 1394
fc73a202 1395 myRaytraceProgram = new OpenGl_ShaderProgram;
5322131b 1396
fc73a202 1397 if (!myRaytraceProgram->Create (myGlContext))
1398 {
1399 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1400
fc73a202 1401 return SafeFailBack ("Failed to create ray-trace shader program");
1402 }
265d4508 1403
fc73a202 1404 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1405 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1406 {
1407 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1408
fc73a202 1409 return SafeFailBack ("Failed to attach ray-trace shader objects");
1410 }
265d4508 1411
7d3e64ef 1412 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1413 if (!myRaytraceProgram->Link (myGlContext))
1414 {
1415 TCollection_AsciiString aLinkLog;
e276548b 1416
fc73a202 1417 if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1418 {
1419 #ifdef RAY_TRACE_PRINT_INFO
1420 std::cout << aLinkLog << std::endl;
1421 #endif
1422 }
265d4508 1423
fc73a202 1424 return SafeFailBack ("Failed to link ray-trace shader program");
1425 }
1426 }
265d4508 1427
fc73a202 1428 {
1429 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1430 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1431
fc73a202 1432 if (aBasicVertShader.IsNull())
1433 {
1434 return SafeFailBack ("Failed to set vertex shader source");
1435 }
265d4508 1436
fc73a202 1437 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
265d4508 1438
fc73a202 1439 myPostFSAAShaderSource.Load (aFiles, 2);
265d4508 1440
bc8c79bb 1441 myPostFSAAShaderSource.SetPrefix (aPrefixString);
fc73a202 1442
1443 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
265d4508 1444
fc73a202 1445 if (myPostFSAAShader.IsNull())
1446 {
1447 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1448
fc73a202 1449 return SafeFailBack ("Failed to set FSAA fragment shader source");
1450 }
265d4508 1451
fc73a202 1452 myPostFSAAProgram = new OpenGl_ShaderProgram;
265d4508 1453
fc73a202 1454 if (!myPostFSAAProgram->Create (myGlContext))
1455 {
1456 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1457
fc73a202 1458 return SafeFailBack ("Failed to create FSAA shader program");
1459 }
1460
1461 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1462 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1463 {
1464 aBasicVertShader->Release (myGlContext.operator->());
1465
1466 return SafeFailBack ("Failed to attach FSAA shader objects");
1467 }
1468
7d3e64ef 1469 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1470 if (!myPostFSAAProgram->Link (myGlContext))
1471 {
1472 TCollection_AsciiString aLinkLog;
1473
1474 if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1475 {
1476 #ifdef RAY_TRACE_PRINT_INFO
1477 std::cout << aLinkLog << std::endl;
1478 #endif
1479 }
1480
1481 return SafeFailBack ("Failed to link FSAA shader program");
1482 }
e276548b 1483 }
fc73a202 1484 }
e276548b 1485
fc73a202 1486 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1487 {
1488 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
e276548b 1489 {
fc73a202 1490 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1491 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1492
7d3e64ef 1493 myGlContext->BindProgram (aShaderProgram);
fc73a202 1494
1495 aShaderProgram->SetSampler (myGlContext,
1496 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1497 aShaderProgram->SetSampler (myGlContext,
1498 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1499 aShaderProgram->SetSampler (myGlContext,
1500 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1501 aShaderProgram->SetSampler (myGlContext,
fc73a202 1502 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1503 aShaderProgram->SetSampler (myGlContext,
1504 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1505 aShaderProgram->SetSampler (myGlContext,
25ef750e 1506 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
fc73a202 1507 aShaderProgram->SetSampler (myGlContext,
25ef750e 1508 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
84c71f29 1509 aShaderProgram->SetSampler (myGlContext,
1510 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1511 aShaderProgram->SetSampler (myGlContext,
1512 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
25ef750e 1513 aShaderProgram->SetSampler (myGlContext,
1514 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1515 aShaderProgram->SetSampler (myGlContext,
1516 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
fc73a202 1517
a89742cf 1518 aShaderProgram->SetSampler (myGlContext,
1519 "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1520 aShaderProgram->SetSampler (myGlContext,
1521 "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1522
fc73a202 1523 if (anIndex == 1)
1524 {
1525 aShaderProgram->SetSampler (myGlContext,
1526 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1527 }
265d4508 1528
fc73a202 1529 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
7d3e64ef 1530 aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
fc73a202 1531
1532 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1533 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1534 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1535 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1536 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1537 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1538 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1539 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1540 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1541 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1542 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1543 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1544 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1545 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1546 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1547 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
25ef750e 1548 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1549 aShaderProgram->GetUniformLocation (myGlContext, "uUnviewMat");
fc73a202 1550
1551 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1552 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1553 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1554 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
25ef750e 1555 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1556 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1557 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1558 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
fc73a202 1559
1560 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1561 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1562 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1563 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1564 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1565 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
312a4043 1566 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1567 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeX");
1568 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1569 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeY");
84c71f29 1570
25ef750e 1571 myUniformLocations[anIndex][OpenGl_RT_uTextures] =
1572 aShaderProgram->GetUniformLocation (myGlContext, "uTextureSamplers");
1573
1574 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1575 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1576 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1577 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1578 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnable] =
84c71f29 1579 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
fc73a202 1580 }
265d4508 1581
7d3e64ef 1582 myGlContext->BindProgram (NULL);
fc73a202 1583 }
265d4508 1584
fc73a202 1585 if (myComputeInitStatus != OpenGl_RT_NONE)
1586 {
1587 return myComputeInitStatus == OpenGl_RT_INIT;
1588 }
265d4508 1589
fc73a202 1590 if (myRaytraceFBO1.IsNull())
1591 {
1592 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1593 }
265d4508 1594
fc73a202 1595 if (myRaytraceFBO2.IsNull())
1596 {
1597 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1598 }
265d4508 1599
fc73a202 1600 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1601 -1.f, 1.f, 0.f,
1602 1.f, 1.f, 0.f,
1603 1.f, 1.f, 0.f,
1604 1.f, -1.f, 0.f,
1605 -1.f, -1.f, 0.f };
265d4508 1606
fc73a202 1607 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
265d4508 1608
fc73a202 1609 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
ca3c13d1 1610
fc73a202 1611 return Standard_True;
1612}
265d4508 1613
fc73a202 1614// =======================================================================
1615// function : NullifyResource
1616// purpose :
1617// =======================================================================
1618inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1619 Handle(OpenGl_Resource)& theResource)
1620{
1621 if (!theResource.IsNull())
1622 {
1623 theResource->Release (theContext.operator->());
1624 theResource.Nullify();
1625 }
1626}
265d4508 1627
fc73a202 1628// =======================================================================
1629// function : ReleaseRaytraceResources
1630// purpose : Releases OpenGL/GLSL shader programs
1631// =======================================================================
1632void OpenGl_Workspace::ReleaseRaytraceResources()
1633{
a89742cf 1634 NullifyResource (myGlContext, myOpenGlFBO);
fc73a202 1635 NullifyResource (myGlContext, myRaytraceFBO1);
1636 NullifyResource (myGlContext, myRaytraceFBO2);
265d4508 1637
fc73a202 1638 NullifyResource (myGlContext, myRaytraceShader);
1639 NullifyResource (myGlContext, myPostFSAAShader);
265d4508 1640
fc73a202 1641 NullifyResource (myGlContext, myRaytraceProgram);
1642 NullifyResource (myGlContext, myPostFSAAProgram);
265d4508 1643
fc73a202 1644 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1645 NullifyResource (myGlContext, mySceneMinPointTexture);
1646 NullifyResource (myGlContext, mySceneMaxPointTexture);
265d4508 1647
fc73a202 1648 NullifyResource (myGlContext, myGeometryVertexTexture);
1649 NullifyResource (myGlContext, myGeometryNormalTexture);
25ef750e 1650 NullifyResource (myGlContext, myGeometryTexCrdTexture);
fc73a202 1651 NullifyResource (myGlContext, myGeometryTriangTexture);
bc8c79bb 1652 NullifyResource (myGlContext, mySceneTransformTexture);
265d4508 1653
fc73a202 1654 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1655 NullifyResource (myGlContext, myRaytraceMaterialTexture);
265d4508 1656
fc73a202 1657 if (myRaytraceScreenQuad.IsValid())
1658 myRaytraceScreenQuad.Release (myGlContext.operator->());
1659}
265d4508 1660
fc73a202 1661// =======================================================================
1662// function : UploadRaytraceData
1663// purpose : Uploads ray-trace data to the GPU
1664// =======================================================================
1665Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1666{
1667 if (!myGlContext->IsGlGreaterEqual (3, 1))
1668 {
265d4508 1669#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1670 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
265d4508 1671#endif
fc73a202 1672 return Standard_False;
e276548b 1673 }
1674
265d4508 1675 /////////////////////////////////////////////////////////////////////////////
25ef750e 1676 // Prepare OpenGL textures
1677
1678 if (myGlContext->arbTexBindless != NULL)
1679 {
1680 // If OpenGL driver supports bindless textures we need
1681 // to get unique 64- bit handles for using on the GPU
1682 if (!myRaytraceGeometry.UpdateTextureHandles (myGlContext))
1683 {
1684#ifdef RAY_TRACE_PRINT_INFO
1685 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1686#endif
1687 return Standard_False;
1688 }
1689 }
1690
1691 /////////////////////////////////////////////////////////////////////////////
e2da917a 1692 // Create OpenGL BVH buffers
265d4508 1693
e2da917a 1694 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
e276548b 1695 {
e2da917a 1696 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1697 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1698 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
84c71f29 1699 mySceneTransformTexture = new OpenGl_TextureBufferArb;
265d4508 1700
e2da917a 1701 if (!mySceneNodeInfoTexture->Create (myGlContext)
1702 || !mySceneMinPointTexture->Create (myGlContext)
1703 || !mySceneMaxPointTexture->Create (myGlContext)
84c71f29 1704 || !mySceneTransformTexture->Create (myGlContext))
e276548b 1705 {
fc73a202 1706#ifdef RAY_TRACE_PRINT_INFO
e2da917a 1707 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
fc73a202 1708#endif
1709 return Standard_False;
1710 }
1711 }
5322131b 1712
e2da917a 1713 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
265d4508 1714 {
fc73a202 1715 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1716 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
25ef750e 1717 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
fc73a202 1718 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
e276548b 1719
fc73a202 1720 if (!myGeometryVertexTexture->Create (myGlContext)
25ef750e 1721 || !myGeometryNormalTexture->Create (myGlContext)
1722 || !myGeometryTexCrdTexture->Create (myGlContext)
1723 || !myGeometryTriangTexture->Create (myGlContext))
fc73a202 1724 {
1725#ifdef RAY_TRACE_PRINT_INFO
1726 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1727#endif
1728 return Standard_False;
1729 }
265d4508 1730 }
5322131b 1731
e2da917a 1732 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
fc73a202 1733 {
1734 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
e276548b 1735
fc73a202 1736 if (!myRaytraceMaterialTexture->Create (myGlContext))
1737 {
1738#ifdef RAY_TRACE_PRINT_INFO
1739 std::cout << "Error: Failed to create buffers for material data" << std::endl;
e276548b 1740#endif
fc73a202 1741 return Standard_False;
1742 }
1743 }
e2da917a 1744
84c71f29 1745 /////////////////////////////////////////////////////////////////////////////
1746 // Write transform buffer
1747
1748 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
84c71f29 1749
e2da917a 1750 bool aResult = true;
1751
84c71f29 1752 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1753 {
1754 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1755 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1756
1757 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1758 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1759
1760 Standard_ASSERT_RETURN (aTransform != NULL,
1761 "OpenGl_TriangleSet does not contain transform", Standard_False);
1762
1763 aNodeTransforms[anElemIndex] = aTransform->Inversed();
84c71f29 1764 }
1765
1766 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1767 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1768
25ef750e 1769 delete [] aNodeTransforms;
84c71f29 1770
1771 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 1772 // Write geometry and bottom-level BVH buffers
84c71f29 1773
fc73a202 1774 Standard_Size aTotalVerticesNb = 0;
1775 Standard_Size aTotalElementsNb = 0;
1776 Standard_Size aTotalBVHNodesNb = 0;
265d4508 1777
fc73a202 1778 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1779 {
1780 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1781 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
265d4508 1782
fc73a202 1783 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1784 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1785
1786 aTotalVerticesNb += aTriangleSet->Vertices.size();
1787 aTotalElementsNb += aTriangleSet->Elements.size();
e276548b 1788
fc73a202 1789 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1790 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
265d4508 1791
fc73a202 1792 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1793 }
e276548b 1794
e2da917a 1795 aTotalBVHNodesNb += myRaytraceGeometry.BVH()->NodeInfoBuffer().size();
1796
fc73a202 1797 if (aTotalBVHNodesNb != 0)
e276548b 1798 {
e2da917a 1799 aResult &= mySceneNodeInfoTexture->Init (
25ef750e 1800 myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
e2da917a 1801 aResult &= mySceneMinPointTexture->Init (
25ef750e 1802 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
e2da917a 1803 aResult &= mySceneMaxPointTexture->Init (
25ef750e 1804 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1805 }
265d4508 1806
fc73a202 1807 if (!aResult)
1808 {
1809#ifdef RAY_TRACE_PRINT_INFO
1810 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1811#endif
1812 return Standard_False;
1813 }
e276548b 1814
fc73a202 1815 if (aTotalElementsNb != 0)
1816 {
25ef750e 1817 aResult &= myGeometryTriangTexture->Init (
1818 myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
fc73a202 1819 }
265d4508 1820
fc73a202 1821 if (aTotalVerticesNb != 0)
1822 {
25ef750e 1823 aResult &= myGeometryVertexTexture->Init (
1824 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1825 aResult &= myGeometryNormalTexture->Init (
1826 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1827 aResult &= myGeometryTexCrdTexture->Init (
1828 myGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1829 }
265d4508 1830
fc73a202 1831 if (!aResult)
1832 {
1833#ifdef RAY_TRACE_PRINT_INFO
1834 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1835#endif
1836 return Standard_False;
1837 }
265d4508 1838
e2da917a 1839 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
1e99558f 1840 const Standard_Integer aBvhLength = aBVH->Length();
1841 if (aBvhLength > 0)
1842 {
1843 aResult &= mySceneNodeInfoTexture->SubData (myGlContext, 0, aBVH->Length(),
1844 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1845 aResult &= mySceneMinPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1846 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1847 aResult &= mySceneMaxPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1848 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1849 }
e2da917a 1850
fc73a202 1851 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1852 {
1853 if (!aBVH->IsOuter (aNodeIdx))
1854 continue;
265d4508 1855
fc73a202 1856 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
e276548b 1857
fc73a202 1858 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1859 "Error: Failed to get triangulation of OpenGL element", Standard_False);
e276548b 1860
e2da917a 1861 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
e276548b 1862
fc73a202 1863 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1864 "Error: Failed to get offset for bottom-level BVH", Standard_False);
e276548b 1865
e2da917a 1866 const Standard_Integer aBvhBuffersSize = aTriangleSet->BVH()->Length();
265d4508 1867
e2da917a 1868 if (aBvhBuffersSize != 0)
fc73a202 1869 {
e2da917a 1870 aResult &= mySceneNodeInfoTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
5cff985a 1871 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
e2da917a 1872 aResult &= mySceneMinPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
5cff985a 1873 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
e2da917a 1874 aResult &= mySceneMaxPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
5cff985a 1875 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
fc73a202 1876 if (!aResult)
e276548b 1877 {
fc73a202 1878#ifdef RAY_TRACE_PRINT_INFO
1879 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1880#endif
e276548b 1881 return Standard_False;
1882 }
1883 }
1884
fc73a202 1885 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
265d4508 1886
fc73a202 1887 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1888 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
265d4508 1889
fc73a202 1890 if (!aTriangleSet->Vertices.empty())
1891 {
5cff985a 1892 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1893 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
25ef750e 1894 aResult &= myGeometryTexCrdTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->TexCrds.size()),
1895 reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
5cff985a 1896 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1897 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
fc73a202 1898 }
e276548b 1899
fc73a202 1900 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
265d4508 1901
fc73a202 1902 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1903 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
e276548b 1904
fc73a202 1905 if (!aTriangleSet->Elements.empty())
e276548b 1906 {
5cff985a 1907 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1908 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
e276548b 1909 }
265d4508 1910
fc73a202 1911 if (!aResult)
1912 {
1913#ifdef RAY_TRACE_PRINT_INFO
1914 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
e276548b 1915#endif
fc73a202 1916 return Standard_False;
1917 }
e276548b 1918 }
e276548b 1919
25ef750e 1920 /////////////////////////////////////////////////////////////////////////////
1921 // Write material buffer
1922
fc73a202 1923 if (myRaytraceGeometry.Materials.size() != 0)
1924 {
25ef750e 1925 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4,
1926 GLsizei (myRaytraceGeometry.Materials.size() * 11), myRaytraceGeometry.Materials.front().Packed());
1927
fc73a202 1928 if (!aResult)
1929 {
1930#ifdef RAY_TRACE_PRINT_INFO
1931 std::cout << "Error: Failed to upload material buffer" << std::endl;
1932#endif
1933 return Standard_False;
1934 }
1935 }
e276548b 1936
fc73a202 1937 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
e276548b 1938
fc73a202 1939#ifdef RAY_TRACE_PRINT_INFO
e276548b 1940
fc73a202 1941 Standard_ShortReal aMemUsed = 0.f;
e276548b 1942
fc73a202 1943 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1944 {
1945 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1946 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
e276548b 1947
fc73a202 1948 aMemUsed += static_cast<Standard_ShortReal> (
25ef750e 1949 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
fc73a202 1950 aMemUsed += static_cast<Standard_ShortReal> (
25ef750e 1951 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
1952 aMemUsed += static_cast<Standard_ShortReal> (
1953 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
fc73a202 1954 aMemUsed += static_cast<Standard_ShortReal> (
1955 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
e276548b 1956
fc73a202 1957 aMemUsed += static_cast<Standard_ShortReal> (
1958 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1959 aMemUsed += static_cast<Standard_ShortReal> (
25ef750e 1960 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
fc73a202 1961 aMemUsed += static_cast<Standard_ShortReal> (
25ef750e 1962 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
fc73a202 1963 }
e276548b 1964
fc73a202 1965 aMemUsed += static_cast<Standard_ShortReal> (
1966 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1967 aMemUsed += static_cast<Standard_ShortReal> (
25ef750e 1968 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
fc73a202 1969 aMemUsed += static_cast<Standard_ShortReal> (
25ef750e 1970 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
e276548b 1971
fc73a202 1972 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
e276548b 1973
fc73a202 1974#endif
e276548b 1975
fc73a202 1976 return aResult;
1977}
e276548b 1978
fc73a202 1979// =======================================================================
1980// function : ResizeRaytraceBuffers
1981// purpose : Resizes OpenGL frame buffers
1982// =======================================================================
1983Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1984 const Standard_Integer theSizeY)
1985{
1986 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1987 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1988 {
1989 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1990 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1991 }
e276548b 1992
fc73a202 1993 return Standard_True;
e276548b 1994}
1995
1996// =======================================================================
fc73a202 1997// function : UpdateCamera
1998// purpose : Generates viewing rays for corners of screen quad
e276548b 1999// =======================================================================
25ef750e 2000void OpenGl_Workspace::UpdateCamera (const OpenGl_Mat4& theOrientation,
2001 const OpenGl_Mat4& theViewMapping,
2002 OpenGl_Vec3 theOrigins[4],
2003 OpenGl_Vec3 theDirects[4],
2004 OpenGl_Mat4& theInvModelProj)
e276548b 2005{
bc8c79bb 2006 // compute inverse model-view-projection matrix
a89742cf 2007 (theViewMapping * theOrientation).Inverted (theInvModelProj);
fc73a202 2008
68333c8f 2009 Standard_Integer aOriginIndex = 0;
2010 Standard_Integer aDirectIndex = 0;
e276548b 2011
fc73a202 2012 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
e276548b 2013 {
fc73a202 2014 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
e276548b 2015 {
25ef750e 2016 OpenGl_Vec4 aOrigin (GLfloat(aX),
2017 GLfloat(aY),
2018 -1.0f,
2019 1.0f);
fc73a202 2020
a89742cf 2021 aOrigin = theInvModelProj * aOrigin;
e276548b 2022
b5ac8292 2023 aOrigin.x() = aOrigin.x() / aOrigin.w();
2024 aOrigin.y() = aOrigin.y() / aOrigin.w();
2025 aOrigin.z() = aOrigin.z() / aOrigin.w();
e276548b 2026
25ef750e 2027 OpenGl_Vec4 aDirect (GLfloat(aX),
2028 GLfloat(aY),
2029 1.0f,
2030 1.0f);
fc73a202 2031
a89742cf 2032 aDirect = theInvModelProj * aDirect;
e276548b 2033
b5ac8292 2034 aDirect.x() = aDirect.x() / aDirect.w();
2035 aDirect.y() = aDirect.y() / aDirect.w();
2036 aDirect.z() = aDirect.z() / aDirect.w();
b5ac8292 2037
2038 aDirect = aDirect - aOrigin;
e276548b 2039
fc73a202 2040 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
e276548b 2041 aDirect.y() * aDirect.y() +
2042 aDirect.z() * aDirect.z());
2043
fc73a202 2044 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2045 static_cast<GLfloat> (aOrigin.y()),
2046 static_cast<GLfloat> (aOrigin.z()));
2047
2048 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
2049 static_cast<GLfloat> (aDirect.y() * aInvLen),
2050 static_cast<GLfloat> (aDirect.z() * aInvLen));
2051 }
2052 }
2053}
2054
2055// =======================================================================
25ef750e 2056// function : SetUniformState
2057// purpose : Sets uniform state for the given ray-tracing shader program
2058// =======================================================================
2059Standard_Boolean OpenGl_Workspace::SetUniformState (const Graphic3d_CView& theCView,
312a4043 2060 const Standard_Integer theSizeX,
2061 const Standard_Integer theSizeY,
25ef750e 2062 const OpenGl_Vec3* theOrigins,
2063 const OpenGl_Vec3* theDirects,
2064 const OpenGl_Mat4& theUnviewMat,
2065 const Standard_Integer theProgramIndex,
2066 Handle(OpenGl_ShaderProgram)& theRaytraceProgram)
2067{
2068 if (theRaytraceProgram.IsNull())
2069 {
2070 return Standard_False;
2071 }
2072
2073 Standard_Integer aLightSourceBufferSize =
2074 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2075
2076 Standard_Boolean aResult = Standard_True;
2077
2078 // Set camera state
2079 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2080 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLB], theOrigins[0]);
2081 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2082 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRB], theOrigins[1]);
2083 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2084 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLT], theOrigins[2]);
2085 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2086 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRT], theOrigins[3]);
2087 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2088 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLB], theDirects[0]);
2089 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2090 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRB], theDirects[1]);
2091 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2092 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLT], theDirects[2]);
2093 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2094 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRT], theDirects[3]);
2095 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2096 myUniformLocations[theProgramIndex][OpenGl_RT_uUnviewMat], theUnviewMat);
2097
312a4043 2098 // Set window size
2099 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2100 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeX], theSizeX);
2101 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2102 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeY], theSizeY);
2103
25ef750e 2104 // Set scene parameters
2105 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2106 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2107 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2108 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2109 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2110 myUniformLocations[theProgramIndex][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2111 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2112 myUniformLocations[theProgramIndex][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2113
2114 // Set rendering options
2115 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2116 myUniformLocations[theProgramIndex][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
2117 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2118 myUniformLocations[theProgramIndex][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
2119
2120 // Set array of 64-bit texture handles
2121 if (myGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2122 {
2123 aResult &= theRaytraceProgram->SetUniform (myGlContext, "uTextureSamplers",
2124 static_cast<GLsizei> (myRaytraceGeometry.TextureHandles().size()), &myRaytraceGeometry.TextureHandles()[0]);
2125 }
2126
2127 if (!aResult)
2128 {
2129#ifdef RAY_TRACE_PRINT_INFO
312a4043 2130 std::cout << "Info: Not all uniforms were detected (for program " << theProgramIndex << ")" << std::endl;
25ef750e 2131#endif
2132 }
2133
2134 return aResult;
2135}
2136
2137// =======================================================================
fc73a202 2138// function : RunRaytraceShaders
2139// purpose : Runs ray-tracing shader programs
2140// =======================================================================
2141Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
2142 const Standard_Integer theSizeX,
2143 const Standard_Integer theSizeY,
2144 const OpenGl_Vec3 theOrigins[4],
2145 const OpenGl_Vec3 theDirects[4],
25ef750e 2146 const OpenGl_Mat4& theUnviewMat,
fc73a202 2147 OpenGl_FrameBuffer* theFrameBuffer)
2148{
2149 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2150 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2151 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
fc73a202 2152 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2153 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
25ef750e 2154 myGeometryTexCrdTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
fc73a202 2155 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
a89742cf 2156 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
fc73a202 2157 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2158 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
a89742cf 2159
2160 myOpenGlFBO->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2161 myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
fc73a202 2162
bc8c79bb 2163 if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
fc73a202 2164 {
2165 myRaytraceFBO1->BindBuffer (myGlContext);
2166
2167 glDisable (GL_BLEND);
2168 }
2169
7d3e64ef 2170 myGlContext->BindProgram (myRaytraceProgram);
fc73a202 2171
25ef750e 2172 SetUniformState (theCView,
312a4043 2173 theSizeX,
2174 theSizeY,
25ef750e 2175 theOrigins,
2176 theDirects,
2177 theUnviewMat,
2178 0, // ID of RT program
2179 myRaytraceProgram);
fc73a202 2180
7d3e64ef 2181 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 2182 {
7d3e64ef 2183 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
fc73a202 2184 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2185 }
7d3e64ef 2186 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
25ef750e 2187
bc8c79bb 2188 if (!theCView.RenderParams.IsAntialiasingEnabled)
fc73a202 2189 {
7d3e64ef 2190 myGlContext->BindProgram (NULL);
fc73a202 2191
a89742cf 2192 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2193 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
e2da917a 2194 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2195 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2196 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
a89742cf 2197 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2198 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
25ef750e 2199 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
a89742cf 2200 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
25ef750e 2201 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
a89742cf 2202 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2203 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
a89742cf 2204
2205 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2206
fc73a202 2207 return Standard_True;
2208 }
2209
945c3529 2210 myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2211
7d3e64ef 2212 myGlContext->BindProgram (myPostFSAAProgram);
fc73a202 2213
25ef750e 2214 SetUniformState (theCView,
312a4043 2215 theSizeX,
2216 theSizeY,
25ef750e 2217 theOrigins,
2218 theDirects,
2219 theUnviewMat,
2220 1, // ID of FSAA program
2221 myPostFSAAProgram);
fc73a202 2222
7d3e64ef 2223 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2224 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
fc73a202 2225
50d0e1ce 2226 // Perform multi-pass adaptive FSAA using ping-pong technique.
2227 // We use 'FLIPTRI' sampling pattern changing for every pixel
2228 // (3 additional samples per pixel, the 1st sample is already
2229 // available from initial ray-traced image).
2230 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
fc73a202 2231 {
2232 GLfloat aOffsetX = 1.f / theSizeX;
2233 GLfloat aOffsetY = 1.f / theSizeY;
2234
50d0e1ce 2235 if (anIt == 1)
fc73a202 2236 {
50d0e1ce 2237 aOffsetX *= -0.55f;
2238 aOffsetY *= 0.55f;
fc73a202 2239 }
50d0e1ce 2240 else if (anIt == 2)
fc73a202 2241 {
50d0e1ce 2242 aOffsetX *= 0.00f;
2243 aOffsetY *= -0.55f;
fc73a202 2244 }
50d0e1ce 2245 else if (anIt == 3)
2246 {
2247 aOffsetX *= 0.55f;
2248 aOffsetY *= 0.00f;
2249 }
2250
fc73a202 2251 myPostFSAAProgram->SetUniform (myGlContext,
50d0e1ce 2252 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
fc73a202 2253 myPostFSAAProgram->SetUniform (myGlContext,
2254 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2255 myPostFSAAProgram->SetUniform (myGlContext,
2256 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2257
50d0e1ce 2258 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
fc73a202 2259
2260 if (anIt == 3) // disable FBO on last iteration
2261 {
2262 glEnable (GL_BLEND);
2263
2264 if (theFrameBuffer != NULL)
2265 theFrameBuffer->BindBuffer (myGlContext);
2266 }
2267 else
2268 {
2269 aFramebuffer->BindBuffer (myGlContext);
2270 }
50d0e1ce 2271
fc73a202 2272 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
e276548b 2273
fc73a202 2274 if (anIt != 3) // set input for the next pass
2275 {
945c3529 2276 aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2277 aFramebuffer->UnbindBuffer (myGlContext);
e276548b 2278 }
2279 }
fc73a202 2280
7d3e64ef 2281 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 2282
7d3e64ef 2283 myGlContext->BindProgram (NULL);
a89742cf 2284 myRaytraceFBO1->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2285 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2286 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
e2da917a 2287 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2288 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2289 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
a89742cf 2290 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2291 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
25ef750e 2292 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
a89742cf 2293 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
25ef750e 2294 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
a89742cf 2295 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2296 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
a89742cf 2297
2298 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
fc73a202 2299
2300 return Standard_True;
e276548b 2301}
2302
2303// =======================================================================
2304// function : Raytrace
fc73a202 2305// purpose : Redraws the window using OpenGL/GLSL ray-tracing
e276548b 2306// =======================================================================
2307Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
68333c8f 2308 const Standard_Integer theSizeX,
2309 const Standard_Integer theSizeY,
a89742cf 2310 const Aspect_CLayer2d& theCOverLayer,
2311 const Aspect_CLayer2d& theCUnderLayer,
fc73a202 2312 OpenGl_FrameBuffer* theFrameBuffer)
e276548b 2313{
bc8c79bb 2314 if (!InitRaytraceResources (theCView))
e276548b 2315 return Standard_False;
2316
fc73a202 2317 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
e276548b 2318 return Standard_False;
2319
fc73a202 2320 if (!UpdateRaytraceEnvironmentMap())
e276548b 2321 return Standard_False;
2322
2323 // Get model-view and projection matrices
25ef750e 2324 OpenGl_Mat4 aOrientationMatrix;
2325 OpenGl_Mat4 aViewMappingMatrix;
e276548b 2326
25ef750e 2327 myView->GetMatrices (aOrientationMatrix,
2328 aViewMappingMatrix);
e276548b 2329
25ef750e 2330 OpenGl_Mat4 aInvOrientationMatrix;
fc73a202 2331 aOrientationMatrix.Inverted (aInvOrientationMatrix);
e276548b 2332
fc73a202 2333 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
e276548b 2334 return Standard_False;
2335
fc73a202 2336 OpenGl_Vec3 aOrigins[4];
2337 OpenGl_Vec3 aDirects[4];
25ef750e 2338 OpenGl_Mat4 anUnviewMat;
e276548b 2339
fc73a202 2340 UpdateCamera (aOrientationMatrix,
2341 aViewMappingMatrix,
2342 aOrigins,
a89742cf 2343 aDirects,
25ef750e 2344 anUnviewMat);
e276548b 2345
84c71f29 2346 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2347 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
e276548b 2348
2349 glDisable (GL_DEPTH_TEST);
2350
a89742cf 2351 if (theFrameBuffer != NULL)
2352 {
2353 theFrameBuffer->BindBuffer (myGlContext);
2354 }
2355
e276548b 2356 if (NamedStatus & OPENGL_NS_WHITEBACK)
2357 {
2358 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2359 }
2360 else
2361 {
2362 glClearColor (myBgColor.rgb[0],
2363 myBgColor.rgb[1],
2364 myBgColor.rgb[2],
2365 1.0f);
2366 }
2367
2368 glClear (GL_COLOR_BUFFER_BIT);
2369
0b0320e7 2370 myView->DrawBackground (this);
e276548b 2371
c827ea3a 2372 myView->RedrawLayer2d (myPrintContext, this, theCView, theCUnderLayer);
a89742cf 2373
c827ea3a 2374 myGlContext->WorldViewState.Push();
2375 myGlContext->ProjectionState.Push();
e276548b 2376
c827ea3a 2377 myGlContext->WorldViewState.SetIdentity();
2378 myGlContext->ProjectionState.SetIdentity();
2379
2380 myGlContext->ApplyProjectionMatrix();
2381 myGlContext->ApplyWorldViewMatrix();
e276548b 2382
fc73a202 2383 glEnable (GL_BLEND);
2384 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
e276548b 2385
c827ea3a 2386 // Generate ray-traced image
e276548b 2387 if (myIsRaytraceDataValid)
2388 {
fc73a202 2389 myRaytraceScreenQuad.Bind (myGlContext);
2390
25ef750e 2391 if (!myRaytraceGeometry.AcquireTextures (myGlContext))
2392 {
2393 const TCollection_ExtendedString aMessage = "Error: Failed to acquire OpenGL image textures";
2394
2395 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2396 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2397 }
2398
fc73a202 2399 RunRaytraceShaders (theCView,
2400 theSizeX,
2401 theSizeY,
2402 aOrigins,
2403 aDirects,
25ef750e 2404 anUnviewMat,
fc73a202 2405 theFrameBuffer);
2406
25ef750e 2407 if (!myRaytraceGeometry.ReleaseTextures (myGlContext))
2408 {
2409 const TCollection_ExtendedString aMessage = "Error: Failed to release OpenGL image textures";
2410
2411 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2412 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2413 }
2414
fc73a202 2415 myRaytraceScreenQuad.Unbind (myGlContext);
e276548b 2416 }
2417
84c71f29 2418 if (!wasBlendingEnabled)
2419 glDisable (GL_BLEND);
fc73a202 2420
84c71f29 2421 if (wasDepthTestEnabled)
2422 glEnable (GL_DEPTH_TEST);
e276548b 2423
c827ea3a 2424 myGlContext->WorldViewState.Pop();
2425 myGlContext->ProjectionState.Pop();
2426
2427 myGlContext->ApplyProjectionMatrix();
a89742cf 2428
2429 // Redraw trihedron
2430 myView->RedrawTrihedron (this);
2431
2432 // Redraw overlay
2433 const int aMode = 0;
2434 DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
c827ea3a 2435 myView->RedrawLayer2d (myPrintContext, this, theCView, theCOverLayer);
a89742cf 2436 DisplayCallback (theCView, aMode);
e276548b 2437 return Standard_True;
2438}
a89742cf 2439
2440IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2441IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2442
2443// =======================================================================
2444// function : CanRender
2445// purpose :
2446// =======================================================================
2447Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2448{
2449 Standard_Boolean aPrevFilterResult = Standard_True;
2450 if (!myPrevRenderFilter.IsNull())
2451 {
2452 aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2453 }
2454 return aPrevFilterResult &&
2455 !OpenGl_Raytrace::IsRaytracedElement (theElement);
2456}