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