0022048: Visualization, AIS_InteractiveContext - single object selection should alway...
[occt.git] / src / AIS / AIS_Dimension.cxx
index c3508be..f3ca770 100755 (executable)
@@ -24,6 +24,7 @@
 #include <Bnd_Box.hxx>
 #include <ElCLib.hxx>
 #include <Font_BRepFont.hxx>
+#include <Font_BRepTextBuilder.hxx>
 #include <GC_MakeCircle.hxx>
 #include <Geom_Line.hxx>
 #include <GeomAdaptor_Curve.hxx>
@@ -50,8 +51,6 @@
 #include <SelectMgr_EntityOwner.hxx>
 #include <SelectMgr_Selection.hxx>
 #include <SelectMgr_SequenceOfOwner.hxx>
-#include <Select3D_ListIteratorOfListOfSensitive.hxx>
-#include <Select3D_ListOfSensitive.hxx>
 #include <Select3D_SensitiveCircle.hxx>
 #include <Select3D_SensitiveGroup.hxx>
 #include <Select3D_SensitiveCurve.hxx>
 #include <TCollection_ExtendedString.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopoDS.hxx>
+#include <TopoDS_Edge.hxx>
 #include <TopoDS_Vertex.hxx>
 #include <Units.hxx>
 #include <Units_UnitsDictionary.hxx>
 #include <UnitsAPI.hxx>
 #include <UnitsAPI_SystemUnits.hxx>
 
-IMPLEMENT_STANDARD_HANDLE(AIS_Dimension, AIS_InteractiveObject)
-IMPLEMENT_STANDARD_RTTIEXT(AIS_Dimension, AIS_InteractiveObject)
+
+IMPLEMENT_STANDARD_RTTIEXT(AIS_Dimension,AIS_InteractiveObject)
 
 namespace
 {
   // default text strings
-  static const Standard_Utf32Char THE_FILL_CHARACTER ('0');
   static const TCollection_ExtendedString THE_EMPTY_LABEL;
   static const TCollection_AsciiString    THE_UNDEFINED_UNITS;
 
@@ -91,23 +90,26 @@ namespace
   // default selection priorities
   static const Standard_Integer THE_NEUTRAL_SEL_PRIORITY = 5;
   static const Standard_Integer THE_LOCAL_SEL_PRIORITY   = 6;
-};
+}
 
 //=======================================================================
 //function : Constructor
 //purpose  : 
 //=======================================================================
 AIS_Dimension::AIS_Dimension (const AIS_KindOfDimension theType)
-: AIS_InteractiveObject(),
-  myCustomValue (0.0),
-  myIsValueCustom (Standard_False),
-  mySpecialSymbol (' '),
+: AIS_InteractiveObject  (),
+  mySelToleranceForText2d(0.0),
+  myValueType            (ValueType_Computed),
+  myCustomValue          (0.0),
+  myCustomStringValue    (),
+  myIsTextPositionFixed  (Standard_False), 
+  mySpecialSymbol        (' '),
   myDisplaySpecialSymbol (AIS_DSS_No),
-  myGeometryType (GeometryType_UndefShapes),
-  myIsPlaneCustom (Standard_False),
-  myFlyout (0.0),
-  myIsValid (Standard_False),
-  myKindOfDimension (theType)
+  myGeometryType         (GeometryType_UndefShapes),
+  myIsPlaneCustom        (Standard_False),
+  myFlyout               (0.0),
+  myIsGeometryValid      (Standard_False),
+  myKindOfDimension      (theType)
 {
 }
 
@@ -117,34 +119,50 @@ AIS_Dimension::AIS_Dimension (const AIS_KindOfDimension theType)
 //=======================================================================
 void AIS_Dimension::SetCustomValue (const Standard_Real theValue)
 {
-  if (myIsValueCustom && myCustomValue == theValue)
+  if (myValueType == ValueType_CustomReal && myCustomValue == theValue)
   {
     return;
   }
 
-  myIsValueCustom = Standard_True;
-
+  myValueType = ValueType_CustomReal;
   myCustomValue = theValue;
 
   SetToUpdate();
 }
 
 //=======================================================================
-//function : GetPlane
+//function : SetCustomValue
 //purpose  : 
 //=======================================================================
-const gp_Pln& AIS_Dimension::GetPlane() const
+void AIS_Dimension::SetCustomValue (const TCollection_ExtendedString& theValue)
 {
-  return myPlane;
+  if (myValueType == ValueType_CustomText && myCustomStringValue == theValue)
+  {
+    return;
+  }
+
+  myValueType = ValueType_CustomText;
+  myCustomStringValue = theValue;
+
+  SetToUpdate();
 }
 
 //=======================================================================
-//function : GetGeometryType
+//function : GetCustomValue
 //purpose  : 
 //=======================================================================
-const Standard_Integer AIS_Dimension::GetGeometryType () const
+const TCollection_ExtendedString& AIS_Dimension::GetCustomValue () const
 {
-  return myGeometryType;
+  return myCustomStringValue;
+}
+
+//=======================================================================
+//function : GetPlane
+//purpose  : 
+//=======================================================================
+const gp_Pln& AIS_Dimension::GetPlane() const
+{
+  return myPlane;
 }
 
 //=======================================================================
@@ -156,13 +174,12 @@ void AIS_Dimension::SetCustomPlane (const gp_Pln& thePlane)
   myPlane = thePlane;
   myIsPlaneCustom = Standard_True;
 
-  // Disable fixed text position
+  // Disable fixed (custom) text position
   UnsetFixedTextPosition();
 
   // Check validity if geometry has been set already.
-  if (myIsValid)
+  if (IsValid())
   {
-    myIsValid &= CheckPlane (myPlane);
     SetToUpdate();
   }
 }
@@ -280,12 +297,20 @@ Standard_Real AIS_Dimension::ValueToDisplayUnits() const
 //=======================================================================
 TCollection_ExtendedString AIS_Dimension::GetValueString (Standard_Real& theWidth) const
 {
-  // format value string using "sprintf"
-  TCollection_AsciiString aFormatStr = myDrawer->DimensionAspect()->ValueStringFormat();
+  TCollection_ExtendedString aValueStr;
+  if (myValueType == ValueType_CustomText)
+  {
+    aValueStr = myCustomStringValue;
+  }
+  else
+  {
+    // format value string using "sprintf"
+    TCollection_AsciiString aFormatStr = myDrawer->DimensionAspect()->ValueStringFormat();
 
-  char aFmtBuffer[256];
-  sprintf (aFmtBuffer, aFormatStr.ToCString(), ValueToDisplayUnits());
-  TCollection_ExtendedString aValueStr = TCollection_ExtendedString (aFmtBuffer);
+    char aFmtBuffer[256];
+    sprintf (aFmtBuffer, aFormatStr.ToCString(), ValueToDisplayUnits());
+    aValueStr = TCollection_ExtendedString (aFmtBuffer);
+  }
 
   // add units to values string
   if (myDrawer->DimensionAspect()->IsUnitsDisplayed())
@@ -302,22 +327,17 @@ TCollection_ExtendedString AIS_Dimension::GetValueString (Standard_Real& theWidt
   }
 
   // Get text style parameters
-  Quantity_Color aColor; 
-  Standard_CString aFontName;
-  Standard_Real aFactor;
-  Standard_Real aSpace;
-  myDrawer->DimensionAspect()->TextAspect()->Aspect()->Values (aColor, aFontName, aFactor, aSpace);
-  Font_FontAspect aFontAspect = myDrawer->DimensionAspect()->TextAspect()->Aspect()->GetTextFontAspect();
-  Standard_Real   aFontHeight = myDrawer->DimensionAspect()->TextAspect()->Height();
-
-  NCollection_Utf8String anUTFString = (Standard_Utf16Char* )aValueStr.ToExtString();
+  Handle(Prs3d_TextAspect) aTextAspect = myDrawer->DimensionAspect()->TextAspect();
+  NCollection_Utf8String anUTFString (aValueStr.ToExtString());
 
   theWidth = 0.0;
 
   if (myDrawer->DimensionAspect()->IsText3d())
   {
     // text width produced by BRepFont
-    Font_BRepFont aFont (aFontName, aFontAspect, aFontHeight);
+    Font_BRepFont aFont (aTextAspect->Aspect()->Font().ToCString(),
+                         aTextAspect->Aspect()->GetTextFontAspect(),
+                         aTextAspect->Height());
 
     for (NCollection_Utf8Iter anIter = anUTFString.Iterator(); *anIter != 0; )
     {
@@ -330,7 +350,10 @@ TCollection_ExtendedString AIS_Dimension::GetValueString (Standard_Real& theWidt
   {
     // Text width for 1:1 scale 2D case
     Handle(Font_FTFont) aFont = new Font_FTFont();
-    aFont->Init (aFontName, aFontAspect, (const unsigned int)aFontHeight, THE_2D_TEXT_RESOLUTION);
+    aFont->Init (aTextAspect->Aspect()->Font().ToCString(),
+                 aTextAspect->Aspect()->GetTextFontAspect(),
+                 (const unsigned int)aTextAspect->Height(),
+                 THE_2D_TEXT_RESOLUTION);
 
     for (NCollection_Utf8Iter anIter = anUTFString.Iterator(); *anIter != 0; )
     {
@@ -351,18 +374,19 @@ void AIS_Dimension::DrawArrow (const Handle(Prs3d_Presentation)& thePresentation
                                const gp_Pnt& theLocation,
                                const gp_Dir& theDirection)
 {
-  Prs3d_Root::NewGroup (thePresentation);
+  Handle(Graphic3d_Group) aGroup = Prs3d_Root::NewGroup (thePresentation);
 
-  Quantity_Length aLength = myDrawer->DimensionAspect()->ArrowAspect()->Length();
-  Standard_Real   anAngle = myDrawer->DimensionAspect()->ArrowAspect()->Angle();
+  Standard_Real aLength = myDrawer->DimensionAspect()->ArrowAspect()->Length();
+  Standard_Real anAngle = myDrawer->DimensionAspect()->ArrowAspect()->Angle();
 
   if (myDrawer->DimensionAspect()->IsArrows3d())
   {
-    Prs3d_Arrow::Draw (thePresentation,
+    Prs3d_Arrow::Draw (aGroup,
                        theLocation,
                        theDirection,
                        anAngle,
                        aLength);
+    aGroup->SetGroupPrimitivesAspect (myDrawer->DimensionAspect()->ArrowAspect()->Aspect());
   }
   else
   {
@@ -379,21 +403,17 @@ void AIS_Dimension::DrawArrow (const Handle(Prs3d_Presentation)& thePresentation
     anArrow->AddVertex (aRightPoint);
 
     // Set aspect for arrow triangles
-    Quantity_Color aColor;
-    Aspect_TypeOfLine aTOL;
-    Standard_Real aWidth;
-    myDrawer->DimensionAspect()->ArrowAspect()->Aspect()->Values (aColor, aTOL, aWidth);
     Graphic3d_MaterialAspect aShadeMat (Graphic3d_NOM_DEFAULT);
     aShadeMat.SetReflectionModeOff (Graphic3d_TOR_AMBIENT);
     aShadeMat.SetReflectionModeOff (Graphic3d_TOR_DIFFUSE);
     aShadeMat.SetReflectionModeOff (Graphic3d_TOR_SPECULAR);
 
     Handle(Prs3d_ShadingAspect) aShadingStyle = new Prs3d_ShadingAspect();
-    aShadingStyle->SetColor (aColor);
+    aShadingStyle->SetColor (myDrawer->DimensionAspect()->ArrowAspect()->Aspect()->Color());
     aShadingStyle->SetMaterial (aShadeMat);
 
-    Prs3d_Root::CurrentGroup (thePresentation)->SetPrimitivesAspect (aShadingStyle->Aspect());
-    Prs3d_Root::CurrentGroup (thePresentation)->AddPrimitiveArray (anArrow);
+    aGroup->SetPrimitivesAspect (aShadingStyle->Aspect());
+    aGroup->AddPrimitiveArray (anArrow);
   }
 
   SelectionGeometry::Arrow& aSensitiveArrow = mySelectionGeom.NewArrow();
@@ -402,10 +422,10 @@ void AIS_Dimension::DrawArrow (const Handle(Prs3d_Presentation)& thePresentation
 }
 
 //=======================================================================
-//function : DrawText
-//purpose  : 
+//function : drawText
+//purpose  :
 //=======================================================================
-void AIS_Dimension::DrawText (const Handle(Prs3d_Presentation)& thePresentation,
+void AIS_Dimension::drawText (const Handle(Prs3d_Presentation)& thePresentation,
                               const gp_Pnt& theTextPos,
                               const gp_Dir& theTextDir,
                               const TCollection_ExtendedString& theText,
@@ -414,18 +434,18 @@ void AIS_Dimension::DrawText (const Handle(Prs3d_Presentation)& thePresentation,
   if (myDrawer->DimensionAspect()->IsText3d())
   {
     // getting font parameters
-    Quantity_Color aColor;
-    Standard_CString aFontName;
-    Standard_Real anExpansionFactor;
-    Standard_Real aSpace;
-    myDrawer->DimensionAspect()->TextAspect()->Aspect()->Values (aColor, aFontName, anExpansionFactor, aSpace);
-    Font_FontAspect aFontAspect = myDrawer->DimensionAspect()->TextAspect()->Aspect()->GetTextFontAspect();
-    Standard_Real aFontHeight = myDrawer->DimensionAspect()->TextAspect()->Height();
+    Handle(Prs3d_TextAspect) aTextAspect = myDrawer->DimensionAspect()->TextAspect();
+    Quantity_Color  aColor      = aTextAspect->Aspect()->Color();
+    Font_FontAspect aFontAspect = aTextAspect->Aspect()->GetTextFontAspect();
+    Standard_Real   aFontHeight = aTextAspect->Height();
 
     // creating TopoDS_Shape for text
-    Font_BRepFont aFont (aFontName, aFontAspect, aFontHeight);
-    NCollection_Utf8String anUTFString = (Standard_Utf16Char* )theText.ToExtString();
-    TopoDS_Shape aTextShape = aFont.RenderText (anUTFString);
+    Font_BRepFont aFont (aTextAspect->Aspect()->Font().ToCString(),
+                         aFontAspect, aFontHeight);
+    NCollection_Utf8String anUTFString (theText.ToExtString());
+
+    Font_BRepTextBuilder aBuilder;
+    TopoDS_Shape aTextShape = aBuilder.Perform (aFont, anUTFString);
 
     // compute text width with kerning
     Standard_Real aTextWidth  = 0.0;
@@ -503,6 +523,11 @@ void AIS_Dimension::DrawText (const Handle(Prs3d_Presentation)& thePresentation,
     if (myDrawer->DimensionAspect()->IsTextShaded())
     {
       // Setting text shading and color parameters
+      if (!myDrawer->HasOwnShadingAspect())
+      {
+        myDrawer->SetShadingAspect (new Prs3d_ShadingAspect());
+      }
+
       Graphic3d_MaterialAspect aShadeMat (Graphic3d_NOM_DEFAULT);
       aShadeMat.SetReflectionModeOff (Graphic3d_TOR_AMBIENT);
       aShadeMat.SetReflectionModeOff (Graphic3d_TOR_DIFFUSE);
@@ -516,8 +541,14 @@ void AIS_Dimension::DrawText (const Handle(Prs3d_Presentation)& thePresentation,
     }
     else
     {
-      // setting color for text
+      // Setting color for text
+      if (!myDrawer->HasOwnFreeBoundaryAspect())
+      {
+        myDrawer->SetFreeBoundaryAspect (new Prs3d_LineAspect (aColor, Aspect_TOL_SOLID, 1.0));
+      }
+
       myDrawer->FreeBoundaryAspect()->Aspect()->SetColor (aColor);
+
       // drawing text
       StdPrs_WFShape::Add (thePresentation, aTextShape, myDrawer);
     }
@@ -534,7 +565,7 @@ void AIS_Dimension::DrawText (const Handle(Prs3d_Presentation)& thePresentation,
   // generate primitives for 2D text
   myDrawer->DimensionAspect()->TextAspect()->Aspect()->SetDisplayType (Aspect_TODT_DIMENSION);
 
-  Prs3d_Text::Draw (thePresentation,
+  Prs3d_Text::Draw (Prs3d_Root::CurrentGroup (thePresentation),
                     myDrawer->DimensionAspect()->TextAspect(),
                     theText,
                     theTextPos);
@@ -568,7 +599,7 @@ void AIS_Dimension::DrawExtension (const Handle(Prs3d_Presentation)& thePresenta
     gp_Pnt aTextPos = ElCLib::Value (theExtensionSize, anExtensionLine);
     gp_Dir aTextDir = theExtensionDir;
 
-    DrawText (thePresentation,
+    drawText (thePresentation,
               aTextPos,
               aTextDir,
               theLabelString,
@@ -625,14 +656,14 @@ void AIS_Dimension::DrawLinearDimension (const Handle(Prs3d_Presentation)& thePr
   // do not build any dimension for equal points
   if (theFirstPoint.IsEqual (theSecondPoint, Precision::Confusion()))
   {
-    Standard_ProgramError::Raise ("Can not build presentation for equal points.");
+    throw Standard_ProgramError("Can not build presentation for equal points.");
   }
 
   Handle(Prs3d_DimensionAspect) aDimensionAspect = myDrawer->DimensionAspect();
 
   // For extensions we need to know arrow size, text size and extension size: get it from aspect
-  Quantity_Length anArrowLength   = aDimensionAspect->ArrowAspect()->Length();
-  Standard_Real   anExtensionSize = aDimensionAspect->ExtensionSize();
+  Standard_Real anArrowLength   = aDimensionAspect->ArrowAspect()->Length();
+  Standard_Real anExtensionSize = aDimensionAspect->ExtensionSize();
   // prepare label string and compute its geometrical width
   Standard_Real aLabelWidth;
   TCollection_ExtendedString aLabelString = GetValueString (aLabelWidth);
@@ -650,29 +681,19 @@ void AIS_Dimension::DrawLinearDimension (const Handle(Prs3d_Presentation)& thePr
   Prs3d_DimensionTextHorizontalPosition aHorisontalTextPos = aDimensionAspect->TextHorizontalPosition();
   if (IsTextPositionCustom())
   {
-    AdjustParametersForLinear (myFixedTextPosition, theFirstPoint, theSecondPoint,
-                               anExtensionSize, aHorisontalTextPos);
-
+    if (!AdjustParametersForLinear (myFixedTextPosition, theFirstPoint, theSecondPoint,
+                                    anExtensionSize, aHorisontalTextPos, myFlyout, myPlane, myIsPlaneCustom))
+    {
+      throw Standard_ProgramError("Can not adjust plane to the custom label position.");
+    }
   }
 
   FitTextAlignmentForLinear (theFirstPoint, theSecondPoint, theIsOneSide, aHorisontalTextPos,
                              aLabelPosition, isArrowsExternal);
 
-    // compute dimension line points
-  gp_Ax1 aPlaneNormal = GetPlane().Axis();
-  gp_Dir aTargetPointsVector = gce_MakeDir (theFirstPoint, theSecondPoint);
-
-  // compute flyout direction vector
-  gp_Dir aFlyoutVector = aPlaneNormal.Direction() ^ aTargetPointsVector;
-
-  // create lines for layouts
-  gp_Lin aLine1 (theFirstPoint, aFlyoutVector);
-  gp_Lin aLine2 (theSecondPoint, aFlyoutVector);
-
-  // Get flyout end points
-  gp_Pnt aLineBegPoint = ElCLib::Value (ElCLib::Parameter (aLine1, theFirstPoint)  + GetFlyout(), aLine1);
-  gp_Pnt aLineEndPoint = ElCLib::Value (ElCLib::Parameter (aLine2, theSecondPoint) + GetFlyout(), aLine2);
-
+  // compute dimension line points
+  gp_Pnt aLineBegPoint, aLineEndPoint;
+  ComputeFlyoutLinePoints (theFirstPoint, theSecondPoint, aLineBegPoint, aLineEndPoint);
   gp_Lin aDimensionLine = gce_MakeLin (aLineBegPoint, aLineEndPoint);
 
   // compute arrows positions and directions
@@ -721,7 +742,7 @@ void AIS_Dimension::DrawLinearDimension (const Handle(Prs3d_Presentation)& thePr
       // add text primitives
       if (theMode == ComputeMode_All || theMode == ComputeMode_Text)
       {
-        DrawText (thePresentation,
+        drawText (thePresentation,
                   aTextPos,
                   aTextDir,
                   aLabelString,
@@ -956,12 +977,32 @@ void AIS_Dimension::DrawLinearDimension (const Handle(Prs3d_Presentation)& thePr
     aPrimSegments->AddVertex (theSecondPoint);
     aPrimSegments->AddVertex (aLineEndPoint);
 
-    Handle(Prs3d_DimensionAspect) aDimensionAspect = myDrawer->DimensionAspect();
     Prs3d_Root::CurrentGroup (thePresentation)->SetPrimitivesAspect (aDimensionAspect->LineAspect()->Aspect());
     Prs3d_Root::CurrentGroup (thePresentation)->AddPrimitiveArray (aPrimSegments);
   }
 
-  myIsComputed = Standard_True;
+  mySelectionGeom.IsComputed = Standard_True;
+}
+
+//=======================================================================
+//function : ComputeFlyoutLinePoints
+//purpose  :
+//=======================================================================
+void AIS_Dimension::ComputeFlyoutLinePoints (const gp_Pnt& theFirstPoint, const gp_Pnt& theSecondPoint,
+                                             gp_Pnt& theLineBegPoint, gp_Pnt& theLineEndPoint)
+{
+  // compute dimension line points
+  gp_Ax1 aPlaneNormal = GetPlane().Axis();
+  // compute flyout direction vector
+  gp_Dir aTargetPointsVector = gce_MakeDir (theFirstPoint, theSecondPoint);
+  gp_Dir aFlyoutVector = aPlaneNormal.Direction() ^ aTargetPointsVector;
+  // create lines for layouts
+  gp_Lin aLine1 (theFirstPoint, aFlyoutVector);
+  gp_Lin aLine2 (theSecondPoint, aFlyoutVector);
+
+  // Get flyout end points
+  theLineBegPoint = ElCLib::Value (ElCLib::Parameter (aLine1, theFirstPoint)  + GetFlyout(), aLine1);
+  theLineEndPoint = ElCLib::Value (ElCLib::Parameter (aLine2, theSecondPoint) + GetFlyout(), aLine2);
 }
 
 //=======================================================================
@@ -1019,6 +1060,48 @@ Standard_Boolean AIS_Dimension::CircleFromPlanarFace (const TopoDS_Face& theFace
   return Standard_False;
 }
 
+//=======================================================================
+//function : CircleFromEdge
+//purpose  : if possible computes circle from edge
+//=======================================================================
+Standard_Boolean AIS_Dimension::CircleFromEdge (const TopoDS_Edge& theEdge,
+                                                gp_Circ&           theCircle,
+                                                gp_Pnt&            theFirstPoint,
+                                                gp_Pnt&            theLastPoint)
+{
+  BRepAdaptor_Curve anAdaptedCurve (theEdge);
+  switch (anAdaptedCurve.GetType())
+  {
+    case GeomAbs_Circle:
+    {
+      theCircle = anAdaptedCurve.Circle();
+      break;
+    }
+    case GeomAbs_Ellipse:
+    {
+      gp_Elips anEll = anAdaptedCurve.Ellipse();
+      if ((anEll.MinorRadius() - anEll.MajorRadius()) >= Precision::Confusion())
+      {
+        return Standard_False;
+      }
+      theCircle = gp_Circ(anEll.Position(),anEll.MinorRadius());
+      break;
+    }
+    case GeomAbs_Line:
+    case GeomAbs_Hyperbola:
+    case GeomAbs_Parabola:
+    case GeomAbs_BezierCurve:
+    case GeomAbs_BSplineCurve:
+    case GeomAbs_OtherCurve:
+    default:
+      return Standard_False;
+  }
+
+  theFirstPoint = anAdaptedCurve.Value (anAdaptedCurve.FirstParameter());
+  theLastPoint  = anAdaptedCurve.Value (anAdaptedCurve.LastParameter());
+  return Standard_True;
+}
+
 //=======================================================================
 //function : InitCircularDimension
 //purpose  : 
@@ -1036,122 +1119,126 @@ Standard_Boolean AIS_Dimension::InitCircularDimension (const TopoDS_Shape& theSh
   Standard_Real aFirstParam = 0.0;
   Standard_Real aLastParam  = 0.0;
 
-  // discover circular geometry
-  if (theShape.ShapeType() == TopAbs_FACE)
+  // Discover circular geometry
+  switch (theShape.ShapeType())
   {
-    AIS::GetPlaneFromFace (TopoDS::Face (theShape), aPln, aBasisSurf, aSurfType, anOffset);
-
-    if (aSurfType == AIS_KOS_Plane)
+    case TopAbs_FACE:
     {
-      Handle(Geom_Curve) aCurve;
-      if (!CircleFromPlanarFace (TopoDS::Face (theShape), aCurve, aFirstPoint, aLastPoint))
-      {
-        return Standard_False;
-      }
+      AIS::GetPlaneFromFace (TopoDS::Face (theShape), aPln, aBasisSurf, aSurfType, anOffset);
 
-      theCircle = Handle(Geom_Circle)::DownCast (aCurve)->Circ();
-    }
-    else
-    {
-      gp_Pnt aCurPos;
-      BRepAdaptor_Surface aSurf1 (TopoDS::Face (theShape));
-      Standard_Real aFirstU = aSurf1.FirstUParameter();
-      Standard_Real aLastU  = aSurf1.LastUParameter();
-      Standard_Real aFirstV = aSurf1.FirstVParameter();
-      Standard_Real aLastV  = aSurf1.LastVParameter();
-      Standard_Real aMidU   = (aFirstU + aLastU) * 0.5;
-      Standard_Real aMidV   = (aFirstV + aLastV) * 0.5;
-      aSurf1.D0 (aMidU, aMidV, aCurPos);
-      Handle (Adaptor3d_HCurve) aBasisCurve;
-      Standard_Boolean isExpectedType = Standard_False;
-      if (aSurfType == AIS_KOS_Cylinder)
+      if (aSurfType == AIS_KOS_Plane)
       {
-        isExpectedType = Standard_True;
+        Handle(Geom_Curve) aCurve;
+        if (!CircleFromPlanarFace (TopoDS::Face (theShape), aCurve, aFirstPoint, aLastPoint))
+        {
+          return Standard_False;
+        }
+
+        theCircle = Handle(Geom_Circle)::DownCast (aCurve)->Circ();
       }
       else
       {
-        if (aSurfType == AIS_KOS_Revolution)
+        gp_Pnt aCurPos;
+        BRepAdaptor_Surface aSurf1 (TopoDS::Face (theShape));
+        Standard_Real aFirstU = aSurf1.FirstUParameter();
+        Standard_Real aLastU  = aSurf1.LastUParameter();
+        Standard_Real aFirstV = aSurf1.FirstVParameter();
+        Standard_Real aLastV  = aSurf1.LastVParameter();
+        Standard_Real aMidU   = (aFirstU + aLastU) * 0.5;
+        Standard_Real aMidV   = (aFirstV + aLastV) * 0.5;
+        aSurf1.D0 (aMidU, aMidV, aCurPos);
+        Handle (Adaptor3d_HCurve) aBasisCurve;
+        Standard_Boolean isExpectedType = Standard_False;
+        if (aSurfType == AIS_KOS_Cylinder)
         {
-          aBasisCurve = aSurf1.BasisCurve();
-          if (aBasisCurve->GetType() == GeomAbs_Line)
-          {
-            isExpectedType = Standard_True;
-          }
+          isExpectedType = Standard_True;
         }
-        else if (aSurfType == AIS_KOS_Extrusion)
+        else
         {
-          aBasisCurve = aSurf1.BasisCurve();
-          if (aBasisCurve->GetType() == GeomAbs_Circle)
+          if (aSurfType == AIS_KOS_Revolution)
+          {
+            aBasisCurve = aSurf1.BasisCurve();
+            if (aBasisCurve->GetType() == GeomAbs_Line)
+            {
+              isExpectedType = Standard_True;
+            }
+          }
+          else if (aSurfType == AIS_KOS_Extrusion)
           {
-            isExpectedType = Standard_True;
+            aBasisCurve = aSurf1.BasisCurve();
+            if (aBasisCurve->GetType() == GeomAbs_Circle)
+            {
+              isExpectedType = Standard_True;
+            }
           }
         }
-      }
 
-      if (!isExpectedType)
-      {
-        return Standard_False;
-      }
+        if (!isExpectedType)
+        {
+          return Standard_False;
+        }
 
-      Handle(Geom_Curve) aCurve;
-      aCurve = aBasisSurf->VIso(aMidV);
-      if (aCurve->DynamicType() == STANDARD_TYPE (Geom_Circle))
-      {
-        theCircle = Handle(Geom_Circle)::DownCast (aCurve)->Circ();
-      }
-      else if (aCurve->DynamicType() == STANDARD_TYPE (Geom_TrimmedCurve))
-      {
-        Handle(Geom_TrimmedCurve) aTrimmedCurve = Handle(Geom_TrimmedCurve)::DownCast (aCurve);
-        aFirstU = aTrimmedCurve->FirstParameter();
-        aLastU  = aTrimmedCurve->LastParameter();
-        if (aTrimmedCurve->DynamicType() == STANDARD_TYPE (Geom_Circle))
+        Handle(Geom_Curve) aCurve = aBasisSurf->VIso(aMidV);
+        if (aCurve->DynamicType() == STANDARD_TYPE (Geom_Circle))
         {
-          theCircle = Handle(Geom_Circle)::DownCast(aTrimmedCurve)->Circ();
+          theCircle = Handle(Geom_Circle)::DownCast (aCurve)->Circ();
+        }
+        else if (aCurve->DynamicType() == STANDARD_TYPE (Geom_TrimmedCurve))
+        {
+          Handle(Geom_TrimmedCurve) aTrimmedCurve = Handle(Geom_TrimmedCurve)::DownCast (aCurve);
+          aFirstU = aTrimmedCurve->FirstParameter();
+          aLastU  = aTrimmedCurve->LastParameter();
+          if (aTrimmedCurve->BasisCurve()->DynamicType() == STANDARD_TYPE (Geom_Circle))
+          {
+            theCircle = Handle(Geom_Circle)::DownCast(aTrimmedCurve->BasisCurve())->Circ();
+          }
+        }
+        else
+        {
+          // Compute a circle from 3 points on "aCurve"
+          gp_Pnt aP1, aP2;
+          aSurf1.D0 (aFirstU, aMidV, aP1);
+          aSurf1.D0 (aLastU, aMidV, aP2);
+          GC_MakeCircle aMkCirc (aP1, aCurPos, aP2);
+          theCircle = aMkCirc.Value()->Circ();
         }
-      }
-      else
-      {
-        // Compute a circle from 3 points on "aCurve"
-        gp_Pnt aP1, aP2;
-        aSurf1.D0 (aFirstU, aMidV, aP1);
-        aSurf1.D0 (aLastU, aMidV, aP2);
-        GC_MakeCircle aMkCirc (aP1, aCurPos, aP2);
-        theCircle = aMkCirc.Value()->Circ();
-      }
 
-      aFirstPoint = ElCLib::Value (aFirstU, theCircle);
-      aLastPoint = ElCLib::Value (aLastU,  theCircle);
+        aFirstPoint = ElCLib::Value (aFirstU, theCircle);
+        aLastPoint = ElCLib::Value (aLastU,  theCircle);
+      }
+      break;
     }
-  }
-  else // TopAbs_EDGE | TopAbs_WIRE
-  {
-    TopoDS_Edge anEdge;
-    if (theShape.ShapeType() == TopAbs_WIRE)
+    case TopAbs_WIRE:
     {
+      TopoDS_Edge anEdge;
       TopExp_Explorer anIt (theShape, TopAbs_EDGE);
       if (anIt.More())
       {
         anEdge = TopoDS::Edge (anIt.Current());
       }
+      if (!AIS_Dimension::CircleFromEdge (anEdge, theCircle, aFirstPoint, aLastPoint))
+      {
+        return Standard_False;
+      }
+      break;
     }
-    else if (theShape.ShapeType() == TopAbs_EDGE)
-    {
-      anEdge = TopoDS::Edge (theShape);
-    }
-    else // Unexpected type of shape
+    case TopAbs_EDGE:
     {
-      return Standard_False;
+      TopoDS_Edge anEdge = TopoDS::Edge (theShape);
+      if (!AIS_Dimension::CircleFromEdge (anEdge, theCircle, aFirstPoint, aLastPoint))
+      {
+        return Standard_False;
+      }
+      break;
     }
-
-    BRepAdaptor_Curve anAdaptedCurve (anEdge);
-    if (!anAdaptedCurve.GetType() == GeomAbs_Circle)
-    {
+    case TopAbs_COMPOUND:
+    case TopAbs_COMPSOLID:
+    case TopAbs_SOLID:
+    case TopAbs_SHELL:
+    case TopAbs_VERTEX:
+    case TopAbs_SHAPE:
+    default:
       return Standard_False;
-    }
-
-    theCircle   = anAdaptedCurve.Circle();
-    aFirstPoint = anAdaptedCurve.Value (anAdaptedCurve.FirstParameter());
-    aLastPoint  = anAdaptedCurve.Value (anAdaptedCurve.LastParameter());
   }
 
   theIsClosed = aFirstPoint.IsEqual (aLastPoint, Precision::Confusion());
@@ -1187,7 +1274,7 @@ Standard_Boolean AIS_Dimension::InitCircularDimension (const TopoDS_Shape& theSh
 void AIS_Dimension::ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
                                       const Standard_Integer theMode)
 {
-  if (!myIsComputed)
+  if (!mySelectionGeom.IsComputed)
   {
     return;
   }
@@ -1230,8 +1317,8 @@ void AIS_Dimension::ComputeSelection (const Handle(SelectMgr_Selection)& theSele
       aGroupOfSensitives->Add (new Select3D_SensitiveCurve (aSensitiveOwner, aSensitivePnts));
     }
 
-    Quantity_Length anArrowLength = myDrawer->DimensionAspect()->ArrowAspect()->Length();
-    Standard_Real   anArrowAngle  = myDrawer->DimensionAspect()->ArrowAspect()->Angle();
+    Standard_Real anArrowLength = myDrawer->DimensionAspect()->ArrowAspect()->Length();
+    Standard_Real anArrowAngle  = myDrawer->DimensionAspect()->ArrowAspect()->Angle();
 
     // sensitives for arrows
     SelectionGeometry::SeqOfArrows::Iterator anArrowIt (mySelectionGeom.Arrows);
@@ -1350,7 +1437,7 @@ gp_Pnt AIS_Dimension::GetTextPositionForLinear (const gp_Pnt& theFirstPoint,
                                                 const gp_Pnt& theSecondPoint,
                                                 const Standard_Boolean theIsOneSide) const
 {
-  if (!myIsValid)
+  if (!IsValid())
   {
     return gp::Origin();
   }
@@ -1418,30 +1505,43 @@ gp_Pnt AIS_Dimension::GetTextPositionForLinear (const gp_Pnt& theFirstPoint,
 }
 
 //=======================================================================
-//function : AdjustAspectParameters
+//function : AdjustParametersForLinear
 //purpose  : 
 //=======================================================================
-void AIS_Dimension::AdjustParametersForLinear (const gp_Pnt& theTextPos,
-                                               const gp_Pnt& theFirstPoint,
-                                               const gp_Pnt& theSecondPoint,
-                                               Standard_Real& theExtensionSize,
-                                               Prs3d_DimensionTextHorizontalPosition& theAlignment)
+Standard_Boolean AIS_Dimension::AdjustParametersForLinear (const gp_Pnt& theTextPos,
+                                                           const gp_Pnt& theFirstPoint,
+                                                           const gp_Pnt& theSecondPoint,
+                                                           Standard_Real& theExtensionSize,
+                                                           Prs3d_DimensionTextHorizontalPosition& theAlignment,
+                                                           Standard_Real& theFlyout,
+                                                           gp_Pln& thePlane,
+                                                           Standard_Boolean& theIsPlaneOld) const
 {
   Handle(Prs3d_DimensionAspect) aDimensionAspect = myDrawer->DimensionAspect();
   Standard_Real anArrowLength = aDimensionAspect->ArrowAspect()->Length();
 
-  //Set new automatic plane.
-  myPlane = gce_MakePln (theTextPos, theFirstPoint, theSecondPoint);
-  myIsPlaneCustom = Standard_False;
-
-  // Compute dimension line points.
-  gp_Dir aPlaneNormal = GetPlane().Axis().Direction();
   gp_Dir aTargetPointsDir = gce_MakeDir (theFirstPoint, theSecondPoint);
   gp_Vec aTargetPointsVec (theFirstPoint, theSecondPoint);
 
+  // Don't set new plane if the text position lies on the attachment points line.
+  gp_Lin aTargetPointsLin (theFirstPoint, aTargetPointsDir);
+  if (!aTargetPointsLin.Contains (theTextPos, Precision::Confusion()))
+  {
+    //Set new automatic plane.
+    thePlane = gce_MakePln (theTextPos, theFirstPoint, theSecondPoint);
+    theIsPlaneOld = Standard_False;
+  }
+
   // Compute flyout direction vector.
+  gp_Dir aPlaneNormal = GetPlane().Axis().Direction();
   gp_Dir aPositiveFlyout = aPlaneNormal ^ aTargetPointsDir;
 
+  // Additional check of collinearity of the plane normal and attachment points vector.
+  if (aPlaneNormal.IsParallel (aTargetPointsDir, Precision::Angular()))
+  {
+    return Standard_False;
+  }
+
   // Set flyout.
   gp_Vec aFirstToTextVec (theFirstPoint, theTextPos);
 
@@ -1453,15 +1553,19 @@ void AIS_Dimension::AdjustParametersForLinear (const gp_Pnt& theTextPos,
   // Compute flyout value and direction.
   gp_Vec aFlyoutVector = gp_Vec (aTextPosProj, theTextPos);
 
-  myFlyout = gp_Dir (aFlyoutVector).IsOpposite (aPositiveFlyout, Precision::Angular())
-              ? -aFlyoutVector.Magnitude()
-              :  aFlyoutVector.Magnitude();
-
+  theFlyout = 0.0;
+  if (aFlyoutVector.Magnitude() > Precision::Confusion())
+  {
+    theFlyout = gp_Dir (aFlyoutVector).IsOpposite (aPositiveFlyout, Precision::Angular())
+                ? -aFlyoutVector.Magnitude()
+                :  aFlyoutVector.Magnitude();
+  }
+  
   // Compute attach points (through which main dimension line passes).
   gp_Pnt aFirstAttach  = theFirstPoint.Translated (aFlyoutVector);
   gp_Pnt aSecondAttach = theSecondPoint.Translated (aFlyoutVector);
 
-  // Set horisontal text alignment.
+  // Set horizontal text alignment.
   if (aCos < 0.0)
   {
     theAlignment = Prs3d_DTHP_Left;
@@ -1480,6 +1584,7 @@ void AIS_Dimension::AdjustParametersForLinear (const gp_Pnt& theTextPos,
   {
     theAlignment = Prs3d_DTHP_Center;
   }
+  return Standard_True;
 }
 
 //=======================================================================
@@ -1513,10 +1618,8 @@ void AIS_Dimension::FitTextAlignmentForLinear (const gp_Pnt& theFirstPoint,
 
   Handle(Prs3d_DimensionAspect) aDimensionAspect = myDrawer->DimensionAspect();
 
-  gp_Lin aDimensionLine = gce_MakeLin (aLineBegPoint, aLineEndPoint);
-
   // For extensions we need to know arrow size, text size and extension size: get it from aspect
-  Quantity_Length anArrowLength = aDimensionAspect->ArrowAspect()->Length();
+  Standard_Real anArrowLength = aDimensionAspect->ArrowAspect()->Length();
 
   // prepare label string and compute its geometrical width
   Standard_Real aLabelWidth;