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