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