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