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