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