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