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_ShaderManager.hxx>
21 #include <OpenGl_View.hxx>
22 #include <OpenGl_Workspace.hxx>
23 #include <Graphic3d_GraphicDriver.hxx>
25 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Layer, Standard_Transient)
27 // =======================================================================
28 // function : OpenGl_Layer
30 // =======================================================================
31 OpenGl_Layer::OpenGl_Layer (const Standard_Integer theNbPriorities,
32 const Handle(Select3D_BVHBuilder3d)& theBuilder)
33 : myArray (0, theNbPriorities - 1),
35 myBVHPrimitivesTrsfPers (theBuilder),
36 myBVHIsLeftChildQueuedFirst (Standard_True),
37 myIsBVHPrimitivesNeedsReset (Standard_False)
39 myIsBoundingBoxNeedsReset[0] = myIsBoundingBoxNeedsReset[1] = true;
42 // =======================================================================
43 // function : ~OpenGl_Layer
45 // =======================================================================
46 OpenGl_Layer::~OpenGl_Layer()
51 // =======================================================================
54 // =======================================================================
55 void OpenGl_Layer::Add (const OpenGl_Structure* theStruct,
56 const Standard_Integer thePriority,
57 Standard_Boolean isForChangePriority)
59 const Standard_Integer anIndex = Min (Max (thePriority, 0), myArray.Length() - 1);
60 if (theStruct == NULL)
65 myArray (anIndex).Add (theStruct);
66 if (theStruct->IsAlwaysRendered())
68 theStruct->MarkAsNotCulled();
69 if (!isForChangePriority)
71 myAlwaysRenderedMap.Add (theStruct);
74 else if (!isForChangePriority)
76 if (theStruct->TransformPersistence().IsNull())
78 myBVHPrimitives.Add (theStruct);
82 myBVHPrimitivesTrsfPers.Add (theStruct);
88 // =======================================================================
91 // =======================================================================
92 bool OpenGl_Layer::Remove (const OpenGl_Structure* theStruct,
93 Standard_Integer& thePriority,
94 Standard_Boolean isForChangePriority)
96 if (theStruct == NULL)
102 const Standard_Integer aNbPriorities = myArray.Length();
103 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
105 OpenGl_IndexedMapOfStructure& aStructures = myArray (aPriorityIter);
107 const Standard_Integer anIndex = aStructures.FindIndex (theStruct);
110 aStructures.Swap (anIndex, aStructures.Size());
111 aStructures.RemoveLast();
113 if (!isForChangePriority)
115 Standard_Boolean isAlwaysRend = theStruct->IsAlwaysRendered();
118 if (!myBVHPrimitives.Remove (theStruct))
120 if (!myBVHPrimitivesTrsfPers.Remove (theStruct))
122 isAlwaysRend = Standard_True;
128 const Standard_Integer anIndex2 = myAlwaysRenderedMap.FindIndex (theStruct);
131 myAlwaysRenderedMap.Swap (myAlwaysRenderedMap.Size(), anIndex2);
132 myAlwaysRenderedMap.RemoveLast();
137 thePriority = aPriorityIter;
146 // =======================================================================
147 // function : InvalidateBVHData
149 // =======================================================================
150 void OpenGl_Layer::InvalidateBVHData() const
152 myIsBVHPrimitivesNeedsReset = Standard_True;
155 //! Calculate a finite bounding box of infinite object as its middle point.
156 inline Graphic3d_BndBox3d centerOfinfiniteBndBox (const Graphic3d_BndBox3d& theBndBox)
158 // bounding borders of infinite line has been calculated as own point in center of this line
159 const Graphic3d_Vec3d aDiagVec = theBndBox.CornerMax() - theBndBox.CornerMin();
160 return aDiagVec.SquareModulus() >= 500000.0 * 500000.0
161 ? Graphic3d_BndBox3d ((theBndBox.CornerMin() + theBndBox.CornerMax()) * 0.5)
162 : Graphic3d_BndBox3d();
165 //! Return true if at least one vertex coordinate out of float range.
166 inline bool isInfiniteBndBox (const Graphic3d_BndBox3d& theBndBox)
168 return Abs (theBndBox.CornerMax().x()) >= ShortRealLast()
169 || Abs (theBndBox.CornerMax().y()) >= ShortRealLast()
170 || Abs (theBndBox.CornerMax().z()) >= ShortRealLast()
171 || Abs (theBndBox.CornerMin().x()) >= ShortRealLast()
172 || Abs (theBndBox.CornerMin().y()) >= ShortRealLast()
173 || Abs (theBndBox.CornerMin().z()) >= ShortRealLast();
176 // =======================================================================
177 // function : BoundingBox
179 // =======================================================================
180 Bnd_Box OpenGl_Layer::BoundingBox (const Standard_Integer theViewId,
181 const Handle(Graphic3d_Camera)& theCamera,
182 const Standard_Integer theWindowWidth,
183 const Standard_Integer theWindowHeight,
184 const Standard_Boolean theToIncludeAuxiliary) const
188 const Standard_Integer aBoxId = !theToIncludeAuxiliary ? 0 : 1;
189 const Graphic3d_Mat4d& aProjectionMat = theCamera->ProjectionMatrix();
190 const Graphic3d_Mat4d& aWorldViewMat = theCamera->OrientationMatrix();
191 if (myIsBoundingBoxNeedsReset[aBoxId])
193 // Recompute layer bounding box
194 myBoundingBox[aBoxId].SetVoid();
196 for (OpenGl_ArrayOfIndexedMapOfStructure::Iterator aMapIter (myArray); aMapIter.More(); aMapIter.Next())
198 const OpenGl_IndexedMapOfStructure& aStructures = aMapIter.Value();
199 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (aStructures); aStructIter.More(); aStructIter.Next())
201 const OpenGl_Structure* aStructure = aStructIter.Value();
202 if (!aStructure->IsVisible (theViewId))
207 // "FitAll" operation ignores object with transform persistence parameter
208 // but adds transform persistence point in a bounding box of layer (only zoom pers. objects).
209 if (!aStructure->TransformPersistence().IsNull())
211 if (!theToIncludeAuxiliary
212 && aStructure->TransformPersistence()->IsZoomOrRotate())
214 const gp_Pnt anAnchor = aStructure->TransformPersistence()->AnchorPoint();
215 myBoundingBox[aBoxId].Add (anAnchor);
218 // Panning and 2d persistence apply changes to projection or/and its translation components.
219 // It makes them incompatible with z-fitting algorithm. Ignored by now.
220 else if (!theToIncludeAuxiliary
221 || aStructure->TransformPersistence()->IsTrihedronOr2d())
227 Graphic3d_BndBox3d aBox = aStructure->BoundingBox();
233 if (aStructure->IsInfinite
234 && !theToIncludeAuxiliary)
236 // include center of infinite object
237 aBox = centerOfinfiniteBndBox (aBox);
240 if (!aStructure->TransformPersistence().IsNull())
242 aStructure->TransformPersistence()->Apply (theCamera, aProjectionMat, aWorldViewMat, theWindowWidth, theWindowHeight, aBox);
245 // skip too big boxes to prevent float overflow at camera parameters calculation
247 && !isInfiniteBndBox (aBox))
249 myBoundingBox[aBoxId].Add (gp_Pnt (aBox.CornerMin().x(), aBox.CornerMin().y(), aBox.CornerMin().z()));
250 myBoundingBox[aBoxId].Add (gp_Pnt (aBox.CornerMax().x(), aBox.CornerMax().y(), aBox.CornerMax().z()));
255 myIsBoundingBoxNeedsReset[aBoxId] = false;
258 Bnd_Box aResBox = myBoundingBox[aBoxId];
259 if (!theToIncludeAuxiliary
260 || myAlwaysRenderedMap.IsEmpty())
265 // add transformation-persistent objects which depend on camera position (and thus can not be cached) for operations like Z-fit
266 for (NCollection_IndexedMap<const OpenGl_Structure*>::Iterator aStructIter (myAlwaysRenderedMap); aStructIter.More(); aStructIter.Next())
268 const OpenGl_Structure* aStructure = aStructIter.Value();
269 if (!aStructure->IsVisible (theViewId))
273 else if (aStructure->TransformPersistence().IsNull()
274 || !aStructure->TransformPersistence()->IsTrihedronOr2d())
279 Graphic3d_BndBox3d aBox = aStructure->BoundingBox();
285 aStructure->TransformPersistence()->Apply (theCamera, aProjectionMat, aWorldViewMat, theWindowWidth, theWindowHeight, aBox);
287 && !isInfiniteBndBox (aBox))
289 aResBox.Add (gp_Pnt (aBox.CornerMin().x(), aBox.CornerMin().y(), aBox.CornerMin().z()));
290 aResBox.Add (gp_Pnt (aBox.CornerMax().x(), aBox.CornerMax().y(), aBox.CornerMax().z()));
297 // =======================================================================
298 // function : considerZoomPersistenceObjects
300 // =======================================================================
301 Standard_Real OpenGl_Layer::considerZoomPersistenceObjects (const Standard_Integer theViewId,
302 const Handle(Graphic3d_Camera)& theCamera,
303 Standard_Integer theWindowWidth,
304 Standard_Integer theWindowHeight) const
306 if (NbOfTransformPersistenceObjects() == 0)
311 const Graphic3d_Mat4d& aProjectionMat = theCamera->ProjectionMatrix();
312 const Graphic3d_Mat4d& aWorldViewMat = theCamera->OrientationMatrix();
313 Standard_Real aMaxCoef = -std::numeric_limits<double>::max();
315 for (OpenGl_ArrayOfIndexedMapOfStructure::Iterator aMapIter (myArray); aMapIter.More(); aMapIter.Next())
317 const OpenGl_IndexedMapOfStructure& aStructures = aMapIter.Value();
318 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (aStructures); aStructIter.More(); aStructIter.Next())
320 const OpenGl_Structure* aStructure = aStructIter.Value();
321 if (!aStructure->IsVisible (theViewId)
322 || aStructure->TransformPersistence().IsNull()
323 || !aStructure->TransformPersistence()->IsZoomOrRotate())
328 Graphic3d_BndBox3d aBox = aStructure->BoundingBox();
334 aStructure->TransformPersistence()->Apply (theCamera, aProjectionMat, aWorldViewMat, theWindowWidth, theWindowHeight, aBox);
336 const BVH_Vec3d& aCornerMin = aBox.CornerMin();
337 const BVH_Vec3d& aCornerMax = aBox.CornerMax();
338 const Standard_Integer aNbOfPoints = 8;
339 const gp_Pnt aPoints[aNbOfPoints] = { gp_Pnt (aCornerMin.x(), aCornerMin.y(), aCornerMin.z()),
340 gp_Pnt (aCornerMin.x(), aCornerMin.y(), aCornerMax.z()),
341 gp_Pnt (aCornerMin.x(), aCornerMax.y(), aCornerMin.z()),
342 gp_Pnt (aCornerMin.x(), aCornerMax.y(), aCornerMax.z()),
343 gp_Pnt (aCornerMax.x(), aCornerMin.y(), aCornerMin.z()),
344 gp_Pnt (aCornerMax.x(), aCornerMin.y(), aCornerMax.z()),
345 gp_Pnt (aCornerMax.x(), aCornerMax.y(), aCornerMin.z()),
346 gp_Pnt (aCornerMax.x(), aCornerMax.y(), aCornerMax.z()) };
347 gp_Pnt aConvertedPoints[aNbOfPoints];
348 Standard_Real aConvertedMinX = std::numeric_limits<double>::max();
349 Standard_Real aConvertedMaxX = -std::numeric_limits<double>::max();
350 Standard_Real aConvertedMinY = std::numeric_limits<double>::max();
351 Standard_Real aConvertedMaxY = -std::numeric_limits<double>::max();
352 for (Standard_Integer anIdx = 0; anIdx < aNbOfPoints; ++anIdx)
354 aConvertedPoints[anIdx] = theCamera->Project (aPoints[anIdx]);
356 aConvertedMinX = Min (aConvertedMinX, aConvertedPoints[anIdx].X());
357 aConvertedMaxX = Max (aConvertedMaxX, aConvertedPoints[anIdx].X());
359 aConvertedMinY = Min (aConvertedMinY, aConvertedPoints[anIdx].Y());
360 aConvertedMaxY = Max (aConvertedMaxY, aConvertedPoints[anIdx].Y());
363 const Standard_Boolean isBigObject = (Abs (aConvertedMaxX - aConvertedMinX) > 2.0) // width of zoom pers. object greater than width of window
364 || (Abs (aConvertedMaxY - aConvertedMinY) > 2.0); // height of zoom pers. object greater than height of window
365 const Standard_Boolean isAlreadyInScreen = (aConvertedMinX > -1.0 && aConvertedMinX < 1.0)
366 && (aConvertedMaxX > -1.0 && aConvertedMaxX < 1.0)
367 && (aConvertedMinY > -1.0 && aConvertedMinY < 1.0)
368 && (aConvertedMaxY > -1.0 && aConvertedMaxY < 1.0);
369 if (isBigObject || isAlreadyInScreen)
374 const gp_Pnt aTPPoint = aStructure->TransformPersistence()->AnchorPoint();
375 gp_Pnt aConvertedTPPoint = theCamera->Project (aTPPoint);
376 aConvertedTPPoint.SetZ (0.0);
378 if (aConvertedTPPoint.Coord().Modulus() < Precision::Confusion())
383 Standard_Real aShiftX = 0.0;
384 if (aConvertedMinX < -1.0)
386 aShiftX = ((aConvertedMaxX < -1.0) ? (-(1.0 + aConvertedMaxX) + (aConvertedMaxX - aConvertedMinX)) : -(1.0 + aConvertedMinX));
388 else if (aConvertedMaxX > 1.0)
390 aShiftX = ((aConvertedMinX > 1.0) ? ((aConvertedMinX - 1.0) + (aConvertedMaxX - aConvertedMinX)) : (aConvertedMaxX - 1.0));
393 Standard_Real aShiftY = 0.0;
394 if (aConvertedMinY < -1.0)
396 aShiftY = ((aConvertedMaxY < -1.0) ? (-(1.0 + aConvertedMaxY) + (aConvertedMaxY - aConvertedMinY)) : -(1.0 + aConvertedMinY));
398 else if (aConvertedMaxY > 1.0)
400 aShiftY = ((aConvertedMinY > 1.0) ? ((aConvertedMinY - 1.0) + (aConvertedMaxY - aConvertedMinY)) : (aConvertedMaxY - 1.0));
403 const Standard_Real aDifX = Abs (aConvertedTPPoint.X()) - aShiftX;
404 const Standard_Real aDifY = Abs (aConvertedTPPoint.Y()) - aShiftY;
405 if (aDifX > Precision::Confusion())
407 aMaxCoef = Max (aMaxCoef, Abs (aConvertedTPPoint.X()) / aDifX);
409 if (aDifY > Precision::Confusion())
411 aMaxCoef = Max (aMaxCoef, Abs (aConvertedTPPoint.Y()) / aDifY);
416 return (aMaxCoef > 0.0) ? aMaxCoef : 1.0;
419 // =======================================================================
420 // function : renderAll
422 // =======================================================================
423 void OpenGl_Layer::renderAll (const Handle(OpenGl_Workspace)& theWorkspace) const
425 const Standard_Integer aViewId = theWorkspace->View()->Identification();
426 for (OpenGl_ArrayOfIndexedMapOfStructure::Iterator aMapIter (myArray); aMapIter.More(); aMapIter.Next())
428 const OpenGl_IndexedMapOfStructure& aStructures = aMapIter.Value();
429 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (aStructures); aStructIter.More(); aStructIter.Next())
431 const OpenGl_Structure* aStruct = aStructIter.Value();
432 if (!aStruct->IsVisible())
436 else if (!aStruct->ViewAffinity.IsNull()
437 && !aStruct->ViewAffinity->IsVisible (aViewId))
442 aStruct->Render (theWorkspace);
447 // =======================================================================
448 // function : updateBVH
450 // =======================================================================
451 void OpenGl_Layer::updateBVH() const
453 if (!myIsBVHPrimitivesNeedsReset)
458 myBVHPrimitives.Clear();
459 myBVHPrimitivesTrsfPers.Clear();
460 myAlwaysRenderedMap.Clear();
461 myIsBVHPrimitivesNeedsReset = Standard_False;
462 for (OpenGl_ArrayOfIndexedMapOfStructure::Iterator aMapIter (myArray); aMapIter.More(); aMapIter.Next())
464 const OpenGl_IndexedMapOfStructure& aStructures = aMapIter.Value();
465 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (aStructures); aStructIter.More(); aStructIter.Next())
467 const OpenGl_Structure* aStruct = aStructIter.Value();
468 if (aStruct->IsAlwaysRendered())
470 aStruct->MarkAsNotCulled();
471 myAlwaysRenderedMap.Add (aStruct);
473 else if (aStruct->TransformPersistence().IsNull())
475 myBVHPrimitives.Add (aStruct);
479 myBVHPrimitivesTrsfPers.Add (aStruct);
485 // =======================================================================
486 // function : renderTraverse
488 // =======================================================================
489 void OpenGl_Layer::renderTraverse (const Handle(OpenGl_Workspace)& theWorkspace) const
493 OpenGl_BVHTreeSelector& aSelector = theWorkspace->View()->BVHTreeSelector();
494 traverse (aSelector);
496 const Standard_Integer aViewId = theWorkspace->View()->Identification();
497 for (OpenGl_ArrayOfIndexedMapOfStructure::Iterator aMapIter (myArray); aMapIter.More(); aMapIter.Next())
499 const OpenGl_IndexedMapOfStructure& aStructures = aMapIter.Value();
500 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (aStructures); aStructIter.More(); aStructIter.Next())
502 const OpenGl_Structure* aStruct = aStructIter.Value();
503 if (aStruct->IsCulled()
504 || !aStruct->IsVisible (aViewId))
509 aStruct->Render (theWorkspace);
510 aStruct->ResetCullingStatus();
515 // =======================================================================
516 // function : traverse
518 // =======================================================================
519 void OpenGl_Layer::traverse (OpenGl_BVHTreeSelector& theSelector) const
521 // handle a case when all objects are infinite
522 if (myBVHPrimitives .Size() == 0
523 && myBVHPrimitivesTrsfPers.Size() == 0)
526 theSelector.CacheClipPtsProjections();
528 opencascade::handle<BVH_Tree<Standard_Real, 3> > aBVHTree;
529 for (Standard_Integer aBVHTreeIdx = 0; aBVHTreeIdx < 2; ++aBVHTreeIdx)
531 const Standard_Boolean isTrsfPers = aBVHTreeIdx == 1;
534 if (myBVHPrimitivesTrsfPers.Size() == 0)
537 const OpenGl_Mat4d& aProjection = theSelector.ProjectionMatrix();
538 const OpenGl_Mat4d& aWorldView = theSelector.WorldViewMatrix();
539 const Graphic3d_WorldViewProjState& aWVPState = theSelector.WorldViewProjState();
540 const Standard_Integer aViewportWidth = theSelector.ViewportWidth();
541 const Standard_Integer aViewportHeight = theSelector.ViewportHeight();
543 aBVHTree = myBVHPrimitivesTrsfPers.BVH (theSelector.Camera(), aProjection, aWorldView, aViewportWidth, aViewportHeight, aWVPState);
547 if (myBVHPrimitives.Size() == 0)
550 aBVHTree = myBVHPrimitives.BVH();
553 Standard_Integer aNode = 0; // a root node
555 if (!theSelector.Intersect (aBVHTree->MinPoint (0),
556 aBVHTree->MaxPoint (0)))
561 Standard_Integer aStack[BVH_Constants_MaxTreeDepth];
562 Standard_Integer aHead = -1;
565 if (!aBVHTree->IsOuter (aNode))
567 const Standard_Integer aLeftChildIdx = aBVHTree->Child<0> (aNode);
568 const Standard_Integer aRightChildIdx = aBVHTree->Child<1> (aNode);
569 const Standard_Boolean isLeftChildIn = theSelector.Intersect (aBVHTree->MinPoint (aLeftChildIdx),
570 aBVHTree->MaxPoint (aLeftChildIdx));
571 const Standard_Boolean isRightChildIn = theSelector.Intersect (aBVHTree->MinPoint (aRightChildIdx),
572 aBVHTree->MaxPoint (aRightChildIdx));
576 aNode = myBVHIsLeftChildQueuedFirst ? aLeftChildIdx : aRightChildIdx;
577 aStack[++aHead] = myBVHIsLeftChildQueuedFirst ? aRightChildIdx : aLeftChildIdx;
578 myBVHIsLeftChildQueuedFirst = !myBVHIsLeftChildQueuedFirst;
580 else if (isLeftChildIn
583 aNode = isLeftChildIn ? aLeftChildIdx : aRightChildIdx;
592 aNode = aStack[aHead--];
597 Standard_Integer aIdx = aBVHTree->BegPrimitive (aNode);
598 const OpenGl_Structure* aStruct =
599 isTrsfPers ? myBVHPrimitivesTrsfPers.GetStructureById (aIdx)
600 : myBVHPrimitives.GetStructureById (aIdx);
601 aStruct->MarkAsNotCulled();
607 aNode = aStack[aHead--];
613 // =======================================================================
616 // =======================================================================
617 Standard_Boolean OpenGl_Layer::Append (const OpenGl_Layer& theOther)
619 // the source priority list shouldn't have more priorities
620 const Standard_Integer aNbPriorities = theOther.NbPriorities();
621 if (aNbPriorities > NbPriorities())
623 return Standard_False;
626 // add all structures to destination priority list
627 for (Standard_Integer aPriorityIter = 0; aPriorityIter < aNbPriorities; ++aPriorityIter)
629 const OpenGl_IndexedMapOfStructure& aStructures = theOther.myArray (aPriorityIter);
630 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (aStructures); aStructIter.More(); aStructIter.Next())
632 Add (aStructIter.Value(), aPriorityIter);
636 return Standard_True;
639 //=======================================================================
640 //function : SetLayerSettings
642 //=======================================================================
643 void OpenGl_Layer::SetLayerSettings (const Graphic3d_ZLayerSettings& theSettings)
645 const Standard_Boolean toUpdateTrsf = !myLayerSettings.Origin().IsEqual (theSettings.Origin(), gp::Resolution());
646 myLayerSettings = theSettings;
649 for (OpenGl_ArrayOfIndexedMapOfStructure::Iterator aMapIter (myArray); aMapIter.More(); aMapIter.Next())
651 OpenGl_IndexedMapOfStructure& aStructures = aMapIter.ChangeValue();
652 for (OpenGl_IndexedMapOfStructure::Iterator aStructIter (aStructures); aStructIter.More(); aStructIter.Next())
654 OpenGl_Structure* aStructure = const_cast<OpenGl_Structure*> (aStructIter.Value());
655 aStructure->updateLayerTransformation();
661 //=======================================================================
664 //=======================================================================
665 void OpenGl_Layer::Render (const Handle(OpenGl_Workspace)& theWorkspace,
666 const OpenGl_GlobalLayerSettings& theDefaultSettings) const
668 const Graphic3d_PolygonOffset anAppliedOffsetParams = theWorkspace->AppliedPolygonOffset();
669 // myLayerSettings.ToClearDepth() is handled outside
672 if (myLayerSettings.ToEnableDepthTest())
674 // assuming depth test is enabled by default
675 glDepthFunc (theDefaultSettings.DepthFunc);
679 glDepthFunc (GL_ALWAYS);
682 // save environment texture
683 Handle(OpenGl_Texture) anEnvironmentTexture = theWorkspace->EnvironmentTexture();
684 if (!myLayerSettings.UseEnvironmentTexture())
686 theWorkspace->SetEnvironmentTexture (Handle(OpenGl_Texture)());
689 // handle depth offset
690 theWorkspace->SetPolygonOffset (myLayerSettings.PolygonOffset());
692 // handle depth write
693 theWorkspace->UseDepthWrite() = myLayerSettings.ToEnableDepthWrite() && theDefaultSettings.DepthMask == GL_TRUE;
694 glDepthMask (theWorkspace->UseDepthWrite() ? GL_TRUE : GL_FALSE);
696 const Standard_Boolean hasLocalCS = !myLayerSettings.OriginTransformation().IsNull();
697 const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
698 const Handle(Graphic3d_Camera)& aWorldCamera = theWorkspace->View()->Camera();
699 Handle(Graphic3d_Camera) aCameraBack;
702 // Apply local camera transformation.
703 // The vertex position is computed by the following formula in GLSL program:
704 // gl_Position = occProjectionMatrix * occWorldViewMatrix * occModelWorldMatrix * occVertex;
706 // occProjectionMatrix - matrix defining orthographic/perspective/stereographic projection
707 // occWorldViewMatrix - world-view matrix defining Camera position and orientation
708 // occModelWorldMatrix - model-world matrix defining Object transformation from local coordinate system to the world coordinate system
709 // occVertex - input vertex position
711 // Since double precision is quite expensive on modern GPUs, and not available on old hardware,
712 // all these values are passed with single float precision to the shader.
713 // As result, single precision become insufficient for handling objects far from the world origin.
715 // Several approaches can be used to solve precision issues:
716 // - [Broute force] migrate to double precision for all matrices and vertex position.
717 // This is too expensive for most hardware.
718 // - Store only translation part with double precision and pass it to GLSL program.
719 // This requires modified GLSL programs for computing transformation
720 // and extra packing mechanism for hardware not supporting double precision natively.
721 // This solution is less expensive then previous one.
722 // - Move translation part of occModelWorldMatrix into occWorldViewMatrix.
723 // The main idea here is that while moving Camera towards the object,
724 // Camera translation part and Object translation part will compensate each other
725 // to fit into single float precision.
726 // But this operation should be performed with double precision - this is why we are moving
727 // translation part of occModelWorldMatrix to occWorldViewMatrix.
729 // All approaches might be useful in different scenarios, but for the moment we consider the last one as main scenario.
730 // Here we do the trick:
731 // - OpenGl_Layer defines the Local Origin, which is expected to be the center of objects stored within it.
732 // This Local Origin is included into occWorldViewMatrix during rendering.
733 // - OpenGl_Structure defines Object local transformation occModelWorldMatrix with subtracted Local Origin of the Layer.
734 // This means that Object itself should be defined within either Local Transformation equal or near to Local Origin of the Layer.
735 theWorkspace->View()->SetLocalOrigin (myLayerSettings.Origin());
737 NCollection_Mat4<Standard_Real> aWorldView = aWorldCamera->OrientationMatrix();
738 Graphic3d_TransformUtils::Translate (aWorldView, myLayerSettings.Origin().X(), myLayerSettings.Origin().Y(), myLayerSettings.Origin().Z());
740 NCollection_Mat4<Standard_ShortReal> aWorldViewF;
741 aWorldViewF.ConvertFrom (aWorldView);
742 aCtx->WorldViewState.SetCurrent (aWorldViewF);
743 aCtx->ShaderManager()->UpdateClippingState();
744 aCtx->ShaderManager()->UpdateLightSourceState();
747 // render priority list
748 theWorkspace->IsCullingEnabled() ? renderTraverse (theWorkspace) : renderAll (theWorkspace);
752 aCtx->ShaderManager()->RevertClippingState();
753 aCtx->ShaderManager()->UpdateLightSourceState();
755 aCtx->WorldViewState.SetCurrent (aWorldCamera->OrientationMatrixF());
756 theWorkspace->View() ->SetLocalOrigin (gp_XYZ (0.0, 0.0, 0.0));
759 // always restore polygon offset between layers rendering
760 theWorkspace->SetPolygonOffset (anAppliedOffsetParams);
762 // restore environment texture
763 if (!myLayerSettings.UseEnvironmentTexture())
765 theWorkspace->SetEnvironmentTexture (anEnvironmentTexture);