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