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