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