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