1 // Created on: 2014-03-31
2 // Created by: Danila ULYANOV
3 // Copyright (c) 2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
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
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.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_Layer.hxx>
18 #include <OpenGl_BVHTreeSelector.hxx>
19 #include <OpenGl_Structure.hxx>
20 #include <OpenGl_View.hxx>
21 #include <OpenGl_Workspace.hxx>
22 #include <Graphic3d_GraphicDriver.hxx>
24 // =======================================================================
25 // function : OpenGl_Layer
27 // =======================================================================
28 OpenGl_Layer::OpenGl_Layer (const Standard_Integer theNbPriorities)
29 : myArray (0, theNbPriorities - 1),
31 myBVHIsLeftChildQueuedFirst (Standard_True),
32 myIsBVHPrimitivesNeedsReset (Standard_False)
34 myIsBoundingBoxNeedsReset[0] = myIsBoundingBoxNeedsReset[1] = true;
37 // =======================================================================
38 // function : ~OpenGl_Layer
40 // =======================================================================
41 OpenGl_Layer::~OpenGl_Layer()
46 // =======================================================================
49 // =======================================================================
50 void OpenGl_Layer::Add (const OpenGl_Structure* theStruct,
51 const Standard_Integer thePriority,
52 Standard_Boolean isForChangePriority)
54 const Standard_Integer anIndex = Min (Max (thePriority, 0), myArray.Length() - 1);
55 if (theStruct == NULL)
60 myArray (anIndex).Add (theStruct);
61 if (theStruct->IsAlwaysRendered())
63 theStruct->MarkAsNotCulled();
65 else if (!isForChangePriority)
67 if (theStruct->TransformPersistence.Flags == Graphic3d_TMF_None)
69 myBVHPrimitives.Add (theStruct);
73 myBVHPrimitivesTrsfPers.Add (theStruct);
79 // =======================================================================
82 // =======================================================================
83 bool OpenGl_Layer::Remove (const OpenGl_Structure* theStruct,
84 Standard_Integer& thePriority,
85 Standard_Boolean isForChangePriority)
87 if (theStruct == NULL)
93 const Standard_Integer aNbPriorities = myArray.Length();
94 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
96 OpenGl_IndexedMapOfStructure& aStructures = myArray (aPriorityIter);
98 const Standard_Integer anIndex = aStructures.FindIndex (theStruct);
101 aStructures.Swap (anIndex, aStructures.Size());
102 aStructures.RemoveLast();
104 if (!theStruct->IsAlwaysRendered()
105 && !isForChangePriority)
107 if (!myBVHPrimitives.Remove (theStruct))
109 myBVHPrimitivesTrsfPers.Remove (theStruct);
113 thePriority = aPriorityIter;
122 // =======================================================================
123 // function : InvalidateBVHData
125 // =======================================================================
126 void OpenGl_Layer::InvalidateBVHData() const
128 myIsBVHPrimitivesNeedsReset = Standard_True;
131 // =======================================================================
132 // function : BoundingBox
134 // =======================================================================
135 const Graphic3d_BndBox4f& OpenGl_Layer::BoundingBox (const Standard_Integer theViewId,
136 const Handle(Graphic3d_Camera)& theCamera,
137 const Standard_Integer theWindowWidth,
138 const Standard_Integer theWindowHeight,
139 const Standard_Boolean theToIgnoreInfiniteFlag) const
141 const Standard_Integer aBoxId = theToIgnoreInfiniteFlag == 0 ? 0 : 1;
143 if (myIsBoundingBoxNeedsReset[aBoxId])
145 // Recompute layer bounding box
146 myBoundingBox[aBoxId].Clear();
148 const Standard_Integer aNbPriorities = myArray.Length();
149 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
151 const OpenGl_IndexedMapOfStructure& aStructures = myArray (aPriorityIter);
152 for (Standard_Integer aStructIdx = 1; aStructIdx <= aStructures.Size(); ++aStructIdx)
154 const OpenGl_Structure* aStructure = aStructures.FindKey (aStructIdx);
155 if (!aStructure->IsVisible())
159 else if (!aStructure->ViewAffinity.IsNull()
160 && !aStructure->ViewAffinity->IsVisible (theViewId))
165 // "FitAll" operation ignores object with transform persistence parameter
166 // but adds transform persistence point in a bounding box of layer (only zoom pers. objects).
167 if (aStructure->TransformPersistence.Flags != Graphic3d_TMF_None)
169 if (!theToIgnoreInfiniteFlag && (aStructure->TransformPersistence.Flags & Graphic3d_TMF_ZoomPers))
171 BVH_Vec4f aTPPoint (static_cast<float> (aStructure->TransformPersistence.Point.x()),
172 static_cast<float> (aStructure->TransformPersistence.Point.y()),
173 static_cast<float> (aStructure->TransformPersistence.Point.z()),
176 myBoundingBox[aBoxId].Combine (aTPPoint);
179 // Panning and 2d persistence apply changes to projection or/and its translation components.
180 // It makes them incompatible with z-fitting algorithm. Ignored by now.
181 else if (!theToIgnoreInfiniteFlag
182 || (aStructure->TransformPersistence.Flags & Graphic3d_TMF_2d)
183 || (aStructure->TransformPersistence.Flags & Graphic3d_TMF_PanPers)
184 || (aStructure->TransformPersistence.Flags & Graphic3d_TMF_TriedronPers))
190 Graphic3d_BndBox4f aBox = aStructure->BoundingBox();
192 if (aStructure->IsInfinite
193 && !theToIgnoreInfiniteFlag)
195 const Graphic3d_Vec4 aDiagVec = aBox.CornerMax() - aBox.CornerMin();
196 if (aDiagVec.xyz().SquareModulus() >= 500000.0f * 500000.0f)
198 // bounding borders of infinite line has been calculated as own point in center of this line
199 aBox = Graphic3d_BndBox4f ((aBox.CornerMin() + aBox.CornerMax()) * 0.5f);
203 aBox = Graphic3d_BndBox4f (Graphic3d_Vec4 (ShortRealFirst(), ShortRealFirst(), ShortRealFirst(), 1.0f),
204 Graphic3d_Vec4 (ShortRealLast(), ShortRealLast(), ShortRealLast(), 1.0f));
208 if (aStructure->TransformPersistence.Flags != Graphic3d_TMF_None)
210 const Graphic3d_Mat4& aProjectionMat = theCamera->ProjectionMatrixF();
211 const Graphic3d_Mat4& aWorldViewMat = theCamera->OrientationMatrixF();
213 aStructure->TransformPersistence.Apply (aProjectionMat,
220 // To prevent float overflow at camera parameters calculation and further
221 // rendering, bounding boxes with at least one vertex coordinate out of
222 // float range are skipped by view fit algorithms
223 if (Abs (aBox.CornerMax().x()) >= ShortRealLast()
224 || Abs (aBox.CornerMax().y()) >= ShortRealLast()
225 || Abs (aBox.CornerMax().z()) >= ShortRealLast()
226 || Abs (aBox.CornerMin().x()) >= ShortRealLast()
227 || Abs (aBox.CornerMin().y()) >= ShortRealLast()
228 || Abs (aBox.CornerMin().z()) >= ShortRealLast())
233 myBoundingBox[aBoxId].Combine (aBox);
237 myIsBoundingBoxNeedsReset[aBoxId] = false;
240 return myBoundingBox[aBoxId];
243 // =======================================================================
244 // function : considerZoomPersistenceObjects
246 // =======================================================================
247 Standard_Real OpenGl_Layer::considerZoomPersistenceObjects (const Standard_Integer theViewId,
248 const Handle(Graphic3d_Camera)& theCamera,
249 Standard_Integer theWindowWidth,
250 Standard_Integer theWindowHeight,
251 Standard_Boolean /*theToIgnoreInfiniteFlag*/) const
253 if (NbOfTransformPersistenceObjects() == 0)
258 const Standard_Integer aNbPriorities = myArray.Length();
259 const Graphic3d_Mat4& aProjectionMat = theCamera->ProjectionMatrixF();
260 const Graphic3d_Mat4& aWorldViewMat = theCamera->OrientationMatrixF();
261 Standard_Real aMaxCoef = -std::numeric_limits<double>::max();
263 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
265 const OpenGl_IndexedMapOfStructure& aStructures = myArray (aPriorityIter);
266 for (Standard_Integer aStructIdx = 1; aStructIdx <= aStructures.Size(); ++aStructIdx)
268 OpenGl_Structure* aStructure = const_cast<OpenGl_Structure*> (aStructures.FindKey (aStructIdx));
269 if (!aStructure->IsVisible())
273 else if (!aStructure->ViewAffinity.IsNull()
274 && !aStructure->ViewAffinity->IsVisible (theViewId))
279 if (!(aStructure->TransformPersistence.Flags & Graphic3d_TMF_ZoomPers))
284 Graphic3d_BndBox4f aBox = aStructure->BoundingBox();
285 aStructure->TransformPersistence.Apply (aProjectionMat, aWorldViewMat, theWindowWidth, theWindowHeight, aBox);
287 const BVH_Vec4f& aCornerMin = aBox.CornerMin();
288 const BVH_Vec4f& aCornerMax = aBox.CornerMax();
289 const Standard_Integer aNbOfPoints = 8;
290 const gp_Pnt aPoints[aNbOfPoints] = { gp_Pnt (aCornerMin.x(), aCornerMin.y(), aCornerMin.z()),
291 gp_Pnt (aCornerMin.x(), aCornerMin.y(), aCornerMax.z()),
292 gp_Pnt (aCornerMin.x(), aCornerMax.y(), aCornerMin.z()),
293 gp_Pnt (aCornerMin.x(), aCornerMax.y(), aCornerMax.z()),
294 gp_Pnt (aCornerMax.x(), aCornerMin.y(), aCornerMin.z()),
295 gp_Pnt (aCornerMax.x(), aCornerMin.y(), aCornerMax.z()),
296 gp_Pnt (aCornerMax.x(), aCornerMax.y(), aCornerMin.z()),
297 gp_Pnt (aCornerMax.x(), aCornerMax.y(), aCornerMax.z()) };
298 gp_Pnt aConvertedPoints[aNbOfPoints];
299 Standard_Real aConvertedMinX = std::numeric_limits<double>::max();
300 Standard_Real aConvertedMaxX = -std::numeric_limits<double>::max();
301 Standard_Real aConvertedMinY = std::numeric_limits<double>::max();
302 Standard_Real aConvertedMaxY = -std::numeric_limits<double>::max();
303 for (Standard_Integer anIdx = 0; anIdx < aNbOfPoints; ++anIdx)
305 aConvertedPoints[anIdx] = theCamera->Project (aPoints[anIdx]);
307 aConvertedMinX = Min (aConvertedMinX, aConvertedPoints[anIdx].X());
308 aConvertedMaxX = Max (aConvertedMaxX, aConvertedPoints[anIdx].X());
310 aConvertedMinY = Min (aConvertedMinY, aConvertedPoints[anIdx].Y());
311 aConvertedMaxY = Max (aConvertedMaxY, aConvertedPoints[anIdx].Y());
314 const Standard_Boolean isBigObject = (Abs (aConvertedMaxX - aConvertedMinX) > 2.0) // width of zoom pers. object greater than width of window
315 || (Abs (aConvertedMaxY - aConvertedMinY) > 2.0); // height of zoom pers. object greater than height of window
316 const Standard_Boolean isAlreadyInScreen = (aConvertedMinX > -1.0 && aConvertedMinX < 1.0)
317 && (aConvertedMaxX > -1.0 && aConvertedMaxX < 1.0)
318 && (aConvertedMinY > -1.0 && aConvertedMinY < 1.0)
319 && (aConvertedMaxY > -1.0 && aConvertedMaxY < 1.0);
320 if (isBigObject || isAlreadyInScreen)
325 const gp_Pnt aTPPoint (aStructure->TransformPersistence.Point.x(),
326 aStructure->TransformPersistence.Point.y(),
327 aStructure->TransformPersistence.Point.z());
328 gp_Pnt aConvertedTPPoint = theCamera->Project (aTPPoint);
329 aConvertedTPPoint.SetZ (0.0);
331 if (aConvertedTPPoint.Coord().Modulus() < Precision::Confusion())
336 Standard_Real aShiftX = 0.0;
337 if (aConvertedMinX < -1.0)
339 aShiftX = ((aConvertedMaxX < -1.0) ? (-(1.0 + aConvertedMaxX) + (aConvertedMaxX - aConvertedMinX)) : -(1.0 + aConvertedMinX));
341 else if (aConvertedMaxX > 1.0)
343 aShiftX = ((aConvertedMinX > 1.0) ? ((aConvertedMinX - 1.0) + (aConvertedMaxX - aConvertedMinX)) : (aConvertedMaxX - 1.0));
346 Standard_Real aShiftY = 0.0;
347 if (aConvertedMinY < -1.0)
349 aShiftY = ((aConvertedMaxY < -1.0) ? (-(1.0 + aConvertedMaxY) + (aConvertedMaxY - aConvertedMinY)) : -(1.0 + aConvertedMinY));
351 else if (aConvertedMaxY > 1.0)
353 aShiftY = ((aConvertedMinY > 1.0) ? ((aConvertedMinY - 1.0) + (aConvertedMaxY - aConvertedMinY)) : (aConvertedMaxY - 1.0));
356 const Standard_Real aDifX = Abs (aConvertedTPPoint.X()) - aShiftX;
357 const Standard_Real aDifY = Abs (aConvertedTPPoint.Y()) - aShiftY;
358 if (aDifX > Precision::Confusion())
360 aMaxCoef = Max (aMaxCoef, Abs (aConvertedTPPoint.X()) / aDifX);
362 if (aDifY > Precision::Confusion())
364 aMaxCoef = Max (aMaxCoef, Abs (aConvertedTPPoint.Y()) / aDifY);
369 return (aMaxCoef > 0.0) ? aMaxCoef : 1.0;
372 // =======================================================================
373 // function : renderAll
375 // =======================================================================
376 void OpenGl_Layer::renderAll (const Handle(OpenGl_Workspace)& theWorkspace) const
378 const Standard_Integer aNbPriorities = myArray.Length();
379 const Standard_Integer aViewId = theWorkspace->View()->Identification();
380 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
382 const OpenGl_IndexedMapOfStructure& aStructures = myArray (aPriorityIter);
383 for (Standard_Integer aStructIdx = 1; aStructIdx <= aStructures.Size(); ++aStructIdx)
385 const OpenGl_Structure* aStruct = aStructures.FindKey (aStructIdx);
386 if (!aStruct->IsVisible())
390 else if (!aStruct->ViewAffinity.IsNull()
391 && !aStruct->ViewAffinity->IsVisible (aViewId))
396 aStruct->Render (theWorkspace);
401 // =======================================================================
402 // function : renderTraverse
404 // =======================================================================
405 void OpenGl_Layer::renderTraverse (const Handle(OpenGl_Workspace)& theWorkspace) const
407 if (myIsBVHPrimitivesNeedsReset)
409 myBVHPrimitives.Clear();
410 myBVHPrimitivesTrsfPers.Clear();
411 myIsBVHPrimitivesNeedsReset = Standard_False;
412 for (Standard_Integer aPriorityIdx = 0, aNbPriorities = myArray.Length(); aPriorityIdx < aNbPriorities; ++aPriorityIdx)
414 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (myArray (aPriorityIdx)); aStructIter.More(); aStructIter.Next())
416 const OpenGl_Structure* aStruct = aStructIter.Value();
418 if (aStruct->IsAlwaysRendered())
421 if (aStruct->TransformPersistence.Flags == Graphic3d_TMF_None)
423 myBVHPrimitives.Add (aStruct);
427 myBVHPrimitivesTrsfPers.Add (aStruct);
433 OpenGl_BVHTreeSelector& aSelector = theWorkspace->View()->BVHTreeSelector();
434 traverse (aSelector);
436 const Standard_Integer aNbPriorities = myArray.Length();
437 const Standard_Integer aViewId = theWorkspace->View()->Identification();
438 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
440 const OpenGl_IndexedMapOfStructure& aStructures = myArray (aPriorityIter);
441 for (Standard_Integer aStructIdx = 1; aStructIdx <= aStructures.Size(); ++aStructIdx)
443 const OpenGl_Structure* aStruct = aStructures.FindKey (aStructIdx);
444 if (!aStruct->IsVisible()
445 || aStruct->IsCulled())
449 else if (!aStruct->ViewAffinity.IsNull()
450 && !aStruct->ViewAffinity->IsVisible (aViewId))
455 aStruct->Render (theWorkspace);
456 aStruct->ResetCullingStatus();
461 // =======================================================================
462 // function : traverse
464 // =======================================================================
465 void OpenGl_Layer::traverse (OpenGl_BVHTreeSelector& theSelector) const
467 // handle a case when all objects are infinite
468 if (myBVHPrimitives .Size() == 0
469 && myBVHPrimitivesTrsfPers.Size() == 0)
472 theSelector.CacheClipPtsProjections();
474 NCollection_Handle<BVH_Tree<Standard_ShortReal, 4> > aBVHTree;
476 for (Standard_Integer aBVHTreeIdx = 0; aBVHTreeIdx < 2; ++aBVHTreeIdx)
478 const Standard_Boolean isTrsfPers = aBVHTreeIdx == 1;
481 if (myBVHPrimitivesTrsfPers.Size() == 0)
484 const OpenGl_Mat4& aProjection = theSelector.ProjectionMatrix();
485 const OpenGl_Mat4& aWorldView = theSelector.WorldViewMatrix();
486 const Graphic3d_WorldViewProjState& aWVPState = theSelector.WorldViewProjState();
487 const Standard_Integer aViewportWidth = theSelector.ViewportWidth();
488 const Standard_Integer aViewportHeight = theSelector.ViewportHeight();
490 aBVHTree = myBVHPrimitivesTrsfPers.BVH (aProjection, aWorldView, aViewportWidth, aViewportHeight, aWVPState);
494 if (myBVHPrimitives.Size() == 0)
497 aBVHTree = myBVHPrimitives.BVH();
500 Standard_Integer aNode = 0; // a root node
502 if (!theSelector.Intersect (aBVHTree->MinPoint (0),
503 aBVHTree->MaxPoint (0)))
508 Standard_Integer aStack[32];
509 Standard_Integer aHead = -1;
512 if (!aBVHTree->IsOuter (aNode))
514 const Standard_Integer aLeftChildIdx = aBVHTree->Child<0> (aNode);
515 const Standard_Integer aRightChildIdx = aBVHTree->Child<1> (aNode);
516 const Standard_Boolean isLeftChildIn = theSelector.Intersect (aBVHTree->MinPoint (aLeftChildIdx),
517 aBVHTree->MaxPoint (aLeftChildIdx));
518 const Standard_Boolean isRightChildIn = theSelector.Intersect (aBVHTree->MinPoint (aRightChildIdx),
519 aBVHTree->MaxPoint (aRightChildIdx));
523 aNode = myBVHIsLeftChildQueuedFirst ? aLeftChildIdx : aRightChildIdx;
524 aStack[++aHead] = myBVHIsLeftChildQueuedFirst ? aRightChildIdx : aLeftChildIdx;
525 myBVHIsLeftChildQueuedFirst = !myBVHIsLeftChildQueuedFirst;
527 else if (isLeftChildIn
530 aNode = isLeftChildIn ? aLeftChildIdx : aRightChildIdx;
539 aNode = aStack[aHead--];
544 Standard_Integer aIdx = aBVHTree->BegPrimitive (aNode);
545 const OpenGl_Structure* aStruct =
546 isTrsfPers ? myBVHPrimitivesTrsfPers.GetStructureById (aIdx)
547 : myBVHPrimitives.GetStructureById (aIdx);
548 aStruct->MarkAsNotCulled();
554 aNode = aStack[aHead--];
560 // =======================================================================
563 // =======================================================================
564 Standard_Boolean OpenGl_Layer::Append (const OpenGl_Layer& theOther)
566 // the source priority list shouldn't have more priorities
567 const Standard_Integer aNbPriorities = theOther.NbPriorities();
568 if (aNbPriorities > NbPriorities())
570 return Standard_False;
573 // add all structures to destination priority list
574 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
576 const OpenGl_IndexedMapOfStructure& aStructures = theOther.myArray (aPriorityIter);
577 for (Standard_Integer aStructIdx = 1; aStructIdx <= aStructures.Size(); ++aStructIdx)
579 Add (aStructures.FindKey (aStructIdx), aPriorityIter);
583 return Standard_True;
586 //=======================================================================
589 //=======================================================================
590 void OpenGl_Layer::Render (const Handle(OpenGl_Workspace)& theWorkspace,
591 const OpenGl_GlobalLayerSettings& theDefaultSettings) const
593 TEL_POFFSET_PARAM anAppliedOffsetParams = theWorkspace->AppliedPolygonOffset();
595 // separate depth buffers
596 if (IsSettingEnabled (Graphic3d_ZLayerDepthClear))
598 glClear (GL_DEPTH_BUFFER_BIT);
602 if (IsSettingEnabled (Graphic3d_ZLayerDepthTest))
604 // assuming depth test is enabled by default
605 glDepthFunc (theDefaultSettings.DepthFunc);
609 glDepthFunc (GL_ALWAYS);
612 // save environment texture
613 Handle(OpenGl_Texture) anEnvironmentTexture = theWorkspace->EnvironmentTexture();
614 if (!myLayerSettings.UseEnvironmentTexture)
616 theWorkspace->SetEnvironmentTexture (Handle(OpenGl_Texture)());
619 // handle depth offset
620 if (IsSettingEnabled (Graphic3d_ZLayerDepthOffset))
622 theWorkspace->SetPolygonOffset (Aspect_POM_Fill,
623 myLayerSettings.DepthOffsetFactor,
624 myLayerSettings.DepthOffsetUnits);
628 theWorkspace->SetPolygonOffset (anAppliedOffsetParams.mode,
629 anAppliedOffsetParams.factor,
630 anAppliedOffsetParams.units);
633 // handle depth write
634 theWorkspace->UseDepthWrite() = IsSettingEnabled (Graphic3d_ZLayerDepthWrite);
635 glDepthMask (theWorkspace->UseDepthWrite() ? GL_TRUE : GL_FALSE);
637 // render priority list
638 theWorkspace->IsCullingEnabled() ? renderTraverse (theWorkspace) : renderAll (theWorkspace);
640 // always restore polygon offset between layers rendering
641 theWorkspace->SetPolygonOffset (anAppliedOffsetParams.mode,
642 anAppliedOffsetParams.factor,
643 anAppliedOffsetParams.units);
645 // restore environment texture
646 if (!myLayerSettings.UseEnvironmentTexture)
648 theWorkspace->SetEnvironmentTexture (anEnvironmentTexture);