0031082: Visualization - crash on display if there are no lights in the view
[occt.git] / src / OpenGl / OpenGl_View_Raytrace.cxx
CommitLineData
91c60b57 1// Created on: 2015-02-20
e276548b 2// Created by: Denis BOGOLEPOV
91c60b57 3// Copyright (c) 2015 OPEN CASCADE SAS
e276548b 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
c357e426 16#include <OpenGl_View.hxx>
91c60b57 17
c357e426 18#include <Graphic3d_TextureParams.hxx>
b7cd4ba7 19#include <OpenGl_PrimitiveArray.hxx>
fc73a202 20#include <OpenGl_VertexBuffer.hxx>
3a9b5dc8 21#include <OpenGl_GlCore44.hxx>
fc73a202 22#include <OSD_Protection.hxx>
91c60b57 23#include <OSD_File.hxx>
e276548b 24
ee5befae 25#include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26#include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27#include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28#include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29#include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30#include "../Shaders/Shaders_Display_fs.pxx"
31
e276548b 32//! Use this macro to output ray-tracing debug info
fc73a202 33// #define RAY_TRACE_PRINT_INFO
e276548b 34
35#ifdef RAY_TRACE_PRINT_INFO
36 #include <OSD_Timer.hxx>
37#endif
38
b6472664 39namespace
40{
41 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
42 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
43}
44
cc8cbabe 45namespace
46{
47 //! Defines OpenGL texture samplers.
48 static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
49
50 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
51 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
52 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
53 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
54
55 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
56 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
57 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
58 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
59
60 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
61 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
62
63 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
64 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
65
66 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
67}
68
e276548b 69// =======================================================================
189f85a3 70// function : updateRaytraceGeometry
91c60b57 71// purpose : Updates 3D scene geometry for ray-tracing
e276548b 72// =======================================================================
91c60b57 73Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
74 const Standard_Integer theViewId,
75 const Handle(OpenGl_Context)& theGlContext)
e276548b 76{
91c60b57 77 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
78 // modifications. This is light-weight procedure performed on each frame
84c71f29 79 if (theMode == OpenGl_GUM_CHECK)
e276548b 80 {
bd6a8454 81 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
91c60b57 82 {
83 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
84 }
85 }
84c71f29 86 else if (theMode == OpenGl_GUM_PREPARE)
87 {
88 myRaytraceGeometry.ClearMaterials();
91c60b57 89
84c71f29 90 myArrayToTrianglesMap.clear();
e276548b 91
92 myIsRaytraceDataValid = Standard_False;
93 }
e276548b 94
95 // The set of processed structures (reflected to ray-tracing)
96 // This set is used to remove out-of-date records from the
97 // hash map of structures
98 std::set<const OpenGl_Structure*> anElements;
99
91c60b57 100 // Set to store all currently visible OpenGL primitive arrays
101 // applicable for ray-tracing
8d3f219f 102 std::set<Standard_Size> anArrayIDs;
84c71f29 103
189f85a3 104 // Set to store all non-raytracable elements allowing tracking
105 // of changes in OpenGL scene (only for path tracing)
106 std::set<Standard_Integer> aNonRaytraceIDs;
107
1c728f2d 108 for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
e276548b 109 {
1c728f2d 110 const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
111 if (aLayer->NbStructures() == 0
112 || !aLayer->LayerSettings().IsRaytracable()
113 || aLayer->LayerSettings().IsImmediate())
114 {
115 continue;
116 }
91c60b57 117
1c728f2d 118 const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
68333c8f 119 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
e276548b 120 {
d325cb7f 121 for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
e276548b 122 {
123 const OpenGl_Structure* aStructure = aStructIt.Value();
124
84c71f29 125 if (theMode == OpenGl_GUM_CHECK)
e276548b 126 {
91c60b57 127 if (toUpdateStructure (aStructure))
e276548b 128 {
91c60b57 129 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
e276548b 130 }
189f85a3 131 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
132 {
133 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
134 }
e2da917a 135 }
84c71f29 136 else if (theMode == OpenGl_GUM_PREPARE)
137 {
91c60b57 138 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
a1954302 139 {
a272ed94 140 continue;
141 }
91c60b57 142 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
a272ed94 143 {
84c71f29 144 continue;
a1954302 145 }
84c71f29 146
3e05329c 147 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
84c71f29 148 {
91c60b57 149 // Extract OpenGL elements from the group (primitives arrays)
84c71f29 150 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
151 {
152 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
153
154 if (aPrimArray != NULL)
155 {
8d3f219f 156 anArrayIDs.insert (aPrimArray->GetUID());
84c71f29 157 }
158 }
159 }
e2da917a 160 }
91c60b57 161 else if (theMode == OpenGl_GUM_REBUILD)
e276548b 162 {
163 if (!aStructure->IsRaytracable())
91c60b57 164 {
e276548b 165 continue;
91c60b57 166 }
167 else if (addRaytraceStructure (aStructure, theGlContext))
168 {
169 anElements.insert (aStructure); // structure was processed
170 }
e276548b 171 }
172 }
173 }
174 }
175
84c71f29 176 if (theMode == OpenGl_GUM_PREPARE)
177 {
25ef750e 178 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
84c71f29 179
91c60b57 180 // Filter out unchanged objects so only their transformations and materials
181 // will be updated (and newly added objects will be processed from scratch)
182 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
84c71f29 183 {
184 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
91c60b57 185 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
84c71f29 186
91c60b57 187 if (aTriangleSet == NULL)
84c71f29 188 {
91c60b57 189 continue;
190 }
191
192 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
193 {
194 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
84c71f29 195
8d3f219f 196 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
84c71f29 197 }
198 }
199
200 myRaytraceGeometry.Objects() = anUnchangedObjects;
201
91c60b57 202 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
84c71f29 203 }
91c60b57 204 else if (theMode == OpenGl_GUM_REBUILD)
e276548b 205 {
91c60b57 206 // Actualize the hash map of structures - remove out-of-date records
d4aaad5b 207 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
e276548b 208
209 while (anIter != myStructureStates.end())
210 {
211 if (anElements.find (anIter->first) == anElements.end())
212 {
213 myStructureStates.erase (anIter++);
214 }
215 else
216 {
217 ++anIter;
218 }
219 }
220
221 // Actualize OpenGL layer list state
bd6a8454 222 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
e276548b 223
91c60b57 224 // Rebuild two-level acceleration structure
265d4508 225 myRaytraceGeometry.ProcessAcceleration();
e276548b 226
91c60b57 227 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
228 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
229 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
e276548b 230
25ef750e 231 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
e276548b 232
91c60b57 233 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
fc73a202 234
91c60b57 235 return uploadRaytraceData (theGlContext);
e276548b 236 }
237
189f85a3 238 if (myRaytraceParameters.GlobalIllumination)
239 {
240 Standard_Boolean toRestart =
241 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
242
243 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
244 {
245 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
246 {
247 toRestart = Standard_True;
248 }
249 }
250
251 if (toRestart)
3a9b5dc8 252 {
189f85a3 253 myAccumFrames = 0;
3a9b5dc8 254 }
189f85a3 255
256 myNonRaytraceStructureIDs = aNonRaytraceIDs;
257 }
258
e276548b 259 return Standard_True;
260}
261
262// =======================================================================
189f85a3 263// function : toUpdateStructure
e2da917a 264// purpose : Checks to see if the structure is modified
e276548b 265// =======================================================================
91c60b57 266Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
e276548b 267{
268 if (!theStructure->IsRaytracable())
269 {
e276548b 270 if (theStructure->ModificationState() > 0)
271 {
272 theStructure->ResetModificationState();
91c60b57 273
274 return Standard_True; // ray-trace element was removed - need to rebuild
e276548b 275 }
276
91c60b57 277 return Standard_False; // did not contain ray-trace elements
e276548b 278 }
279
d4aaad5b 280 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
e276548b 281
d4aaad5b 282 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
91c60b57 283 {
d4aaad5b 284 return Standard_True;
285 }
286 else if (theStructure->InstancedStructure() != NULL)
287 {
288 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
91c60b57 289 }
e276548b 290
d4aaad5b 291 return Standard_False;
e276548b 292}
293
25ef750e 294// =======================================================================
189f85a3 295// function : buildTextureTransform
25ef750e 296// purpose : Constructs texture transformation matrix
297// =======================================================================
189f85a3 298void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
25ef750e 299{
300 theMatrix.InitIdentity();
cc8cbabe 301 if (theParams.IsNull())
302 {
303 return;
304 }
25ef750e 305
306 // Apply scaling
307 const Graphic3d_Vec2& aScale = theParams->Scale();
308
309 theMatrix.ChangeValue (0, 0) *= aScale.x();
310 theMatrix.ChangeValue (1, 0) *= aScale.x();
311 theMatrix.ChangeValue (2, 0) *= aScale.x();
312 theMatrix.ChangeValue (3, 0) *= aScale.x();
313
314 theMatrix.ChangeValue (0, 1) *= aScale.y();
315 theMatrix.ChangeValue (1, 1) *= aScale.y();
316 theMatrix.ChangeValue (2, 1) *= aScale.y();
317 theMatrix.ChangeValue (3, 1) *= aScale.y();
318
319 // Apply translation
320 const Graphic3d_Vec2 aTrans = -theParams->Translation();
321
322 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
323 theMatrix.GetValue (0, 1) * aTrans.y();
324
325 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
326 theMatrix.GetValue (1, 1) * aTrans.y();
327
328 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
329 theMatrix.GetValue (2, 1) * aTrans.y();
330
331 // Apply rotation
332 const Standard_ShortReal aSin = std::sin (
333 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
334 const Standard_ShortReal aCos = std::cos (
335 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
336
337 BVH_Mat4f aRotationMat;
338 aRotationMat.SetValue (0, 0, aCos);
339 aRotationMat.SetValue (1, 1, aCos);
340 aRotationMat.SetValue (0, 1, -aSin);
341 aRotationMat.SetValue (1, 0, aSin);
342
343 theMatrix = theMatrix * aRotationMat;
344}
345
e276548b 346// =======================================================================
189f85a3 347// function : convertMaterial
e276548b 348// purpose : Creates ray-tracing material properties
349// =======================================================================
bf5f0ca2 350OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
91c60b57 351 const Handle(OpenGl_Context)& theGlContext)
e276548b 352{
61168418 353 OpenGl_RaytraceMaterial aResMat;
25ef750e 354
b6472664 355 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
356 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
357 const float aShine = 128.0f * float(aSrcMat.Shininess());
b6472664 358
61168418 359 const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
360 const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
361 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
362 const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
363 switch (aSrcMat.MaterialType())
b6472664 364 {
61168418 365 case Graphic3d_MATERIAL_ASPECT:
366 {
367 aResMat.Ambient .SetValues (aSrcAmb * aMatCol, 1.0f);
368 aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
369 aResMat.Emission.SetValues (aSrcEms * aMatCol, 1.0f);
370 break;
371 }
372 case Graphic3d_MATERIAL_PHYSIC:
373 {
374 aResMat.Ambient .SetValues (aSrcAmb, 1.0f);
375 aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
376 aResMat.Emission.SetValues (aSrcEms, 1.0f);
377 break;
378 }
b6472664 379 }
380
b6472664 381 {
61168418 382 // interior color is always ignored for Specular
383 aResMat.Specular.SetValues (aSrcSpe, aShine);
384 const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
385 Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
386 aResMat.Diffuse.z() + aResMat.Specular.z()));
b6472664 387 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
61168418 388 aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
b6472664 389 }
390
391 const float anIndex = (float )aSrcMat.RefractionIndex();
61168418 392 aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
393 anIndex == 0 ? 1.0f : anIndex,
394 anIndex == 0 ? 1.0f : 1.0f / anIndex);
25ef750e 395
ba00aab7 396 aResMat.Ambient = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
397 aResMat.Diffuse = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
398 aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
399 aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
400
189f85a3 401 // Serialize physically-based material properties
b6472664 402 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
189f85a3 403
61168418 404 aResMat.BSDF.Kc = aBSDF.Kc;
405 aResMat.BSDF.Ks = aBSDF.Ks;
406 aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
407 aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
408 aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
189f85a3 409
61168418 410 aResMat.BSDF.Absorption = aBSDF.Absorption;
189f85a3 411
61168418 412 aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
413 aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
189f85a3 414
415 // Handle material textures
cc8cbabe 416 if (!theAspect->Aspect()->ToMapTexture())
25ef750e 417 {
61168418 418 return aResMat;
cc8cbabe 419 }
91c60b57 420
cc8cbabe 421 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
422 if (aTextureSet.IsNull()
423 || aTextureSet->IsEmpty()
424 || aTextureSet->First().IsNull())
425 {
61168418 426 return aResMat;
cc8cbabe 427 }
91c60b57 428
cc8cbabe 429 if (theGlContext->HasRayTracingTextures())
430 {
431 const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
61168418 432 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
91c60b57 433
cc8cbabe 434 // write texture ID to diffuse w-component
61168418 435 aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
cc8cbabe 436 }
437 else if (!myIsRaytraceWarnTextures)
438 {
61168418 439 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
440 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
441 "Please try to update graphics card driver. At the moment textures will be ignored.");
cc8cbabe 442 myIsRaytraceWarnTextures = Standard_True;
25ef750e 443 }
e276548b 444
61168418 445 return aResMat;
e276548b 446}
447
448// =======================================================================
189f85a3 449// function : addRaytraceStructure
e276548b 450// purpose : Adds OpenGL structure to ray-traced scene geometry
451// =======================================================================
91c60b57 452Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
453 const Handle(OpenGl_Context)& theGlContext)
e276548b 454{
e276548b 455 if (!theStructure->IsVisible())
456 {
d4aaad5b 457 myStructureStates[theStructure] = StructState (theStructure);
91c60b57 458
e276548b 459 return Standard_True;
460 }
461
462 // Get structure material
2831708b 463 OpenGl_RaytraceMaterial aDefaultMaterial;
1f7f5a90 464 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
0717ddc1 465
466 // Process all connected OpenGL structures
d4aaad5b 467 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
468
469 if (anInstanced != NULL && anInstanced->IsRaytracable())
0717ddc1 470 {
1f7f5a90 471 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
0717ddc1 472 }
473
d4aaad5b 474 myStructureStates[theStructure] = StructState (theStructure);
91c60b57 475
476 return aResult;
0717ddc1 477}
478
479// =======================================================================
189f85a3 480// function : addRaytraceGroups
0717ddc1 481// purpose : Adds OpenGL groups to ray-traced scene geometry
482// =======================================================================
8c820969 483Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
484 const OpenGl_RaytraceMaterial& theStructMat,
1f7f5a90 485 const Handle(Geom_Transformation)& theTrsf,
8c820969 486 const Handle(OpenGl_Context)& theGlContext)
0717ddc1 487{
1f7f5a90 488 OpenGl_Mat4 aMat4;
3e05329c 489 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
e276548b 490 {
491 // Get group material
8c820969 492 OpenGl_RaytraceMaterial aGroupMaterial;
bf5f0ca2 493 if (aGroupIter.Value()->GlAspects() != NULL)
e276548b 494 {
bf5f0ca2 495 aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
e276548b 496 }
497
8c820969 498 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 499
8c820969 500 // Use group material if available, otherwise use structure material
bf5f0ca2 501 myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
e276548b 502
265d4508 503 // Add OpenGL elements from group (extract primitives arrays and aspects)
b64d84be 504 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
e276548b 505 {
bf5f0ca2 506 OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
91c60b57 507
5322131b 508 if (anAspect != NULL)
e276548b 509 {
5322131b 510 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 511
91c60b57 512 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
e276548b 513
5322131b 514 myRaytraceGeometry.Materials.push_back (aMaterial);
e276548b 515 }
5322131b 516 else
e276548b 517 {
518 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
84c71f29 519
e276548b 520 if (aPrimArray != NULL)
521 {
8d3f219f 522 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
523
84c71f29 524 if (aSetIter != myArrayToTrianglesMap.end())
525 {
526 OpenGl_TriangleSet* aSet = aSetIter->second;
f5b72419 527 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
1f7f5a90 528 if (!theTrsf.IsNull())
84c71f29 529 {
1f7f5a90 530 theTrsf->Trsf().GetMat4 (aMat4);
531 aTransform->SetTransform (aMat4);
84c71f29 532 }
91c60b57 533
84c71f29 534 aSet->SetProperties (aTransform);
25ef750e 535 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
84c71f29 536 {
537 aSet->SetMaterialIndex (aMatID);
538 }
539 }
540 else
541 {
f5b72419 542 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
84c71f29 543 {
f5b72419 544 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
1f7f5a90 545 if (!theTrsf.IsNull())
84c71f29 546 {
1f7f5a90 547 theTrsf->Trsf().GetMat4 (aMat4);
548 aTransform->SetTransform (aMat4);
84c71f29 549 }
550
551 aSet->SetProperties (aTransform);
84c71f29 552 myRaytraceGeometry.Objects().Append (aSet);
553 }
554 }
e276548b 555 }
556 }
557 }
e276548b 558 }
559
e276548b 560 return Standard_True;
561}
562
563// =======================================================================
189f85a3 564// function : addRaytracePrimitiveArray
e276548b 565// purpose : Adds OpenGL primitive array to ray-traced scene geometry
566// =======================================================================
f5b72419 567Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
568 const Standard_Integer theMaterial,
569 const OpenGl_Mat4* theTransform)
e276548b 570{
91c60b57 571 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
871fa103 572 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
573 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
91c60b57 574
871fa103 575 if (theArray->DrawMode() < GL_TRIANGLES
91c60b57 576 #ifndef GL_ES_VERSION_2_0
871fa103 577 || theArray->DrawMode() > GL_POLYGON
ca3c13d1 578 #else
579 || theArray->DrawMode() > GL_TRIANGLE_FAN
580 #endif
871fa103 581 || anAttribs.IsNull())
e276548b 582 {
f5b72419 583 return Handle(OpenGl_TriangleSet)();
e276548b 584 }
585
25ef750e 586 OpenGl_Mat4 aNormalMatrix;
25ef750e 587 if (theTransform != NULL)
588 {
589 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
590 "Error: Failed to compute normal transformation matrix", NULL);
591
592 aNormalMatrix.Transpose();
593 }
594
f5b72419 595 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
e276548b 596 {
871fa103 597 aSet->Vertices.reserve (anAttribs->NbElements);
91c60b57 598 aSet->Normals.reserve (anAttribs->NbElements);
599 aSet->TexCrds.reserve (anAttribs->NbElements);
25ef750e 600
871fa103 601 const size_t aVertFrom = aSet->Vertices.size();
da87ddc3 602
603 Standard_Integer anAttribIndex = 0;
604 Standard_Size anAttribStride = 0;
605 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
265d4508 606 {
da87ddc3 607 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
608 if (anAttrib.DataType == Graphic3d_TOD_VEC2
609 || anAttrib.DataType == Graphic3d_TOD_VEC3
610 || anAttrib.DataType == Graphic3d_TOD_VEC4)
871fa103 611 {
da87ddc3 612 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
871fa103 613 {
da87ddc3 614 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
615 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
871fa103 616 }
617 }
da87ddc3 618 }
619 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
620 {
621 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
622 if (anAttrib.DataType == Graphic3d_TOD_VEC3
623 || anAttrib.DataType == Graphic3d_TOD_VEC4)
871fa103 624 {
da87ddc3 625 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
871fa103 626 {
da87ddc3 627 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
25ef750e 628 }
629 }
da87ddc3 630 }
631 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
632 {
633 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
634 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
25ef750e 635 {
da87ddc3 636 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
25ef750e 637 {
da87ddc3 638 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
871fa103 639 }
640 }
265d4508 641 }
e276548b 642
871fa103 643 if (aSet->Normals.size() != aSet->Vertices.size())
265d4508 644 {
871fa103 645 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
265d4508 646 {
25ef750e 647 aSet->Normals.push_back (BVH_Vec3f());
648 }
649 }
650
651 if (aSet->TexCrds.size() != aSet->Vertices.size())
652 {
653 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
654 {
655 aSet->TexCrds.push_back (BVH_Vec2f());
265d4508 656 }
871fa103 657 }
e276548b 658
25ef750e 659 if (theTransform != NULL)
871fa103 660 {
661 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
662 {
25ef750e 663 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
664
91c60b57 665 BVH_Vec4f aTransVertex = *theTransform *
666 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
25ef750e 667
668 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
871fa103 669 }
670 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
671 {
25ef750e 672 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
673
91c60b57 674 BVH_Vec4f aTransNormal = aNormalMatrix *
675 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
25ef750e 676
677 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
871fa103 678 }
e276548b 679 }
680
871fa103 681 if (!aBounds.IsNull())
265d4508 682 {
91c60b57 683 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
265d4508 684 {
871fa103 685 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
e276548b 686
91c60b57 687 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
265d4508 688 {
f5b72419 689 aSet.Nullify();
690 return Handle(OpenGl_TriangleSet)();
265d4508 691 }
692
693 aBoundStart += aVertNum;
694 }
695 }
696 else
e276548b 697 {
871fa103 698 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
e276548b 699
91c60b57 700 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
e276548b 701 {
f5b72419 702 aSet.Nullify();
703 return Handle(OpenGl_TriangleSet)();
e276548b 704 }
e276548b 705 }
706 }
e276548b 707
265d4508 708 if (aSet->Size() != 0)
91c60b57 709 {
265d4508 710 aSet->MarkDirty();
91c60b57 711 }
e276548b 712
265d4508 713 return aSet;
e276548b 714}
715
716// =======================================================================
189f85a3 717// function : addRaytraceVertexIndices
e276548b 718// purpose : Adds vertex indices to ray-traced scene geometry
719// =======================================================================
91c60b57 720Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
721 const Standard_Integer theMatID,
722 const Standard_Integer theCount,
723 const Standard_Integer theOffset,
724 const OpenGl_PrimitiveArray& theArray)
e276548b 725{
871fa103 726 switch (theArray.DrawMode())
e276548b 727 {
91c60b57 728 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
729 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
730 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
ca3c13d1 731 #if !defined(GL_ES_VERSION_2_0)
91c60b57 732 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
733 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
734 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
ca3c13d1 735 #endif
e276548b 736 }
91c60b57 737
871fa103 738 return Standard_False;
e276548b 739}
740
741// =======================================================================
189f85a3 742// function : addRaytraceTriangleArray
e276548b 743// purpose : Adds OpenGL triangle array to ray-traced scene geometry
744// =======================================================================
91c60b57 745Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
746 const Standard_Integer theMatID,
747 const Standard_Integer theCount,
748 const Standard_Integer theOffset,
749 const Handle(Graphic3d_IndexBuffer)& theIndices)
e276548b 750{
265d4508 751 if (theCount < 3)
91c60b57 752 {
e276548b 753 return Standard_True;
91c60b57 754 }
e276548b 755
871fa103 756 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
265d4508 757
871fa103 758 if (!theIndices.IsNull())
e276548b 759 {
265d4508 760 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 761 {
871fa103 762 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
763 theIndices->Index (aVert + 1),
764 theIndices->Index (aVert + 2),
765 theMatID));
e276548b 766 }
767 }
768 else
769 {
265d4508 770 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 771 {
91c60b57 772 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
e276548b 773 }
774 }
775
776 return Standard_True;
777}
778
779// =======================================================================
189f85a3 780// function : addRaytraceTriangleFanArray
e276548b 781// purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
782// =======================================================================
91c60b57 783Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
784 const Standard_Integer theMatID,
785 const Standard_Integer theCount,
786 const Standard_Integer theOffset,
787 const Handle(Graphic3d_IndexBuffer)& theIndices)
e276548b 788{
265d4508 789 if (theCount < 3)
91c60b57 790 {
e276548b 791 return Standard_True;
91c60b57 792 }
e276548b 793
871fa103 794 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 795
871fa103 796 if (!theIndices.IsNull())
e276548b 797 {
265d4508 798 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 799 {
871fa103 800 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
801 theIndices->Index (aVert + 1),
802 theIndices->Index (aVert + 2),
803 theMatID));
e276548b 804 }
805 }
806 else
807 {
265d4508 808 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 809 {
871fa103 810 theSet.Elements.push_back (BVH_Vec4i (theOffset,
811 aVert + 1,
812 aVert + 2,
813 theMatID));
e276548b 814 }
815 }
816
817 return Standard_True;
818}
819
820// =======================================================================
189f85a3 821// function : addRaytraceTriangleStripArray
e276548b 822// purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
823// =======================================================================
91c60b57 824Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
825 const Standard_Integer theMatID,
826 const Standard_Integer theCount,
827 const Standard_Integer theOffset,
828 const Handle(Graphic3d_IndexBuffer)& theIndices)
e276548b 829{
265d4508 830 if (theCount < 3)
91c60b57 831 {
e276548b 832 return Standard_True;
91c60b57 833 }
e276548b 834
871fa103 835 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 836
871fa103 837 if (!theIndices.IsNull())
e276548b 838 {
265d4508 839 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 840 {
ad2a55b2 841 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
842 theIndices->Index (aVert + (aCW ? 0 : 1)),
871fa103 843 theIndices->Index (aVert + 2),
844 theMatID));
e276548b 845 }
846 }
847 else
848 {
265d4508 849 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 850 {
ad2a55b2 851 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
852 aVert + (aCW ? 0 : 1),
871fa103 853 aVert + 2,
854 theMatID));
e276548b 855 }
856 }
857
858 return Standard_True;
859}
860
861// =======================================================================
189f85a3 862// function : addRaytraceQuadrangleArray
e276548b 863// purpose : Adds OpenGL quad array to ray-traced scene geometry
864// =======================================================================
91c60b57 865Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
866 const Standard_Integer theMatID,
867 const Standard_Integer theCount,
868 const Standard_Integer theOffset,
869 const Handle(Graphic3d_IndexBuffer)& theIndices)
e276548b 870{
265d4508 871 if (theCount < 4)
91c60b57 872 {
e276548b 873 return Standard_True;
91c60b57 874 }
e276548b 875
871fa103 876 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
265d4508 877
871fa103 878 if (!theIndices.IsNull())
e276548b 879 {
265d4508 880 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 881 {
871fa103 882 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
883 theIndices->Index (aVert + 1),
884 theIndices->Index (aVert + 2),
885 theMatID));
886 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
887 theIndices->Index (aVert + 2),
888 theIndices->Index (aVert + 3),
889 theMatID));
e276548b 890 }
891 }
892 else
893 {
265d4508 894 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 895 {
871fa103 896 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
897 theMatID));
898 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
899 theMatID));
e276548b 900 }
901 }
902
903 return Standard_True;
904}
905
906// =======================================================================
189f85a3 907// function : addRaytraceQuadrangleStripArray
e276548b 908// purpose : Adds OpenGL quad strip array to ray-traced scene geometry
909// =======================================================================
91c60b57 910Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
911 const Standard_Integer theMatID,
912 const Standard_Integer theCount,
913 const Standard_Integer theOffset,
914 const Handle(Graphic3d_IndexBuffer)& theIndices)
e276548b 915{
265d4508 916 if (theCount < 4)
91c60b57 917 {
e276548b 918 return Standard_True;
91c60b57 919 }
e276548b 920
871fa103 921 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
265d4508 922
871fa103 923 if (!theIndices.IsNull())
e276548b 924 {
265d4508 925 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 926 {
871fa103 927 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
928 theIndices->Index (aVert + 1),
929 theIndices->Index (aVert + 2),
930 theMatID));
931
932 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
933 theIndices->Index (aVert + 3),
934 theIndices->Index (aVert + 2),
935 theMatID));
e276548b 936 }
937 }
938 else
939 {
265d4508 940 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 941 {
871fa103 942 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
943 aVert + 1,
944 aVert + 2,
945 theMatID));
946
947 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
948 aVert + 3,
949 aVert + 2,
950 theMatID));
e276548b 951 }
952 }
953
954 return Standard_True;
955}
956
957// =======================================================================
189f85a3 958// function : addRaytracePolygonArray
e276548b 959// purpose : Adds OpenGL polygon array to ray-traced scene geometry
960// =======================================================================
91c60b57 961Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
962 const Standard_Integer theMatID,
963 const Standard_Integer theCount,
964 const Standard_Integer theOffset,
965 const Handle(Graphic3d_IndexBuffer)& theIndices)
e276548b 966{
265d4508 967 if (theCount < 3)
91c60b57 968 {
e276548b 969 return Standard_True;
91c60b57 970 }
e276548b 971
871fa103 972 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 973
871fa103 974 if (!theIndices.IsNull())
e276548b 975 {
265d4508 976 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 977 {
871fa103 978 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
979 theIndices->Index (aVert + 1),
980 theIndices->Index (aVert + 2),
981 theMatID));
e276548b 982 }
983 }
984 else
985 {
265d4508 986 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 987 {
871fa103 988 theSet.Elements.push_back (BVH_Vec4i (theOffset,
989 aVert + 1,
990 aVert + 2,
991 theMatID));
e276548b 992 }
993 }
994
995 return Standard_True;
996}
997
189f85a3 998const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
999
e276548b 1000// =======================================================================
fc73a202 1001// function : Source
1002// purpose : Returns shader source combined with prefix
e276548b 1003// =======================================================================
91c60b57 1004TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
e276548b 1005{
f8ae3605 1006 const TCollection_AsciiString aVersion = "#version 140";
e276548b 1007
fc73a202 1008 if (myPrefix.IsEmpty())
e276548b 1009 {
fc73a202 1010 return aVersion + "\n" + mySource;
e276548b 1011 }
1012
fc73a202 1013 return aVersion + "\n" + myPrefix + "\n" + mySource;
e276548b 1014}
1015
1016// =======================================================================
ee5befae 1017// function : LoadFromFiles
fc73a202 1018// purpose : Loads shader source from specified files
e276548b 1019// =======================================================================
ee5befae 1020Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1021 const TCollection_AsciiString& thePrefix)
e276548b 1022{
73722cc9 1023 myError.Clear();
fc73a202 1024 mySource.Clear();
ee5befae 1025 myPrefix = thePrefix;
1026
73722cc9 1027 TCollection_AsciiString aMissingFiles;
189f85a3 1028 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
fc73a202 1029 {
1030 OSD_File aFile (theFileNames[anIndex]);
73722cc9 1031 if (aFile.Exists())
1032 {
1033 aFile.Open (OSD_ReadOnly, OSD_Protection());
1034 }
1035 if (!aFile.IsOpen())
1036 {
1037 if (!aMissingFiles.IsEmpty())
1038 {
1039 aMissingFiles += ", ";
1040 }
1041 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1042 continue;
1043 }
1044 else if (!aMissingFiles.IsEmpty())
1045 {
1046 aFile.Close();
1047 continue;
1048 }
265d4508 1049
fc73a202 1050 TCollection_AsciiString aSource;
fc73a202 1051 aFile.Read (aSource, (Standard_Integer) aFile.Size());
fc73a202 1052 if (!aSource.IsEmpty())
1053 {
1054 mySource += TCollection_AsciiString ("\n") + aSource;
1055 }
fc73a202 1056 aFile.Close();
68333c8f 1057 }
189f85a3 1058
73722cc9 1059 if (!aMissingFiles.IsEmpty())
1060 {
1061 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1062 return Standard_False;
1063 }
1064 return Standard_True;
e276548b 1065}
1066
ee5befae 1067// =======================================================================
1068// function : LoadFromStrings
1069// purpose :
1070// =======================================================================
1071Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1072 const TCollection_AsciiString& thePrefix)
1073{
1074 myError.Clear();
1075 mySource.Clear();
1076 myPrefix = thePrefix;
1077
1078 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1079 {
1080 TCollection_AsciiString aSource = theStrings[anIndex];
1081 if (!aSource.IsEmpty())
1082 {
1083 mySource += TCollection_AsciiString ("\n") + aSource;
1084 }
1085 }
1086 return Standard_True;
1087}
1088
e276548b 1089// =======================================================================
189f85a3 1090// function : generateShaderPrefix
91c60b57 1091// purpose : Generates shader prefix based on current ray-tracing options
1092// =======================================================================
1093TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1094{
1095 TCollection_AsciiString aPrefixString =
1096 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1097 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1098
1099 if (myRaytraceParameters.TransparentShadows)
1100 {
1101 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1102 }
ba00aab7 1103 if (!theGlContext->ToRenderSRGB())
1104 {
1105 aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
1106 }
91c60b57 1107
f483f2ed 1108 // If OpenGL driver supports bindless textures and texturing
1109 // is actually used, activate texturing in ray-tracing mode
1110 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
91c60b57 1111 {
1112 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1113 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1114 }
1115
3a9b5dc8 1116 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
189f85a3 1117 {
1118 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
3a9b5dc8 1119
1120 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1121 {
e084dbbc 1122 if (theGlContext->IsGlGreaterEqual (4, 4))
3a9b5dc8 1123 {
66d1cdc6 1124 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
e084dbbc 1125 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1126 && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1127 {
1128 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1129 }
3a9b5dc8 1130 }
1131 }
b4327ba8 1132
1133 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1134 {
1135 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1136 }
eb85ed36 1137
1138 switch (myRaytraceParameters.ToneMappingMethod)
1139 {
1140 case Graphic3d_ToneMappingMethod_Disabled:
1141 break;
1142 case Graphic3d_ToneMappingMethod_Filmic:
1143 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1144 break;
1145 }
189f85a3 1146 }
1147
b27ab03d 1148 if (myRaytraceParameters.DepthOfField)
1149 {
1150 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1151 }
1152
91c60b57 1153 return aPrefixString;
1154}
1155
1156// =======================================================================
189f85a3 1157// function : safeFailBack
91c60b57 1158// purpose : Performs safe exit when shaders initialization fails
1159// =======================================================================
1160Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1161 const Handle(OpenGl_Context)& theGlContext)
1162{
3b523c4c 1163 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1164 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
91c60b57 1165
1166 myRaytraceInitStatus = OpenGl_RT_FAIL;
1167
1168 releaseRaytraceResources (theGlContext);
1169
1170 return Standard_False;
1171}
1172
1173// =======================================================================
189f85a3 1174// function : initShader
fc73a202 1175// purpose : Creates new shader object with specified source
e276548b 1176// =======================================================================
91c60b57 1177Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1178 const ShaderSource& theSource,
1179 const Handle(OpenGl_Context)& theGlContext)
e276548b 1180{
fc73a202 1181 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
91c60b57 1182 if (!aShader->Create (theGlContext))
e276548b 1183 {
74413ca7 1184 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1185 TCollection_ExtendedString ("Error: Failed to create ") +
1186 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1187 aShader->Release (theGlContext.get());
fc73a202 1188 return Handle(OpenGl_ShaderObject)();
1189 }
e276548b 1190
74413ca7 1191 if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
e276548b 1192 {
74413ca7 1193 aShader->Release (theGlContext.get());
fc73a202 1194 return Handle(OpenGl_ShaderObject)();
1195 }
fc73a202 1196 return aShader;
e276548b 1197}
1198
1199// =======================================================================
189f85a3 1200// function : initProgram
1201// purpose : Creates GLSL program from the given shader objects
1202// =======================================================================
1203Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1204 const Handle(OpenGl_ShaderObject)& theVertShader,
d95f5ce1 1205 const Handle(OpenGl_ShaderObject)& theFragShader,
1206 const TCollection_AsciiString& theName)
189f85a3 1207{
d95f5ce1 1208 const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1209 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
189f85a3 1210
1211 if (!aProgram->Create (theGlContext))
1212 {
1213 theVertShader->Release (theGlContext.operator->());
1214
3b523c4c 1215 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1216 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
189f85a3 1217
1218 return Handle(OpenGl_ShaderProgram)();
1219 }
1220
1221 if (!aProgram->AttachShader (theGlContext, theVertShader)
1222 || !aProgram->AttachShader (theGlContext, theFragShader))
1223 {
1224 theVertShader->Release (theGlContext.operator->());
1225
3b523c4c 1226 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1227 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
189f85a3 1228
1229 return Handle(OpenGl_ShaderProgram)();
1230 }
1231
1232 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1233
1234 TCollection_AsciiString aLinkLog;
1235
1236 if (!aProgram->Link (theGlContext))
1237 {
1238 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1239
1240 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1241 "Failed to link shader program:\n") + aLinkLog;
1242
3b523c4c 1243 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1244 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
189f85a3 1245
1246 return Handle(OpenGl_ShaderProgram)();
1247 }
1248 else if (theGlContext->caps->glslWarnings)
1249 {
47e9c178 1250 aProgram->FetchInfoLog (theGlContext, aLinkLog);
189f85a3 1251 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1252 {
1253 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1254 "Shader program was linked with following warnings:\n") + aLinkLog;
1255
3b523c4c 1256 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1257 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
189f85a3 1258 }
1259 }
1260
1261 return aProgram;
1262}
1263
1264// =======================================================================
1265// function : initRaytraceResources
91c60b57 1266// purpose : Initializes OpenGL/GLSL shader programs
e276548b 1267// =======================================================================
66d1cdc6 1268Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1269 const Standard_Integer theSizeY,
1270 const Handle(OpenGl_Context)& theGlContext)
e276548b 1271{
91c60b57 1272 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1273 {
1274 return Standard_False;
1275 }
265d4508 1276
91c60b57 1277 Standard_Boolean aToRebuildShaders = Standard_False;
265d4508 1278
d877e610 1279 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1280 {
1281 myRaytraceInitStatus = OpenGl_RT_NONE;
1282 releaseRaytraceResources (theGlContext, Standard_True);
1283 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1284 }
1285
91c60b57 1286 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1287 {
1288 if (!myIsRaytraceDataValid)
d877e610 1289 {
91c60b57 1290 return Standard_True;
d877e610 1291 }
07039714 1292
91c60b57 1293 const Standard_Integer aRequiredStackSize =
f2474958 1294 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
e276548b 1295
91c60b57 1296 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1297 {
1298 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
e276548b 1299
fc73a202 1300 aToRebuildShaders = Standard_True;
1301 }
1302 else
1303 {
bc8c79bb 1304 if (aRequiredStackSize < myRaytraceParameters.StackSize)
fc73a202 1305 {
bc8c79bb 1306 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
fc73a202 1307 {
bc8c79bb 1308 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
fc73a202 1309 aToRebuildShaders = Standard_True;
1310 }
1311 }
1312 }
e276548b 1313
b4327ba8 1314 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1315 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1316 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1317 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
66d1cdc6 1318 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
f483f2ed 1319 {
b4327ba8 1320 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1321 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1322 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1323 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
f483f2ed 1324 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
189f85a3 1325 aToRebuildShaders = Standard_True;
1326 }
1327
e084dbbc 1328 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling
1329 || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3a9b5dc8 1330 {
e084dbbc 1331 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1332 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
3a9b5dc8 1333 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1334 {
1335 if (!theGlContext->HasRayTracingAdaptiveSampling())
1336 {
1337 // disable the feature if it is not supported
1338 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1339 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
e084dbbc 1340 "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1341 }
1342 else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1343 && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1344 {
1345 // disable the feature if it is not supported
1346 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1347 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1348 "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
3a9b5dc8 1349 }
1350 }
1351
1352 aToRebuildShaders = Standard_True;
1353 }
66d1cdc6 1354 myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
3a9b5dc8 1355
b27ab03d 1356 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1357 if (myRaytraceParameters.DepthOfField != toEnableDof)
1358 {
1359 myRaytraceParameters.DepthOfField = toEnableDof;
1360 aToRebuildShaders = Standard_True;
1361 }
1362
eb85ed36 1363 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1364 {
1365 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1366 aToRebuildShaders = true;
1367 }
1368
fc73a202 1369 if (aToRebuildShaders)
1370 {
189f85a3 1371 // Reject accumulated frames
1372 myAccumFrames = 0;
e276548b 1373
3a9b5dc8 1374 // Environment map should be updated
91c60b57 1375 myToUpdateEnvironmentMap = Standard_True;
84c71f29 1376
3a9b5dc8 1377 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
bc8c79bb 1378
1379#ifdef RAY_TRACE_PRINT_INFO
1380 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1381#endif
265d4508 1382
bc8c79bb 1383 myRaytraceShaderSource.SetPrefix (aPrefixString);
1384 myPostFSAAShaderSource.SetPrefix (aPrefixString);
3a9b5dc8 1385 myOutImageShaderSource.SetPrefix (aPrefixString);
265d4508 1386
737e9a8d 1387 if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
1388 || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
1389 || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source()))
fc73a202 1390 {
91c60b57 1391 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
fc73a202 1392 }
1393
91c60b57 1394 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1395 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
3a9b5dc8 1396 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1397
91c60b57 1398 if (!myRaytraceProgram->Link (theGlContext)
3a9b5dc8 1399 || !myPostFSAAProgram->Link (theGlContext)
1400 || !myOutImageProgram->Link (theGlContext))
fc73a202 1401 {
91c60b57 1402 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
fc73a202 1403 }
1404 }
e276548b 1405 }
1406
91c60b57 1407 if (myRaytraceInitStatus == OpenGl_RT_NONE)
fc73a202 1408 {
6e728f3b 1409 myAccumFrames = 0; // accumulation should be restarted
d877e610 1410
91c60b57 1411 if (!theGlContext->IsGlGreaterEqual (3, 1))
fc73a202 1412 {
91c60b57 1413 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
25ef750e 1414 }
91c60b57 1415 else if (!theGlContext->arbTboRGB32)
25ef750e 1416 {
91c60b57 1417 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1418 }
1419 else if (!theGlContext->arbFBOBlit)
1420 {
1421 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
fc73a202 1422 }
5322131b 1423
c357e426 1424 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
bc8c79bb 1425
ee5befae 1426 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
fc73a202 1427 if (myIsRaytraceDataValid)
1428 {
bc8c79bb 1429 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
f2474958 1430 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
fc73a202 1431 }
265d4508 1432
3a9b5dc8 1433 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
bc8c79bb 1434
1435#ifdef RAY_TRACE_PRINT_INFO
1436 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1437#endif
1438
73722cc9 1439 ShaderSource aBasicVertShaderSrc;
fc73a202 1440 {
ee5befae 1441 if (!aShaderFolder.IsEmpty())
fc73a202 1442 {
ee5befae 1443 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1444 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1445 {
1446 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1447 }
1448 }
1449 else
1450 {
1451 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1452 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
fc73a202 1453 }
73722cc9 1454 }
265d4508 1455
73722cc9 1456 {
ee5befae 1457 if (!aShaderFolder.IsEmpty())
1458 {
1459 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1460 aShaderFolder + "/PathtraceBase.fs",
1461 aShaderFolder + "/RaytraceRender.fs",
1462 "" };
1463 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1464 {
1465 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1466 }
1467 }
1468 else
73722cc9 1469 {
ee5befae 1470 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1471 Shaders_PathtraceBase_fs,
1472 Shaders_RaytraceRender_fs,
1473 "" };
1474 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
73722cc9 1475 }
e276548b 1476
73722cc9 1477 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1478 if (aBasicVertShader.IsNull())
1479 {
1480 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1481 }
265d4508 1482
91c60b57 1483 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
fc73a202 1484 if (myRaytraceShader.IsNull())
1485 {
91c60b57 1486 aBasicVertShader->Release (theGlContext.operator->());
91c60b57 1487 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
fc73a202 1488 }
265d4508 1489
d95f5ce1 1490 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
189f85a3 1491 if (myRaytraceProgram.IsNull())
fc73a202 1492 {
189f85a3 1493 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
fc73a202 1494 }
1495 }
265d4508 1496
fc73a202 1497 {
ee5befae 1498 if (!aShaderFolder.IsEmpty())
1499 {
1500 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1501 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1502 {
1503 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1504 }
1505 }
1506 else
73722cc9 1507 {
ee5befae 1508 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1509 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
73722cc9 1510 }
265d4508 1511
73722cc9 1512 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
fc73a202 1513 if (aBasicVertShader.IsNull())
1514 {
91c60b57 1515 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
fc73a202 1516 }
265d4508 1517
91c60b57 1518 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
fc73a202 1519 if (myPostFSAAShader.IsNull())
1520 {
91c60b57 1521 aBasicVertShader->Release (theGlContext.operator->());
91c60b57 1522 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
fc73a202 1523 }
265d4508 1524
d95f5ce1 1525 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
189f85a3 1526 if (myPostFSAAProgram.IsNull())
fc73a202 1527 {
189f85a3 1528 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
fc73a202 1529 }
189f85a3 1530 }
fc73a202 1531
189f85a3 1532 {
ee5befae 1533 if (!aShaderFolder.IsEmpty())
1534 {
1535 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1536 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1537 {
1538 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1539 }
1540 }
1541 else
73722cc9 1542 {
ee5befae 1543 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1544 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
73722cc9 1545 }
fc73a202 1546
73722cc9 1547 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
189f85a3 1548 if (aBasicVertShader.IsNull())
1549 {
1550 return safeFailBack ("Failed to set vertex shader source", theGlContext);
fc73a202 1551 }
1552
3a9b5dc8 1553 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1554 if (myOutImageShader.IsNull())
fc73a202 1555 {
189f85a3 1556 aBasicVertShader->Release (theGlContext.operator->());
189f85a3 1557 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
07039714 1558 }
fc73a202 1559
d95f5ce1 1560 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
189f85a3 1561 if (myOutImageProgram.IsNull())
1562 {
3a9b5dc8 1563 return safeFailBack ("Failed to initialize display shader program", theGlContext);
fc73a202 1564 }
e276548b 1565 }
fc73a202 1566 }
e276548b 1567
91c60b57 1568 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
fc73a202 1569 {
1570 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
e276548b 1571 {
fc73a202 1572 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1573 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1574
91c60b57 1575 theGlContext->BindProgram (aShaderProgram);
fc73a202 1576
91c60b57 1577 aShaderProgram->SetSampler (theGlContext,
fc73a202 1578 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
91c60b57 1579 aShaderProgram->SetSampler (theGlContext,
fc73a202 1580 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
91c60b57 1581 aShaderProgram->SetSampler (theGlContext,
fc73a202 1582 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
91c60b57 1583 aShaderProgram->SetSampler (theGlContext,
fc73a202 1584 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
91c60b57 1585 aShaderProgram->SetSampler (theGlContext,
fc73a202 1586 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
91c60b57 1587 aShaderProgram->SetSampler (theGlContext,
25ef750e 1588 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
91c60b57 1589 aShaderProgram->SetSampler (theGlContext,
25ef750e 1590 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
91c60b57 1591 aShaderProgram->SetSampler (theGlContext,
84c71f29 1592 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
91c60b57 1593 aShaderProgram->SetSampler (theGlContext,
84c71f29 1594 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
91c60b57 1595 aShaderProgram->SetSampler (theGlContext,
25ef750e 1596 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
91c60b57 1597 aShaderProgram->SetSampler (theGlContext,
25ef750e 1598 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
fc73a202 1599
1600 if (anIndex == 1)
1601 {
91c60b57 1602 aShaderProgram->SetSampler (theGlContext,
189f85a3 1603 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1604 }
1605 else
1606 {
1607 aShaderProgram->SetSampler (theGlContext,
1608 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
fc73a202 1609 }
265d4508 1610
fc73a202 1611 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
91c60b57 1612 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
fc73a202 1613
1614 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
91c60b57 1615 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
fc73a202 1616 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
91c60b57 1617 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
fc73a202 1618 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
91c60b57 1619 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
fc73a202 1620 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
91c60b57 1621 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
fc73a202 1622 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
91c60b57 1623 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
fc73a202 1624 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
91c60b57 1625 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
fc73a202 1626 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
91c60b57 1627 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
fc73a202 1628 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
91c60b57 1629 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
3a9b5dc8 1630 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1d865689 1631 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
25ef750e 1632 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
91c60b57 1633 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
fc73a202 1634
1635 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
91c60b57 1636 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
fc73a202 1637 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
91c60b57 1638 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
25ef750e 1639 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
91c60b57 1640 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
25ef750e 1641 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
91c60b57 1642 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
fc73a202 1643
1644 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
91c60b57 1645 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
fc73a202 1646 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
91c60b57 1647 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
fc73a202 1648 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
91c60b57 1649 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
84c71f29 1650
189f85a3 1651 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
91c60b57 1652 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
25ef750e 1653
189f85a3 1654 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1655 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1656 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1657 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1658 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1659 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1660 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1661 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
8c820969 1662 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1663 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
189f85a3 1664
3a9b5dc8 1665 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1666 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1667 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1668 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1669
383c6c9f 1670 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1671 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
189f85a3 1672 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1673 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1674
3a9b5dc8 1675 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1676 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
e084dbbc 1677 myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1678 aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
3a9b5dc8 1679 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1680 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
66d1cdc6 1681 myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1682 aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1683 myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1684 aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
3a9b5dc8 1685
189f85a3 1686 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1687 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1688 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1689 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
b09447ed 1690
1691 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1692 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
fc73a202 1693 }
265d4508 1694
189f85a3 1695 theGlContext->BindProgram (myOutImageProgram);
1696
1697 myOutImageProgram->SetSampler (theGlContext,
1698 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1699
1d865689 1700 myOutImageProgram->SetSampler (theGlContext,
3a9b5dc8 1701 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1d865689 1702
91c60b57 1703 theGlContext->BindProgram (NULL);
fc73a202 1704 }
265d4508 1705
91c60b57 1706 if (myRaytraceInitStatus != OpenGl_RT_NONE)
fc73a202 1707 {
91c60b57 1708 return myRaytraceInitStatus == OpenGl_RT_INIT;
fc73a202 1709 }
265d4508 1710
fc73a202 1711 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1712 -1.f, 1.f, 0.f,
1713 1.f, 1.f, 0.f,
1714 1.f, 1.f, 0.f,
1715 1.f, -1.f, 0.f,
1716 -1.f, -1.f, 0.f };
265d4508 1717
91c60b57 1718 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
265d4508 1719
91c60b57 1720 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
ca3c13d1 1721
fc73a202 1722 return Standard_True;
1723}
265d4508 1724
fc73a202 1725// =======================================================================
189f85a3 1726// function : nullifyResource
3a9b5dc8 1727// purpose : Releases OpenGL resource
fc73a202 1728// =======================================================================
aa00364d 1729template <class T>
3a9b5dc8 1730inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
fc73a202 1731{
1732 if (!theResource.IsNull())
1733 {
ad67e367 1734 theResource->Release (theGlContext.get());
fc73a202 1735 theResource.Nullify();
1736 }
1737}
265d4508 1738
fc73a202 1739// =======================================================================
189f85a3 1740// function : releaseRaytraceResources
fc73a202 1741// purpose : Releases OpenGL/GLSL shader programs
1742// =======================================================================
d877e610 1743void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
fc73a202 1744{
d877e610 1745 // release shader resources
189f85a3 1746 nullifyResource (theGlContext, myRaytraceShader);
1747 nullifyResource (theGlContext, myPostFSAAShader);
265d4508 1748
189f85a3 1749 nullifyResource (theGlContext, myRaytraceProgram);
1750 nullifyResource (theGlContext, myPostFSAAProgram);
1751 nullifyResource (theGlContext, myOutImageProgram);
265d4508 1752
d877e610 1753 if (!theToRebuild) // complete release
1754 {
ad67e367 1755 myRaytraceFBO1[0]->Release (theGlContext.get());
1756 myRaytraceFBO1[1]->Release (theGlContext.get());
1757 myRaytraceFBO2[0]->Release (theGlContext.get());
1758 myRaytraceFBO2[1]->Release (theGlContext.get());
d877e610 1759
1760 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1761 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
265d4508 1762
b27ab03d 1763 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1764 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1765 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1766 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
e084dbbc 1767 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1768 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
265d4508 1769
d877e610 1770 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1771 nullifyResource (theGlContext, mySceneMinPointTexture);
1772 nullifyResource (theGlContext, mySceneMaxPointTexture);
265d4508 1773
d877e610 1774 nullifyResource (theGlContext, myGeometryVertexTexture);
1775 nullifyResource (theGlContext, myGeometryNormalTexture);
1776 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1777 nullifyResource (theGlContext, myGeometryTriangTexture);
1778 nullifyResource (theGlContext, mySceneTransformTexture);
47e9c178 1779
d877e610 1780 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1781 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1782
1783 myRaytraceGeometry.ReleaseResources (theGlContext);
1784
1785 if (myRaytraceScreenQuad.IsValid ())
1786 {
ad67e367 1787 myRaytraceScreenQuad.Release (theGlContext.get());
d877e610 1788 }
3a9b5dc8 1789 }
91c60b57 1790}
1791
1792// =======================================================================
bf02aa7d 1793// function : updateRaytraceBuffers
1794// purpose : Updates auxiliary OpenGL frame buffers.
91c60b57 1795// =======================================================================
bf02aa7d 1796Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
91c60b57 1797 const Standard_Integer theSizeY,
1798 const Handle(OpenGl_Context)& theGlContext)
1799{
6dd6e5c7 1800 // Auxiliary buffers are not used
bf02aa7d 1801 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
91c60b57 1802 {
bf02aa7d 1803 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1804 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1805 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1806 myRaytraceFBO2[1]->Release (theGlContext.operator->());
3a9b5dc8 1807
bf02aa7d 1808 return Standard_True;
1809 }
1810
4eaaf9d8 1811 if (myRaytraceParameters.AdaptiveScreenSampling)
6dd6e5c7 1812 {
66d1cdc6 1813 Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1814 myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1815 myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
4eaaf9d8 1816 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1817 {
1818 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1819 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1820 }
bf02aa7d 1821 }
66d1cdc6 1822
1823 for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
bf02aa7d 1824 {
66d1cdc6 1825 if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
4eaaf9d8 1826 {
66d1cdc6 1827 myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1828 myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
e084dbbc 1829 myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
66d1cdc6 1830 myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
4eaaf9d8 1831 }
1832
66d1cdc6 1833 if (aViewIter == 1
1834 && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
4eaaf9d8 1835 {
1836 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1837 myRaytraceFBO2[1]->Release (theGlContext.operator->());
66d1cdc6 1838 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1839 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1840 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1841 continue;
4eaaf9d8 1842 }
3a9b5dc8 1843
66d1cdc6 1844 if (myRaytraceParameters.AdaptiveScreenSampling)
3a9b5dc8 1845 {
66d1cdc6 1846 if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1847 && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1848 && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1849 && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1850 {
e084dbbc 1851 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1852 {
1853 continue; // offsets texture is dynamically resized
1854 }
1855 else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1856 && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1857 {
1858 continue;
1859 }
66d1cdc6 1860 }
b27ab03d 1861
66d1cdc6 1862 myAccumFrames = 0;
b27ab03d 1863
66d1cdc6 1864 // Due to limitations of OpenGL image load-store extension
1865 // atomic operations are supported only for single-channel
1866 // images, so we define GL_R32F image. It is used as array
1867 // of 6D floating point vectors:
1868 // 0 - R color channel
1869 // 1 - G color channel
1870 // 2 - B color channel
1871 // 3 - hit time transformed into OpenGL NDC space
1872 // 4 - luminance accumulated for odd samples only
1873 myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1874
1875 // workaround for some NVIDIA drivers
1876 myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
e084dbbc 1877 myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
ba00aab7 1878 myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
1879 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1880 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1881 Graphic3d_TOT_2D);
e084dbbc 1882 if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1883 {
ba00aab7 1884 myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
1885 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1886 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1887 Graphic3d_TOT_2D);
e084dbbc 1888 }
66d1cdc6 1889 }
1890 else // non-adaptive mode
1891 {
1892 if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1893 || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1894 {
1895 myAccumFrames = 0; // accumulation should be restarted
1896 }
b27ab03d 1897
66d1cdc6 1898 myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1899 myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
3a9b5dc8 1900 }
1901 }
91c60b57 1902 return Standard_True;
1903}
1904
1905// =======================================================================
189f85a3 1906// function : updateCamera
91c60b57 1907// purpose : Generates viewing rays for corners of screen quad
1908// =======================================================================
1909void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1910 const OpenGl_Mat4& theViewMapping,
1911 OpenGl_Vec3* theOrigins,
1912 OpenGl_Vec3* theDirects,
3a9b5dc8 1913 OpenGl_Mat4& theViewPr,
91c60b57 1914 OpenGl_Mat4& theUnview)
1915{
1d865689 1916 // compute view-projection matrix
3a9b5dc8 1917 theViewPr = theViewMapping * theOrientation;
1d865689 1918
1919 // compute inverse view-projection matrix
3a9b5dc8 1920 theViewPr.Inverted (theUnview);
91c60b57 1921
1922 Standard_Integer aOriginIndex = 0;
1923 Standard_Integer aDirectIndex = 0;
1924
1925 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1926 {
1927 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1928 {
1929 OpenGl_Vec4 aOrigin (GLfloat(aX),
1930 GLfloat(aY),
b27ab03d 1931 -1.0f,
91c60b57 1932 1.0f);
1933
1934 aOrigin = theUnview * aOrigin;
1935
1936 aOrigin.x() = aOrigin.x() / aOrigin.w();
1937 aOrigin.y() = aOrigin.y() / aOrigin.w();
1938 aOrigin.z() = aOrigin.z() / aOrigin.w();
1939
1940 OpenGl_Vec4 aDirect (GLfloat(aX),
1941 GLfloat(aY),
1942 1.0f,
1943 1.0f);
1944
1945 aDirect = theUnview * aDirect;
1946
1947 aDirect.x() = aDirect.x() / aDirect.w();
1948 aDirect.y() = aDirect.y() / aDirect.w();
1949 aDirect.z() = aDirect.z() / aDirect.w();
1950
1951 aDirect = aDirect - aOrigin;
1952
91c60b57 1953 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1954 static_cast<GLfloat> (aOrigin.y()),
1955 static_cast<GLfloat> (aOrigin.z()));
1956
b0dc79bc 1957 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1958 static_cast<GLfloat> (aDirect.y()),
1959 static_cast<GLfloat> (aDirect.z()));
91c60b57 1960 }
1961 }
fc73a202 1962}
265d4508 1963
b27ab03d 1964// =======================================================================
1965// function : updatePerspCameraPT
1966// purpose : Generates viewing rays (path tracing, perspective camera)
1967// =======================================================================
1968void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
1969 const OpenGl_Mat4& theViewMapping,
1970 Graphic3d_Camera::Projection theProjection,
1971 OpenGl_Mat4& theViewPr,
1972 OpenGl_Mat4& theUnview,
1973 const int theWinSizeX,
1974 const int theWinSizeY)
1975{
1976 // compute view-projection matrix
1977 theViewPr = theViewMapping * theOrientation;
1978
1979 // compute inverse view-projection matrix
1980 theViewPr.Inverted(theUnview);
1981
1982 // get camera stereo params
1983 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
1984 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
1985 : static_cast<float> (myCamera->IOD());
1986
1987 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
1988 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
1989 : static_cast<float> (myCamera->ZFocus());
1990
1991 // get camera view vectors
1992 const gp_Pnt anOrig = myCamera->Eye();
1993
1994 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
1995 static_cast<float> (anOrig.Y()),
1996 static_cast<float> (anOrig.Z()));
1997
1998 const gp_Dir aView = myCamera->Direction();
1999
2000 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2001 static_cast<float> (aView.Y()),
2002 static_cast<float> (aView.Z()));
2003
2004 const gp_Dir anUp = myCamera->Up();
2005
2006 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2007 static_cast<float> (anUp.Y()),
2008 static_cast<float> (anUp.Z()));
2009
2010 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2011
2012 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2013 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2014
2015 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2016 static_cast<float> (aScaleY));
2017
2018 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2019 {
2020 myEyeView = anEyeViewMono;
2021 }
2022 else // stereo camera
2023 {
2024 // compute z-focus point
2025 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2026
2027 // compute stereo camera shift
2028 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2029 myEyeOrig += myEyeSide.Normalized() * aDx;
2030
2031 // estimate new camera direction vector and correct its length
2032 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2033 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2034 }
2035}
2036
fc73a202 2037// =======================================================================
189f85a3 2038// function : uploadRaytraceData
fc73a202 2039// purpose : Uploads ray-trace data to the GPU
2040// =======================================================================
91c60b57 2041Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
fc73a202 2042{
91c60b57 2043 if (!theGlContext->IsGlGreaterEqual (3, 1))
fc73a202 2044 {
265d4508 2045#ifdef RAY_TRACE_PRINT_INFO
fc73a202 2046 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
265d4508 2047#endif
fc73a202 2048 return Standard_False;
e276548b 2049 }
2050
189f85a3 2051 myAccumFrames = 0; // accumulation should be restarted
2052
25ef750e 2053 /////////////////////////////////////////////////////////////////////////////
2054 // Prepare OpenGL textures
2055
91c60b57 2056 if (theGlContext->arbTexBindless != NULL)
25ef750e 2057 {
2058 // If OpenGL driver supports bindless textures we need
2059 // to get unique 64- bit handles for using on the GPU
91c60b57 2060 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
25ef750e 2061 {
2062#ifdef RAY_TRACE_PRINT_INFO
2063 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2064#endif
2065 return Standard_False;
2066 }
2067 }
2068
265d4508 2069 /////////////////////////////////////////////////////////////////////////////
e2da917a 2070 // Create OpenGL BVH buffers
265d4508 2071
3a9b5dc8 2072 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
e276548b 2073 {
e2da917a 2074 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2075 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2076 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
84c71f29 2077 mySceneTransformTexture = new OpenGl_TextureBufferArb;
265d4508 2078
91c60b57 2079 if (!mySceneNodeInfoTexture->Create (theGlContext)
2080 || !mySceneMinPointTexture->Create (theGlContext)
2081 || !mySceneMaxPointTexture->Create (theGlContext)
2082 || !mySceneTransformTexture->Create (theGlContext))
e276548b 2083 {
fc73a202 2084#ifdef RAY_TRACE_PRINT_INFO
e2da917a 2085 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
fc73a202 2086#endif
2087 return Standard_False;
2088 }
2089 }
5322131b 2090
3a9b5dc8 2091 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
265d4508 2092 {
fc73a202 2093 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2094 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
25ef750e 2095 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
fc73a202 2096 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
e276548b 2097
91c60b57 2098 if (!myGeometryVertexTexture->Create (theGlContext)
2099 || !myGeometryNormalTexture->Create (theGlContext)
2100 || !myGeometryTexCrdTexture->Create (theGlContext)
2101 || !myGeometryTriangTexture->Create (theGlContext))
fc73a202 2102 {
2103#ifdef RAY_TRACE_PRINT_INFO
2104 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2105#endif
2106 return Standard_False;
2107 }
265d4508 2108 }
5322131b 2109
e2da917a 2110 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
fc73a202 2111 {
2112 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
e276548b 2113
91c60b57 2114 if (!myRaytraceMaterialTexture->Create (theGlContext))
fc73a202 2115 {
2116#ifdef RAY_TRACE_PRINT_INFO
2117 std::cout << "Error: Failed to create buffers for material data" << std::endl;
e276548b 2118#endif
fc73a202 2119 return Standard_False;
2120 }
2121 }
e2da917a 2122
84c71f29 2123 /////////////////////////////////////////////////////////////////////////////
2124 // Write transform buffer
2125
2126 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
84c71f29 2127
e2da917a 2128 bool aResult = true;
2129
84c71f29 2130 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2131 {
2132 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2133 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2134
f5b72419 2135 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
84c71f29 2136 Standard_ASSERT_RETURN (aTransform != NULL,
2137 "OpenGl_TriangleSet does not contain transform", Standard_False);
2138
2139 aNodeTransforms[anElemIndex] = aTransform->Inversed();
84c71f29 2140 }
2141
91c60b57 2142 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
84c71f29 2143 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2144
25ef750e 2145 delete [] aNodeTransforms;
84c71f29 2146
2147 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 2148 // Write geometry and bottom-level BVH buffers
84c71f29 2149
fc73a202 2150 Standard_Size aTotalVerticesNb = 0;
2151 Standard_Size aTotalElementsNb = 0;
2152 Standard_Size aTotalBVHNodesNb = 0;
265d4508 2153
fc73a202 2154 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2155 {
2156 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2157 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
265d4508 2158
fc73a202 2159 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2160 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2161
2162 aTotalVerticesNb += aTriangleSet->Vertices.size();
2163 aTotalElementsNb += aTriangleSet->Elements.size();
e276548b 2164
f2474958 2165 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
fc73a202 2166 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
265d4508 2167
f2474958 2168 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
fc73a202 2169 }
e276548b 2170
f2474958 2171 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
e2da917a 2172
fc73a202 2173 if (aTotalBVHNodesNb != 0)
e276548b 2174 {
e2da917a 2175 aResult &= mySceneNodeInfoTexture->Init (
91c60b57 2176 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
e2da917a 2177 aResult &= mySceneMinPointTexture->Init (
91c60b57 2178 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
e2da917a 2179 aResult &= mySceneMaxPointTexture->Init (
91c60b57 2180 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
fc73a202 2181 }
265d4508 2182
fc73a202 2183 if (!aResult)
2184 {
2185#ifdef RAY_TRACE_PRINT_INFO
2186 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2187#endif
2188 return Standard_False;
2189 }
e276548b 2190
fc73a202 2191 if (aTotalElementsNb != 0)
2192 {
25ef750e 2193 aResult &= myGeometryTriangTexture->Init (
91c60b57 2194 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
fc73a202 2195 }
265d4508 2196
fc73a202 2197 if (aTotalVerticesNb != 0)
2198 {
25ef750e 2199 aResult &= myGeometryVertexTexture->Init (
91c60b57 2200 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
25ef750e 2201 aResult &= myGeometryNormalTexture->Init (
91c60b57 2202 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
25ef750e 2203 aResult &= myGeometryTexCrdTexture->Init (
91c60b57 2204 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
fc73a202 2205 }
265d4508 2206
fc73a202 2207 if (!aResult)
2208 {
2209#ifdef RAY_TRACE_PRINT_INFO
2210 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2211#endif
2212 return Standard_False;
2213 }
265d4508 2214
f2474958 2215 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
91c60b57 2216
2217 if (aBVH->Length() > 0)
1e99558f 2218 {
91c60b57 2219 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
1e99558f 2220 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
91c60b57 2221 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
1e99558f 2222 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
91c60b57 2223 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
1e99558f 2224 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2225 }
e2da917a 2226
fc73a202 2227 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2228 {
2229 if (!aBVH->IsOuter (aNodeIdx))
2230 continue;
265d4508 2231
fc73a202 2232 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
e276548b 2233
fc73a202 2234 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2235 "Error: Failed to get triangulation of OpenGL element", Standard_False);
e276548b 2236
e2da917a 2237 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
e276548b 2238
fc73a202 2239 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2240 "Error: Failed to get offset for bottom-level BVH", Standard_False);
e276548b 2241
f2474958 2242 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
265d4508 2243
e2da917a 2244 if (aBvhBuffersSize != 0)
fc73a202 2245 {
91c60b57 2246 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
f2474958 2247 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
91c60b57 2248 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
f2474958 2249 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
91c60b57 2250 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
f2474958 2251 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
91c60b57 2252
fc73a202 2253 if (!aResult)
e276548b 2254 {
fc73a202 2255#ifdef RAY_TRACE_PRINT_INFO
2256 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2257#endif
e276548b 2258 return Standard_False;
2259 }
2260 }
2261
fc73a202 2262 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
265d4508 2263
fc73a202 2264 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2265 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
265d4508 2266
fc73a202 2267 if (!aTriangleSet->Vertices.empty())
2268 {
91c60b57 2269 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2270 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2271 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2272 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2273 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2274 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
fc73a202 2275 }
e276548b 2276
fc73a202 2277 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
265d4508 2278
fc73a202 2279 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2280 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
e276548b 2281
fc73a202 2282 if (!aTriangleSet->Elements.empty())
e276548b 2283 {
91c60b57 2284 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
5cff985a 2285 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
e276548b 2286 }
265d4508 2287
fc73a202 2288 if (!aResult)
2289 {
2290#ifdef RAY_TRACE_PRINT_INFO
2291 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
e276548b 2292#endif
fc73a202 2293 return Standard_False;
2294 }
e276548b 2295 }
e276548b 2296
25ef750e 2297 /////////////////////////////////////////////////////////////////////////////
2298 // Write material buffer
2299
fc73a202 2300 if (myRaytraceGeometry.Materials.size() != 0)
2301 {
91c60b57 2302 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
05aa616d 2303 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
25ef750e 2304
fc73a202 2305 if (!aResult)
2306 {
2307#ifdef RAY_TRACE_PRINT_INFO
2308 std::cout << "Error: Failed to upload material buffer" << std::endl;
2309#endif
2310 return Standard_False;
2311 }
2312 }
e276548b 2313
fc73a202 2314 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
e276548b 2315
fc73a202 2316#ifdef RAY_TRACE_PRINT_INFO
e276548b 2317
f2474958 2318 Standard_ShortReal aMemTrgUsed = 0.f;
2319 Standard_ShortReal aMemBvhUsed = 0.f;
e276548b 2320
fc73a202 2321 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2322 {
f2474958 2323 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
e276548b 2324
f2474958 2325 aMemTrgUsed += static_cast<Standard_ShortReal> (
25ef750e 2326 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
f2474958 2327 aMemTrgUsed += static_cast<Standard_ShortReal> (
25ef750e 2328 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
f2474958 2329 aMemTrgUsed += static_cast<Standard_ShortReal> (
25ef750e 2330 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
f2474958 2331 aMemTrgUsed += static_cast<Standard_ShortReal> (
fc73a202 2332 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
e276548b 2333
f2474958 2334 aMemBvhUsed += static_cast<Standard_ShortReal> (
2335 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2336 aMemBvhUsed += static_cast<Standard_ShortReal> (
2337 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2338 aMemBvhUsed += static_cast<Standard_ShortReal> (
2339 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
fc73a202 2340 }
e276548b 2341
f2474958 2342 aMemBvhUsed += static_cast<Standard_ShortReal> (
2343 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2344 aMemBvhUsed += static_cast<Standard_ShortReal> (
2345 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2346 aMemBvhUsed += static_cast<Standard_ShortReal> (
2347 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
e276548b 2348
f2474958 2349 std::cout << "GPU Memory Used (Mb):\n"
2350 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2351 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
e276548b 2352
fc73a202 2353#endif
e276548b 2354
fc73a202 2355 return aResult;
2356}
e276548b 2357
fc73a202 2358// =======================================================================
189f85a3 2359// function : updateRaytraceLightSources
91c60b57 2360// purpose : Updates 3D scene light sources for ray-tracing
fc73a202 2361// =======================================================================
91c60b57 2362Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
fc73a202 2363{
992ed6b3 2364 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2365 myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
dc89236f 2366 if (myShadingModel != Graphic3d_TOSM_UNLIT
992ed6b3 2367 && !myLights.IsNull())
6e728f3b 2368 {
992ed6b3 2369 const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
2370 myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
91c60b57 2371
6e728f3b 2372 // move positional light sources at the front of the list
992ed6b3 2373 aLightSources.reserve (myLights->Extent());
2374 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2375 aLightIter.More(); aLightIter.Next())
2376 {
2377 const Graphic3d_CLight& aLight = *aLightIter.Value();
2378 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2379 {
2380 aLightSources.push_back (aLightIter.Value());
2381 }
2382 }
2383
2384 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2385 aLightIter.More(); aLightIter.Next())
2386 {
2387 if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2388 {
2389 aLightSources.push_back (aLightIter.Value());
2390 }
2391 }
6e728f3b 2392 }
2393
2394 // get number of 'real' (not ambient) light sources
992ed6b3 2395 const size_t aNbLights = aLightSources.size();
6e728f3b 2396 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
6e728f3b 2397 if (wasUpdated)
2398 {
2399 myRaytraceGeometry.Sources.resize (aNbLights);
2400 }
2401
6e728f3b 2402 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
91c60b57 2403 {
992ed6b3 2404 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2405 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2406 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2407 aLightColor.g() * aLight.Intensity(),
2408 aLightColor.b() * aLight.Intensity(),
6e728f3b 2409 1.0f);
91c60b57 2410
992ed6b3 2411 BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
2412 -aLight.PackedDirection().y(),
2413 -aLight.PackedDirection().z(),
91c60b57 2414 0.0f);
2415
992ed6b3 2416 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
91c60b57 2417 {
992ed6b3 2418 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2419 static_cast<float>(aLight.Position().Y()),
2420 static_cast<float>(aLight.Position().Z()),
91c60b57 2421 1.0f);
189f85a3 2422
6e728f3b 2423 // store smoothing radius in W-component
992ed6b3 2424 aEmission.w() = Max (aLight.Smoothness(), 0.f);
189f85a3 2425 }
2426 else
2427 {
6e728f3b 2428 // store cosine of smoothing angle in W-component
992ed6b3 2429 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
91c60b57 2430 }
2431
992ed6b3 2432 if (aLight.IsHeadlight())
91c60b57 2433 {
2434 aPosition = theInvModelView * aPosition;
2435 }
2436
6e728f3b 2437 for (int aK = 0; aK < 4; ++aK)
2438 {
2439 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2440 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2441 }
2442
2443 if (wasUpdated)
2444 {
2445 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2446 }
2447
2448 ++aRealIdx;
91c60b57 2449 }
2450
6e728f3b 2451 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
91c60b57 2452 {
2453 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
91c60b57 2454 }
189f85a3 2455
6e728f3b 2456 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
fc73a202 2457 {
91c60b57 2458 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2459 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2460 {
2461#ifdef RAY_TRACE_PRINT_INFO
2462 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2463#endif
2464 return Standard_False;
2465 }
e276548b 2466
6e728f3b 2467 myAccumFrames = 0; // accumulation should be restarted
91c60b57 2468 }
e276548b 2469
6e728f3b 2470 return Standard_True;
fc73a202 2471}
2472
25ef750e 2473// =======================================================================
189f85a3 2474// function : setUniformState
25ef750e 2475// purpose : Sets uniform state for the given ray-tracing shader program
2476// =======================================================================
3a9b5dc8 2477Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2478 const Standard_Integer theWinSizeX,
2479 const Standard_Integer theWinSizeY,
b27ab03d 2480 Graphic3d_Camera::Projection theProjection,
91c60b57 2481 const Handle(OpenGl_Context)& theGlContext)
25ef750e 2482{
3a9b5dc8 2483 // Get projection state
2484 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2485
2486 OpenGl_Mat4 aViewPrjMat;
2487 OpenGl_Mat4 anUnviewMat;
2488 OpenGl_Vec3 aOrigins[4];
2489 OpenGl_Vec3 aDirects[4];
2490
b27ab03d 2491 if (myCamera->IsOrthographic()
2492 || !myRenderParams.IsGlobalIlluminationEnabled)
2493 {
2494 updateCamera (myCamera->OrientationMatrixF(),
2495 aCntxProjectionState.Current(),
2496 aOrigins,
2497 aDirects,
2498 aViewPrjMat,
2499 anUnviewMat);
2500 }
2501 else
2502 {
2503 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2504 aCntxProjectionState.Current(),
2505 theProjection,
2506 aViewPrjMat,
2507 anUnviewMat,
2508 theWinSizeX,
2509 theWinSizeY);
2510 }
3a9b5dc8 2511
2512 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2513 ? myRaytraceProgram
2514 : myPostFSAAProgram;
91c60b57 2515
2516 if (theProgram.IsNull())
25ef750e 2517 {
2518 return Standard_False;
2519 }
b27ab03d 2520
2521 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2522 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2523 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2524 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2525 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2526
2527 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2528 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2529
25ef750e 2530 // Set camera state
189f85a3 2531 theProgram->SetUniform (theGlContext,
3a9b5dc8 2532 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
189f85a3 2533 theProgram->SetUniform (theGlContext,
3a9b5dc8 2534 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
189f85a3 2535 theProgram->SetUniform (theGlContext,
3a9b5dc8 2536 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
189f85a3 2537 theProgram->SetUniform (theGlContext,
3a9b5dc8 2538 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
189f85a3 2539 theProgram->SetUniform (theGlContext,
3a9b5dc8 2540 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
189f85a3 2541 theProgram->SetUniform (theGlContext,
3a9b5dc8 2542 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
189f85a3 2543 theProgram->SetUniform (theGlContext,
3a9b5dc8 2544 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
189f85a3 2545 theProgram->SetUniform (theGlContext,
3a9b5dc8 2546 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
1d865689 2547 theProgram->SetUniform (theGlContext,
3a9b5dc8 2548 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
189f85a3 2549 theProgram->SetUniform (theGlContext,
3a9b5dc8 2550 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
312a4043 2551
b09447ed 2552 // Set screen dimensions
2553 myRaytraceProgram->SetUniform (theGlContext,
2554 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2555 myRaytraceProgram->SetUniform (theGlContext,
2556 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2557
2558 // Set 3D scene parameters
189f85a3 2559 theProgram->SetUniform (theGlContext,
91c60b57 2560 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
189f85a3 2561 theProgram->SetUniform (theGlContext,
91c60b57 2562 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
3a9b5dc8 2563
b09447ed 2564 // Set light source parameters
3a9b5dc8 2565 const Standard_Integer aLightSourceBufferSize =
2566 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
b09447ed 2567
189f85a3 2568 theProgram->SetUniform (theGlContext,
91c60b57 2569 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
8c820969 2570
25ef750e 2571 // Set array of 64-bit texture handles
91c60b57 2572 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
25ef750e 2573 {
47e9c178 2574 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2575
189f85a3 2576 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
3a9b5dc8 2577 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
25ef750e 2578 }
2579
ba00aab7 2580 // Set background colors (only vertical gradient background supported)
2581 OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
077a220c 2582 if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2583 && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
25ef750e 2584 {
ba00aab7 2585 aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
2586 aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
67c12d80 2587 }
ba00aab7 2588 aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
2589 aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
2590 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
2591 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
25ef750e 2592
b09447ed 2593 // Set environment map parameters
cc8cbabe 2594 const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2595 || myTextureEnv->IsEmpty()
2596 || !myTextureEnv->First()->IsValid();
2597
6e728f3b 2598 theProgram->SetUniform (theGlContext,
2599 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2600
189f85a3 2601 theProgram->SetUniform (theGlContext,
c357e426 2602 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
189f85a3 2603
b09447ed 2604 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2605 {
2606 theProgram->SetUniform (theGlContext,
2607 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2608
2609 theProgram->SetUniform (theGlContext,
2610 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2611
2612 // Check whether we should restart accumulation for run-time parameters
2613 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2614 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2615 {
2616 myAccumFrames = 0; // accumulation should be restarted
2617
2618 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2619 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2620 }
2621 }
2622 else // RT parameters
2623 {
2624 // Set ambient light source
2625 theProgram->SetUniform (theGlContext,
2626 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2627
2628 // Enable/disable run-time ray-tracing effects
2629 theProgram->SetUniform (theGlContext,
2630 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2631 theProgram->SetUniform (theGlContext,
2632 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2633 }
2634
189f85a3 2635 return Standard_True;
25ef750e 2636}
2637
91c60b57 2638// =======================================================================
189f85a3 2639// function : bindRaytraceTextures
91c60b57 2640// purpose : Binds ray-trace textures to corresponding texture units
2641// =======================================================================
66d1cdc6 2642void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2643 int theStereoView)
91c60b57 2644{
66d1cdc6 2645 if (myRaytraceParameters.AdaptiveScreenSampling
2646 && myRaytraceParameters.GlobalIllumination)
3a9b5dc8 2647 {
2648 #if !defined(GL_ES_VERSION_2_0)
66d1cdc6 2649 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2650 myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2651 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2652 myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
e084dbbc 2653 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2654 {
2655 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2656 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2657 }
2658 else
2659 {
2660 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2661 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2662 }
66d1cdc6 2663 #else
2664 (void )theStereoView;
2665 #endif
3a9b5dc8 2666 }
2667
cc8cbabe 2668 if (!myTextureEnv.IsNull()
2669 && !myTextureEnv->IsEmpty()
2670 && myTextureEnv->First()->IsValid())
6e728f3b 2671 {
cc8cbabe 2672 myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
6e728f3b 2673 }
2674
cc8cbabe 2675 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2676 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2677 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2678 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2679 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2680 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2681 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2682 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2683 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2684 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
91c60b57 2685}
2686
2687// =======================================================================
189f85a3 2688// function : unbindRaytraceTextures
91c60b57 2689// purpose : Unbinds ray-trace textures from corresponding texture units
2690// =======================================================================
2691void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2692{
cc8cbabe 2693 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2694 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2695 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2696 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2697 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2698 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2699 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2700 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2701 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2702 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
91c60b57 2703
91c60b57 2704 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2705}
2706
fc73a202 2707// =======================================================================
189f85a3 2708// function : runRaytraceShaders
fc73a202 2709// purpose : Runs ray-tracing shader programs
2710// =======================================================================
c357e426 2711Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
91c60b57 2712 const Standard_Integer theSizeY,
bf02aa7d 2713 Graphic3d_Camera::Projection theProjection,
38a0206f 2714 OpenGl_FrameBuffer* theReadDrawFbo,
91c60b57 2715 const Handle(OpenGl_Context)& theGlContext)
fc73a202 2716{
3a9b5dc8 2717 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
189f85a3 2718
3a9b5dc8 2719 aResult &= setUniformState (0,
2720 theSizeX,
2721 theSizeY,
b27ab03d 2722 theProjection,
3a9b5dc8 2723 theGlContext);
bf02aa7d 2724
3a9b5dc8 2725 if (myRaytraceParameters.GlobalIllumination) // path tracing
189f85a3 2726 {
66d1cdc6 2727 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
2728 aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
189f85a3 2729 }
3a9b5dc8 2730 else // Whitted-style ray-tracing
fc73a202 2731 {
3a9b5dc8 2732 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
fc73a202 2733 }
2734
3a9b5dc8 2735 return aResult;
2736}
fc73a202 2737
3a9b5dc8 2738// =======================================================================
2739// function : runRaytrace
2740// purpose : Runs Whitted-style ray-tracing
2741// =======================================================================
2742Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2743 const Standard_Integer theSizeY,
2744 Graphic3d_Camera::Projection theProjection,
2745 OpenGl_FrameBuffer* theReadDrawFbo,
2746 const Handle(OpenGl_Context)& theGlContext)
2747{
2748 Standard_Boolean aResult = Standard_True;
fc73a202 2749
3a9b5dc8 2750 // Choose proper set of frame buffers for stereo rendering
66d1cdc6 2751 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2752 bindRaytraceTextures (theGlContext, aFBOIdx);
3a9b5dc8 2753
2754 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2755 {
2756 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2757
2758 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
fc73a202 2759 }
25ef750e 2760
189f85a3 2761 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
fc73a202 2762
3a9b5dc8 2763 if (myRenderParams.IsAntialiasingEnabled)
189f85a3 2764 {
3a9b5dc8 2765 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
1d865689 2766
3a9b5dc8 2767 // bind ray-tracing output image as input
cc8cbabe 2768 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
189f85a3 2769
2770 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2771
3a9b5dc8 2772 aResult &= setUniformState (1 /* FSAA ID */,
2773 theSizeX,
2774 theSizeY,
b27ab03d 2775 theProjection,
189f85a3 2776 theGlContext);
2777
91c60b57 2778 // Perform multi-pass adaptive FSAA using ping-pong technique.
2779 // We use 'FLIPTRI' sampling pattern changing for every pixel
2780 // (3 additional samples per pixel, the 1st sample is already
2781 // available from initial ray-traced image).
2782 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
50d0e1ce 2783 {
91c60b57 2784 GLfloat aOffsetX = 1.f / theSizeX;
2785 GLfloat aOffsetY = 1.f / theSizeY;
50d0e1ce 2786
91c60b57 2787 if (anIt == 1)
2788 {
2789 aOffsetX *= -0.55f;
2790 aOffsetY *= 0.55f;
2791 }
2792 else if (anIt == 2)
2793 {
2794 aOffsetX *= 0.00f;
2795 aOffsetY *= -0.55f;
2796 }
2797 else if (anIt == 3)
2798 {
2799 aOffsetX *= 0.55f;
2800 aOffsetY *= 0.00f;
2801 }
fc73a202 2802
91c60b57 2803 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2804 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2805 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2806 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2807 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2808 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
fc73a202 2809
3a9b5dc8 2810 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2811 ? myRaytraceFBO2[aFBOIdx]
2812 : myRaytraceFBO1[aFBOIdx];
fc73a202 2813
d9e72440 2814 aFramebuffer->BindBuffer (theGlContext);
50d0e1ce 2815
3a9b5dc8 2816 // perform adaptive FSAA pass
91c60b57 2817 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
e276548b 2818
cc8cbabe 2819 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
e276548b 2820 }
d9e72440 2821
66d1cdc6 2822 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2823 const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
d9e72440 2824
3a9b5dc8 2825 glEnable (GL_DEPTH_TEST);
d9e72440 2826
3a9b5dc8 2827 // Display filtered image
d9e72440 2828 theGlContext->BindProgram (myOutImageProgram);
2829
d9e72440 2830 if (theReadDrawFbo != NULL)
2831 {
2832 theReadDrawFbo->BindBuffer (theGlContext);
2833 }
2834 else
2835 {
3a9b5dc8 2836 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
d9e72440 2837 }
2838
cc8cbabe 2839 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2840 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
d9e72440 2841
3a9b5dc8 2842 // copy the output image with depth values
d9e72440 2843 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2844
cc8cbabe 2845 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2846 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
e276548b 2847 }
fc73a202 2848
91c60b57 2849 unbindRaytraceTextures (theGlContext);
a89742cf 2850
91c60b57 2851 theGlContext->BindProgram (NULL);
fc73a202 2852
91c60b57 2853 return aResult;
e276548b 2854}
2855
3a9b5dc8 2856// =======================================================================
2857// function : runPathtrace
2858// purpose : Runs path tracing shader
2859// =======================================================================
4eaaf9d8 2860Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2861 const Standard_Integer theSizeY,
2862 const Graphic3d_Camera::Projection theProjection,
3a9b5dc8 2863 const Handle(OpenGl_Context)& theGlContext)
2864{
6e728f3b 2865 if (myToUpdateEnvironmentMap) // check whether the map was changed
2866 {
2867 myAccumFrames = myToUpdateEnvironmentMap = 0;
2868 }
b27ab03d 2869
2870 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2871 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2872 {
b27ab03d 2873 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2874 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
b27ab03d 2875 myAccumFrames = 0;
2876 }
2877
2878 // Choose proper set of frame buffers for stereo rendering
66d1cdc6 2879 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
6e728f3b 2880
3a9b5dc8 2881 if (myRaytraceParameters.AdaptiveScreenSampling)
2882 {
2883 if (myAccumFrames == 0)
2884 {
2885 myTileSampler.Reset(); // reset tile sampler to its initial state
3a9b5dc8 2886
b27ab03d 2887 // Adaptive sampling is starting at the second frame
e084dbbc 2888 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2889 {
2890 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2891 }
2892 else
2893 {
2894 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2895 }
3a9b5dc8 2896
66d1cdc6 2897 #if !defined(GL_ES_VERSION_2_0)
2898 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2899 #endif
2900 }
b27ab03d 2901
66d1cdc6 2902 // Clear adaptive screen sampling images
2903 #if !defined(GL_ES_VERSION_2_0)
2904 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2905 #endif
2906 }
3a9b5dc8 2907
66d1cdc6 2908 bindRaytraceTextures (theGlContext, aFBOIdx);
3a9b5dc8 2909
66d1cdc6 2910 const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
cc8cbabe 2911 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3a9b5dc8 2912
66d1cdc6 2913 // Set frame accumulation weight
2914 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
3a9b5dc8 2915
66d1cdc6 2916 // Set image uniforms for render program
3a9b5dc8 2917 if (myRaytraceParameters.AdaptiveScreenSampling)
2918 {
66d1cdc6 2919 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
e084dbbc 2920 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage], OpenGl_RT_TileSamplesImage);
66d1cdc6 2921 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2922 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
3a9b5dc8 2923 }
2924
66d1cdc6 2925 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2926 aRenderImageFramebuffer->BindBuffer (theGlContext);
e084dbbc 2927 if (myRaytraceParameters.AdaptiveScreenSampling
2928 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
4eaaf9d8 2929 {
66d1cdc6 2930 // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
2931 // redirected to inner tiles (full tile size) are drawn entirely
2932 const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
2933 glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
4eaaf9d8 2934 }
2935
3a9b5dc8 2936 // Generate for the given RNG seed
66d1cdc6 2937 glDisable (GL_DEPTH_TEST);
3a9b5dc8 2938
e084dbbc 2939 // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
2940 // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
2941 //
2942 // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
2943 // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
2944 // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
2945 //
2946 // Single-pass rendering is more optimal due to smaller amount of draw calls,
2947 // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
2948 // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
2949 // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
2950 const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
2951 && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
2952 ? myTileSampler.MaxTileSamples()
2953 : 1;
2954 if (myAccumFrames == 0)
2955 {
2956 myRNG.SetSeed(); // start RNG from beginning
2957 }
2958 for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
2959 {
2960 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2961 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2962 if (myRaytraceParameters.AdaptiveScreenSampling)
2963 {
2964 #if !defined(GL_ES_VERSION_2_0)
2965 theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
2966 #endif
2967 }
2968 }
66d1cdc6 2969 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2970
e084dbbc 2971 if (myRaytraceParameters.AdaptiveScreenSampling
2972 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
4eaaf9d8 2973 {
66d1cdc6 2974 glViewport (0, 0, theSizeX, theSizeY);
4eaaf9d8 2975 }
66d1cdc6 2976 return true;
2977}
4eaaf9d8 2978
66d1cdc6 2979// =======================================================================
2980// function : runPathtraceOut
2981// purpose :
2982// =======================================================================
2983Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
2984 OpenGl_FrameBuffer* theReadDrawFbo,
2985 const Handle(OpenGl_Context)& theGlContext)
2986{
3a9b5dc8 2987 // Output accumulated path traced image
2988 theGlContext->BindProgram (myOutImageProgram);
2989
66d1cdc6 2990 // Choose proper set of frame buffers for stereo rendering
2991 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2992
3a9b5dc8 2993 if (myRaytraceParameters.AdaptiveScreenSampling)
2994 {
2995 // Set uniforms for display program
66d1cdc6 2996 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
3a9b5dc8 2997 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
66d1cdc6 2998 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
3a9b5dc8 2999 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
66d1cdc6 3000 myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
3001 myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
3a9b5dc8 3002 }
3003
eb85ed36 3004 if (myRaytraceParameters.GlobalIllumination)
3005 {
3006 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3007 switch (myRaytraceParameters.ToneMappingMethod)
3008 {
3009 case Graphic3d_ToneMappingMethod_Disabled:
3010 break;
3011 case Graphic3d_ToneMappingMethod_Filmic:
3012 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3013 break;
3014 }
3015 }
3016
3a9b5dc8 3017 if (theReadDrawFbo != NULL)
3018 {
3019 theReadDrawFbo->BindBuffer (theGlContext);
3020 }
3a9b5dc8 3021
66d1cdc6 3022 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
cc8cbabe 3023 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3a9b5dc8 3024
3a9b5dc8 3025 // Copy accumulated image with correct depth values
66d1cdc6 3026 glEnable (GL_DEPTH_TEST);
3a9b5dc8 3027 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3028
cc8cbabe 3029 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3a9b5dc8 3030
3031 if (myRaytraceParameters.AdaptiveScreenSampling)
3032 {
66d1cdc6 3033 // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3034 myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
e084dbbc 3035 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3036 {
3037 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3038 }
3039 else
3040 {
3041 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3042 }
3a9b5dc8 3043 }
3044
3045 unbindRaytraceTextures (theGlContext);
3a9b5dc8 3046 theGlContext->BindProgram (NULL);
66d1cdc6 3047 return true;
3a9b5dc8 3048}
3049
e276548b 3050// =======================================================================
189f85a3 3051// function : raytrace
fc73a202 3052// purpose : Redraws the window using OpenGL/GLSL ray-tracing
e276548b 3053// =======================================================================
c357e426 3054Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
91c60b57 3055 const Standard_Integer theSizeY,
bf02aa7d 3056 Graphic3d_Camera::Projection theProjection,
38a0206f 3057 OpenGl_FrameBuffer* theReadDrawFbo,
91c60b57 3058 const Handle(OpenGl_Context)& theGlContext)
e276548b 3059{
66d1cdc6 3060 if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
91c60b57 3061 {
e276548b 3062 return Standard_False;
91c60b57 3063 }
3064
bf02aa7d 3065 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
91c60b57 3066 {
3067 return Standard_False;
3068 }
e276548b 3069
3a9b5dc8 3070 OpenGl_Mat4 aLightSourceMatrix;
e276548b 3071
3a9b5dc8 3072 // Get inversed model-view matrix for transforming lights
3073 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
e276548b 3074
3a9b5dc8 3075 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
a89742cf 3076 {
3a9b5dc8 3077 return Standard_False;
a89742cf 3078 }
3079
3a9b5dc8 3080 // Generate image using Whitted-style ray-tracing or path tracing
e276548b 3081 if (myIsRaytraceDataValid)
3082 {
189f85a3 3083 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
fc73a202 3084
91c60b57 3085 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
25ef750e 3086 {
3b523c4c 3087 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3088 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
25ef750e 3089 }
3090
1d865689 3091 glDisable (GL_BLEND);
3a9b5dc8 3092
3093 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3094 theSizeY,
3095 theProjection,
3096 theReadDrawFbo,
3097 theGlContext);
1d865689 3098
91c60b57 3099 if (!aResult)
25ef750e 3100 {
3b523c4c 3101 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3102 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
91c60b57 3103 }
25ef750e 3104
91c60b57 3105 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3106 {
3b523c4c 3107 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3108 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
25ef750e 3109 }
3110
189f85a3 3111 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
e276548b 3112 }
3113
e276548b 3114 return Standard_True;
f8ae3605 3115}