0028726: Quantity_NameOfColor should be replaced by Quantity_Color in function input...
[occt.git] / src / ViewerTest / ViewerTest_ObjectCommands.cxx
index 427d134..d0cdf88 100644 (file)
 
 #include <ViewerTest.hxx>
 
+#include <AIS_PlaneTrihedron.hxx>
+
 #include <Quantity_NameOfColor.hxx>
 #include <Draw_Interpretor.hxx>
 #include <Draw.hxx>
 #include <Draw_Appli.hxx>
 #include <DBRep.hxx>
+#include <DBRep_DrawableShape.hxx>
 
 #include <Font_BRepFont.hxx>
+#include <Font_BRepTextBuilder.hxx>
 #include <Font_FontMgr.hxx>
+
+#include <NCollection_List.hxx>
+
 #include <OSD_Chronometer.hxx>
 #include <TCollection_AsciiString.hxx>
-#include <Visual3d_View.hxx>
 #include <V3d_Viewer.hxx>
 #include <V3d_View.hxx>
 #include <V3d.hxx>
@@ -78,6 +84,7 @@
 #include <AIS_Trihedron.hxx>
 #include <AIS_Axis.hxx>
 #include <gp_Trsf.hxx>
+#include <gp_Quaternion.hxx>
 #include <TopLoc_Location.hxx>
 
 #include <HLRAlgo_Projector.hxx>
 #include <Standard_Real.hxx>
 
 #include <AIS_Circle.hxx>
-#include <AIS_Drawer.hxx>
 #include <BRepBuilderAPI_MakeEdge.hxx>
 #include <BRepBuilderAPI_MakeFace.hxx>
 #include <BRepBuilderAPI_MakeWire.hxx>
 #include <Geom_Circle.hxx>
 #include <GC_MakeCircle.hxx>
-#include <Prs3d_Presentation.hxx>
 #include <Select3D_SensitiveCircle.hxx>
 #include <SelectMgr_EntityOwner.hxx>
 #include <SelectMgr_Selection.hxx>
 
 #include <AIS_MultipleConnectedInteractive.hxx>
 #include <AIS_ConnectedInteractive.hxx>
+#include <AIS_TextLabel.hxx>
 #include <TopLoc_Location.hxx>
 #include <TColStd_ListOfInteger.hxx>
 #include <TColStd_ListIteratorOfListOfInteger.hxx>
 #include <BRepExtrema_ExtPC.hxx>
 #include <BRepExtrema_ExtPF.hxx>
 
+#include <Prs3d_Arrow.hxx>
+#include <Prs3d_ArrowAspect.hxx>
+#include <Prs3d_DatumAttribute.hxx>
+#include <Prs3d_DatumAspect.hxx>
+#include <Prs3d_Drawer.hxx>
 #include <Prs3d_VertexDrawMode.hxx>
 #include <Prs3d_LineAspect.hxx>
 #include <Prs3d_PointAspect.hxx>
+#include <Prs3d_Presentation.hxx>
+#include <Prs3d_TextAspect.hxx>
 
 #include <Image_AlienPixMap.hxx>
 #include <TColStd_HArray1OfAsciiString.hxx>
-
-#ifdef _WIN32
-# define _CRT_SECURE_NO_DEPRECATE
-# pragma warning (disable:4996)
-#endif
+#include <TColStd_HSequenceOfAsciiString.hxx>
 
 extern ViewerTest_DoubleMapOfInteractiveAndName& GetMapOfAIS();
 extern Standard_Boolean VDisplayAISObject (const TCollection_AsciiString& theName,
@@ -147,140 +156,443 @@ extern Standard_Boolean VDisplayAISObject (const TCollection_AsciiString& theNam
 extern int ViewerMainLoop(Standard_Integer argc, const char** argv);
 extern Handle(AIS_InteractiveContext)& TheAISContext();
 
+namespace
+{
+  static bool convertToColor (const Handle(TColStd_HSequenceOfAsciiString)& theColorValues,
+                              Quantity_Color& theColor)
+  {
+    const char* anArgs[3] =
+    {
+      theColorValues->Size() >= 1 ? theColorValues->Value (1).ToCString() : "",
+      theColorValues->Size() >= 2 ? theColorValues->Value (2).ToCString() : "",
+      theColorValues->Size() >= 3 ? theColorValues->Value (3).ToCString() : ""
+    };
+    return ViewerTest::ParseColor (theColorValues->Size(), anArgs, theColor) != 0;
+  }
+
+  static bool convertToDatumPart (const TCollection_AsciiString& theValue,
+                                  Prs3d_DatumParts& theDatumPart)
+  {
+    TCollection_AsciiString aValue = theValue;
+    aValue.LowerCase();
+    if      (aValue == "origin")  theDatumPart = Prs3d_DP_Origin;
+    else if (aValue == "xaxis")   theDatumPart = Prs3d_DP_XAxis;
+    else if (aValue == "yaxis")   theDatumPart = Prs3d_DP_YAxis;
+    else if (aValue == "zaxis")   theDatumPart = Prs3d_DP_ZAxis;
+    else if (aValue == "xarrow")  theDatumPart = Prs3d_DP_XArrow;
+    else if (aValue == "yarrow")  theDatumPart = Prs3d_DP_YArrow;
+    else if (aValue == "zarrow")  theDatumPart = Prs3d_DP_ZArrow;
+    else if (aValue == "xoyaxis") theDatumPart = Prs3d_DP_XOYAxis;
+    else if (aValue == "yozaxis") theDatumPart = Prs3d_DP_YOZAxis;
+    else if (aValue == "xozaxis") theDatumPart = Prs3d_DP_XOZAxis;
+    else if (aValue == "whole")   theDatumPart = Prs3d_DP_None;
+    else
+    {
+      return false;
+    }
+    return true;
+  }
+
+  static void convertToDatumParts (const TCollection_AsciiString& theValue,
+                                   NCollection_List<Prs3d_DatumParts>& theParts)
+  {
+    TCollection_AsciiString aValue = theValue;
+    const Standard_Integer aSplitPos = theValue.Search ("|");
+    Prs3d_DatumParts aPart = Prs3d_DP_None;
+    if (aSplitPos > 0)
+    {
+      convertToDatumParts (theValue.SubString (aSplitPos + 1, theValue.Length()), theParts);
+      if (aSplitPos == 1) // first symbol
+      {
+        return;
+      }
+      aValue = theValue.SubString (1, aSplitPos - 1);
+    }
+    if (convertToDatumPart (aValue, aPart))
+    {
+      theParts.Append (aPart);
+    }
+  }
+
+  static bool convertToDatumAttribute (const TCollection_AsciiString& theValue,
+                                       Prs3d_DatumAttribute& theAttribute)
+  {
+    TCollection_AsciiString aValue = theValue;
+    aValue.LowerCase();
+    if      (aValue == "xaxislength")       theAttribute = Prs3d_DA_XAxisLength;
+    else if (aValue == "yaxislength")       theAttribute = Prs3d_DA_YAxisLength;
+    else if (aValue == "zaxislength")       theAttribute = Prs3d_DA_ZAxisLength;
+    else if (aValue == "tuberadiuspercent") theAttribute = Prs3d_DP_ShadingTubeRadiusPercent;
+    else if (aValue == "coneradiuspercent") theAttribute = Prs3d_DP_ShadingConeRadiusPercent;
+    else if (aValue == "conelengthpercent") theAttribute = Prs3d_DP_ShadingConeLengthPercent;
+    else if (aValue == "originradiuspercent") theAttribute = Prs3d_DP_ShadingOriginRadiusPercent;
+    else if (aValue == "shadingnumberoffacettes") theAttribute = Prs3d_DP_ShadingNumberOfFacettes;
+    else
+      return false;
+    return true;
+  }
+
+  static void convertToDatumAttributes (const TCollection_AsciiString& theValue,
+                                        NCollection_List<Prs3d_DatumAttribute>& theAttributes)
+  {
+    TCollection_AsciiString aValue = theValue;
+    const Standard_Integer aSplitPos = theValue.Search ("|");
+    Prs3d_DatumAttribute anAttribute = Prs3d_DA_XAxisLength;
+    if (aSplitPos > 0)
+    {
+      convertToDatumAttributes (theValue.SubString (aSplitPos + 1, theValue.Length()), theAttributes);
+      if (aSplitPos == 1) // first symbol
+      {
+        return;
+      }
+      aValue = theValue.SubString (1, aSplitPos - 1);
+    }
+    if (convertToDatumAttribute (aValue, anAttribute))
+    {
+      theAttributes.Append (anAttribute);
+    }
+  }
+
+  static bool convertToDatumAxes (const TCollection_AsciiString& theValue,
+                                  Prs3d_DatumAxes& theDatumAxes)
+  {
+    TCollection_AsciiString aValue = theValue;
+    aValue.LowerCase();
+    if      (aValue == "x")   theDatumAxes = Prs3d_DA_XAxis;
+    else if (aValue == "y")   theDatumAxes = Prs3d_DA_YAxis;
+    else if (aValue == "z")   theDatumAxes = Prs3d_DA_ZAxis;
+    else if (aValue == "xy")  theDatumAxes = Prs3d_DA_XYAxis;
+    else if (aValue == "zy")  theDatumAxes = Prs3d_DA_YZAxis;
+    else if (aValue == "xz")  theDatumAxes = Prs3d_DA_XZAxis;
+    else if (aValue == "xyz") theDatumAxes = Prs3d_DA_XYZAxis;
+    else
+    {
+      return false;
+    }
+    return true;
+  }
+
+  static Standard_Boolean setTrihedronParams (Standard_Integer  theArgsNb,
+                                              const char** theArgVec,
+                                              Handle(AIS_Trihedron) theTrihedron)
+  {
+    NCollection_DataMap<TCollection_AsciiString, Handle(TColStd_HSequenceOfAsciiString)> aMapOfArgs;
+    TCollection_AsciiString aParseKey;
+    for (Standard_Integer anArgIt = 1; anArgIt < theArgsNb; ++anArgIt)
+    {
+      TCollection_AsciiString anArg (theArgVec [anArgIt]);
+      if (anArg.Value (1) == '-'
+      && !anArg.IsRealValue())
+      {
+        aParseKey = anArg;
+        aParseKey.Remove (1);
+        aParseKey.LowerCase();
+        std::string aKey = aParseKey.ToCString();
+        aMapOfArgs.Bind (aParseKey, new TColStd_HSequenceOfAsciiString());
+        continue;
+      }
+
+      if (aParseKey.IsEmpty())
+      {
+        continue;
+      }
+
+      aMapOfArgs (aParseKey)->Append (anArg);
+    }
+
+    // Check parameters
+    if ((aMapOfArgs.IsBound ("xaxis") && !aMapOfArgs.IsBound ("zaxis"))
+    || (!aMapOfArgs.IsBound ("xaxis") &&  aMapOfArgs.IsBound ("zaxis")))
+    {
+      std::cout << "Syntax error: -xaxis and -zaxis parameters are to set together.\n";
+      return Standard_False;
+    }
+
+    Handle(TColStd_HSequenceOfAsciiString) aValues;
+    Handle(Geom_Axis2Placement) aComponent = theTrihedron->Component();
+    if (aMapOfArgs.Find ("origin", aValues))
+    {
+      aComponent->SetLocation (gp_Pnt (aValues->Value (1).RealValue(),
+                                       aValues->Value (2).RealValue(),
+                                       aValues->Value (3).RealValue()));
+    }
+    Handle(TColStd_HSequenceOfAsciiString) aXValues, aZValues;
+    if (aMapOfArgs.Find ("xaxis", aXValues) && aMapOfArgs.Find ("zaxis", aZValues))
+    {
+      gp_Dir aXDir (aXValues->Value (1).RealValue(),
+                    aXValues->Value (2).RealValue(),
+                    aXValues->Value (3).RealValue());
+
+      gp_Dir aZDir (aZValues->Value (1).RealValue(),
+                    aZValues->Value (2).RealValue(),
+                    aZValues->Value (3).RealValue());
+
+      if (!aZDir.IsNormal (aXDir, M_PI / 180.0))
+      {
+        std::cout << "Syntax error - parameters 'xaxis' and 'zaxis' are not applied as VectorX is not normal to VectorZ\n";
+        return Standard_False;
+      }
+
+      aComponent->SetXDirection(aXDir);
+      aComponent->SetDirection (aZDir);
+    }
+
+    if (aMapOfArgs.Find ("dispmode", aValues))
+    {
+      TCollection_AsciiString aValue (aValues->Value (1));
+      bool isWireframe = true;
+      if (aValue.IsEqual ("sh") || aValue.IsEqual ("shading"))
+        isWireframe = false;
+      theTrihedron->SetDatumDisplayMode (isWireframe ? Prs3d_DM_WireFrame
+                                                     : Prs3d_DM_Shaded);
+    }
+
+    if (aMapOfArgs.Find ("hidelabels", aValues))
+    {
+      if (aValues->Size() == 0)
+      {
+        std::cout << "Syntax error: -hidelabels expects parameter 'on' or 'off' after.\n";
+        return Standard_False;
+      }
+
+      Standard_Boolean toHideLabels = Standard_True;
+      ViewerTest::ParseOnOff (aValues->Value (1).ToCString(), toHideLabels);
+      if (!theTrihedron->Attributes()->HasOwnDatumAspect())
+        theTrihedron->Attributes()->SetDatumAspect(new Prs3d_DatumAspect());
+      theTrihedron->Attributes()->DatumAspect()->SetToDrawLabels (!toHideLabels);
+    }
+
+    if (aMapOfArgs.Find ("color", aValues))
+    {
+      NCollection_List<Prs3d_DatumParts> aParts;
+      if (aValues->Size() < 2)
+      {
+        std::cout << "Syntax error: -color wrong parameters.\n";
+        return Standard_False;
+      }
+
+      convertToDatumParts (aValues->Value(1), aParts);
+      aValues->Remove (1); // datum part is processed
+      Quantity_Color aColor;
+      if (!convertToColor (aValues, aColor))
+      {
+        std::cout << "Syntax error: -color wrong parameters.\n";
+        return Standard_False;
+      }
+
+      for (NCollection_List<Prs3d_DatumParts>::Iterator anIterator (aParts); anIterator.More(); anIterator.Next())
+      {
+        Prs3d_DatumParts aDatumPart = anIterator.Value();
+        if (aDatumPart == Prs3d_DP_None)
+        {
+          theTrihedron->SetColor (aColor);
+        }
+        else
+        {
+          theTrihedron->SetDatumPartColor (aDatumPart, aColor);
+        }
+      }
+    }
+
+    if (aMapOfArgs.Find ("textcolor", aValues))
+    {
+      Quantity_Color aColor;
+      if (!convertToColor (aValues, aColor))
+      {
+        std::cout << "Syntax error: -textcolor wrong parameters.\n";
+        return Standard_False;
+      }
+      theTrihedron->SetTextColor (aColor);
+    }
+
+    if (aMapOfArgs.Find ("arrowcolor", aValues))
+    {
+      Quantity_Color aColor;
+      if (!convertToColor (aValues, aColor))
+      {
+        std::cout << "Syntax error: -arrowcolor wrong parameters.\n";
+        return Standard_False;
+      }
+      theTrihedron->SetArrowColor (aColor);
+    }
+
+    if (aMapOfArgs.Find ("attribute", aValues))
+    {
+      NCollection_List<Prs3d_DatumAttribute> anAttributes;
+      if (aValues->Size() != 2)
+      {
+        std::cout << "Syntax error: -attribute wrong parameters.\n";
+        return Standard_False;
+      }
+
+      convertToDatumAttributes (aValues->Value (1), anAttributes);
+      if (!theTrihedron->Attributes()->HasOwnDatumAspect())
+        theTrihedron->Attributes()->SetDatumAspect(new Prs3d_DatumAspect());
+      for (NCollection_List<Prs3d_DatumAttribute>::Iterator anIterator (anAttributes); anIterator.More(); anIterator.Next())
+      {
+        theTrihedron->Attributes()->DatumAspect()->SetAttribute (anIterator.Value(), aValues->Value (2).RealValue());
+      }
+    }
+
+    if (aMapOfArgs.Find ("priority", aValues))
+    {
+      Prs3d_DatumParts aDatumPart;
+      if (aValues->Size() < 2
+      || !convertToDatumPart (aValues->Value (1), aDatumPart))
+      {
+        std::cout << "Syntax error: -priority wrong parameters.\n";
+        return Standard_False;
+      }
+      theTrihedron->SetSelectionPriority (aDatumPart, aValues->Value (2).IntegerValue());
+    }
+
+    if (aMapOfArgs.Find ("labels", aValues))
+    {
+      Prs3d_DatumParts aDatumPart = Prs3d_DP_None;
+      if (aValues->Size() > 2
+       && convertToDatumPart(aValues->Value(1), aDatumPart)
+       && aDatumPart >= Prs3d_DP_XAxis
+       && aDatumPart <= Prs3d_DP_ZAxis) // labels are set to axes only
+      {
+        theTrihedron->SetLabel (aDatumPart, aValues->Value (2));
+      }
+      else
+      {
+        std::cout << "Syntax error: -labels wrong parameters.\n";
+        return Standard_False;
+      }
+    }
+
+    if (aMapOfArgs.Find ("drawaxes", aValues))
+    {
+      Prs3d_DatumAxes aDatumAxes = Prs3d_DA_XAxis;
+      if (aValues->Size() < 1
+      || !convertToDatumAxes (aValues->Value (1), aDatumAxes))
+      {
+        std::cout << "Syntax error: -drawaxes wrong parameters.\n";
+        return Standard_False;
+      }
+      if (!theTrihedron->Attributes()->HasOwnDatumAspect())
+        theTrihedron->Attributes()->SetDatumAspect(new Prs3d_DatumAspect());
+      theTrihedron->Attributes()->DatumAspect()->SetDrawDatumAxes (aDatumAxes);
+    }
+    return Standard_True;
+  }
+}
 
 //==============================================================================
 //function : Vtrihedron 2d
 //purpose  : Create a plane with a 2D  trihedron from a faceselection
 //Draw arg : vtri2d  name
 //==============================================================================
-#include <AIS_PlaneTrihedron.hxx>
+static int VTrihedron2D (Draw_Interpretor& /*theDI*/,
+                         Standard_Integer  theArgsNum,
+                         const char**      theArgVec)
+{
+  if (theArgsNum != 2)
+  {
+    std::cerr << theArgVec[0]<< " error.\n";
+    return 1;
+  }
 
+  TopTools_ListOfShape aShapes;
+  ViewerTest::GetSelectedShapes (aShapes);
 
+  if (aShapes.Extent() != 1)
+  {
+    std::cerr << "Error: wrong number of selected shapes.\n";
+    return 1;
+  }
 
-static int VTrihedron2D (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
+  const TopoDS_Shape& aShape = aShapes.First();
 
-{
-  // Verification des arguments
-  if ( argc!=2) {di<<argv[0]<<" error"<<"\n"; return 1;}
+  TopoDS_Face     aFace = TopoDS::Face (aShape);
+  TopExp_Explorer aFaceExp (aFace, TopAbs_EDGE);
+  TopoDS_Edge     anEdge0 = TopoDS::Edge (aFaceExp.Current());
 
-  // Declarations
-  Standard_Integer myCurrentIndex;
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
-  // Ouverture d'un contexte local et recuperation de son index.
-  TheAISContext()->OpenLocalContext();
-  myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-  // On active les modes de selections faces.
-  TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4) );
-  di<<" Select a face ."<<"\n";
-
-  // Boucle d'attente waitpick.
-  Standard_Integer argccc = 5;
-  const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-  const char **argvvv = (const char **) bufff;
-  while (ViewerMainLoop( argccc, argvvv) ) { }
-  // fin de la boucle
-
-  TopoDS_Shape ShapeB;
-  for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-    ShapeB = TheAISContext()->SelectedShape();
-  }
-
-  TopoDS_Face  FaceB=TopoDS::Face(ShapeB);
-
-  // Construction du Plane
-  // recuperation des edges des faces.
-  TopExp_Explorer FaceExpB(FaceB,TopAbs_EDGE);
-
-  TopoDS_Edge EdgeB=TopoDS::Edge(FaceExpB.Current() );
-  // declarations
   gp_Pnt A,B,C;
-
-  // si il y a plusieurs edges
-  if (FaceExpB.More() ) {
-    FaceExpB.Next();
-    TopoDS_Edge EdgeC=TopoDS::Edge(FaceExpB.Current() );
-    BRepAdaptor_Curve theCurveB(EdgeB);
-    BRepAdaptor_Curve theCurveC(EdgeC);
-    A=theCurveC.Value(0.1);
-    B=theCurveC.Value(0.9);
-    C=theCurveB.Value(0.5);
+  if (aFaceExp.More())
+  {
+    aFaceExp.Next();
+    TopoDS_Edge anEdge1 = TopoDS::Edge (aFaceExp.Current() );
+    BRepAdaptor_Curve aCurve0 (anEdge0);
+    BRepAdaptor_Curve aCurve1 (anEdge1);
+    A = aCurve1.Value (0.1);
+    B = aCurve1.Value (0.9);
+    C = aCurve0.Value (0.5);
   }
-  else {
-    // FaceB a 1 unique edge courbe
-    BRepAdaptor_Curve theCurveB(EdgeB);
-    A=theCurveB.Value(0.1);
-    B=theCurveB.Value(0.9);
-    C=theCurveB.Value(0.5);
+  else
+  {
+    BRepAdaptor_Curve aCurve0 (anEdge0);
+    A = aCurve0.Value (0.1);
+    B = aCurve0.Value (0.9);
+    C = aCurve0.Value (0.5);
   }
-  // Construction du Geom_Plane
-  GC_MakePlane MkPlane(A,B,C);
-  Handle(Geom_Plane) theGeomPlane=MkPlane.Value();
 
-  // Construction de l'AIS_PlaneTrihedron
-  Handle(AIS_PlaneTrihedron) theAISPlaneTri= new AIS_PlaneTrihedron(theGeomPlane );
+  GC_MakePlane aMkPlane (A,B,C);
 
-  // Fermeture du contexte local.
-  TheAISContext()->CloseLocalContext(myCurrentIndex);
+  Handle(AIS_PlaneTrihedron) anAISPlaneTri = new AIS_PlaneTrihedron (aMkPlane.Value());
+  TCollection_AsciiString aName (theArgVec[1]);
 
-  // on le display & bind
-  TheAISContext()->Display(theAISPlaneTri );
-  GetMapOfAIS().Bind ( theAISPlaneTri ,argv[1]);
+  VDisplayAISObject (aName, anAISPlaneTri);
 
   return 0;
 }
 
-
-
-//==============================================================================
-//function : VTriherdron
-//purpose  : Create a trihedron. If no arguments are set, the default
-//           trihedron (Oxyz) is created.
-//Draw arg : vtrihedron  name  [Xo] [Yo] [Zo] [Zu] [Zv] [Zw] [Xu] [Xv] [Xw]
-//==============================================================================
-
-static int VTrihedron (Draw_Interpretor& theDi,
-                       Standard_Integer  theArgsNb,
-                       const char**      theArgVec)
+//=======================================================================
+//function : VTrihedron
+//purpose  :
+//=======================================================================
+static int VTrihedron (Draw_Interpretor& ,
+                       Standard_Integer theArgsNb,
+                       const char** theArgVec)
 {
-  if (theArgsNb != 2 && theArgsNb != 5 && theArgsNb != 11)
+  if (theArgsNb < 2)
   {
-    theDi << theArgVec[0] << " Syntax error\n";
+    std::cout << "Syntax error: the wrong number of input parameters.\n";
     return 1;
   }
 
-  gp_Pnt anOrigin (0.0, 0.0, 0.0);
-  gp_Dir aDirZ = gp::DZ();
-  gp_Dir aDirX = gp::DX();
-  Standard_Integer anArgIter = 2; // 1st is an IO name
-  if (anArgIter < theArgsNb)
+  TCollection_AsciiString aName (theArgVec[1]);
+  gp_Pln aWorkingPlane;
+  Standard_Boolean toUpdate = Standard_True;
+
+  NCollection_DataMap<TCollection_AsciiString, Standard_Real> aRealParams;
+  NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString> aStringParams;
+
+  Handle(AIS_Trihedron) aTrihedron;
+  if (GetMapOfAIS().IsBound2 (aName))
   {
-    anOrigin.SetX (Draw::Atof (theArgVec[anArgIter++]));
-    anOrigin.SetY (Draw::Atof (theArgVec[anArgIter++]));
-    anOrigin.SetZ (Draw::Atof (theArgVec[anArgIter++]));
-    if (anArgIter < theArgsNb)
+    Handle(AIS_InteractiveObject) anObject = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aName));
+    aTrihedron = Handle(AIS_Trihedron)::DownCast (anObject);
+    if (aTrihedron.IsNull())
     {
-      Standard_Real aX = Draw::Atof (theArgVec[anArgIter++]);
-      Standard_Real aY = Draw::Atof (theArgVec[anArgIter++]);
-      Standard_Real aZ = Draw::Atof (theArgVec[anArgIter++]);
-      aDirZ.SetCoord (aX, aY, aZ);
-
-      aX = Draw::Atof (theArgVec[anArgIter++]);
-      aY = Draw::Atof (theArgVec[anArgIter++]);
-      aZ = Draw::Atof (theArgVec[anArgIter++]);
-      aDirX.SetCoord (aX, aY, aZ);
+      std::cout << "Syntax error: no trihedron with this name.\n";
+      return 1;
     }
   }
+  else
+  {
+    Handle(Geom_Axis2Placement) aPlacement = new Geom_Axis2Placement (gp_Pnt (0.0, 0.0, 0.0),
+                                                                      gp::DZ(), gp::DX());
+    aTrihedron = new AIS_Trihedron (aPlacement);
+  }
 
-  if (!aDirZ.IsNormal (aDirX, M_PI / 180.0))
+  if (!setTrihedronParams (theArgsNb, theArgVec, aTrihedron))
   {
-    theDi << theArgVec[0] << " - VectorX is not normal to VectorZ\n";
     return 1;
   }
 
-  Handle(Geom_Axis2Placement) aPlacement = new Geom_Axis2Placement (anOrigin, aDirZ, aDirX);
-  Handle(AIS_Trihedron) aShape = new AIS_Trihedron (aPlacement);
-  VDisplayAISObject (theArgVec[1], aShape);
+  // Redisplay a dimension after parameter changing.
+  if (ViewerTest::GetAISContext()->IsDisplayed (aTrihedron))
+  {
+    ViewerTest::GetAISContext()->Redisplay (aTrihedron, toUpdate);
+  }
+  else
+  {
+    VDisplayAISObject (theArgVec[1], aTrihedron);
+  }
+
   return 0;
 }
 
@@ -302,22 +614,18 @@ static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv
   Standard_Real                value;
   Standard_Boolean             hascol;
 
-  Quantity_NameOfColor         col = Quantity_NOC_BLACK ;
+  Quantity_Color col = Quantity_NOC_BLACK;
 
   // Verification des arguments
-  if ( argc>3 ) {di<<argv[0]<<" Syntaxe error"<<"\n"; return 1;}
+  if ( argc>3 ) {di<<argv[0]<<" Syntaxe error\n"; return 1;}
 
   // Verification du nombre d'arguments
   if (argc==1)      {ThereIsName=Standard_False;value=100;}
   else if (argc==2) {ThereIsName=Standard_False;value=Draw::Atof(argv[1]);}
   else              {ThereIsName=Standard_True;value=Draw::Atof(argv[2]);}
 
-  // On ferme le contexte local pour travailler dans le contexte global
-  if(TheAISContext()->HasOpenedContext())
-    TheAISContext()->CloseLocalContext();
-
   // On set le booleen ThereIsCurrent
-  if (TheAISContext() -> NbCurrents() > 0) {ThereIsCurrent=Standard_True;}
+  if (TheAISContext() -> NbSelected() > 0) {ThereIsCurrent=Standard_True;}
   else {ThereIsCurrent=Standard_False;}
 
 
@@ -336,24 +644,28 @@ static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv
       Handle(AIS_InteractiveObject) aShape=
         Handle(AIS_InteractiveObject)::DownCast(it.Key1());
 
-      if (!aShape.IsNull() &&  TheAISContext()->IsCurrent(aShape) )
+      if (!aShape.IsNull() &&  TheAISContext()->IsSelected(aShape) )
       {
 
         // On verifie que l'AIS InteraciveObject selectionne est bien
         // un AIS_Trihedron
         if (aShape->Type()==AIS_KOI_Datum && aShape->Signature()==3) {
 
-          if (aShape->HasColor()) {
-            hascol=Standard_True;
+          if (aShape->HasColor())
+          {
+            hascol = Standard_True;
 
             // On recupere la couleur de aShape
-            col=aShape->Color();}
-
-          else hascol=Standard_False;
+            aShape->Color (col);
+          }
+          else
+          {
+            hascol = Standard_False;
+          }
 
           // On downcast aShape  de AIS_InteractiveObject a AIS_Trihedron
           // pour lui appliquer la methode SetSize()
-          Handle(AIS_Trihedron) aTrihedron = *(Handle(AIS_Trihedron)*) &aShape;
+          Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast (aShape);
 
           // C'est bien un triedre,on chage sa valeur!
           aTrihedron->SetSize(value);
@@ -403,18 +715,21 @@ static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv
       if (!aShape.IsNull() &&
         aShape->Type()==AIS_KOI_Datum && aShape->Signature()==3)
       {
-
-        if (aShape->HasColor()) {
+        if (aShape->HasColor())
+        {
           hascol=Standard_True;
 
           // On recupere la couleur de aShape
-          col=aShape->Color();}
-
-        else hascol=Standard_False;
+          aShape->Color (col);
+        }
+        else
+        {
+          hascol = Standard_False;
+        }
 
         // On downcast aShape de AIS_InteractiveObject a AIS_Trihedron
         // pour lui appliquer la methode SetSize()
-        Handle(AIS_Trihedron) aTrihedron = *(Handle(AIS_Trihedron)*) &aShape;
+        Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast (aShape);
 
         // C'est bien un triedre,on chage sa valeur
         aTrihedron->SetSize(value);
@@ -450,59 +765,24 @@ static int VPlaneTrihedron (Draw_Interpretor& di, Standard_Integer argc, const c
 
 {
   // Verification des arguments
-  if ( argc!=2) {di<<argv[0]<<" error"<<"\n"; return 1;}
+  if ( argc!=2) {di<<argv[0]<<" error\n"; return 1;}
 
-  // Declarations
-  Standard_Integer myCurrentIndex;
-  // Fermeture des contextes locaux
-  TheAISContext()->CloseAllContexts();
-
-  // On recupere tous les trihedrons de la GetMapOfAIS()
-  // et on active le mode de selection par face.
-  // =================================================
-
-  // Ouverture d'un contexte local et recuperation de son index.
-  TheAISContext()->OpenLocalContext(Standard_False);
-  myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-  ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName
-    it (GetMapOfAIS());
-  while(it.More()){
-    Handle(AIS_InteractiveObject) ShapeA =
-      Handle(AIS_InteractiveObject)::DownCast(it.Key1());
-    // On verifie que c'est bien un trihedron
-    if (!ShapeA.IsNull() &&
-      ShapeA->Type()==AIS_KOI_Datum  && ShapeA->Signature()==3  ) {
-        // on le downcast
-        Handle(AIS_Trihedron) TrihedronA =((*(Handle(AIS_Trihedron)*)&ShapeA));
-        // on le charge dans le contexte et on active le mode Plane.
-        TheAISContext()->Load(TrihedronA,0,Standard_False);
-        TheAISContext()->Activate(TrihedronA,3);
-      }
-      it.Next();
+  if (TheAISContext()->NbSelected() != 1)
+  {
+    std::cerr << "Error: Wrong number of selected shapes.\n";
+    return 1;
   }
 
-  di<<" Select a plane."<<"\n";
-  // Boucle d'attente waitpick.
-  Standard_Integer argccc = 5;
-  const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-  const char **argvvv = (const char **) bufff;
-  while (ViewerMainLoop( argccc, argvvv) ) { }
-  // fin de la boucle
-
-  Handle(AIS_InteractiveObject) theIOB;
-  for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-    theIOB = TheAISContext()->Interactive();
+  TheAISContext()->InitSelected();
+  Handle(AIS_InteractiveObject) aTest = TheAISContext()->SelectedInteractive();
+  Handle(AIS_Plane) aPlane = Handle(AIS_Plane)::DownCast (aTest);
+  if (aPlane.IsNull())
+  {
+    std::cerr << "Error: Selected shape is not a plane.\n";
+    return 1;
   }
-  // on le downcast
-  Handle(AIS_Plane) PlaneB =((*(Handle(AIS_Plane)*)&theIOB));
 
-  // Fermeture du contexte local.
-  TheAISContext()->CloseLocalContext(myCurrentIndex);
-
-  // on le display & bind
-  TheAISContext()->Display(PlaneB );
-  GetMapOfAIS().Bind ( PlaneB ,argv[1]);
+  VDisplayAISObject (argv[1], aPlane);
 
   return 0;
 }
@@ -534,16 +814,16 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
   // Declarations
   Standard_Boolean HasArg;
   TCollection_AsciiString name;
-  Standard_Integer MyCurrentIndex;
 
   // Verification
-  if (argc<2 || argc>8 ) {di<<" Syntaxe error"<<"\n";return 1;}
+  if (argc<2 || argc>8 ) {di<<" Syntaxe error\n";return 1;}
   if (argc==8) HasArg=Standard_True;
   else HasArg=Standard_False;
 
   name=argv[1];
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
+
+  TopTools_ListOfShape aShapes;
+  ViewerTest::GetSelectedShapes (aShapes);
 
   // Cas ou il y a des arguments
   // Purpose: Teste le constructeur AIS_Axis::AIS_Axis(x: Line from Geom)
@@ -558,7 +838,7 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
     Handle(Geom_Line) myLine=new Geom_Line (p1 ,myVect );
     Handle(AIS_Axis) TheAxis=new AIS_Axis (myLine );
     GetMapOfAIS().Bind (TheAxis,name);
-    TheAISContext()->Display(TheAxis);
+    TheAISContext()->Display(TheAxis, Standard_True);
   }
 
   // Pas d'arguments
@@ -566,70 +846,41 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
     // fonction vaxis
     // Purpose: Teste le constructeur AIS_Axis::AIS_Axis (x:Axis1Placement from Geom)
     if ( !strcasecmp(argv[0], "vaxis")) {
-      TheAISContext()->OpenLocalContext();
-      MyCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active le mode edge et le mode vertex
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(1) );
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(2) );
-      di<<" Select an edge or a vertex."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // fin de la boucle
-
-      // recuperation de la shape.
-      TopoDS_Shape ShapeA;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeA = TheAISContext()->SelectedShape();
-      }
-      // recuperation de l'AIS_InteractiveObject
-      //Handle(AIS_InteractiveObject) myAISio=TheAISContext()->Current();
-      // down cast en AIS_Point si sig et type
-      // AIS_Point -> Geom_Pnt ....
-
-      if (ShapeA.ShapeType()==TopAbs_VERTEX) {
-        // on desactive le mode edge
-        TheAISContext()->DeactivateStandardMode(AIS_Shape::SelectionType(2) );
-        di<<" Select a different vertex."<<"\n";
-
-        TopoDS_Shape ShapeB;
-        do {
-          // Boucle d'attente waitpick.
-          Standard_Integer argccc = 5;
-          const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-          const char **argvvv = (const char **) bufff;
-          while (ViewerMainLoop( argccc, argvvv) ) { }
-          // fin de la boucle
-          for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-            ShapeB = TheAISContext()->SelectedShape();
-          }
-
+      if (aShapes.Extent() != 2 && aShapes.Extent() != 1)
+      {
+        std::cerr << "Error: Wrong number of selected shapes.\n";
+        return 1;
+      }
 
-        } while(ShapeB.IsSame(ShapeA) );
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      if (aShapeA.ShapeType() == TopAbs_VERTEX)
+      {
+        if (aShapes.Extent() != 2)
+        {
+          std::cerr << "Error: Wron number of selected shapes.\n";
+          return 1;
+        }
 
-        // Fermeture du context local
-        TheAISContext()->CloseLocalContext(MyCurrentIndex);
+        const TopoDS_Shape& aShapeB = aShapes.Last();
+        if (aShapeB.ShapeType() != TopAbs_VERTEX)
+        {
+          std::cerr << "Syntax error: You should select two vertices or one edge.\n";
+          return 1;
+        }
 
         // Construction de l'axe
-        gp_Pnt   A=BRep_Tool::Pnt(TopoDS::Vertex(ShapeA)  );
-        gp_Pnt   B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB)  );
-        gp_Vec   V (A,B);
-        gp_Dir   D (V);
+        gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
+        gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
+        gp_Vec V (A,B);
+        gp_Dir D (V);
         Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (A,D);
         Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
         GetMapOfAIS().Bind (TheAxis,name);
-        TheAISContext()->Display(TheAxis);
-      }
-      else {
-        // Un unique edge (ShapeA) a ete picke
-        // Fermeture du context local
-        TheAISContext()->CloseLocalContext(MyCurrentIndex);
-        // Constuction de l'axe
-        TopoDS_Edge    ed =TopoDS::Edge(ShapeA);
+        TheAISContext()->Display (TheAxis, Standard_True);
+      }
+      else
+      {
+        TopoDS_Edge    ed =TopoDS::Edge (aShapeA);
         TopoDS_Vertex  Va,Vb;
         TopExp::Vertices(ed,Va,Vb );
         gp_Pnt A=BRep_Tool::Pnt(Va);
@@ -639,56 +890,32 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
         Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (A,D);
         Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
         GetMapOfAIS().Bind (TheAxis,name);
-        TheAISContext()->Display(TheAxis);
+        TheAISContext()->Display (TheAxis, Standard_True);
       }
 
     }
 
     // Fonction axispara
     // Purpose: Teste le constructeur AIS_Axis::AIS_Axis(x: Axis2Placement from Geom, y: TypeOfAxis from AIS)
-    else if ( !strcasecmp(argv[0], "vaxispara")) {
-
-      TheAISContext()->OpenLocalContext();
-      MyCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active le mode edge
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(2) );
-      di<<" Select an edge."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // fin de la boucle
-
-      TopoDS_Shape ShapeA;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeA = TheAISContext()->SelectedShape();
-      }
-      // Active le mode vertex et deactive edges
-      TheAISContext()->DeactivateStandardMode(AIS_Shape::SelectionType(2) );
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(1) );
-      di<<" Select a vertex."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argccc = 5;
-      const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvvv = (const char **) bufff;
-      while (ViewerMainLoop( argccc, argvvv) ) { }
-      // fin de la boucle
-
-      // On peut choisir un pnt sur l'edge
-      TopoDS_Shape ShapeB;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeB = TheAISContext()->SelectedShape();
-      }
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(MyCurrentIndex);
+    else if ( !strcasecmp(argv[0], "vaxispara"))
+    {
+      if (aShapes.Extent() != 2)
+      {
+        std::cerr << "Error: Wrong number of selected shapes.\n";
+        return 1;
+      }
 
-      // Construction de l'axe
-      TopoDS_Edge    ed=TopoDS::Edge(ShapeA) ;
-      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB) );
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      const TopoDS_Shape& aShapeB = aShapes.Last();
+      if (!(aShapeA.ShapeType() == TopAbs_EDGE
+         && aShapeB.ShapeType() == TopAbs_VERTEX))
+      {
+        std::cerr << "Syntax error: You should select face and then vertex.\n";
+        return 1;
+      }
+
+      TopoDS_Edge    ed=TopoDS::Edge (aShapeA);
+      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
       TopoDS_Vertex  Va,Vc;
       TopExp::Vertices(ed,Va,Vc );
       gp_Pnt A=BRep_Tool::Pnt(Va);
@@ -698,53 +925,31 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
       Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (B,D);
       Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
       GetMapOfAIS().Bind (TheAxis,name);
-      TheAISContext()->Display(TheAxis);
+      TheAISContext()->Display (TheAxis, Standard_True);
 
     }
 
     // Fonction axisortho
-    else  {
-      TheAISContext()->OpenLocalContext();
-      MyCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active le mode edge
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(2) );
-      di<<" Select an edge."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // fin de la boucle
-
-      TopoDS_Shape ShapeA;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeA = TheAISContext()->SelectedShape();
-      }
-      // Active le mode vertex et deactive edges
-      TheAISContext()->DeactivateStandardMode(AIS_Shape::SelectionType(2) );
-      TheAISContext()->ActivateStandardMode(AIS_Shape::SelectionType(1) );
-      di<<" Slect a vertex."<<"\n";
-
-      // Boucle d'attente waitpick.
-      Standard_Integer argccc = 5;
-      const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvvv = (const char **) bufff;
-      while (ViewerMainLoop( argccc, argvvv) ) { }
-      // fin de la boucle
-
-      // On peut choisir un pnt sur l'edge
-      TopoDS_Shape ShapeB;
-      for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-        ShapeB = TheAISContext()->SelectedShape();
-      }
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(MyCurrentIndex);
+    else
+    {
+      if (aShapes.Extent() != 2)
+      {
+        std::cerr << "Error: Wrong number of selected shapes.\n";
+        return 1;
+      }
+
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      const TopoDS_Shape& aShapeB = aShapes.Last();
+      if (!(aShapeA.ShapeType() == TopAbs_EDGE
+         && aShapeB.ShapeType() == TopAbs_VERTEX))
+      {
+        std::cerr << "Syntax error: You should select face and then vertex.\n";
+        return 1;
+      }
 
       // Construction de l'axe
-      TopoDS_Edge    ed=TopoDS::Edge(ShapeA) ;
-      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB) );
+      TopoDS_Edge    ed=TopoDS::Edge(aShapeA) ;
+      gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(aShapeB) );
       TopoDS_Vertex  Va,Vc;
       TopExp::Vertices(ed,Va,Vc );
       gp_Pnt A=BRep_Tool::Pnt(Va);
@@ -755,7 +960,7 @@ static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
       Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (B,D);
       Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
       GetMapOfAIS().Bind (TheAxis,name);
-      TheAISContext()->Display(TheAxis);
+      TheAISContext()->Display (TheAxis, Standard_True);
 
     }
 
@@ -787,16 +992,13 @@ static int VPointBuilder(Draw_Interpretor& di, Standard_Integer argc, const char
   // Declarations
   Standard_Boolean HasArg;
   TCollection_AsciiString name;
-  Standard_Integer myCurrentIndex;
 
   // Verification
-  if (argc<2 || argc>5 ) {di<<" Syntaxe error"<<"\n";return 1;}
+  if (argc<2 || argc>5 ) {di<<" Syntaxe error\n";return 1;}
   if (argc==5) HasArg=Standard_True;
   else HasArg=Standard_False;
 
   name=argv[1];
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
 
   // Il y a des arguments: teste l'unique constructeur AIS_Pnt::AIS_Pnt(Point from Geom)
   if (HasArg) {
@@ -806,50 +1008,35 @@ static int VPointBuilder(Draw_Interpretor& di, Standard_Integer argc, const char
     Handle(Geom_CartesianPoint )  myGeomPoint= new Geom_CartesianPoint (thecoord[0],thecoord[1],thecoord[2]);
     Handle(AIS_Point)  myAISPoint=new AIS_Point(myGeomPoint );
     GetMapOfAIS().Bind (myAISPoint,name);
-    TheAISContext()->Display(myAISPoint);
+    TheAISContext()->Display (myAISPoint, Standard_True);
   }
 
   // Il n'a pas d'arguments
-  else {
-    TheAISContext()->OpenLocalContext();
-    myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-    // Active le mode Vertex et Edges
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1) );
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(2) );
-    di<<" Select a vertex or an edge(build the middle)"<<"\n";
-
-    // Boucle d'attente waitpick.
-    Standard_Integer argcc = 5;
-    const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-    const char **argvv = (const char **) buff;
-    while (ViewerMainLoop( argcc, argvv) ) { }
-    // fin de la boucle
+  else
+  {
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
 
-    TopoDS_Shape ShapeA;
-    for (TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-      ShapeA= TheAISContext()->SelectedShape();
+    if (aShapes.Extent() != 1)
+    {
+      std::cerr << "Error: Wrong number of selected shapes.\n";
+      std::cerr << "\tYou should select one edge or vertex.\n";
+      return 1;
     }
 
-    if (ShapeA.ShapeType()==TopAbs_VERTEX ) {
-      // Un vertex a ete selectionne
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
+    const TopoDS_Shape& aShapeA = aShapes.First();
 
-      // Construction du point
-      gp_Pnt A=BRep_Tool::Pnt(TopoDS::Vertex(ShapeA ) );
+    if (aShapeA.ShapeType()==TopAbs_VERTEX )
+    {
+      gp_Pnt A=BRep_Tool::Pnt(TopoDS::Vertex(aShapeA ) );
       Handle(Geom_CartesianPoint) myGeomPoint= new Geom_CartesianPoint (A );
       Handle(AIS_Point)  myAISPoint = new AIS_Point  (myGeomPoint );
       GetMapOfAIS().Bind(myAISPoint,name);
-      TheAISContext()->Display(myAISPoint);
+      TheAISContext()->Display (myAISPoint, Standard_True);
     }
-    else {
-      // Un Edge a ete selectionne
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
-
-      // Construction du point milieu de l'edge
-      TopoDS_Edge myEdge=TopoDS::Edge(ShapeA);
+    else
+    {
+      TopoDS_Edge myEdge=TopoDS::Edge(aShapeA);
       TopoDS_Vertex myVertexA,myVertexB;
       TopExp::Vertices (myEdge ,myVertexA ,myVertexB );
       gp_Pnt A=BRep_Tool::Pnt(myVertexA );
@@ -858,7 +1045,7 @@ static int VPointBuilder(Draw_Interpretor& di, Standard_Integer argc, const char
       Handle(Geom_CartesianPoint) myGeomPointM= new Geom_CartesianPoint ( (A.X()+B.X())/2  , (A.Y()+B.Y())/2  , (A.Z()+B.Z())/2  );
       Handle(AIS_Point)  myAISPointM = new AIS_Point  (myGeomPointM );
       GetMapOfAIS().Bind(myAISPointM,name);
-      TheAISContext()->Display(myAISPointM);
+      TheAISContext()->Display (myAISPointM, Standard_True);
     }
 
   }
@@ -893,7 +1080,6 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
   // Declarations
   Standard_Boolean hasArg;
   TCollection_AsciiString aName;
-  Standard_Integer aCurrentIndex;
 
   // Verification
   if (argc<2 || argc>6 )
@@ -907,8 +1093,6 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
     hasArg=Standard_False;
 
   aName=argv[1];
-  // Close all contexts
-  TheAISContext()->CloseAllContexts();
 
   // There are some arguments
   if (hasArg)
@@ -981,21 +1165,21 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
            Abs(aCartPointB->Z()-aCartPointA->Z())<=Precision::Confusion())
         {
           // B=A
-          std::cout<<"vplane error: same points"<<"\n";return 1;
+          std::cout<<"vplane error: same points\n";return 1;
         }
         if(Abs(aCartPointC->X()-aCartPointA->X())<=Precision::Confusion() &&
            Abs(aCartPointC->Y()-aCartPointA->Y())<=Precision::Confusion() &&
            Abs(aCartPointC->Z()-aCartPointA->Z())<=Precision::Confusion())
         {
           // C=A
-          std::cout<<"vplane error: same points"<<"\n";return 1;
+          std::cout<<"vplane error: same points\n";return 1;
         }
         if(Abs(aCartPointC->X()-aCartPointB->X())<=Precision::Confusion() &&
            Abs(aCartPointC->Y()-aCartPointB->Y())<=Precision::Confusion() &&
            Abs(aCartPointC->Z()-aCartPointB->Z())<=Precision::Confusion())
         {
           // C=B
-          std::cout<<"vplane error: same points"<<"\n";return 1;
+          std::cout<<"vplane error: same points\n";return 1;
         }
 
         gp_Pnt A = aCartPointA->Pnt();
@@ -1024,7 +1208,7 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
             anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
           }
         }
-        TheAISContext()->Display(anAISPlane);
+        TheAISContext()->Display (anAISPlane, Standard_True);
       }
 
       // The first argument is an AIS_Axis
@@ -1082,7 +1266,7 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
         }
       }
-      TheAISContext()->Display(anAISPlane);
+      TheAISContext()->Display (anAISPlane, Standard_True);
 
     }
     // The first argumnet is an AIS_Plane
@@ -1137,7 +1321,7 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
         }
       }
-      TheAISContext()->Display(anAISPlane);
+      TheAISContext()->Display (anAISPlane, Standard_True);
     }
     // Error
     else
@@ -1149,103 +1333,32 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
   // There are no arguments
   else 
   {
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
+
     // Function vplane
     // Test the constructor AIS_Plane::AIS_Plane(Geom_Plane, Standard_Boolean )
     if (!strcasecmp(argv[0], "vplane"))
     {
-      TheAISContext()->OpenLocalContext();
-      aCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-      // Active modes Vertex, Edge and Face
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(2));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4));
-      std::cout<<"Select a vertex, a face or an edge\n";
-
-      // Wait for picking
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // end of the loop
-
-      TopoDS_Shape aShapeA;
-      for (TheAISContext()->InitSelected();
-           TheAISContext()->MoreSelected();
-           TheAISContext()->NextSelected())
+      if (aShapes.Extent() < 1 || aShapes.Extent() > 3)
       {
-        aShapeA = TheAISContext()->SelectedShape();
+        std::cerr << "Error: Wront number of selected shapes.\n";
+        std::cerr << "\tYou should one of variant: face, edge and vertex or three vertices.\n";
+        return 1;
       }
 
-      // aShapeA is a Vertex
-      if (aShapeA.ShapeType()==TopAbs_VERTEX )
+      const TopoDS_Shape& aShapeA = aShapes.First();
+      if (aShapeA.ShapeType() == TopAbs_VERTEX)
       {
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        std::cout<<" Select an edge or a different vertex\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-          TheAISContext()->MoreSelected();
-          TheAISContext()->NextSelected())
+        if (aShapes.Extent() == 2)
         {
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-        // aShapeB is a Vertex
-        if (aShapeB.ShapeType()==TopAbs_VERTEX)
-        {
-          // A and B are the same
-          if (aShapeB.IsSame(aShapeA))
+          const TopoDS_Shape& aShapeB = aShapes.Last();
+          if (aShapeB.ShapeType() != TopAbs_EDGE)
           {
-            std::cout<<" vplane: error, same points selected\n";
-            return 1;
-          }
-          TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(2));
-          std::cout<<" Select a different vertex\n";
-
-          // Wait for picking
-          Standard_Integer argcccc = 5;
-          const char *buffff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-          const char **argvvvv = (const char **) buffff;
-          while (ViewerMainLoop( argcccc, argvvvv) ) { }
-          // end of the loop
-
-          TopoDS_Shape aShapeC;
-          for (TheAISContext()->InitSelected();
-               TheAISContext()->MoreSelected();
-               TheAISContext()->NextSelected())
-          {
-            aShapeC = TheAISContext()->SelectedShape();
-          }
-          // aShapeC is the same as A or B
-          if (aShapeC.IsSame(aShapeA)||aShapeC.IsSame(aShapeB))
-          {
-            std::cout<<" vplane: error, same points selected\n";
+            std::cerr << "Syntax error: Together with vertex should be edge.\n";
             return 1;
           }
 
-          // Close the local context
-          TheAISContext()->CloseLocalContext(aCurrentIndex);
-
-          // Construction of plane
-          gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(aShapeA));
-          gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
-          gp_Pnt C = BRep_Tool::Pnt(TopoDS::Vertex(aShapeC));
-          GC_MakePlane MkPlane(A, B, C);
-          Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
-          GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        // ShapeB is an edge
-        else
-        {
           // Verify that the vertex is not on the edge ShapeB
           TopoDS_Edge anEdgeB = TopoDS::Edge(aShapeB);
           TopoDS_Vertex aVertA = TopoDS::Vertex(aShapeA);
@@ -1259,9 +1372,6 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           }
           else
           {
-            // Close the local context
-            TheAISContext()->CloseLocalContext(aCurrentIndex);
-            // Construction of plane
             gp_Pnt A = BRep_Tool::Pnt(aVertA);
             TopoDS_Vertex aVBa, aVBb;
             TopExp::Vertices(anEdgeB ,aVBa ,aVBb);
@@ -1271,32 +1381,56 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
             Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
             Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
             GetMapOfAIS().Bind (anAISPlane, aName);
-            TheAISContext()->Display(anAISPlane);
+            TheAISContext()->Display (anAISPlane, Standard_True);
+          }
+        }
+        else if (aShapes.Extent() == 3)
+        {
+          TopTools_ListOfShape::Iterator anIter (aShapes);
+
+          anIter.Next();
+          const TopoDS_Shape& aShapeB = anIter.Value();
+
+          anIter.Next();
+          const TopoDS_Shape& aShapeC = anIter.Value();
+
+          if (!(aShapeB.ShapeType() == TopAbs_VERTEX
+             && aShapeC.ShapeType() == TopAbs_VERTEX))
+          {
+            std::cerr << "Syntax error: You should one of variant: face, edge and vertex or three vertices.\n";
+            return 1;
           }
+
+          gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(aShapeA));
+          gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
+          gp_Pnt C = BRep_Tool::Pnt(TopoDS::Vertex(aShapeC));
+          GC_MakePlane MkPlane(A, B, C);
+          Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
+          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
+          GetMapOfAIS().Bind (anAISPlane, aName);
+          TheAISContext()->Display (anAISPlane, Standard_True);
+        }
+        else
+        {
+          std::cerr << "Syntax error: You should one of variant: face, edge and vertex or three vertices.\n";
+          return 1;
         }
       }
-      // aShapeA is an edge
-      else if (aShapeA.ShapeType()==TopAbs_EDGE)
+      else if (aShapeA.ShapeType() == TopAbs_EDGE)
       {
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(2));
-        std::cout<<" Select a vertex that don't belong to the edge\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
+        if (aShapes.Extent() != 2)
+        {
+          std::cerr << "Error: wrong number of selected shapes.\n";
+          return 1;
+        }
 
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
+        const TopoDS_Shape& aShapeB = aShapes.Last();
+        if (aShapeB.ShapeType() != TopAbs_VERTEX)
         {
-          aShapeB = TheAISContext()->SelectedShape();
+          std::cerr << "Syntax error: Together with edge should be vertex.\n";
+          return 1;
         }
-        // aShapeB should be a Vertex
+
         // Check that the vertex aShapeB is not on the edge
         TopoDS_Edge anEdgeA = TopoDS::Edge(aShapeA);
         TopoDS_Vertex aVertB = TopoDS::Vertex(aShapeB);
@@ -1308,29 +1442,20 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           std::cout<<" vplane: error point is on the edge\n";
           return 1;
         }
-        else
-        {
-          // Close the local context
-          TheAISContext()->CloseLocalContext(aCurrentIndex);
-          // Construction of plane
-          gp_Pnt B = BRep_Tool::Pnt(aVertB);
-          TopoDS_Vertex aVAa, aVAb;
-          TopExp::Vertices(anEdgeA, aVAa, aVAb);
-          gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
-          gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
-          GC_MakePlane MkPlane (B,Aa,Ab);
-          Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
-          GetMapOfAIS().Bind (anAISPlane ,aName);
-          TheAISContext()->Display(anAISPlane);
-        }
+
+        gp_Pnt B = BRep_Tool::Pnt(aVertB);
+        TopoDS_Vertex aVAa, aVAb;
+        TopExp::Vertices(anEdgeA, aVAa, aVAb);
+        gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
+        gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
+        GC_MakePlane MkPlane (B,Aa,Ab);
+        Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
+        Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
+        GetMapOfAIS().Bind (anAISPlane ,aName);
+        TheAISContext()->Display (anAISPlane, Standard_True);
       }
-      // aShapeA is a Face
-      else
+      else if (aShapeA.ShapeType() == TopAbs_FACE)
       {
-        // Close the local context: nothing to select
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
-        // Construction of plane
         TopoDS_Face aFace = TopoDS::Face(aShapeA);
         BRepAdaptor_Surface aSurface (aFace, Standard_False);
         if (aSurface.GetType()==GeomAbs_Plane)
@@ -1339,7 +1464,7 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           Handle(Geom_Plane) aGeomPlane = new Geom_Plane(aPlane);
           Handle(AIS_Plane) anAISPlane = new AIS_Plane(aGeomPlane);
           GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
+          TheAISContext()->Display (anAISPlane, Standard_True);
         }
         else
         {
@@ -1347,6 +1472,11 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
           return 1;
         }
       }
+      else
+      {
+        std::cerr << "Syntax error: You should one of variant: face, edge and vertex or three vertices.\n";
+        return 1;
+      }
     }
 
     // Function vPlanePara
@@ -1354,120 +1484,44 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
     // test the constructor AIS_Plane::AIS_Plane(Geom_Plane,gp_Pnt)
     else if (!strcasecmp(argv[0], "vplanepara"))
     {
-      TheAISContext()->OpenLocalContext();
-      aCurrentIndex = TheAISContext()->IndexOfCurrentLocal();
-
-      // Activate modes Vertex and Face
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4));
-      std::cout<<" Select a vertex or a face\n";
-
-      // Wait for picking
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // end of the loop
-
-      TopoDS_Shape aShapeA;
-      for (TheAISContext()->InitSelected();
-           TheAISContext()->MoreSelected();
-           TheAISContext()->NextSelected())
+      if (aShapes.Extent() != 2)
       {
-        aShapeA = TheAISContext()->SelectedShape();
+        std::cerr << "Error: Wrong number of selected shapes.\n";
+        return 1;
       }
 
-      if (aShapeA.ShapeType()==TopAbs_VERTEX )
+      const TopoDS_Shape* aShapeA = &aShapes.First();
+      const TopoDS_Shape* aShapeB = &aShapes.Last();
+      if (aShapeA->ShapeType() != TopAbs_VERTEX)
       {
-        // aShapeA is a vertex
-        // Deactivate the mode Vertex
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(1));
-        std::cout<<" Select a face\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // A vertex ShapeA can be on Face ShapeB
-          aShapeB = TheAISContext()->SelectedShape();
-        }
+        std::swap (aShapeA, aShapeB);
+      }
 
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
+      if (!(aShapeA->ShapeType() == TopAbs_VERTEX
+         && aShapeB->ShapeType() == TopAbs_FACE))
+      {
+        std::cerr << "Syntax error: you should select face and vertex.\n";
+        return 1;
+      }
 
-        // Construction of plane
-        gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(aShapeA));
+      gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(*aShapeA));
 
-        TopoDS_Face aFace = TopoDS::Face(aShapeB);
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane )
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          // Construct a plane parallel to aGeomPlane through A
-          aPlane.SetLocation(A);
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          Handle(AIS_Plane) aAISPlane = new AIS_Plane (aGeomPlane, A);
-          GetMapOfAIS().Bind (aAISPlane ,aName);
-          TheAISContext()->Display(aAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplanepara: error\n";
-          return 1;
-        }
+      TopoDS_Face aFace = TopoDS::Face(*aShapeB);
+      BRepAdaptor_Surface aSurface (aFace, Standard_False);
+      if (aSurface.GetType() == GeomAbs_Plane)
+      {
+        gp_Pln aPlane = aSurface.Plane();
+        // Construct a plane parallel to aGeomPlane through A
+        aPlane.SetLocation(A);
+        Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
+        Handle(AIS_Plane) aAISPlane = new AIS_Plane (aGeomPlane, A);
+        GetMapOfAIS().Bind (aAISPlane ,aName);
+        TheAISContext()->Display (aAISPlane, Standard_True);
       }
       else
       {
-        // ShapeA is a Face
-        // Deactive the mode Face
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        std::cout<<" Select a vertex\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // A vertex ShapeB can be on Face ShapeA
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
-
-        // Construction of plane
-        gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
-
-        TopoDS_Face aFace=TopoDS::Face(aShapeA);
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane )
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          aPlane.SetLocation(B);
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          // Construct a plane parallel to aGeomPlane through B
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, B);
-          GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplanepara: error"<<"\n";return 1;
-        }
+        std::cerr << "Error: Builded surface is not a plane.\n";
+        return 1;
       }
     }
 
@@ -1476,165 +1530,70 @@ static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
     // test the constructor AIS_Plane::AIS_Plane(Geom_Plane,gp_Pnt,gp_Pnt,gp_Pnt)
     else
     {
-      TheAISContext()->OpenLocalContext();
-      aCurrentIndex = TheAISContext()->IndexOfCurrentLocal();
-
-      // Activate the modes Edge and Face
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(2));
-      TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4));
-      std::cout<<" Select a face and an edge coplanar\n";
+      if (aShapes.Extent() != 2)
+      {
+        std::cerr << "Error: wrong number of selected shapes.\n";
+        return 1;
+      }
 
-      // Wait for picking
-      Standard_Integer argcc = 5;
-      const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvv = (const char **) buff;
-      while (ViewerMainLoop( argcc, argvv) ) { }
-      // end of the loop
+      const TopoDS_Shape* aShapeA = &aShapes.First();
+      const TopoDS_Shape* aShapeB = &aShapes.Last();
 
-      TopoDS_Shape aShapeA;
-      for (TheAISContext()->InitSelected();
-           TheAISContext()->MoreSelected();
-           TheAISContext()->NextSelected())
+      if (aShapeA->ShapeType() != TopAbs_EDGE)
       {
-        aShapeA = TheAISContext()->SelectedShape();
+        std::swap (aShapeA, aShapeB);
       }
 
-      if (aShapeA.ShapeType()==TopAbs_EDGE )
+      if (!(aShapeA->ShapeType() == TopAbs_EDGE
+         && aShapeB->ShapeType() == TopAbs_FACE))
       {
-        // ShapeA is an edge, deactivate the mode Edge...
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(2));
-        std::cout<<" Select a face\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // Edge ShapeA can be on Face ShapeB
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
-
-        // Construction of plane
-        TopoDS_Edge anEdgeA = TopoDS::Edge(aShapeA);
-        TopoDS_Vertex aVAa, aVAb;
-        TopExp::Vertices(anEdgeA, aVAa, aVAb);
-        gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
-        gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
-        gp_Vec ab (Aa,Ab);
-
-        gp_Dir Dab (ab);
-        // Creation of rotation axis
-        gp_Ax1 aRotAxis (Aa,Dab);
-
-        TopoDS_Face aFace = TopoDS::Face(aShapeB);
-        // The edge must be parallel to the face
-        BRepExtrema_ExtPF aHeightA (aVAa, aFace);
-        BRepExtrema_ExtPF aHeightB (aVAb, aFace);
-        // Compare to heights
-        if (fabs(sqrt(aHeightA.SquareDistance(1)) - sqrt(aHeightB.SquareDistance(1)))
-            >Precision::Confusion())
-        {
-          // the edge is not parallel to the face
-          std::cout<<" vplaneortho error: the edge is not parallel to the face\n";
-          return 1;
-        }
-        // the edge is OK
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane)
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          // It rotates a half turn round the axis of rotation
-          aPlane.Rotate(aRotAxis , M_PI/2);
+        std::cerr << "Error: you should select edge and face.\n";
+        return 1;
+      }
 
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          // constructed aGeomPlane parallel to a plane containing the edge (center mid-edge)
-          gp_Pnt aMiddle ((Aa.X()+Ab.X() )/2 ,(Aa.Y()+Ab.Y() )/2 ,(Aa.Z()+Ab.Z() )/2 );
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, aMiddle);
-          GetMapOfAIS().Bind (anAISPlane, aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplaneortho: error\n";
-          return 1;
-        }
+      // Construction of plane
+      TopoDS_Edge anEdgeA = TopoDS::Edge(*aShapeA);
+      TopoDS_Vertex aVAa, aVAb;
+      TopExp::Vertices(anEdgeA, aVAa, aVAb);
+      gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
+      gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
+      gp_Vec ab (Aa,Ab);
+
+      gp_Dir Dab (ab);
+      // Creation of rotation axis
+      gp_Ax1 aRotAxis (Aa,Dab);
+
+      TopoDS_Face aFace = TopoDS::Face(*aShapeB);
+      // The edge must be parallel to the face
+      BRepExtrema_ExtPF aHeightA (aVAa, aFace);
+      BRepExtrema_ExtPF aHeightB (aVAb, aFace);
+      // Compare to heights
+      if (fabs(sqrt(aHeightA.SquareDistance(1)) - sqrt(aHeightB.SquareDistance(1)))
+          >Precision::Confusion())
+      {
+        // the edge is not parallel to the face
+        std::cout<<" vplaneortho error: the edge is not parallel to the face\n";
+        return 1;
+      }
+      // the edge is OK
+      BRepAdaptor_Surface aSurface (aFace, Standard_False);
+      if (aSurface.GetType()==GeomAbs_Plane)
+      {
+        gp_Pln aPlane = aSurface.Plane();
+        // It rotates a half turn round the axis of rotation
+        aPlane.Rotate(aRotAxis , M_PI/2);
+
+        Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
+        // constructed aGeomPlane parallel to a plane containing the edge (center mid-edge)
+        gp_Pnt aMiddle ((Aa.X()+Ab.X() )/2 ,(Aa.Y()+Ab.Y() )/2 ,(Aa.Z()+Ab.Z() )/2 );
+        Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, aMiddle);
+        GetMapOfAIS().Bind (anAISPlane, aName);
+        TheAISContext()->Display (anAISPlane, Standard_True);
       }
       else
       {
-        // ShapeA is a Face, deactive the mode Face.
-        TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4));
-        std::cout<<" Select an edge\n";
-
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
-
-        TopoDS_Shape aShapeB;
-        for (TheAISContext()->InitSelected();
-             TheAISContext()->MoreSelected();
-             TheAISContext()->NextSelected())
-        {
-          // Edge ShapeB can be on Face ShapeA
-          aShapeB = TheAISContext()->SelectedShape();
-        }
-        // Close the local context
-        TheAISContext()->CloseLocalContext(aCurrentIndex);
-
-        // Construction of plane
-        TopoDS_Edge anEdgeB = TopoDS::Edge(aShapeB);
-        TopoDS_Vertex aVBa, aVBb;
-        TopExp::Vertices(anEdgeB, aVBa, aVBb);
-        gp_Pnt aBa = BRep_Tool::Pnt(aVBa);
-        gp_Pnt aBb = BRep_Tool::Pnt(aVBb);
-        gp_Vec ab (aBa,aBb);
-        gp_Dir Dab (ab);
-        // Creation of rotation axe
-        gp_Ax1 aRotAxis (aBa,Dab);
-
-        TopoDS_Face aFace = TopoDS::Face(aShapeA);
-        // The edge must be parallel to the face
-        BRepExtrema_ExtPF aHeightA (aVBa, aFace);
-        BRepExtrema_ExtPF aHeightB (aVBb, aFace);
-        // Comparing the two heights
-        if (fabs(sqrt(aHeightA.SquareDistance(1)) - sqrt(aHeightB.SquareDistance(1)))
-            >Precision::Confusion())
-        {
-          // the edge is not parallel to the face
-          std::cout<<" vplaneortho error: the edge is not parallel to the face\n";
-          return 1;
-        }
-        // The edge is OK
-        BRepAdaptor_Surface aSurface (aFace, Standard_False);
-        if (aSurface.GetType()==GeomAbs_Plane)
-        {
-          gp_Pln aPlane = aSurface.Plane();
-          // It rotates a half turn round the axis of rotation
-          aPlane.Rotate(aRotAxis , M_PI/2);
-          Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
-          // constructed aGeomPlane parallel to a plane containing the edge theGeomPlane (center mid-edge)
-          gp_Pnt aMiddle ((aBa.X()+aBb.X() )/2 , (aBa.Y()+aBb.Y() )/2 , (aBa.Z()+aBb.Z() )/2 );
-          Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, aMiddle);
-          GetMapOfAIS().Bind (anAISPlane ,aName);
-          TheAISContext()->Display(anAISPlane);
-        }
-        else
-        {
-          std::cout<<" vplaneortho: error\n";
-          return 1;
-        }
+        std::cout<<" vplaneortho: error\n";
+        return 1;
       }
     }
   }
@@ -1743,10 +1702,7 @@ static int VChangePlane (Draw_Interpretor& /*theDi*/, Standard_Integer theArgsNb
   aPlane->SetComponent (new Geom_Plane (aCenterPnt, aDirection));
   aPlane->SetSize (aSizeX, aSizeY);
 
-  if (isUpdate)
-  {
-    aContextAIS->Update (aPlane, Standard_True);
-  }
+  aContextAIS->Update (aPlane, isUpdate);
 
   return 0;
 }
@@ -1768,11 +1724,8 @@ static int VChangePlane (Draw_Interpretor& /*theDi*/, Standard_Integer theArgsNb
 
 static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
 {
-  Standard_Integer myCurrentIndex;
   // Verifications
-  if (argc!=4 && argc!=8 && argc!=2 )  {di<<"vline error: number of arguments not correct "<<"\n";return 1; }
-  // Fermeture des contextes
-  TheAISContext()->CloseAllContexts();
+  if (argc!=4 && argc!=8 && argc!=2 )  {di<<"vline error: number of arguments not correct \n";return 1; }
 
   // On recupere les parametres
   Handle(AIS_InteractiveObject) theShapeA;
@@ -1792,31 +1745,31 @@ static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
         if (theShapeA.IsNull() ||
           (!(theShapeB->Type()==AIS_KOI_Datum && theShapeB->Signature()==1)))
         {
-          di <<"vline error: wrong type of 2de argument."<<"\n";
+          di <<"vline error: wrong type of 2de argument.\n";
           return 1;
         }
       }
-    else {di <<"vline error: wrong type of 1st argument."<<"\n";return 1; }
+    else {di <<"vline error: wrong type of 1st argument.\n";return 1; }
     // Les deux parametres sont du bon type. On verifie que les points ne sont pas confondus
-    Handle(AIS_Point) theAISPointA= *(Handle(AIS_Point)*)& theShapeA;
-    Handle(AIS_Point) theAISPointB= *(Handle(AIS_Point)*)& theShapeB;
+    Handle(AIS_Point) theAISPointA= Handle(AIS_Point)::DownCast (theShapeA);
+    Handle(AIS_Point) theAISPointB= Handle(AIS_Point)::DownCast (theShapeB);
 
     Handle(Geom_Point ) myGeomPointBA=  theAISPointA->Component();
-    Handle(Geom_CartesianPoint ) myCartPointA= *((Handle(Geom_CartesianPoint)*)&  myGeomPointBA);
+    Handle(Geom_CartesianPoint ) myCartPointA= Handle(Geom_CartesianPoint)::DownCast (myGeomPointBA);
     //    Handle(Geom_CartesianPoint ) myCartPointA= *(Handle(Geom_CartesianPoint)*)& (theAISPointA->Component() ) ;
 
     Handle(Geom_Point ) myGeomPointB=  theAISPointB->Component();
-    Handle(Geom_CartesianPoint ) myCartPointB= *((Handle(Geom_CartesianPoint)*)&  myGeomPointB);
+    Handle(Geom_CartesianPoint ) myCartPointB= Handle(Geom_CartesianPoint)::DownCast (myGeomPointB);
     //    Handle(Geom_CartesianPoint ) myCartPointB= *(Handle(Geom_CartesianPoint)*)& (theAISPointB->Component() ) ;
 
     if (myCartPointB->X()==myCartPointA->X() && myCartPointB->Y()==myCartPointA->Y() && myCartPointB->Z()==myCartPointA->Z() ) {
       // B=A
-      di<<"vline error: same points"<<"\n";return 1;
+      di<<"vline error: same points\n";return 1;
     }
     // Les deux points sont OK...Construction de l'AIS_Line (en faite, le segment AB)
     Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
     GetMapOfAIS().Bind(theAISLine,argv[1] );
-    TheAISContext()->Display(theAISLine );
+    TheAISContext()->Display (theAISLine, Standard_True);
 
   }
 
@@ -1837,74 +1790,43 @@ static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char*
 
     Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
     GetMapOfAIS().Bind(theAISLine,argv[1] );
-    TheAISContext()->Display(theAISLine );
+    TheAISContext()->Display (theAISLine, Standard_True);
 
   }
 
   // Pas de parametres: Selection dans le viewer.
   // ============================================
 
-  else {
-    TheAISContext()->OpenLocalContext();
-    myCurrentIndex=TheAISContext()->IndexOfCurrentLocal();
-
-    // Active le mode Vertex.
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1) );
-    di<<" Select a vertex "<<"\n";
-
-    // Boucle d'attente waitpick.
-    Standard_Integer argcc = 5;
-    const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-    const char **argvv = (const char **) buff;
-    while (ViewerMainLoop( argcc, argvv) ) { }
-    // fin de la boucle
-
-    TopoDS_Shape ShapeA;
-    for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-      ShapeA = TheAISContext()->SelectedShape();
+  else
+  {
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
+    if (aShapes.Extent() != 2)
+    {
+      std::cerr << "Error: wrong number of selected shapes.\n";
+      return 1;
     }
 
-    // ShapeA est un Vertex
-    if (ShapeA.ShapeType()==TopAbs_VERTEX ) {
-
-      di<<" Select a different vertex."<<"\n";
-
-      TopoDS_Shape ShapeB;
-      do {
-
-        // Boucle d'attente waitpick.
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // fin de la boucle
+    const TopoDS_Shape& aShapeA = aShapes.First();
+    const TopoDS_Shape& aShapeB = aShapes.Last();
 
-        for(TheAISContext()->InitSelected() ;TheAISContext()->MoreSelected() ;TheAISContext()->NextSelected() ) {
-          ShapeB = TheAISContext()->SelectedShape();
-        }
-
-
-      } while(ShapeB.IsSame(ShapeA) );
-
-      // Fermeture du context local
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
-
-      // Construction de la line
-      gp_Pnt   A=BRep_Tool::Pnt(TopoDS::Vertex(ShapeA)  );
-      gp_Pnt   B=BRep_Tool::Pnt(TopoDS::Vertex(ShapeB)  );
-
-      Handle(Geom_CartesianPoint ) myCartPointA=new Geom_CartesianPoint(A);
-      Handle(Geom_CartesianPoint ) myCartPointB=new Geom_CartesianPoint(B);
+    if (!(aShapeA.ShapeType() == TopAbs_VERTEX
+       && aShapeB.ShapeType() == TopAbs_VERTEX))
+    {
+      std::cerr << "Error: you should select two different vertex.\n";
+      return 1;
+    }
 
-      Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
-      GetMapOfAIS().Bind(theAISLine,argv[1] );
-      TheAISContext()->Display(theAISLine );
+    // Construction de la line
+    gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
+    gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
 
-    }
-    else  {
-      di<<"vline error."<<"\n";
-    }
+    Handle(Geom_CartesianPoint ) myCartPointA=new Geom_CartesianPoint(A);
+    Handle(Geom_CartesianPoint ) myCartPointB=new Geom_CartesianPoint(B);
 
+    Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
+    GetMapOfAIS().Bind(theAISLine,argv[1] );
+    TheAISContext()->Display (theAISLine, Standard_True);
   }
 
   return 0;
@@ -1929,13 +1851,11 @@ Handle(Geom_Circle) CreateCircle(gp_Pnt theCenter, Standard_Real theRadius)
   return aCircle;
 }
 
-DEFINE_STANDARD_HANDLE(FilledCircle, AIS_InteractiveObject)
-
 class FilledCircle : public AIS_InteractiveObject 
 {
 public:
     // CASCADE RTTI
-    DEFINE_STANDARD_RTTI(FilledCircle); 
+    DEFINE_STANDARD_RTTI_INLINE(FilledCircle,AIS_InteractiveObject); 
 
     FilledCircle(gp_Pnt theCenter, Standard_Real theRadius);
     FilledCircle(Handle(Geom_Circle) theCircle);
@@ -1946,10 +1866,10 @@ private:
     // Virtual methods implementation
     void Compute (  const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
                   const Handle(Prs3d_Presentation)& thePresentation,
-                  const Standard_Integer theMode);
+                  const Standard_Integer theMode) Standard_OVERRIDE;
 
     void ComputeSelection (  const Handle(SelectMgr_Selection)& theSelection, 
-                           const Standard_Integer theMode);
+                           const Standard_Integer theMode) Standard_OVERRIDE;
 
 protected:
     Handle(Geom_Circle) myCircle;
@@ -1957,8 +1877,6 @@ protected:
 
 }; 
 
-IMPLEMENT_STANDARD_HANDLE(FilledCircle, AIS_InteractiveObject)
-IMPLEMENT_STANDARD_RTTIEXT(FilledCircle, AIS_InteractiveObject)
 
 FilledCircle::FilledCircle(gp_Pnt theCenter, Standard_Real theRadius) 
 {
@@ -2054,27 +1972,25 @@ void DisplayCircle (Handle (Geom_Circle) theGeomCircle,
    GetMapOfAIS().Bind(aCircle, theName);
 
    // Display the circle
-   TheAISContext()->Display(aCircle);
+   TheAISContext()->Display (aCircle, Standard_True);
   
 }
 
 static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const char** argv)
 {
-  Standard_Integer myCurrentIndex;
   // Verification of the arguments
   if (argc>6 || argc<2) 
   { 
     std::cout << "vcircle error: expect 4 arguments.\n"; 
     return 1; // TCL_ERROR 
   }
-  TheAISContext()->CloseAllContexts();
 
   // There are all arguments
   if (argc == 6) 
   {
     // Get arguments
     TCollection_AsciiString aName(argv[1]);
-    Standard_Boolean isFilled = (Standard_Boolean)Draw::Atoi(argv[5]);
+    Standard_Boolean isFilled = Draw::Atoi(argv[5]) != 0;
 
     Handle(AIS_InteractiveObject) theShapeA;
     Handle(AIS_InteractiveObject) theShapeB;
@@ -2226,85 +2142,40 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
     // Get the name of the circle 
     TCollection_AsciiString aName(argv[1]);
 
-    TheAISContext()->OpenLocalContext();
-    myCurrentIndex = TheAISContext()->IndexOfCurrentLocal();
-
-    // Activate selection mode for vertices and faces
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(1) );
-    TheAISContext()->ActivateStandardMode (AIS_Shape::SelectionType(4) );
-    std::cout << " Select a vertex or a face\n";
-
-    // Wait for picking
-    Standard_Integer argcc = 5;
-    const char *buff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-    const char **argvv = (const char **) buff;
-    while (ViewerMainLoop( argcc, argvv) ) { }
-    // end of the loop
-
-    TopoDS_Shape ShapeA;
-    for(TheAISContext()->InitSelected(); 
-      TheAISContext()->MoreSelected(); 
-      TheAISContext()->NextSelected() ) 
+    TopTools_ListOfShape aShapes;
+    ViewerTest::GetSelectedShapes (aShapes);
+    if (aShapes.Extent() != 3 && aShapes.Extent() != 2)
     {
-      ShapeA = TheAISContext()->SelectedShape();
+      std::cerr << "Error: Wrong number of selected shapes.\n";
+      return 1;
     }
 
-    // ShapeA is a Vertex
-    if (ShapeA.ShapeType() == TopAbs_VERTEX ) 
+    const TopoDS_Shape& aShapeA = aShapes.First();
+    if (aShapeA.ShapeType() == TopAbs_VERTEX ) 
     {
-      TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4) );
-      std::cout << " Select a different vertex\n";
-
-      TopoDS_Shape ShapeB;
-      do 
+      if (aShapes.Extent() != 3)
       {
-        // Wait for picking
-        Standard_Integer argccc = 5;
-        const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvv = (const char **) bufff;
-        while (ViewerMainLoop( argccc, argvvv) ) { }
-        // end of the loop
+        std::cerr << "Error: wrong number of selected shapes.\n";
+        return 1;
+      }
 
-        for(TheAISContext()->InitSelected(); 
-          TheAISContext()->MoreSelected(); 
-          TheAISContext()->NextSelected() ) 
-        {
-          ShapeB = TheAISContext()->SelectedShape();
-        }
-      } while(ShapeB.IsSame(ShapeA) );
+      TopTools_ListOfShape::Iterator anIter (aShapes);
 
-      // Selection of ShapeC
-      std::cout << " Select the last vertex\n";
-      TopoDS_Shape ShapeC;
-      do 
-      {
-        // Wait for picking
-        Standard_Integer argcccc = 5;
-        const char *buffff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-        const char **argvvvv = (const char **) buffff;
-        while (ViewerMainLoop( argcccc, argvvvv) ) { }
-        // end of the loop
+      anIter.Next();
+      const TopoDS_Shape& aShapeB = anIter.Value();
 
-        for(TheAISContext()->InitSelected(); 
-          TheAISContext()->MoreSelected(); 
-          TheAISContext()->NextSelected() ) 
-        {
-          ShapeC = TheAISContext()->SelectedShape();
-        }
-      } while(ShapeC.IsSame(ShapeA) || ShapeC.IsSame(ShapeB) );
+      anIter.Next();
+      const TopoDS_Shape& aShapeC = anIter.Value();
       
       // Get isFilled
       Standard_Boolean isFilled;
       std::cout << "Enter filled status (0 or 1)\n";
       cin >> isFilled;
 
-      // Close the local context
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
-
       // Construction of the circle
-      gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(ShapeA));
-      gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(ShapeB));
-      gp_Pnt C = BRep_Tool::Pnt(TopoDS::Vertex(ShapeC));
+      gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
+      gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
+      gp_Pnt C = BRep_Tool::Pnt (TopoDS::Vertex (aShapeC));
 
       GC_MakeCircle Cir = GC_MakeCircle (A, B, C);
       Handle (Geom_Circle) theGeomCircle;
@@ -2321,26 +2192,9 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       DisplayCircle(theGeomCircle, aName, isFilled);
 
     }
-    // Shape is a face
-    else
+    else if (aShapeA.ShapeType() == TopAbs_FACE)
     {
-      std::cout << " Select a vertex (in your face)\n";
-      TheAISContext()->DeactivateStandardMode (AIS_Shape::SelectionType(4) );
-
-      TopoDS_Shape ShapeB;
-      // Wait for picking
-      Standard_Integer argccc = 5;
-      const char *bufff[] = { "VPick", "X", "VPickY","VPickZ", "VPickShape" };
-      const char **argvvv = (const char **) bufff;
-      while (ViewerMainLoop( argccc, argvvv) ) { }
-      // end of the loop
-
-      for(TheAISContext()->InitSelected(); 
-        TheAISContext()->MoreSelected(); 
-        TheAISContext()->NextSelected() ) 
-      {
-        ShapeB = TheAISContext()->SelectedShape();
-      }
+      const TopoDS_Shape& aShapeB = aShapes.Last();
 
       // Recover the radius 
       Standard_Real theRad;
@@ -2355,12 +2209,8 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       std::cout << "Enter filled status (0 or 1)\n";
       cin >> isFilled;
 
-      // Close the local context
-      TheAISContext()->CloseLocalContext(myCurrentIndex);
-      // Construction of the circle
-
       // Recover the normal to the plane. tag
-      TopoDS_Face myFace = TopoDS::Face(ShapeA);
+      TopoDS_Face myFace = TopoDS::Face(aShapeA);
       BRepAdaptor_Surface mySurface (myFace, Standard_False);
       gp_Pln myPlane = mySurface.Plane();
       Handle(Geom_Plane) theGeomPlane = new Geom_Plane (myPlane);
@@ -2369,7 +2219,7 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       gp_Dir theDir = thegpAxe.Direction();
 
       // Recover the center
-      gp_Pnt theCenter = BRep_Tool::Pnt(TopoDS::Vertex(ShapeB));
+      gp_Pnt theCenter = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
 
       // Construct the circle
       GC_MakeCircle Cir = GC_MakeCircle (theCenter, theDir ,theRad);
@@ -2385,235 +2235,416 @@ static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const
       }
 
       DisplayCircle(theGeomCircle, aName, isFilled);
-      
     }
-
+    else
+    {
+      std::cerr << "Error: You should select face and vertex or three vertices.\n";
+      return 1;
+    }
   }
 
   return 0;
 }
 
-
-//===============================================================================================
+//=======================================================================
 //function : VDrawText
-//author   : psn
-//purpose  : Create a text.
-//Draw arg : vdrawtext  name  [X] [Y] [Z] [R] [G] [B] [hor_align] [ver_align] [angle] [zoomable]
-//===============================================================================================
-#include <Graphic3d_Group.hxx>
-#include <Graphic3d_Structure.hxx>
-#include <Graphic3d_AspectText3d.hxx>
-#include <Graphic3d_AspectFillArea3d.hxx>
-#include <Graphic3d_StructureManager.hxx>
-#include <Graphic3d_VerticalTextAlignment.hxx>
-#include <Graphic3d_HorizontalTextAlignment.hxx>
+//purpose  :
+//=======================================================================
+static int VDrawText (Draw_Interpretor& theDI,
+                      Standard_Integer  theArgsNb,
+                      const char**      theArgVec)
+{
+  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
+  if (theArgsNb < 3)
+  {
+    std::cout << "Error: wrong number of arguments! See usage:\n";
+    theDI.PrintHelp (theArgVec[0]);
+    return 1;
+  }
+  else if (aContext.IsNull())
+  {
+    std::cout << "Error: no active view!\n";
+    return 1;
+  }
 
-#include <Font_NameOfFont.hxx>
+  Standard_Integer           anArgIt = 1;
+  TCollection_ExtendedString aName (theArgVec[anArgIt++], Standard_True);
+  TCollection_ExtendedString aText (theArgVec[anArgIt++], Standard_True);
+  Handle(AIS_TextLabel)      aTextPrs;
+  ViewerTest_AutoUpdater     anAutoUpdater (aContext, ViewerTest::CurrentView());
 
-#include <Visual3d_ViewManager.hxx>
+  Standard_Boolean isNewPrs = Standard_False;
+  if (GetMapOfAIS().IsBound2 (aName))
+  {
+    aTextPrs = Handle(AIS_TextLabel)::DownCast (GetMapOfAIS().Find2 (aName));
+  }
 
-#include <Standard_DefineHandle.hxx>
+  if (aTextPrs.IsNull())
+  {
+    isNewPrs = Standard_True;
+    aTextPrs = new AIS_TextLabel();
+    aTextPrs->SetFont ("Courier");
+  }
 
-#include <Prs3d_Root.hxx>
-#include <Prs3d_Text.hxx>
-#include <Prs3d_TextAspect.hxx>
-#include <Prs3d_ShadingAspect.hxx>
-#include <PrsMgr_PresentationManager3d.hxx>
+  aTextPrs->SetText (aText);
 
-#include <TCollection_ExtendedString.hxx>
-#include <TCollection_AsciiString.hxx>
+  Handle(Graphic3d_TransformPers) aTrsfPers;
+  Aspect_TypeOfDisplayText aDisplayType = Aspect_TODT_NORMAL;
 
-#include <gp_Pnt.hxx>
-#include <Quantity_NameOfColor.hxx>
-#include <Quantity_Color.hxx>
+  Standard_Boolean aHasPlane = Standard_False;
+  gp_Dir           aNormal;
+  gp_Dir           aDirection;
+  gp_Pnt           aPos;
 
+  for (; anArgIt < theArgsNb; ++anArgIt)
+  {
+    TCollection_AsciiString aParam (theArgVec[anArgIt]);
+    aParam.LowerCase();
 
-DEFINE_STANDARD_HANDLE(MyTextClass, AIS_InteractiveObject)
+    if (anAutoUpdater.parseRedrawMode (aParam))
+    {
+      continue;
+    }
+    else if (aParam == "-pos"
+          || aParam == "-position")
+    {
+      if (anArgIt + 3 >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-class MyTextClass:public AIS_InteractiveObject
-{
-public:
-  // CASCADE RTTI
-  DEFINE_STANDARD_RTTI(MyTextClass );
-
-  MyTextClass(){};
-
-  MyTextClass
-    (
-      const TCollection_ExtendedString& , const gp_Pnt& ,
-      Quantity_Color color,
-      Standard_Integer aHJust,
-      Standard_Integer aVJust ,
-      Standard_Real Angle ,
-      Standard_Boolean Zoom ,
-      Standard_Real  Height,
-      Font_FontAspect FontAspect,
-      Standard_CString Font
-    );
+      aPos.SetX (Draw::Atof (theArgVec[++anArgIt]));
+      aPos.SetY (Draw::Atof (theArgVec[++anArgIt]));
+      aPos.SetZ (Draw::Atof (theArgVec[++anArgIt]));
+      aTextPrs->SetPosition (aPos);
+    }
+    else if (aParam == "-color")
+    {
+      if (anArgIt + 1 >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-private:
+      TCollection_AsciiString aColor (theArgVec[anArgIt + 1]);
+      Quantity_NameOfColor aNameOfColor = Quantity_NOC_BLACK;
+      if (Quantity_Color::ColorFromName (aColor.ToCString(), aNameOfColor))
+      {
+        anArgIt += 1;
+        aTextPrs->SetColor (aNameOfColor);
+        continue;
+      }
+      else if (anArgIt + 3 >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-  void Compute (  const Handle(PrsMgr_PresentationManager3d)& aPresentationManager,
-                  const Handle(Prs3d_Presentation)& aPresentation,
-                  const Standard_Integer aMode);
+      TCollection_AsciiString aGreen (theArgVec[anArgIt + 2]);
+      TCollection_AsciiString aBlue  (theArgVec[anArgIt + 3]);
+      if (!aColor.IsRealValue()
+       || !aGreen.IsRealValue()
+       || !aBlue.IsRealValue())
+      {
+        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-  void ComputeSelection (  const Handle(SelectMgr_Selection)& /*aSelection*/,
-                           const Standard_Integer /*aMode*/){} ;
+      const Graphic3d_Vec3d anRGB (aColor.RealValue(),
+                                   aGreen.RealValue(),
+                                   aBlue.RealValue());
 
-protected:
-  TCollection_ExtendedString          aText;
-  gp_Pnt                              aPosition;
-  Standard_Real                       Red;
-  Standard_Real                       Green;
-  Standard_Real                       Blue;
-  Standard_Real                       aAngle;
-  Standard_Real                       aHeight;
-  Standard_Boolean                    aZoomable;
-  Quantity_Color                      aColor;
-  TCollection_AsciiString             aFont;
-  Font_FontAspect                     aFontAspect;
-  Graphic3d_HorizontalTextAlignment   aHJustification;
-  Graphic3d_VerticalTextAlignment     aVJustification;
-};
+      aTextPrs->SetColor (Quantity_Color (anRGB.r(), anRGB.g(), anRGB.b(), Quantity_TOC_RGB));
+      anArgIt += 3;
+    }
+    else if (aParam == "-halign")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      TCollection_AsciiString aType (theArgVec[anArgIt]);
+      aType.LowerCase();
+      if (aType == "left")
+      {
+        aTextPrs->SetHJustification (Graphic3d_HTA_LEFT);
+      }
+      else if (aType == "center")
+      {
+        aTextPrs->SetHJustification (Graphic3d_HTA_CENTER);
+      }
+      else if (aType == "right")
+      {
+        aTextPrs->SetHJustification (Graphic3d_HTA_RIGHT);
+      }
+      else
+      {
+        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-valign")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      TCollection_AsciiString aType (theArgVec[anArgIt]);
+      aType.LowerCase();
+      if (aType == "top")
+      {
+        aTextPrs->SetVJustification (Graphic3d_VTA_TOP);
+      }
+      else if (aType == "center")
+      {
+        aTextPrs->SetVJustification (Graphic3d_VTA_CENTER);
+      }
+      else if (aType == "bottom")
+      {
+        aTextPrs->SetVJustification (Graphic3d_VTA_BOTTOM);
+      }
+      else if (aType == "topfirstline")
+      {
+        aTextPrs->SetVJustification (Graphic3d_VTA_TOPFIRSTLINE);
+      }
+      else
+      {
+        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-angle")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
+      aTextPrs->SetAngle (Draw::Atof (theArgVec[anArgIt]) * (M_PI / 180.0));
+    }
+    else if (aParam == "-zoom")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
+      aTextPrs->SetZoomable (Draw::Atoi (theArgVec[anArgIt]) == 1);
+    }
+    else if (aParam == "-height")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-IMPLEMENT_STANDARD_HANDLE(MyTextClass, AIS_InteractiveObject)
-IMPLEMENT_STANDARD_RTTIEXT(MyTextClass, AIS_InteractiveObject)
+      aTextPrs->SetHeight (Draw::Atof(theArgVec[anArgIt]));
+    }
+    else if (aParam == "-aspect")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
+      TCollection_AsciiString anOption (theArgVec[anArgIt]);
+      anOption.LowerCase();
+      if (anOption.IsEqual ("regular"))
+      {
+        aTextPrs->SetFontAspect (Font_FA_Regular);
+      }
+      else if (anOption.IsEqual ("bold"))
+      {
+        aTextPrs->SetFontAspect (Font_FA_Bold);
+      }
+      else if (anOption.IsEqual ("italic"))
+      {
+        aTextPrs->SetFontAspect (Font_FA_Italic);
+      }
+      else if (anOption.IsEqual ("bolditalic"))
+      {
+        aTextPrs->SetFontAspect (Font_FA_BoldItalic);
+      }
+    }
+    else if (aParam == "-font")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-MyTextClass::MyTextClass( const TCollection_ExtendedString& text, const gp_Pnt& position,
-                          Quantity_Color    color       = Quantity_NOC_YELLOW,
-                          Standard_Integer  aHJust      = Graphic3d_HTA_LEFT,
-                          Standard_Integer  aVJust      = Graphic3d_VTA_BOTTOM,
-                          Standard_Real     angle       = 0.0 ,
-                          Standard_Boolean  zoomable    = Standard_True,
-                          Standard_Real     height      = 12.,
-                          Font_FontAspect   fontAspect  = Font_FA_Regular,
-                          Standard_CString  font        = "Courier")
-{
-  aText           = text;
-  aPosition       = position;
-  aHJustification = Graphic3d_HorizontalTextAlignment(aHJust);
-  aVJustification = Graphic3d_VerticalTextAlignment(aVJust);
-  aAngle          = angle;
-  aZoomable       = zoomable;
-  aHeight         = height;
-  aColor          = color;
-  aFontAspect     = fontAspect;
-  aFont           = font;
-};
+      aTextPrs->SetFont (theArgVec[anArgIt]);
+    }
+    else if (aParam == "-plane")
+    {
+      if (anArgIt + 6 >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
+      Standard_Real aX = Draw::Atof (theArgVec[++anArgIt]);
+      Standard_Real aY = Draw::Atof (theArgVec[++anArgIt]);
+      Standard_Real aZ = Draw::Atof (theArgVec[++anArgIt]);
+      aNormal.SetCoord (aX, aY, aZ);
 
+      aX = Draw::Atof (theArgVec[++anArgIt]);
+      aY = Draw::Atof (theArgVec[++anArgIt]);
+      aZ = Draw::Atof (theArgVec[++anArgIt]);
+      aDirection.SetCoord (aX, aY, aZ);
 
-//////////////////////////////////////////////////////////////////////////////
-void MyTextClass::Compute(const Handle(PrsMgr_PresentationManager3d)& /*aPresentationManager*/,
-                          const Handle(Prs3d_Presentation)& aPresentation,
-                          const Standard_Integer /*aMode*/)
-{
+      aHasPlane = Standard_True;
+    }
+    else if (aParam == "-flipping")
+    {
+      aTextPrs->SetFlipping (Standard_True);
+    }
+    else if (aParam == "-disptype"
+          || aParam == "-displaytype")
+    {
+      if (++anArgIt >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+      TCollection_AsciiString aType (theArgVec[anArgIt]);
+      aType.LowerCase();
+      if (aType == "subtitle")
+        aDisplayType = Aspect_TODT_SUBTITLE;
+      else if (aType == "decal")
+        aDisplayType = Aspect_TODT_DEKALE;
+      else if (aType == "blend")
+        aDisplayType = Aspect_TODT_BLEND;
+      else if (aType == "dimension")
+        aDisplayType = Aspect_TODT_DIMENSION;
+      else if (aType == "normal")
+        aDisplayType = Aspect_TODT_NORMAL;
+      else
+      {
+        std::cout << "Error: wrong display type '" << aType << "'.\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-subcolor"
+          || aParam == "-subtitlecolor")
+    {
+      if (anArgIt + 1 >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-  aPresentation->Clear();
+      TCollection_AsciiString aColor (theArgVec[anArgIt + 1]);
+      Quantity_NameOfColor aNameOfColor = Quantity_NOC_BLACK;
+      if (Quantity_Color::ColorFromName (aColor.ToCString(), aNameOfColor))
+      {
+        anArgIt += 1;
+        aTextPrs->SetColorSubTitle (aNameOfColor);
+        continue;
+      }
+      else if (anArgIt + 3 >= theArgsNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-  if (!myDrawer->HasTextAspect())
-  {
-    myDrawer->SetTextAspect (new Prs3d_TextAspect());
-    *myDrawer->TextAspect()->Aspect() = *myDrawer->Link()->TextAspect()->Aspect();
-  }
+      TCollection_AsciiString aGreen (theArgVec[anArgIt + 2]);
+      TCollection_AsciiString aBlue  (theArgVec[anArgIt + 3]);
+      if (!aColor.IsRealValue()
+       || !aGreen.IsRealValue()
+       || !aBlue.IsRealValue())
+      {
+        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-  Handle(Prs3d_TextAspect) asp = myDrawer->TextAspect();
+      const Graphic3d_Vec3d anRGB (aColor.RealValue(),
+                                   aGreen.RealValue(),
+                                   aBlue.RealValue());
 
-  asp->SetFont(aFont.ToCString());
-  asp->SetColor(aColor);
-  asp->SetHeight(aHeight); // I am changing the myHeight value
+      aTextPrs->SetColorSubTitle (Quantity_Color (anRGB.r(), anRGB.g(), anRGB.b(), Quantity_TOC_RGB));
+      anArgIt += 3;
+    }
+    else if (aParam == "-2d")
+    {
+      aTrsfPers = new Graphic3d_TransformPers (Graphic3d_TMF_2d);
+    }
+    else if (aParam == "-trsfperspos"
+          || aParam == "-perspos")
+    {
+      if (anArgIt + 2 >= theArgsNb)
+      {
+        std::cerr << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
 
-  asp->SetHorizontalJustification(aHJustification);
-  asp->SetVerticalJustification(aVJustification);
-  asp->Aspect()->SetTextZoomable(aZoomable);
-  asp->Aspect()->SetTextAngle(aAngle);
-  asp->Aspect()->SetTextFontAspect(aFontAspect);
-  Prs3d_Text::Draw(aPresentation, asp, aText, aPosition);
+      TCollection_AsciiString aX (theArgVec[++anArgIt]);
+      TCollection_AsciiString aY (theArgVec[++anArgIt]);
+      TCollection_AsciiString aZ = "0";
+      if (!aX.IsIntegerValue()
+       || !aY.IsIntegerValue())
+      {
+        std::cerr << "Error: wrong syntax at '" << aParam << "'.\n";
+        return 1;
+      }
+      if (anArgIt + 1 < theArgsNb)
+      {
+        TCollection_AsciiString aTemp = theArgVec[anArgIt + 1];
+        if (aTemp.IsIntegerValue())
+        {
+          aZ = aTemp;
+          ++anArgIt;
+        }
+      }
 
-  /* This comment code is worked
-  Handle(Graphic3d_Group) TheGroup = Prs3d_Root::CurrentGroup(aPresentation);
-  Handle(Graphic3d_AspectFillArea3d) aspect = myDrawer->ShadingAspect()->Aspect();
-  Graphic3d_Vertex vertices_text;
-  vertices_text.SetCoord(aPosition.X(),aPosition.Y(),aPosition.Y());
-  TheGroup->SetPrimitivesAspect(aspect);
-  TheGroup->Text(aText,vertices_text,aHeight,Standard_True);
-  */
-};
+      aTrsfPers = Graphic3d_TransformPers::FromDeprecatedParams (Graphic3d_TMF_2d, gp_Pnt (aX.IntegerValue(), aY.IntegerValue(), aZ.IntegerValue()));
+    }
+    else
+    {
+      std::cout << "Error: unknown argument '" << aParam << "'\n";
+      return 1;
+    }
+  }
 
-static int VDrawText (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
-{
-  // Check arguments
-  if (argc < 14)
+  if (aHasPlane)
   {
-    di<<"Error: "<<argv[0]<<" - invalid number of arguments\n";
-    di<<"Usage: type help "<<argv[0]<<"\n";
-    return 1; //TCL_ERROR
+    aTextPrs->SetOrientation3D (gp_Ax2 (aPos, aNormal, aDirection));
   }
 
-  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
+  aTextPrs->SetDisplayType (aDisplayType);
 
-  // Create 3D view if it doesn't exist
-  if ( aContext.IsNull() )
+  if (!aTrsfPers.IsNull())
   {
-    ViewerTest::ViewerInit();
-    aContext = ViewerTest::GetAISContext();
-    if( aContext.IsNull() )
+    aContext->SetTransformPersistence (aTextPrs, aTrsfPers);
+    aTextPrs->SetZLayer(Graphic3d_ZLayerId_TopOSD);
+    if (aTextPrs->Position().Z() != 0)
     {
-      di << "Error: Cannot create a 3D view\n";
-      return 1; //TCL_ERROR
+      aTextPrs->SetPosition (gp_Pnt(aTextPrs->Position().X(), aTextPrs->Position().Y(), 0));
     }
   }
+  else if (!aTextPrs->TransformPersistence().IsNull())
+  {
+    aContext->SetTransformPersistence (aTextPrs, Handle(Graphic3d_TransformPers)());
+  }
 
-  // Text position
-  const Standard_Real X = Draw::Atof(argv[2]);
-  const Standard_Real Y = Draw::Atof(argv[3]);
-  const Standard_Real Z = Draw::Atof(argv[4]);
-  const gp_Pnt pnt(X,Y,Z);
-
-  // Text color
-  const Quantity_Parameter R = Draw::Atof(argv[5])/255.;
-  const Quantity_Parameter G = Draw::Atof(argv[6])/255.;
-  const Quantity_Parameter B = Draw::Atof(argv[7])/255.;
-  const Quantity_Color aColor( R, G, B, Quantity_TOC_RGB );
-
-  // Text alignment
-  const int hor_align = Draw::Atoi(argv[8]);
-  const int ver_align = Draw::Atoi(argv[9]);
-
-  // Text angle
-  const Standard_Real angle = Draw::Atof(argv[10]);
-
-  // Text zooming
-  const Standard_Boolean zoom = Draw::Atoi(argv[11]);
-
-  // Text height
-  const Standard_Real height = Draw::Atof(argv[12]);
-
-  // Text aspect
-  const Font_FontAspect aspect = Font_FontAspect(Draw::Atoi(argv[13]));
-
-  // Text font
-  TCollection_AsciiString font;
-  if(argc < 15)
-    font.AssignCat("Courier");
+  if (isNewPrs)
+  {
+    ViewerTest::Display (aName, aTextPrs, Standard_False);
+  }
   else
-    font.AssignCat(argv[14]);
-
-  // Text is multibyte
-  const Standard_Boolean isMultibyte = (argc < 16)? Standard_False : (Draw::Atoi(argv[15]) != 0);
-
-  // Read text string
-  TCollection_ExtendedString name(argv[1],isMultibyte);
-
-  if (name.Length())
   {
-    Handle(MyTextClass) myT = new MyTextClass(name,pnt,aColor,hor_align,ver_align,angle,zoom,height,aspect,font.ToCString());
-    aContext->Display(myT,Standard_True);
+    aContext->Redisplay (aTextPrs, Standard_False, Standard_True);
   }
-
   return 0;
 }
 
@@ -2630,7 +2661,7 @@ static int VDrawText (Draw_Interpretor& di, Standard_Integer argc, const char**
 #include <TShort_HArray1OfShortReal.hxx>
 
 #include <AIS_Triangulation.hxx>
-#include <StdPrs_ToolShadedShape.hxx>
+#include <StdPrs_ToolTriangulatedShape.hxx>
 #include <Poly_Connect.hxx>
 #include <TColgp_Array1OfDir.hxx>
 #include <Graphic3d_GraphicDriver.hxx>
@@ -2646,6 +2677,7 @@ static int VDrawText (Draw_Interpretor& di, Standard_Integer argc, const char**
 #include <TopExp_Explorer.hxx>
 #include <TopAbs.hxx>
 #include <StdSelect_ShapeTypeFilter.hxx>
+#include <AIS_InteractiveObject.hxx>
 
 
 //===============================================================================================
@@ -2864,11 +2896,11 @@ Handle( Poly_Triangulation ) CalculationOfSphere( double X , double Y , double Z
         Nor = gp_Dir(eqPlan);
       else
         Nor = gp_Dir(0., 0., 1.);
-
-      Standard_Integer j = (i - PointsOfArray.Lower()) * 3;
-      Normals->SetValue(j + 1, (Standard_ShortReal)Nor.X());
-      Normals->SetValue(j + 2, (Standard_ShortReal)Nor.Y());
-      Normals->SetValue(j + 3, (Standard_ShortReal)Nor.Z());
+      
+      Standard_Integer k = (i - PointsOfArray.Lower()) * 3;
+      Normals->SetValue(k + 1, (Standard_ShortReal)Nor.X());
+      Normals->SetValue(k + 2, (Standard_ShortReal)Nor.Y());
+      Normals->SetValue(k + 3, (Standard_ShortReal)Nor.Z());
   }
 
   delete pc;
@@ -2922,20 +2954,13 @@ static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const c
 
   // stupid initialization of Green color in RGBA space as integer
   // probably wrong for big-endian CPUs
-  Standard_Integer aRed    = 0;
-  Standard_Integer aGreen  = 255;
-  Standard_Integer aBlue   = 0;
-  Standard_Integer anAlpha = 0; // not used
-  Standard_Integer aColorInt = aRed;
-  aColorInt += aGreen  << 8;
-  aColorInt += aBlue   << 16;
-  aColorInt += anAlpha << 24;
+  const Graphic3d_Vec4ub aColor (0, 255, 0, 0);
 
   // setup colors array per vertex
   Handle(TColStd_HArray1OfInteger) aColorArray = new TColStd_HArray1OfInteger (1, aNumberPoints);
   for (Standard_Integer aNodeId = 1; aNodeId <= aNumberPoints; ++aNodeId)
   {
-    aColorArray->SetValue (aNodeId, aColorInt);
+    aColorArray->SetValue (aNodeId, *reinterpret_cast<const Standard_Integer*> (&aColor));
   }
   aShape->SetColors (aColorArray);
 
@@ -2963,8 +2988,8 @@ static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const c
 
   // Setting material properties, very important for desirable visual result!
   Graphic3d_MaterialAspect aMat (Graphic3d_NOM_PLASTIC);
-  aMat.SetAmbient (0.2);
-  aMat.SetSpecular (0.5);
+  aMat.SetAmbient  (0.2f);
+  aMat.SetSpecular (0.5f);
   Handle(Graphic3d_AspectFillArea3d) anAspect
     = new Graphic3d_AspectFillArea3d (Aspect_IS_SOLID,
                                       Quantity_NOC_RED,
@@ -3009,7 +3034,7 @@ static int VComputeHLR (Draw_Interpretor& di,
   if ( argc != 3 &&  argc != 12 )
   {
     di << "Usage: " << argv[0] << " ShapeName HlrName "
-       << "[ eye_x eye_y eye_z dir_x dir_y dir_z upx upy upz ]" << "\n"
+       << "[ eye_x eye_y eye_z dir_x dir_y dir_z upx upy upz ]\n"
        << "                    ShapeName - name of the initial shape\n"
        << "                    HlrName - result hlr object from initial shape\n"
        << "                    eye, dir are eye position and look direction\n"
@@ -3040,10 +3065,6 @@ static int VComputeHLR (Draw_Interpretor& di,
     return 1;
   }
 
-  // close local context
-  if (aContextAIS->HasOpenedContext ())
-    aContextAIS->CloseLocalContext ();
-
   Handle(HLRBRep_PolyAlgo) aPolyAlgo = new HLRBRep_PolyAlgo();
   HLRBRep_PolyHLRToShape aHLRToShape;
 
@@ -3116,7 +3137,7 @@ static int VComputeHLR (Draw_Interpretor& di,
   // create an AIS shape and display it
   Handle(AIS_Shape) anObject = new AIS_Shape (aHlrShape);
   GetMapOfAIS().Bind (anObject, aHlrName);
-  aContextAIS->Display (anObject);
+  aContextAIS->Display (anObject, Standard_False);
 
   aContextAIS->UpdateCurrentViewer ();
 
@@ -3125,7 +3146,7 @@ static int VComputeHLR (Draw_Interpretor& di,
 
 // This class is a wrap for Graphic3d_ArrayOfPrimitives; it is used for
 // manipulating and displaying such an array with AIS context
-DEFINE_STANDARD_HANDLE(MyPArrayObject, AIS_InteractiveObject)
+
 class MyPArrayObject : public AIS_InteractiveObject
 {
 
@@ -3138,16 +3159,16 @@ public:
     myMarkerAspect = theMarkerAspect;
   }
 
-  DEFINE_STANDARD_RTTI(MyPArrayObject);
+  DEFINE_STANDARD_RTTI_INLINE(MyPArrayObject,AIS_InteractiveObject);
 
 private:
 
   void Compute (const Handle(PrsMgr_PresentationManager3d)& aPresentationManager,
                 const Handle(Prs3d_Presentation)& aPresentation,
-                const Standard_Integer aMode);
+                const Standard_Integer aMode) Standard_OVERRIDE;
 
   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
-                         const Standard_Integer /*theMode*/);
+                         const Standard_Integer /*theMode*/) Standard_OVERRIDE;
 
   bool CheckInputCommand (const TCollection_AsciiString theCommand,
                           const Handle(TColStd_HArray1OfAsciiString) theArgsArray,
@@ -3162,8 +3183,6 @@ protected:
 
 };
 
-IMPLEMENT_STANDARD_HANDLE(MyPArrayObject, AIS_InteractiveObject)
-IMPLEMENT_STANDARD_RTTIEXT(MyPArrayObject, AIS_InteractiveObject)
 
 void MyPArrayObject::Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPresentationManager*/,
                               const Handle(Prs3d_Presentation)& aPresentation,
@@ -3319,6 +3338,8 @@ void MyPArrayObject::Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPre
   {
     Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myMarkerAspect);
   }
+  Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myDrawer->LineAspect()->Aspect());
+  Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myDrawer->ShadingAspect()->Aspect());
   Prs3d_Root::CurrentGroup (aPresentation)->AddPrimitiveArray (anArray);
 }
 
@@ -3467,12 +3488,47 @@ static int VDrawPArray (Draw_Interpretor& di, Standard_Integer argc, const char*
   return 0;
 }
 
+namespace
+{
+  //! Auxiliary function for parsing translation vector - either 2D or 3D.
+  static Standard_Integer parseTranslationVec (Standard_Integer theArgNb,
+                                               const char**     theArgVec,
+                                               gp_Vec&          theVec)
+  {
+    if (theArgNb < 2)
+    {
+      return 0;
+    }
+
+    TCollection_AsciiString anX (theArgVec[0]);
+    TCollection_AsciiString anY (theArgVec[1]);
+    if (!anX.IsRealValue()
+     || !anY.IsRealValue())
+    {
+      return 0;
+    }
+
+    theVec.SetX (anX.RealValue());
+    theVec.SetY (anY.RealValue());
+    if (theArgNb >= 3)
+    {
+      TCollection_AsciiString anZ (theArgVec[2]);
+      if (anZ.IsRealValue())
+      {
+        theVec.SetZ (anZ.RealValue());
+        return 3;
+      }
+    }
+    return 2;
+  }
+}
+
 //=======================================================================
 //function : VSetLocation
 //purpose  : Change location of AIS interactive object
 //=======================================================================
 
-static Standard_Integer VSetLocation (Draw_Interpretor& /*di*/,
+static Standard_Integer VSetLocation (Draw_Interpretor& theDI,
                                       Standard_Integer  theArgNb,
                                       const char**      theArgVec)
 {
@@ -3484,221 +3540,330 @@ static Standard_Integer VSetLocation (Draw_Interpretor& /*di*/,
     return 1;
   }
 
-  TCollection_AsciiString aName;
-  gp_Vec aLocVec;
-  Standard_Boolean isSetLoc = Standard_False;
-
-  Standard_Integer anArgIter = 1;
-  for (; anArgIter < theArgNb; ++anArgIter)
+  Standard_Boolean toPrintInfo = Standard_True;
+  Handle(AIS_InteractiveObject) anObj;
+  TCollection_AsciiString aCmdName (theArgVec[0]);
+  aCmdName.LowerCase();
+  for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
   {
-    Standard_CString anArg = theArgVec[anArgIter];
-    if (anUpdateTool.parseRedrawMode (theArgVec[anArgIter]))
+    TCollection_AsciiString anArg = theArgVec[anArgIter];
+    anArg.LowerCase();
+    if (anUpdateTool.parseRedrawMode (anArg))
     {
       continue;
     }
-    else if (aName.IsEmpty())
-    {
-      aName = anArg;
-    }
-    else if (!isSetLoc)
+    else if (anObj.IsNull())
     {
-      isSetLoc = Standard_True;
-      if (anArgIter + 1 >= theArgNb)
+      const TCollection_AsciiString aName (theArgVec[anArgIter]);
+      const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
+      if (aMap.IsBound2 (aName))
       {
-        std::cout << "Error: syntax error at '" << anArg << "'\n";
-        return 1;
+        anObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (aName));
       }
-      aLocVec.SetX (Draw::Atof (theArgVec[anArgIter++]));
-      aLocVec.SetY (Draw::Atof (theArgVec[anArgIter]));
-      if (anArgIter + 1 < theArgNb)
+      if (anObj.IsNull())
       {
-        aLocVec.SetZ (Draw::Atof (theArgVec[++anArgIter]));
+        std::cout << "Error: object '" << aName << "' is not displayed!\n";
+        return 1;
       }
     }
-    else
+    else if (anArg == "-reset")
     {
-      std::cout << "Error: unknown argument '" << anArg << "'\n";
-      return 1;
+      toPrintInfo = Standard_False;
+      aContext->SetLocation (anObj, gp_Trsf());
     }
-  }
-
-  // find object
-  const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
-  Handle(AIS_InteractiveObject) anIObj;
-  if (aMap.IsBound2 (aName))
-  {
-    anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (aName));
-  }
-  if (anIObj.IsNull())
-  {
-    std::cout << "Error: object '" << aName << "' is not displayed!\n";
-    return 1;
-  }
-
-  gp_Trsf aTrsf;
-  aTrsf.SetTranslation (aLocVec);
-  TopLoc_Location aLocation (aTrsf);
-  aContext->SetLocation (anIObj, aLocation);
-  return 0;
-}
-
-//=======================================================================
-//function : TransformPresentation
-//purpose  : Change transformation of AIS interactive object
-//=======================================================================
-static Standard_Integer LocalTransformPresentation (Draw_Interpretor& /*theDi*/,
-                                                    Standard_Integer theArgNb,
-                                                    const char** theArgVec)
-{
-  if (theArgNb <= 1)
-  {
-    std::cout << "Error: too few arguments.\n";
-    return 1;
-  }
-
-  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
-  ViewerTest_AutoUpdater anUpdateTool(aContext, ViewerTest::CurrentView());
-  if (aContext.IsNull())
-  {
-    std::cout << "Error: no active view!\n";
-    return 1;
-  }
-
-  gp_Trsf aTrsf;
-  Standard_Integer aLast = theArgNb;
-  const char* aName = theArgVec[0];
-
-  Standard_Boolean isReset = Standard_False;
-  Standard_Boolean isMove = Standard_False;
-
-  // Prefix 'vloc'
-  aName += 4;
-
-  if (!strcmp (aName, "reset"))
-  {
-    isReset = Standard_True;
-  }
-  else if (!strcmp (aName, "move"))
-  {
-    if (theArgNb < 3)
+    else if (anArg == "-copyfrom"
+          || anArg == "-copy")
     {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
-    }
+      if (anArgIter + 1 >= theArgNb)
+      {
+        std::cout << "Syntax error at '" << anArg << "'\n";
+        return 1;
+      }
 
-    const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
+      const TCollection_AsciiString aName2 (theArgVec[anArgIter + 1]);
+      const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
+      Handle(AIS_InteractiveObject) anObj2;
+      if (aMap.IsBound2 (aName2))
+      {
+        anObj2 = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (aName2));
+      }
+      if (anObj2.IsNull())
+      {
+        std::cout << "Error: object '" << aName2 << "' is not displayed!\n";
+        return 1;
+      }
 
-    Handle(AIS_InteractiveObject) anIObj;
-    if (aMap.IsBound2 (theArgVec[theArgNb - 1]))
-    {
-      anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (theArgVec[theArgNb - 1]));
+      ++anArgIter;
+      aContext->SetLocation (anObj, anObj2->LocalTransformation());
     }
-
-    if (anIObj.IsNull())
+    else if (anArg == "-rotate")
     {
-      std::cout << "Error: object '" << theArgVec[theArgNb - 1] << "' is not displayed!\n";
-      return 1;
-    }
+      toPrintInfo = Standard_False;
+      if (anArgIter + 7 >= theArgNb)
+      {
+        std::cout << "Syntax error at '" << anArg << "'\n";
+        return 1;
+      }
 
-    isMove = Standard_True;
+      gp_Trsf aTrsf;
+      aTrsf.SetRotation (gp_Ax1 (gp_Pnt (Draw::Atof (theArgVec[anArgIter + 1]),
+                                         Draw::Atof (theArgVec[anArgIter + 2]),
+                                         Draw::Atof (theArgVec[anArgIter + 3])),
+                                 gp_Vec (Draw::Atof (theArgVec[anArgIter + 4]),
+                                         Draw::Atof (theArgVec[anArgIter + 5]),
+                                         Draw::Atof (theArgVec[anArgIter + 6]))),
+                                         Draw::Atof (theArgVec[anArgIter + 7]) * (M_PI / 180.0));
+      anArgIter += 7;
 
-    aTrsf = anIObj->Transformation();
-    aLast = theArgNb - 1;
-  }
-  else if (!strcmp (aName, "translate"))
-  {
-    if (theArgNb < 5)
-    {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
+      aTrsf = anObj->LocalTransformation() * aTrsf;
+      aContext->SetLocation (anObj, aTrsf);
     }
-    aTrsf.SetTranslation (gp_Vec (Draw::Atof (theArgVec[theArgNb - 3]),
-                                  Draw::Atof (theArgVec[theArgNb - 2]),
-                                  Draw::Atof (theArgVec[theArgNb - 1])));
-    aLast = theArgNb - 3;
-  }
-  else if (!strcmp (aName, "rotate"))
-  {
-    if (theArgNb < 9)
+    else if (anArg == "-translate")
     {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
+      toPrintInfo = Standard_False;
+      gp_Vec aLocVec;
+      Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter - 1, theArgVec + anArgIter + 1, aLocVec);
+      anArgIter += aNbParsed;
+      if (aNbParsed == 0)
+      {
+        std::cout << "Syntax error at '" << anArg << "'\n";
+        return 1;
+      }
+
+      gp_Trsf aTrsf;
+      aTrsf.SetTranslationPart (aLocVec);
+      aTrsf = anObj->LocalTransformation() * aTrsf;
+      aContext->SetLocation (anObj, aTrsf);
     }
+    else if (anArg == "-scale"
+          || anArg == "-setscale")
+    {
+      toPrintInfo = Standard_False;
+      gp_XYZ aScaleLoc;
+      Standard_Real aScale = 1.0;
+      Standard_Boolean toPrintScale = Standard_True;
+      Standard_Boolean hasScaleLoc  = Standard_False;
+      if (anArgIter + 4 < theArgNb)
+      {
+        TCollection_AsciiString aScaleArgs[4] =
+        {
+          TCollection_AsciiString (theArgVec[anArgIter + 1]),
+          TCollection_AsciiString (theArgVec[anArgIter + 2]),
+          TCollection_AsciiString (theArgVec[anArgIter + 3]),
+          TCollection_AsciiString (theArgVec[anArgIter + 4])
+        };
+        Standard_Integer aScaleArgIter = 0;
+        for (; aScaleArgIter < 4; ++aScaleArgIter)
+        {
+          if (!aScaleArgs[aScaleArgIter].IsRealValue())
+          {
+            break;
+          }
+        }
+        if (aScaleArgIter == 4)
+        {
+          aScaleLoc.SetCoord (aScaleArgs[0].RealValue(), aScaleArgs[1].RealValue(), aScaleArgs[2].RealValue());
+          aScale = aScaleArgs[3].RealValue();
+          anArgIter += 4;
+          toPrintScale = Standard_False;
+          hasScaleLoc  = Standard_True;
+        }
+        else if (aScaleArgIter >= 1)
+        {
+          aScale = aScaleArgs[0].RealValue();
+          ++anArgIter;
+          toPrintScale = Standard_False;
+        }
+      }
+      else if (anArgIter + 1 < theArgNb)
+      {
+        TCollection_AsciiString aScaleArg (theArgVec[anArgIter + 1]);
+        if (aScaleArg.IsRealValue())
+        {
+          aScale = aScaleArg.RealValue();
+          ++anArgIter;
+          toPrintScale = Standard_False;
+        }
+      }
 
-    aTrsf.SetRotation (
-      gp_Ax1 (gp_Pnt (Draw::Atof (theArgVec[theArgNb - 7]),
-                      Draw::Atof (theArgVec[theArgNb - 6]),
-                      Draw::Atof (theArgVec[theArgNb - 5])),
-              gp_Vec (Draw::Atof (theArgVec[theArgNb - 4]),
-                      Draw::Atof (theArgVec[theArgNb - 3]),
-                      Draw::Atof (theArgVec[theArgNb - 2]))),
-      Draw::Atof (theArgVec[theArgNb - 1]) * (M_PI / 180.0));
+      if (toPrintScale)
+      {
+        if (anArg == "-setscale")
+        {
+          std::cout << "Syntax error at '" << anArg << "'\n";
+          return 1;
+        }
 
-    aLast = theArgNb - 7;
-  }
-  else if (!strcmp (aName, "mirror"))
-  {
-    if (theArgNb < 8)
-    {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
+        char aText[1024];
+        Sprintf (aText, "%g ", anObj->LocalTransformation().ScaleFactor());
+        theDI << aText;
+        continue;
+      }
+
+      if (anArg == "-setscale")
+      {
+        gp_Trsf aTrsf = anObj->LocalTransformation();
+        if (hasScaleLoc)
+        {
+          aTrsf.SetScale (aScaleLoc, aScale);
+        }
+        else
+        {
+          aTrsf.SetScaleFactor (aScale);
+        }
+        aContext->SetLocation (anObj, aTrsf);
+      }
+      else
+      {
+        gp_Trsf aTrsf;
+        if (hasScaleLoc)
+        {
+          aTrsf.SetScale (aScaleLoc, aScale);
+          aTrsf = anObj->LocalTransformation() * aTrsf;
+        }
+        else
+        {
+          aTrsf = anObj->LocalTransformation();
+          aTrsf.SetScaleFactor (aTrsf.ScaleFactor() * aScale);
+        }
+        aContext->SetLocation (anObj, aTrsf);
+      }
     }
+    else if (anArg == "-mirror")
+    {
+      toPrintInfo = Standard_False;
+      if (anArgIter + 6 >= theArgNb)
+      {
+        std::cout << "Syntax error at '" << anArg << "'\n";
+        return 1;
+      }
 
-    aTrsf.SetMirror (gp_Ax2 (gp_Pnt (Draw::Atof(theArgVec[theArgNb - 6]),
-                                     Draw::Atof(theArgVec[theArgNb - 5]),
-                                     Draw::Atof(theArgVec[theArgNb - 4])),
-                             gp_Vec (Draw::Atof(theArgVec[theArgNb - 3]),
-                                     Draw::Atof(theArgVec[theArgNb - 2]),
-                                     Draw::Atof(theArgVec[theArgNb - 1]))));
-    aLast = theArgNb - 6;
-  }
-  else if (!strcmp (aName, "scale"))
-  {
-    if (theArgNb < 6)
+      gp_Trsf aTrsf;
+      aTrsf.SetMirror (gp_Ax2 (gp_Pnt (Draw::Atof(theArgVec[theArgNb - 6]),
+                                       Draw::Atof(theArgVec[theArgNb - 5]),
+                                       Draw::Atof(theArgVec[theArgNb - 4])),
+                               gp_Vec (Draw::Atof(theArgVec[theArgNb - 3]),
+                                       Draw::Atof(theArgVec[theArgNb - 2]),
+                                       Draw::Atof(theArgVec[theArgNb - 1]))));
+      anArgIter += 6;
+      aTrsf = anObj->LocalTransformation() * aTrsf;
+      aContext->SetLocation (anObj, aTrsf);
+    }
+    else if (anArg == "-setrotation"
+          || anArg == "-rotation")
     {
-      std::cout << "Error: too few arguments.\n";
-      return 1;
-    }
+      toPrintInfo = Standard_False;
+      if (anArgIter + 4 < theArgNb)
+      {
+        TCollection_AsciiString aQuatArgs[4] =
+        {
+          TCollection_AsciiString (theArgVec[anArgIter + 1]),
+          TCollection_AsciiString (theArgVec[anArgIter + 2]),
+          TCollection_AsciiString (theArgVec[anArgIter + 3]),
+          TCollection_AsciiString (theArgVec[anArgIter + 4])
+        };
+        Standard_Integer aQuatArgIter = 0;
+        for (; aQuatArgIter < 4; ++aQuatArgIter)
+        {
+          if (!aQuatArgs[aQuatArgIter].IsRealValue())
+          {
+            break;
+          }
+        }
 
-    aTrsf.SetScale (gp_Pnt (Draw::Atof(theArgVec[theArgNb - 4]),
-                            Draw::Atof(theArgVec[theArgNb - 3]),
-                            Draw::Atof(theArgVec[theArgNb - 2])),
-                    Draw::Atof(theArgVec[theArgNb - 1]));
-    aLast = theArgNb - 4;
-  }
+        if (aQuatArgIter == 4)
+        {
+          anArgIter += 4;
+          const gp_Quaternion aQuat (aQuatArgs[0].RealValue(),
+                                     aQuatArgs[1].RealValue(),
+                                     aQuatArgs[2].RealValue(),
+                                     aQuatArgs[3].RealValue());
+          gp_Trsf aTrsf = anObj->LocalTransformation();
+          aTrsf.SetRotation (aQuat);
+          aContext->SetLocation (anObj, aTrsf);
+          continue;
+        }
+        else if (anArg == "-setrotation")
+        {
+          std::cout << "Syntax error at '" << anArg << "'\n";
+          return 1;
+        }
+      }
 
-  for (Standard_Integer anIdx = 1; anIdx < aLast; anIdx++)
-  {
-    // find object
-    const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
-    Handle(AIS_InteractiveObject) anIObj;
-    if (aMap.IsBound2 (theArgVec[anIdx]))
-    {
-      anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (theArgVec[anIdx]));
-    }
-    if (anIObj.IsNull())
-    {
-      std::cout << "Error: object '" << theArgVec[anIdx] << "' is not displayed!\n";
-      return 1;
+      char aText[1024];
+      const gp_Quaternion aQuat = anObj->LocalTransformation().GetRotation();
+      Sprintf (aText, "%g %g %g %g ", aQuat.X(), aQuat.Y(), aQuat.Z(), aQuat.W());
+      theDI << aText;
     }
-    
-    if (isReset)
+    else if (anArg == "-setlocation"
+          || anArg == "-location")
     {
-      // aTrsf already identity
+      toPrintInfo = Standard_False;
+      gp_Vec aLocVec;
+      Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter - 1, theArgVec + anArgIter + 1, aLocVec);
+      anArgIter += aNbParsed;
+      if (aNbParsed != 0)
+      {
+        gp_Trsf aTrsf = anObj->LocalTransformation();
+        aTrsf.SetTranslationPart (aLocVec);
+        aContext->SetLocation (anObj, aTrsf);
+      }
+      else if (anArg == "-setlocation")
+      {
+        std::cout << "Syntax error at '" << anArg << "'\n";
+        return 1;
+      }
+
+      char aText[1024];
+      const gp_XYZ aLoc = anObj->LocalTransformation().TranslationPart();
+      Sprintf (aText, "%g %g %g ", aLoc.X(), aLoc.Y(), aLoc.Z());
+      theDI << aText;
     }
-    else if (isMove)
+    else if (aCmdName == "vsetlocation")
     {
-      aTrsf = anIObj->LocalTransformation() * anIObj->Transformation().Inverted() * aTrsf;
+      // compatibility with old syntax
+      gp_Vec aLocVec;
+      Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter, theArgVec + anArgIter, aLocVec);
+      if (aNbParsed == 0)
+      {
+        std::cout << "Syntax error at '" << anArg << "'\n";
+        return 1;
+      }
+      anArgIter = anArgIter + aNbParsed - 1;
+
+      gp_Trsf aTrsf;
+      aTrsf.SetTranslationPart (aLocVec);
+      aContext->SetLocation (anObj, aTrsf);
+      toPrintInfo = Standard_False;
     }
     else
     {
-      aTrsf = anIObj->LocalTransformation() * aTrsf;
+      std::cout << "Error: unknown argument '" << anArg << "'\n";
+      return 1;
     }
+  }
 
-    TopLoc_Location aLocation (aTrsf);
-    aContext->SetLocation (anIObj, aLocation);
+  if (anObj.IsNull())
+  {
+    std::cout << "Syntax error - wrong number of arguments\n";
+    return 1;
+  }
+  else if (!toPrintInfo)
+  {
+    return 0;
   }
 
+  const gp_Trsf       aTrsf = anObj->LocalTransformation();
+  const gp_XYZ        aLoc  = aTrsf.TranslationPart();
+  const gp_Quaternion aRot  = aTrsf.GetRotation();
+  char aText[4096];
+  Sprintf (aText, "Location: %g %g %g\n"
+                  "Rotation: %g %g %g %g\n"
+                  "Scale:    %g\n",
+                  aLoc.X(), aLoc.Y(), aLoc.Z(),
+                  aRot.X(), aRot.Y(), aRot.Z(), aRot.W(),
+                  aTrsf.ScaleFactor());
+  theDI << aText;
   return 0;
 }
 
@@ -3763,14 +3928,15 @@ static Standard_Integer VConnect (Draw_Interpretor& /*di*/,
     }
     else
     {
-      Standard_CString aName = anOriginObjectName.ToCString();
-      TopoDS_Shape aTDShape = DBRep::Get (aName);
+      Standard_CString aOriginName = anOriginObjectName.ToCString();
+      TopoDS_Shape aTDShape = DBRep::Get (aOriginName);
       if (aTDShape.IsNull())
       {
         std::cout << "vconnect error: object " << anOriginObjectName << " doesn't exist\n";
         continue;
       }
       anObject = new AIS_Shape (aTDShape);
+      aContext->Load (anObject);
       anObject->SetColor (ViewerTest::GetColorFromName (aColorName));
     }
 
@@ -3815,7 +3981,7 @@ static Standard_Integer VConnect (Draw_Interpretor& /*di*/,
   GetMapOfAIS().Bind (anOriginObject, aName);
 
   // Display connected object
-  TheAISContext()->Display (anOriginObject);
+  TheAISContext()->Display (anOriginObject, Standard_True);
 
   return 0;
 }
@@ -3823,7 +3989,7 @@ static Standard_Integer VConnect (Draw_Interpretor& /*di*/,
 //===============================================================================================
 //function : VConnectTo
 //purpose  : Creates and displays AIS_ConnectedInteractive object from input object and location 
-//Draw arg : vconnectto name Xo Yo Zo object
+//Draw arg : vconnectto name Xo Yo Zo object [-nodisplay|-noupdate|-update]
 //===============================================================================================
 
 static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/, 
@@ -3832,13 +3998,14 @@ static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/,
 {
   // Check the viewer
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
+  ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
   if (aContext.IsNull())
   {
     std::cout << "vconnect error : call vinit before\n";
     return 1; // TCL_ERROR
   }
   // Check argumnets 
-  if (argc != 6)
+  if (argc != 6 && argc != 7)
   {
     std::cout << "vconnect error: expect at least 5 arguments\n";
     return 1; // TCL_ERROR
@@ -3867,14 +4034,15 @@ static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/,
   }
   else
   {
-    Standard_CString aName = anOriginObjectName.ToCString();
-    TopoDS_Shape aTDShape = DBRep::Get (aName);
+    Standard_CString aOriginName = anOriginObjectName.ToCString();
+    TopoDS_Shape aTDShape = DBRep::Get (aOriginName);
     if (aTDShape.IsNull())
     {
       std::cout << "vconnect error: object " << anOriginObjectName << " doesn't exist\n";
       return 1; // TCL_ERROR
     }
     anOriginObject = new AIS_Shape (aTDShape);
+    GetMapOfAIS().Bind (anOriginObject, anOriginObjectName);
   }
  
   // Get location data
@@ -3907,8 +4075,21 @@ static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/,
   // Bind connected object to its name
   GetMapOfAIS().Bind (aConnected, aName);
 
+  if (argc == 7)
+  {
+    TCollection_AsciiString anArg = argv[6];
+    anArg.LowerCase();
+    if (anArg == "-nodisplay")
+      return 0;
+
+    if (!anUpdateTool.parseRedrawMode (anArg))
+    {
+      std::cout << "Warning! Unknown argument '" << anArg << "' passed, -nodisplay|-noupdate|-update expected at this point.\n";
+    }
+  }
+
   // Display connected object
-  TheAISContext()->Display (aConnected);
+  TheAISContext()->Display (aConnected, Standard_False);
 
   return 0;
 }
@@ -3924,13 +4105,13 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << argv[0] << "ERROR : use 'vinit' command before " << "\n";
+    std::cout << argv[0] << "ERROR : use 'vinit' command before \n";
     return 1;
   }
   
   if (argc != 3)
   {
-    std::cout << "ERROR : Usage : " << argv[0] << " name object" << "\n";
+    std::cout << "ERROR : Usage : " << argv[0] << " name object\n";
     return 1;
   }
 
@@ -3943,14 +4124,14 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
   Handle(AIS_MultipleConnectedInteractive) anAssembly;
   if (!aMap.IsBound2 (aName) )
   {
-    std::cout << "Use 'vdisplay' before" << "\n";
+    std::cout << "Use 'vdisplay' before\n";
     return 1;
   }
 
   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
   if (anAssembly.IsNull())
   {
-    di << "Not an assembly" << "\n";
+    di << "Not an assembly\n";
     return 1;
   }
 
@@ -3973,7 +4154,7 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
     }
     else
     {
-      std::cout << "Use 'vdisplay' before" << "\n";
+      std::cout << "Use 'vdisplay' before\n";
       return 1;
     }    
   }
@@ -3984,7 +4165,7 @@ static Standard_Integer VDisconnect (Draw_Interpretor& di,
     anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (anObject));
   }
 
-  anAssembly->Disconnect (anIObj);
+  aContext->Disconnect (anAssembly, anIObj);
   aContext->UpdateCurrentViewer();
 
   return 0;
@@ -4001,7 +4182,7 @@ static Standard_Integer VAddConnected (Draw_Interpretor& di,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << argv[0] << "error : use 'vinit' command before " << "\n";
+    std::cout << argv[0] << "error : use 'vinit' command before \n";
     return 1;
   }
   
@@ -4022,21 +4203,21 @@ static Standard_Integer VAddConnected (Draw_Interpretor& di,
   Handle(AIS_MultipleConnectedInteractive) anAssembly;
   if (!aMap.IsBound2 (aName) )
   {
-    std::cout << "Use 'vdisplay' before" << "\n";
+    std::cout << "Use 'vdisplay' before\n";
     return 1;
   }
 
   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
   if (anAssembly.IsNull())
   {
-    di << "Not an assembly" << "\n";
+    di << "Not an assembly\n";
     return 1;
   }
 
   Handle(AIS_InteractiveObject) anIObj;
   if (!aMap.IsBound2 (anObject))
   {
-      std::cout << "Use 'vdisplay' before" << "\n";
+      std::cout << "Use 'vdisplay' before\n";
       return 1; 
   }
 
@@ -4046,7 +4227,7 @@ static Standard_Integer VAddConnected (Draw_Interpretor& di,
   aTrsf.SetTranslation (gp_Vec (aX, aY, aZ));
  
   anAssembly->Connect (anIObj, aTrsf);
-  TheAISContext()->Display (anAssembly);
+  TheAISContext()->Display (anAssembly, Standard_False);
   TheAISContext()->RecomputeSelectionOnly (anAssembly);
   aContext->UpdateCurrentViewer();
 
@@ -4064,13 +4245,13 @@ static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
   if (aContext.IsNull())
   {
-    std::cout << argv[0] << "ERROR : use 'vinit' command before " << "\n";
+    std::cout << argv[0] << "ERROR : use 'vinit' command before \n";
     return 1;
   }
   
   if (argc != 2)
   {
-    std::cout << "ERROR : Usage : " << argv[0] << " name" << "\n";
+    std::cout << "ERROR : Usage : " << argv[0] << " name\n";
     return 1;
   }
 
@@ -4081,14 +4262,14 @@ static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
   Handle(AIS_MultipleConnectedInteractive) anAssembly;
   if (!aMap.IsBound2 (aName) )
   {
-    std::cout << "Use 'vdisplay' before" << "\n";
+    std::cout << "Use 'vdisplay' before\n";
     return 1;
   }
 
   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
   if (anAssembly.IsNull())
   {
-    std::cout << "Not an assembly" << "\n";
+    std::cout << "Not an assembly\n";
     return 1;
   }
 
@@ -4099,8 +4280,8 @@ static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
   {
     if (GetMapOfAIS().IsBound1 (anIter.Value()))
     {
-      TCollection_AsciiString aName = GetMapOfAIS().Find1 (anIter.Value());
-      std::cout << aCounter << ")  " << aName << "    (" << anIter.Value()->DynamicType()->Name() << ")";
+      TCollection_AsciiString aCuurrentName = GetMapOfAIS().Find1 (anIter.Value());
+      std::cout << aCounter << ")  " << aCuurrentName << "    (" << anIter.Value()->DynamicType()->Name() << ")";
     }
 
     std::cout << aCounter << ")  " << anIter.Value()->DynamicType()->Name();
@@ -4136,7 +4317,7 @@ namespace
     }
     return Standard_False;
   }
-};
+}
 
 //===============================================================================================
 //function : VSetSelectionMode
@@ -4156,16 +4337,21 @@ static Standard_Integer VSetSelectionMode (Draw_Interpretor& /*di*/,
   }
 
   // Check the arguments
-  if (theArgc != 3 && theArgc != 4)
+  if (theArgc < 3 && theArgc > 5)
   {
     std::cerr << "vselmode error : expects at least 2 arguments.\n"
               << "Type help "<< theArgv[0] <<" for more information." << std::endl;
     return 1;
   }
 
+  TCollection_AsciiString aLastArg (theArgv[theArgc - 1]);
+  aLastArg.LowerCase();
+  Standard_Boolean isToOpenLocalCtx = aLastArg == "-local";
+
   // get objects to change selection mode
   AIS_ListOfInteractive aTargetIOs;
-  if (theArgc == 3)
+  Standard_Integer anArgNb = isToOpenLocalCtx ? theArgc - 1 : theArgc;
+  if (anArgNb == 3)
   {
     anAISContext->DisplayedObjects (aTargetIOs);
   }
@@ -4185,12 +4371,37 @@ static Standard_Integer VSetSelectionMode (Draw_Interpretor& /*di*/,
     }
   }
 
-  const Standard_Integer aSelectionMode = Draw::Atoi (theArgc == 3 ? theArgv[1] : theArgv[2]);
-  const Standard_Boolean toTurnOn       = Draw::Atoi (theArgc == 3 ? theArgv[2] : theArgv[3]);
+  Standard_Integer aSelectionMode = -1;
+  Standard_Boolean toTurnOn = Standard_True;
+  {
+    const TCollection_AsciiString aSelModeString (theArgv[anArgNb == 3 ? 1 : 2]);
+    TopAbs_ShapeEnum aShapeType = TopAbs_SHAPE;
+    if (aSelModeString.IsIntegerValue())
+    {
+      aSelectionMode = aSelModeString.IntegerValue();
+    }
+    else if (TopAbs::ShapeTypeFromString (aSelModeString.ToCString(), aShapeType))
+    {
+      aSelectionMode = AIS_Shape::SelectionMode (aShapeType);
+    }
+    else
+    {
+      std::cout << "Syntax error: unknown selection mode '" << aSelModeString  << "'\n";
+      return 1;
+    }
+  }
+  if (!ViewerTest::ParseOnOff (theArgv[anArgNb == 3 ? 2 : 3], toTurnOn))
+  {
+    std::cout << "Syntax error: on/off is expected by found '" << theArgv[anArgNb == 3 ? 2 : 3] << "'\n";
+    return 1;
+  }
+
+  Standard_DISABLE_DEPRECATION_WARNINGS
   if (aSelectionMode == 0 && anAISContext->HasOpenedContext())
   {
     anAISContext->CloseLocalContext();
   }
+  Standard_ENABLE_DEPRECATION_WARNINGS
 
   if (aSelectionMode == 0)
   {
@@ -4199,6 +4410,12 @@ static Standard_Integer VSetSelectionMode (Draw_Interpretor& /*di*/,
       for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
       {
         const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
+        TColStd_ListOfInteger anActiveModes;
+        anAISContext->ActivatedModes (anIO, anActiveModes);
+        if (!anActiveModes.IsEmpty())
+        {
+          anAISContext->Deactivate (anIO);
+        }
         if (!InList (anAISContext, anIO, aSelectionMode))
         {
           anAISContext->Activate (anIO);
@@ -4220,70 +4437,105 @@ static Standard_Integer VSetSelectionMode (Draw_Interpretor& /*di*/,
 
   if (aSelectionMode != 0 && toTurnOn) // Turn on specified mode
   {
-    if (!anAISContext->HasOpenedContext())
+    Standard_DISABLE_DEPRECATION_WARNINGS
+    if (!anAISContext->HasOpenedContext() && isToOpenLocalCtx)
     {
       anAISContext->OpenLocalContext (Standard_False);
     }
+    Standard_ENABLE_DEPRECATION_WARNINGS
 
     for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
     {
       const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
-      if (!InList (anAISContext, anIO, aSelectionMode))
-      {
-        anAISContext->Load (anIO, -1, Standard_True);
-        anAISContext->Activate (anIO, aSelectionMode);
-      }
+      anAISContext->Deactivate (anIO, 0);
+      anAISContext->Load (anIO, -1, Standard_True);
+      anAISContext->Activate (anIO, aSelectionMode);
+    }
+  }
+
+  if (aSelectionMode != 0 && !toTurnOn) // Turn off specified mode
+  {
+    for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
+    {
+      anAISContext->Deactivate (aSelectionMode);
     }
   }
 
-  if (aSelectionMode != 0 && !toTurnOn) // Turn off specified mode
+  return 0;
+}
+
+//===============================================================================================
+//function : VSelectionNext
+//purpose  : 
+//===============================================================================================
+static Standard_Integer VSelectionNext(Draw_Interpretor& /*theDI*/,
+                                 Standard_Integer /*theArgsNb*/,
+                                 const char** /*theArgVec*/)
+{
+  // Check errors
+  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
+  Handle(V3d_View) aView = ViewerTest::CurrentView();
+
+  if (anAISContext.IsNull())
   {
-    if (!anAISContext->HasOpenedContext())
-    {
-      return 0;
-    }
+    std::cerr << "Call vinit before!" << std::endl;
+    return 1;
+  }
 
-    for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
-    {
-      const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
-      if (InList (anAISContext, anIO, aSelectionMode))
-      {
-        anAISContext->Deactivate (anIO, aSelectionMode);
-      }
-    }
+  anAISContext->HilightNextDetected (aView);
+  return 0;
+}
+
+//===============================================================================================
+//function : VSelectionPrevious
+//purpose  : 
+//===============================================================================================
+static Standard_Integer VSelectionPrevious(Draw_Interpretor& /*theDI*/,
+                                 Standard_Integer /*theArgsNb*/,
+                                 const char** /*theArgVec*/)
+{
+  // Check errors
+  Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
+  Handle(V3d_View) aView = ViewerTest::CurrentView();
+
+  if (anAISContext.IsNull())
+  {
+    std::cerr << "Call vinit before!" << std::endl;
+    return 1;
   }
 
+  anAISContext->HilightPreviousDetected (aView);
   return 0;
 }
 
+
 //==========================================================================
 //class   : Triangle 
 //purpose : creates Triangle based on AIS_InteractiveObject. 
 //          This class was implemented for testing Select3D_SensitiveTriangle
 //===========================================================================
-DEFINE_STANDARD_HANDLE(Triangle, AIS_InteractiveObject)
+
 class Triangle: public AIS_InteractiveObject 
 {
 public: 
   // CASCADE RTTI
-  DEFINE_STANDARD_RTTI(FilledCircle); 
+  DEFINE_STANDARD_RTTI_INLINE(Triangle,AIS_InteractiveObject);
   Triangle (const gp_Pnt& theP1, 
             const gp_Pnt& theP2, 
             const gp_Pnt& theP3);
 protected:
   void Compute (  const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
                   const Handle(Prs3d_Presentation)& thePresentation,
-                  const Standard_Integer theMode);
+                  const Standard_Integer theMode) Standard_OVERRIDE;
 
   void ComputeSelection (  const Handle(SelectMgr_Selection)& theSelection, 
-                           const Standard_Integer theMode);
+                           const Standard_Integer theMode) Standard_OVERRIDE;
 private: 
   gp_Pnt myPoint1;
   gp_Pnt myPoint2;
   gp_Pnt myPoint3;
 };
-IMPLEMENT_STANDARD_HANDLE(Triangle, AIS_InteractiveObject)
-IMPLEMENT_STANDARD_RTTIEXT(Triangle, AIS_InteractiveObject)
+
 
 Triangle::Triangle (const gp_Pnt& theP1,
                     const gp_Pnt& theP2,
@@ -4381,8 +4633,6 @@ static Standard_Integer VTriangle (Draw_Interpretor& /*di*/,
     return 1; // TCL_ERROR
   }
 
-  TheAISContext()->CloseAllContexts();
-
   // Get and check values
   TCollection_AsciiString aName(argv[1]);
 
@@ -4449,33 +4699,32 @@ static Standard_Integer VTriangle (Draw_Interpretor& /*di*/,
   GetMapOfAIS().Bind(aTriangle, aName);
 
   // Display triangle
-  TheAISContext()->Display(aTriangle);
+  TheAISContext()->Display (aTriangle, Standard_True);
   return 0;
 }
 
 //class  : SegmentObject
 //purpose: creates segment based on AIS_InteractiveObject.
 //         This class was implemented for testing Select3D_SensitiveCurve
-DEFINE_STANDARD_HANDLE(SegmentObject, AIS_InteractiveObject)
+
 class SegmentObject: public AIS_InteractiveObject
 {
 public:
   // CASCADE RTTI
-  DEFINE_STANDARD_RTTI(SegmentObject); 
+  DEFINE_STANDARD_RTTI_INLINE(SegmentObject,AIS_InteractiveObject); 
   SegmentObject (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2);
 protected:
   void Compute (const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
                 const Handle(Prs3d_Presentation)& thePresentation,
-                const Standard_Integer theMode);
+                const Standard_Integer theMode) Standard_OVERRIDE;
 
   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection, 
-                         const Standard_Integer theMode);
+                         const Standard_Integer theMode) Standard_OVERRIDE;
 private:
   gp_Pnt myPoint1;
   gp_Pnt myPoint2;
 };
-IMPLEMENT_STANDARD_HANDLE(SegmentObject, AIS_InteractiveObject)
-IMPLEMENT_STANDARD_RTTIEXT(SegmentObject, AIS_InteractiveObject)
+
 
 SegmentObject::SegmentObject (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2)
 {
@@ -4524,8 +4773,6 @@ static Standard_Integer VSegment (Draw_Interpretor& /*di*/,
     return 1; // TCL_ERROR
   }
 
-  TheAISContext()->CloseAllContexts();
-
   // Get and check arguments
   TCollection_AsciiString aName(argv[1]);
   Handle(AIS_Point) aPoint1, aPoint2;
@@ -4567,7 +4814,7 @@ static Standard_Integer VSegment (Draw_Interpretor& /*di*/,
   GetMapOfAIS().Bind(aSegment, aName);
 
   // Display segment
-  TheAISContext()->Display(aSegment);
+  TheAISContext()->Display (aSegment, Standard_True);
   return 0;
 }
 
@@ -4608,7 +4855,7 @@ static Standard_Integer VObjZLayer (Draw_Interpretor& di,
   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
   if (!aMap.IsBound2 (aName))
   {
-    di << "Use 'vdisplay' before" << "\n";
+    di << "Use 'vdisplay' before\n";
     return 1;
   }
 
@@ -4813,13 +5060,10 @@ static Standard_Integer VShowFaceBoundary (Draw_Interpretor& /*di*/,
   // select appropriate line type
   if (argc == 8)
   {
-    switch (Draw::Atoi (argv[7]))
+    if (!ViewerTest::ParseLineType (argv[7], aLineType))
     {
-      case 1: aLineType = Aspect_TOL_DASH;    break;
-      case 2: aLineType = Aspect_TOL_DOT;     break;
-      case 3: aLineType = Aspect_TOL_DOTDASH; break;
-      default:
-        aLineType = Aspect_TOL_SOLID;
+      std::cout << "Syntax error: unknown line type '" << argv[7] << "'\n";
+      return 1;
     }
   }
 
@@ -4830,13 +5074,13 @@ static Standard_Integer VShowFaceBoundary (Draw_Interpretor& /*di*/,
 
   aDrawer->SetFaceBoundaryAspect (aBoundaryAspect);
 
-  TheAISContext()->Redisplay (anInterObj);
+  TheAISContext()->Redisplay (anInterObj, Standard_True);
   
   return 0;
 }
 
 // This class is used for testing markers.
-DEFINE_STANDARD_HANDLE(ViewerTest_MarkersArrayObject, AIS_InteractiveObject)
+
 class ViewerTest_MarkersArrayObject : public AIS_InteractiveObject
 {
 
@@ -4851,16 +5095,16 @@ public:
     myMarkerAspect = theMarkerAspect;
   }
 
-  DEFINE_STANDARD_RTTI(MyPArrayObject);
+  DEFINE_STANDARD_RTTI_INLINE(ViewerTest_MarkersArrayObject,AIS_InteractiveObject);
 
 private:
 
   void Compute (const Handle(PrsMgr_PresentationManager3d)& aPresentationManager,
                 const Handle(Prs3d_Presentation)& aPresentation,
-                const Standard_Integer aMode);
+                const Standard_Integer aMode) Standard_OVERRIDE;
 
   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
-                         const Standard_Integer /*theMode*/);
+                         const Standard_Integer /*theMode*/) Standard_OVERRIDE;
 
 protected:
 
@@ -4869,8 +5113,6 @@ protected:
   Handle(Graphic3d_AspectMarker3d) myMarkerAspect;
 };
 
-IMPLEMENT_STANDARD_HANDLE(ViewerTest_MarkersArrayObject, AIS_InteractiveObject)
-IMPLEMENT_STANDARD_RTTIEXT(ViewerTest_MarkersArrayObject, AIS_InteractiveObject)
 
 void ViewerTest_MarkersArrayObject::Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPresentationManager*/,
                               const Handle(Prs3d_Presentation)& aPresentation,
@@ -5006,6 +5248,14 @@ static Standard_Integer VMarkersTest (Draw_Interpretor&,
       std::cerr << "Could not load image from file '" << aFileName << "'!\n";
       return 1;
     }
+    if (anImage->Format() == Image_Format_Gray)
+    {
+      anImage->SetFormat (Image_Format_Alpha);
+    }
+    else if (anImage->Format() == Image_Format_GrayF)
+    {
+      anImage->SetFormat (Image_Format_AlphaF);
+    }
     anAspect = new Graphic3d_AspectMarker3d (anImage);
   }
   else
@@ -5066,69 +5316,210 @@ static TCollection_AsciiString fontStyleString (const Font_FontAspect theAspect)
 //function : TextToBrep
 //purpose  : Tool for conversion text to occt-shapes
 //=======================================================================
-
 static int TextToBRep (Draw_Interpretor& /*theDI*/,
                        Standard_Integer  theArgNb,
                        const char**      theArgVec)
 {
   // Check arguments
-  if (theArgNb < 5)
+  if (theArgNb < 3)
   {
     std::cerr << "Error: " << theArgVec[0] << " - invalid syntax\n";
     return 1;
   }
 
-  Standard_Integer    anArgIter = 1;
-  Standard_CString    aResName  = theArgVec[anArgIter++];
-  Standard_CString    aText     = theArgVec[anArgIter++];
-  Standard_CString    aFontName = theArgVec[anArgIter++];
-  const Standard_Real aSize     = Atof (theArgVec[anArgIter++]);
+  Standard_Integer anArgIt = 1;
+  Standard_CString aName   = theArgVec[anArgIt++];
+  Standard_CString aText   = theArgVec[anArgIt++];
+
+  Font_BRepFont           aFont;
+  TCollection_AsciiString aFontName ("Courier");
+  Standard_Real           aTextHeight        = 16.0;
+  Font_FontAspect         aFontAspect        = Font_FA_Regular;
+  Standard_Boolean        anIsCompositeCurve = Standard_False;
+  gp_Ax3                  aPenAx3    (gp::XOY());
+  gp_Dir                  aNormal    (0.0, 0.0, 1.0);
+  gp_Dir                  aDirection (1.0, 0.0, 0.0);
+  gp_Pnt                  aPenLoc;
 
-  Font_BRepFont    aFont;
-  Font_FontAspect  aFontAspect      = Font_FA_Regular;
-  Standard_Boolean isCompositeCurve = Standard_False;
-  gp_Ax3           aPenAx3 (gp::XOY());
-  gp_Pnt           aPenLoc;
-  while (anArgIter < theArgNb)
+  Graphic3d_HorizontalTextAlignment aHJustification = Graphic3d_HTA_LEFT;
+  Graphic3d_VerticalTextAlignment   aVJustification = Graphic3d_VTA_BOTTOM;
+
+  for (; anArgIt < theArgNb; ++anArgIt)
   {
-    const TCollection_AsciiString anArg (theArgVec[anArgIter++]);
-    TCollection_AsciiString anArgCase (anArg);
-    anArgCase.LowerCase();
-    if (anArgCase.Search ("x=") > -1)
+    TCollection_AsciiString aParam (theArgVec[anArgIt]);
+    aParam.LowerCase();
+
+    if (aParam == "-pos"
+     || aParam == "-position")
+    {
+      if (anArgIt + 3 >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      aPenLoc.SetX (Draw::Atof(theArgVec[++anArgIt]));
+      aPenLoc.SetY (Draw::Atof(theArgVec[++anArgIt]));
+      aPenLoc.SetZ (Draw::Atof(theArgVec[++anArgIt]));
+    }
+    else if (aParam == "-halign")
+    {
+      if (++anArgIt >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      TCollection_AsciiString aType (theArgVec[anArgIt]);
+      aType.LowerCase();
+      if (aType == "left")
+      {
+        aHJustification = Graphic3d_HTA_LEFT;
+      }
+      else if (aType == "center")
+      {
+        aHJustification = Graphic3d_HTA_CENTER;
+      }
+      else if (aType == "right")
+      {
+        aHJustification = Graphic3d_HTA_RIGHT;
+      }
+      else
+      {
+        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-valign")
+    {
+      if (++anArgIt >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      TCollection_AsciiString aType (theArgVec[anArgIt]);
+      aType.LowerCase();
+      if (aType == "top")
+      {
+        aVJustification = Graphic3d_VTA_TOP;
+      }
+      else if (aType == "center")
+      {
+        aVJustification = Graphic3d_VTA_CENTER;
+      }
+      else if (aType == "bottom")
+      {
+        aVJustification = Graphic3d_VTA_BOTTOM;
+      }
+      else if (aType == "topfirstline")
+      {
+        aVJustification = Graphic3d_VTA_TOPFIRSTLINE;
+      }
+      else
+      {
+        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-height")
     {
-      aPenLoc.SetX (anArg.Token ("=", 2).RealValue());
+      if (++anArgIt >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      aTextHeight = Draw::Atof(theArgVec[anArgIt]);
     }
-    else if (anArgCase.Search ("y=") > -1)
+    else if (aParam == "-aspect")
     {
-      aPenLoc.SetY (anArg.Token ("=", 2).RealValue());
+      if (++anArgIt >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      TCollection_AsciiString anOption (theArgVec[anArgIt]);
+      anOption.LowerCase();
+
+      if (anOption.IsEqual ("regular"))
+      {
+        aFontAspect = Font_FA_Regular;
+      }
+      else if (anOption.IsEqual ("bold"))
+      {
+        aFontAspect = Font_FA_Bold;
+      }
+      else if (anOption.IsEqual ("italic"))
+      {
+        aFontAspect = Font_FA_Italic;
+      }
+      else if (anOption.IsEqual ("bolditalic"))
+      {
+        aFontAspect = Font_FA_BoldItalic;
+      }
+      else
+      {
+        std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
     }
-    else if (anArgCase.Search ("z=") > -1)
+    else if (aParam == "-font")
     {
-      aPenLoc.SetZ (anArg.Token ("=", 2).RealValue());
+      if (++anArgIt >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      aFontName = theArgVec[anArgIt];
     }
-    else if (anArgCase.Search ("composite=") > -1)
+    else if (aParam == "-composite")
     {
-      isCompositeCurve = (anArg.Token ("=", 2).IntegerValue() == 1);
+      if (++anArgIt >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      ViewerTest::ParseOnOff (theArgVec[anArgIt], anIsCompositeCurve);
     }
-    else if (parseFontStyle (anArgCase, aFontAspect))
+    else if (aParam == "-plane")
     {
-      //
+      if (anArgIt + 6 >= theArgNb)
+      {
+        std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
+        return 1;
+      }
+
+      Standard_Real aX = Draw::Atof (theArgVec[++anArgIt]);
+      Standard_Real aY = Draw::Atof (theArgVec[++anArgIt]);
+      Standard_Real aZ = Draw::Atof (theArgVec[++anArgIt]);
+      aNormal.SetCoord (aX, aY, aZ);
+
+      aX = Draw::Atof (theArgVec[++anArgIt]);
+      aY = Draw::Atof (theArgVec[++anArgIt]);
+      aZ = Draw::Atof (theArgVec[++anArgIt]);
+      aDirection.SetCoord (aX, aY, aZ);
     }
     else
     {
-      std::cerr << "Warning! Unknown argument '" << anArg.ToCString() << "'\n";
+      std::cerr << "Warning! Unknown argument '" << aParam << "'\n";
     }
   }
 
-  aFont.SetCompositeCurveMode (isCompositeCurve);
-  if (!aFont.Init (aFontName, aFontAspect, aSize))
+  aFont.SetCompositeCurveMode (anIsCompositeCurve);
+  if (!aFont.Init (aFontName.ToCString(), aFontAspect, aTextHeight))
   {
     std::cerr << "Font initialization error\n";
     return 1;
   }
 
-  aPenAx3.SetLocation (aPenLoc);
-  DBRep::Set (aResName, aFont.RenderText (aText, aPenAx3));
+  aPenAx3 = gp_Ax3 (aPenLoc, aNormal, aDirection);
+
+  Font_BRepTextBuilder aBuilder;
+  DBRep::Set (aName, aBuilder.Perform (aFont, aText, aPenAx3, aHJustification, aVJustification));
   return 0;
 }
 
@@ -5291,8 +5682,14 @@ static int VSetEdgeType (Draw_Interpretor& theDI,
   Handle(AIS_InteractiveObject) anObject = 
     Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(aName));
   
-  // Enable trianle edge mode
-  anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeOn();
+  // Enable triangle edge mode
+  if (!anObject->Attributes()->HasOwnShadingAspect())
+  {
+    anObject->Attributes()->SetShadingAspect (new Prs3d_ShadingAspect());
+    *anObject->Attributes()->ShadingAspect()->Aspect() = *anObject->Attributes()->Link()->ShadingAspect()->Aspect();
+  }
+  const Handle(Prs3d_ShadingAspect)& aFillAreaAspect = anObject->Attributes()->ShadingAspect();
+  aFillAreaAspect->Aspect()->SetEdgeOn();
 
   // Parse parameters
   for (Standard_Integer anIt = 2; anIt < theArgNum; ++anIt)
@@ -5309,31 +5706,14 @@ static int VSetEdgeType (Draw_Interpretor& theDI,
           return 1;
         }
 
-        TCollection_AsciiString aType = theArgs[++anIt];
-        aType.UpperCase();
-
-        if (aType.IsEqual ("SOLID"))
+        ++anIt;
+        Aspect_TypeOfLine aTypeEnum = Aspect_TOL_SOLID;
+        if (!ViewerTest::ParseLineType (theArgs[anIt], aTypeEnum))
         {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_SOLID);
-        }
-        else if (aType.IsEqual ("DASH"))
-        {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_DASH);
-        }
-        else if (aType.IsEqual ("DOT"))
-        {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_DOT);
-        }
-        else if (aType.IsEqual ("DOTDASH"))
-        {
-          anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType(Aspect_TOL_DOTDASH);
-        }
-        else
-        {
-          theDI <<  theArgs[0] << " error: wrong line type: '" << aType.ToCString() << "'.\n";
+          std::cout << "Syntax error: wrong line type: '" << theArgs[anIt] << "'.\n";
           return 1;
         }
-        
+        anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType (aTypeEnum);
       }
       else if (aParam.IsEqual ("-color"))
       {
@@ -5352,7 +5732,7 @@ static int VSetEdgeType (Draw_Interpretor& theDI,
                                                 aB > 1 ? aB / 255.0 : aB,
                                                 Quantity_TOC_RGB);
 
-        anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeColor (aColor);
+        aFillAreaAspect->Aspect()->SetEdgeColor (aColor);
       }
       else if (aParam.IsEqual ("-force"))
       {
@@ -5370,11 +5750,11 @@ static int VSetEdgeType (Draw_Interpretor& theDI,
   // Update shape presentation as aspect parameters were changed
   if (isForceRedisplay)
   {
-    ViewerTest::GetAISContext()->Redisplay (anObject);
+    ViewerTest::GetAISContext()->Redisplay (anObject, Standard_False);
   }
   else
   {
-    anObject->SetAspect (anObject->Attributes()->ShadingAspect());
+    anObject->SetAspect (aFillAreaAspect);
   }
 
   //Update view
@@ -5434,7 +5814,7 @@ static int VUnsetEdgeType (Draw_Interpretor& theDI,
   // Update shape presentation as aspect parameters were changed
   if (isForceRedisplay)
   {
-    ViewerTest::GetAISContext()->Redisplay (anObject);
+    ViewerTest::GetAISContext()->Redisplay (anObject, Standard_False);
   }
   else
   {
@@ -5649,7 +6029,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
     for (TopExp_Explorer aFaceIt (aShape, TopAbs_FACE); aFaceIt.More(); aFaceIt.Next())
     {
       const TopoDS_Face& aFace = TopoDS::Face (aFaceIt.Current());
-      Handle(Poly_Triangulation) aTriangulation = StdPrs_ToolShadedShape::Triangulation (aFace, aLocation);
+      Handle(Poly_Triangulation) aTriangulation = BRep_Tool::Triangulation (aFace, aLocation);
       if (!aTriangulation.IsNull())
       {
         aNbPoints += aTriangulation->NbNodes();
@@ -5665,7 +6045,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
     for (TopExp_Explorer aFaceIt (aShape, TopAbs_FACE); aFaceIt.More(); aFaceIt.Next())
     {
       const TopoDS_Face& aFace = TopoDS::Face (aFaceIt.Current());
-      Handle(Poly_Triangulation) aTriangulation = StdPrs_ToolShadedShape::Triangulation (aFace, aLocation);
+      Handle(Poly_Triangulation) aTriangulation = BRep_Tool::Triangulation (aFace, aLocation);
       if (aTriangulation.IsNull())
       {
         continue;
@@ -5679,7 +6059,7 @@ static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
       if (hasNormals)
       {
         Poly_Connect aPolyConnect (aTriangulation);
-        StdPrs_ToolShadedShape::Normal (aFace, aPolyConnect, aNormals);
+        StdPrs_ToolTriangulatedShape::Normal (aFace, aPolyConnect, aNormals);
       }
 
       for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter)
@@ -5840,6 +6220,217 @@ static int VPriority (Draw_Interpretor& theDI,
   return 0;
 }
 
+//! Auxiliary class for command vnormals.
+class MyShapeWithNormals : public AIS_Shape
+{
+  DEFINE_STANDARD_RTTI_INLINE(MyShapeWithNormals, AIS_Shape);
+public:
+
+  Standard_Real    NormalLength;
+  Standard_Integer NbAlongU;
+  Standard_Integer NbAlongV;
+  Standard_Boolean ToUseMesh;
+  Standard_Boolean ToOrient;
+
+public:
+
+  //! Main constructor.
+  MyShapeWithNormals (const TopoDS_Shape& theShape)
+  : AIS_Shape   (theShape),
+    NormalLength(10),
+    NbAlongU  (1),
+    NbAlongV  (1),
+    ToUseMesh (Standard_False),
+    ToOrient  (Standard_False) {}
+
+protected:
+
+  //! Comnpute presentation.
+  virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr,
+                        const Handle(Prs3d_Presentation)&           thePrs,
+                        const Standard_Integer                      theMode) Standard_OVERRIDE
+  {
+    AIS_Shape::Compute (thePrsMgr, thePrs, theMode);
+
+    NCollection_DataMap<TopoDS_Face, NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> > > aNormalMap;
+    if (ToUseMesh)
+    {
+      DBRep_DrawableShape::addMeshNormals (aNormalMap, myshape, NormalLength);
+    }
+    else
+    {
+      DBRep_DrawableShape::addSurfaceNormals (aNormalMap, myshape, NormalLength, NbAlongU, NbAlongV);
+    }
+
+    Handle(Graphic3d_Group) aPrsGroup = Prs3d_Root::NewGroup (thePrs);
+    aPrsGroup->SetGroupPrimitivesAspect (myDrawer->ArrowAspect()->Aspect());
+
+    const Standard_Real aArrowAngle  = myDrawer->ArrowAspect()->Angle();
+    const Standard_Real aArrowLength = myDrawer->ArrowAspect()->Length();
+    for (NCollection_DataMap<TopoDS_Face, NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> > >::Iterator aFaceIt (aNormalMap);
+         aFaceIt.More(); aFaceIt.Next())
+    {
+      const Standard_Boolean toReverse = ToOrient && aFaceIt.Key().Orientation() == TopAbs_REVERSED;
+      Handle(Graphic3d_ArrayOfSegments) aSegments = new Graphic3d_ArrayOfSegments (2 * aFaceIt.Value().Size());
+      for (NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> >::Iterator aPntIt (aFaceIt.Value()); aPntIt.More(); aPntIt.Next())
+      {
+        std::pair<gp_Pnt, gp_Pnt> aPair = aPntIt.Value();
+        if (toReverse)
+        {
+          const gp_Vec aDir = aPair.first.XYZ() - aPair.second.XYZ();
+          aPair.second = aPair.first.XYZ() + aDir.XYZ();
+        }
+
+        aSegments->AddVertex (aPair.first);
+        aSegments->AddVertex (aPair.second);
+        Prs3d_Arrow::Draw (aPrsGroup, aPair.second, gp_Vec(aPair.first, aPair.second), aArrowAngle, aArrowLength);
+      }
+
+      aPrsGroup->AddPrimitiveArray (aSegments);
+    }
+  }
+
+};
+
+//=======================================================================
+//function : VNormals
+//purpose  : Displays/Hides normals calculated on shape geometry or retrieved from triangulation
+//=======================================================================
+static int VNormals (Draw_Interpretor& theDI,
+                     Standard_Integer  theArgNum,
+                     const char**      theArgs)
+{
+  Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
+  if (aContext.IsNull())
+  {
+    std::cout << "Error: no view available, call 'vinit' before!\n";
+    return 1;
+  }
+  else if (theArgNum < 2)
+  {
+    std::cout << "Error: wrong number of arguments! See usage:\n";
+    theDI.PrintHelp (theArgs[0]);
+    return 1;
+  }
+
+  Standard_Integer anArgIter = 1;
+  Standard_CString aShapeName = theArgs[anArgIter++];
+  TopoDS_Shape     aShape     = DBRep::Get (aShapeName);
+  Standard_Boolean isOn = Standard_True;
+  if (aShape.IsNull())
+  {
+    std::cout << "Error: shape with name '" << aShapeName << "' is not found\n";
+    return 1;
+  }
+
+  ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
+  Handle(MyShapeWithNormals) aShapePrs;
+  if (aMap.IsBound2 (aShapeName))
+  {
+    aShapePrs = Handle(MyShapeWithNormals)::DownCast (aMap.Find2 (aShapeName));
+  }
+
+  Standard_Boolean isUseMesh = Standard_False;
+  Standard_Real    aLength = 10.0;
+  Standard_Integer aNbAlongU = 1, aNbAlongV = 1;
+  Standard_Boolean isOriented = Standard_False;
+  for (; anArgIter < theArgNum; ++anArgIter)
+  {
+    TCollection_AsciiString aParam (theArgs[anArgIter]);
+    aParam.LowerCase();
+    if (anArgIter == 2
+     && ViewerTest::ParseOnOff (aParam.ToCString(), isOn))
+    {
+      continue;
+    }
+    else if (aParam == "-usemesh"
+          || aParam == "-mesh")
+    {
+      isUseMesh = Standard_True;
+    }
+    else if (aParam == "-length"
+          || aParam == "-len")
+    {
+      ++anArgIter;
+      aLength = anArgIter < theArgNum ? Draw::Atof (theArgs[anArgIter]) : 0.0;
+      if (Abs (aLength) <= gp::Resolution())
+      {
+        std::cout << "Syntax error: length should not be zero\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-orient"
+          || aParam == "-oriented")
+    {
+      isOriented = Standard_True;
+      if (anArgIter + 1 < theArgNum
+        && ViewerTest::ParseOnOff (theArgs[anArgIter + 1], isOriented))
+      {
+        ++anArgIter;
+      }
+    }
+    else if (aParam == "-nbalongu"
+          || aParam == "-nbu")
+    {
+      ++anArgIter;
+      aNbAlongU = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
+      if (aNbAlongU < 1)
+      {
+        std::cout << "Syntax error: NbAlongU should be >=1\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-nbalongv"
+          || aParam == "-nbv")
+    {
+      ++anArgIter;
+      aNbAlongV = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
+      if (aNbAlongV < 1)
+      {
+        std::cout << "Syntax error: NbAlongV should be >=1\n";
+        return 1;
+      }
+    }
+    else if (aParam == "-nbalong"
+          || aParam == "-nbuv")
+    {
+      ++anArgIter;
+      aNbAlongU = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
+      aNbAlongV = aNbAlongU;
+      if (aNbAlongU < 1)
+      {
+        std::cout << "Syntax error: NbAlong should be >=1\n";
+        return 1;
+      }
+    }
+    else
+    {
+      std::cout << "Syntax error: unknwon argument '" << aParam << "'\n";
+      return 1;
+    }
+  }
+
+  if (isOn)
+  {
+    if (aShapePrs.IsNull())
+    {
+      aShapePrs = new MyShapeWithNormals (aShape);
+    }
+    aShapePrs->ToUseMesh    = isUseMesh;
+    aShapePrs->ToOrient     = isOriented;
+    aShapePrs->NormalLength = aLength;
+    aShapePrs->NbAlongU     = aNbAlongU;
+    aShapePrs->NbAlongV     = aNbAlongV;
+    VDisplayAISObject (aShapeName, aShapePrs);
+  }
+  else if (!aShapePrs.IsNull())
+  {
+    VDisplayAISObject (aShapeName, new AIS_Shape (aShape));
+  }
+
+  return 0;
+}
+
 //=======================================================================
 //function : ObjectsCommands
 //purpose  :
@@ -5848,40 +6439,93 @@ static int VPriority (Draw_Interpretor& theDI,
 void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
 {
   const char *group ="AISObjects";
-  theCommands.Add("vtrihedron",
-    "vtrihedron         : vtrihedron name [Xo] [Yo] [Zo] [Zu] [Zv] [Zw] [Xu] [Xv] [Xw] ",
-    __FILE__,VTrihedron,group);
+
+  theCommands.Add ("vtrihedron",
+                   "vtrihedron : vtrihedron name"
+                   "\n\t\t: [-dispMode {wireframe|shading} ]"
+                   "\n\t\t: [-origin x y z ]"
+                   "\n\t\t: [-zaxis u v w -xaxis u v w ]"
+                   "\n\t\t: [-drawaxes {X|Y|Z|XY|YZ|XZ|XYZ}]"
+                   "\n\t\t: [-hidelabels {on|off}]"
+                   "\n\t\t: [-label {XAxis|YAxis|ZAxis} value]"
+                   "\n\t\t: [-attribute {XAxisLength|YAxisLength|ZAxisLength"
+                   "\n\t\t:             |TubeRadiusPercent|ConeRadiusPercent"
+                   "\n\t\t:             |ConeLengthPercent|OriginRadiusPercent"
+                   "\n\t\t:             |ShadingNumberOfFacettes} value]"
+                   "\n\t\t: [-color {Origin|XAxis|YAxis|ZAxis|XOYAxis|YOZAxis"
+                   "\n\t\t:         |XOZAxis|Whole} {r g b | colorName}]"
+                   "\n\t\t: [-textcolor {r g b | colorName}]"
+                   "\n\t\t: [-arrowscolor {r g b | colorName}]"
+                   "\n\t\t: [-priority {Origin|XAxis|YAxis|ZAxis|XArrow"
+                   "\n\t\t:            |YArrow|ZArrow|XOYAxis|YOZAxis"
+                   "\n\t\t:            |XOZAxis|Whole} value]"
+                   "\n\t\t:"
+                   "\n\t\t: Creates a new *AIS_Trihedron* object or changes parameters of "
+                   "\n\t\t: existing trihedron. If no argument is set,"
+                   "\n\t\t: the default trihedron (0XYZ) is created."
+                   "\n\t\t: -dispMode mode of visualization: wf - wireframe,"
+                   "\n\t\t:                                  sh - shading."
+                   "\n\t\t:               Default value is wireframe."
+                   "\n\t\t: -origin allows to set trihedron location."
+                   "\n\t\t: -zaxis/-xaxis allows to set trihedron X and Z"
+                   "\n\t\t:               directions. The directions should"
+                   "\n\t\t:               be orthogonal. Y direction is calculated."
+                   "\n\t\t: -drawaxes allows to set what axes are drawn in the"
+                   "\n\t\t:           trihedron, default state is XYZ"
+                   "\n\t\t: -hidelabels allows to hide or show trihedron labels"
+                   "\n\t\t: -labels allows to change default X/Y/Z titles of axes"
+                   "\n\t\t: -attribute sets parameters of trihedron"
+                   "\n\t\t: -color sets color properties of parts of trihedron"
+                   "\n\t\t: -textcolor sets color properties of trihedron labels"
+                   "\n\t\t: -arrowscolor sets color properties of trihedron arrows"
+                   "\n\t\t: -priority allows to change default selection priority"
+                   "\n\t\t: of trihedron components",
+                   __FILE__,VTrihedron,group);
 
   theCommands.Add("vtri2d",
-    "vtri2d Name Selection in the viewer only ",
+    "vtri2d Name"
+    "\n\t\t: Creates a plane with a 2D trihedron from an interactively selected face.",
     __FILE__,VTrihedron2D ,group);
 
   theCommands.Add("vplanetri",
-    "vplanetri Name Selection in the viewer only ",
+    "vplanetri name"
+    "\n\t\t: Create a plane from a trihedron selection. If no arguments are set, the default",
     __FILE__,VPlaneTrihedron ,group);
 
   theCommands.Add("vsize",
-    "vsize       : vsize [name(Default=Current)] [size(Default=100)] ",
+    "vsize       : vsize [name(Default=Current)] [size(Default=100)] "
+    "\n\t\t: Changes the size of a named or selected trihedron."
+    "\n\t\t: If the name is not defined: it affects the selected trihedrons otherwise nothing is done."
+    "\n\t\t: If the value is not defined: it is set to 100 by default.",
     __FILE__,VSize,group);
 
   theCommands.Add("vaxis",
-    "vaxis nom [Xa] [Ya] [Za] [Xb] [Yb] [Zb]",
+    "vaxis name [Xa] [Ya] [Za] [Xb] [Yb] [Zb]"
+    "\n\t\t: Creates an axis. If  the values are not defined, an axis is created by interactive selection of two vertices or one edge",
     __FILE__,VAxisBuilder,group);
 
   theCommands.Add("vaxispara",
-    "vaxispara  nom ",
+    "vaxispara name "
+    "\n\t\t: Creates an axis by interactive selection of an edge and a vertex.",
     __FILE__,VAxisBuilder,group);
 
   theCommands.Add("vaxisortho",
-    "vaxisotho  nom ",
+    "vaxisortho name "
+    "\n\t\t: Creates an axis by interactive selection of an edge and a vertex. The axis will be orthogonal to the selected edge.",
     __FILE__,VAxisBuilder,group);
 
   theCommands.Add("vpoint",
-    "vpoint  PointName [Xa] [Ya] [Za] ",
+    "vpoint  PointName [Xa] [Ya] [Za] "
+    "\n\t\t: Creates a point from coordinates. If the values are not defined,"
+    "\n\t\t: a point is created by interactive selection of a vertice or an edge (in the center of the edge).",
     __FILE__,VPointBuilder,group);
 
   theCommands.Add("vplane",
-    "vplane  PlaneName [AxisName/PlaneName/PointName] [PointName/PointName/PointName] [Nothing/Nothing/PointName] [TypeOfSensitivity]",
+    "vplane  PlaneName [AxisName/PlaneName/PointName] [PointName/PointName/PointName] [Nothing/Nothing/PointName] [TypeOfSensitivity {0|1}]"
+    "\n\t\t: Creates a plane from named or interactively selected entities."
+    "\n\t\t: TypeOfSensitivity:"
+    "\n\t\t:   0 - Interior"
+    "\n\t\t:   1 - Boundary",
     __FILE__,VPlaneBuilder,group);
 
   theCommands.Add ("vchangeplane", "vchangeplane usage: \n"
@@ -5899,32 +6543,77 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
     __FILE__, VChangePlane, group);
 
   theCommands.Add("vplanepara",
-    "vplanepara  PlaneName  ",
+    "vplanepara  PlaneName  "
+    "\n\t\t: Creates a plane from interactively selected vertex and face.",
     __FILE__,VPlaneBuilder,group);
 
   theCommands.Add("vplaneortho",
-    "vplaneortho  PlaneName  ",
+    "vplaneortho  PlaneName  "
+    "\n\t\t: Creates a plane from interactive selected face and coplanar edge. ",
     __FILE__,VPlaneBuilder,group);
 
   theCommands.Add("vline",
-    "vline: vline LineName [Xa/PointName] [Ya/PointName] [Za] [Xb] [Yb] [Zb]  ",
+    "vline LineName [Xa/PointName] [Ya/PointName] [Za] [Xb] [Yb] [Zb]  "
+    "\n\t\t: Creates a line from coordinates, named or interactively selected vertices. ",
     __FILE__,VLineBuilder,group);
 
   theCommands.Add("vcircle",
-    "vcircle CircleName [PointName PointName PointName IsFilled]\n\t\t\t\t\t[PlaneName PointName Radius IsFilled]",
+    "vcircle CircleName [PointName PointName PointName IsFilled]\n\t\t\t\t\t[PlaneName PointName Radius IsFilled]"
+    "\n\t\t: Creates a circle from named or interactively selected entities."
+    "\n\t\t: Parameter IsFilled is defined as 0 or 1.",
     __FILE__,VCircleBuilder,group);
 
-  theCommands.Add("vdrawtext",
-    "vdrawtext  : vdrawtext name X Y Z R G B hor_align ver_align angle zoomable height Aspect [Font [isMultiByte]]",
-    __FILE__,VDrawText,group);
+  theCommands.Add ("vdrawtext",
+                   "vdrawtext name text"
+                   "\n\t\t: [-pos X=0 Y=0 Z=0]"
+                   "\n\t\t: [-color {R G B|name}=yellow]"
+                   "\n\t\t: [-halign {left|center|right}=left]"
+                   "\n\t\t: [-valign {top|center|bottom|topfirstline}=bottom}]"
+                   "\n\t\t: [-angle angle=0]"
+                   "\n\t\t: [-zoom {0|1}=0]"
+                   "\n\t\t: [-height height=16]"
+                   "\n\t\t: [-aspect {regular|bold|italic|bolditalic}=regular]"
+                   "\n\t\t: [-font font=Times]"
+                   "\n\t\t: [-2d]"
+                   "\n\t\t: [-perspos {X Y Z}=0 0 0], where"
+                   "\n\t\t X and Y define the coordinate origin in 2d space relative to the view window"
+                   "\n\t\t Example: X=0 Y=0 is center, X=1 Y=1 is upper right corner etc..."
+                   "\n\t\t Z coordinate defines the gap from border of view window (except center position)."
+                   "\n\t\t: [-disptype {blend|decal|subtitle|dimension|normal}=normal}"
+                   "\n\t\t: [-subcolor {R G B|name}=white]"
+                   "\n\t\t: [-noupdate]"
+                   "\n\t\t: [-plane NormX NormY NormZ DirX DirY DirZ]"
+                   "\n\t\t: [-flipping]"
+                   "\n\t\t: Display text label at specified position.",
+    __FILE__, VDrawText, group);
 
   theCommands.Add("vdrawsphere",
     "vdrawsphere: vdrawsphere shapeName Fineness [X=0.0 Y=0.0 Z=0.0] [Radius=100.0] [ToShowEdges=0] [ToPrintInfo=1]\n",
     __FILE__,VDrawSphere,group);
 
+  theCommands.Add ("vlocation",
+                "vlocation name"
+      "\n\t\t:   [-reset]"
+      "\n\t\t:   [-copyFrom otherName]"
+      "\n\t\t:   [-translate X Y [Z]]"
+      "\n\t\t:   [-rotate x y z dx dy dz angle]"
+      "\n\t\t:   [-scale [X Y Z] scale]"
+      "\n\t\t:   [-mirror x y z dx dy dz]"
+      "\n\t\t:   [-setLocation X Y [Z]]"
+      "\n\t\t:   [-setRotation QX QY QZ QW]"
+      "\n\t\t:   [-setScale [X Y Z] scale]"
+      "\n\t\t: Object local transformation management:"
+      "\n\t\t:   -reset       reset transformation to identity"
+      "\n\t\t:   -translate   translate object"
+      "\n\t\t:   -rotate      applies rotation to local transformation"
+      "\n\t\t:   -scale       applies scale    to local transformation"
+      "\n\t\t:   -mirror      applies mirror   to local transformation"
+      "\n\t\t:   -setLocation assign object location"
+      "\n\t\t:   -setRotation assign object rotation (quaternion)"
+      "\n\t\t:   -setScale    assign object scale factor",
+        __FILE__, VSetLocation, group);
   theCommands.Add ("vsetlocation",
-                   "vsetlocation [-noupdate|-update] name x y z"
-                   "\n\t\t: Set new location for an interactive object.",
+                   "alias for vlocation",
         __FILE__, VSetLocation, group);
 
   theCommands.Add (
@@ -5937,13 +6626,14 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
     __FILE__,VDrawPArray,group);
 
   theCommands.Add("vconnect", 
-    "vconnect : assembly_name Xo Yo Zo object1 object2 ..."
-    "  Makes an assembly of object instances located in point (Xo Yo Zo).",
+    "vconnect name Xo Yo Zo object1 object2 ... [color=NAME]"
+    "\n\t\t: Creates and displays AIS_ConnectedInteractive object from input object and location.",
     __FILE__, VConnect, group);
 
   theCommands.Add("vconnectto",
-    "vconnectto : instance_name Xo Yo Zo object"
-    "  Makes an instance 'instance_name' of 'object' with position (Xo Yo Zo).", 
+    "vconnectto : instance_name Xo Yo Zo object [-nodisplay|-noupdate|-update]"
+    "  Makes an instance 'instance_name' of 'object' with position (Xo Yo Zo)."
+    "\n\t\t:   -nodisplay - only creates interactive object, but not displays it",
     __FILE__, VConnectTo,group);
 
   theCommands.Add("vdisconnect",
@@ -5983,12 +6673,22 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
     "    0 if mode is to be switched off\n", 
     __FILE__, VSetSelectionMode, group);
 
+  theCommands.Add("vselnext",
+    "vselnext : hilight next detected",
+    __FILE__, VSelectionNext, group);
+
+  theCommands.Add("vselprev",
+    "vselnext : hilight previous detected",
+    __FILE__, VSelectionPrevious, group);
+
   theCommands.Add("vtriangle",
-    "vtriangle Name PointName PointName PointName", 
+    "vtriangle Name PointName PointName PointName"
+    "\n\t\t: Creates and displays a filled triangle from named points.", 
     __FILE__, VTriangle,group);
 
   theCommands.Add("vsegment",
-    "vsegment Name PointName PointName", 
+    "vsegment Name PointName PointName"
+    "\n\t\t: Creates and displays a segment from named points.", 
     __FILE__, VSegment,group);
 
   theCommands.Add("vobjzlayer",
@@ -6010,7 +6710,15 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
                    __FILE__, VMarkersTest, group);
 
   theCommands.Add ("text2brep",
-                   "text2brep: res text fontName fontSize [x=0.0 y=0.0 z=0.0 composite=1 {regular,bold,italic,bolditalic=regular}]\n",
+                   "text2brep: name text"
+                   "\n\t\t: [-pos X=0 Y=0 Z=0]"
+                   "\n\t\t: [-halign {left|center|right}=left]"
+                   "\n\t\t: [-valign {top|center|bottom|topfirstline}=bottom}]"
+                   "\n\t\t: [-height height=16]"
+                   "\n\t\t: [-aspect {regular|bold|italic|bolditalic}=regular]"
+                   "\n\t\t: [-font font=Courier]"
+                   "\n\t\t: [-composite {on|off}=off]"
+                   "\n\t\t: [-plane NormX NormY NormZ DirX DirY DirZ]",
                    __FILE__, TextToBRep, group);
   theCommands.Add ("vfont",
                             "vfont [add pathToFont [fontName] [regular,bold,italic,bolditalic=undefined]]"
@@ -6054,38 +6762,15 @@ void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
                    "\n",
                    __FILE__, VPointCloud, group);
 
-  theCommands.Add("vlocreset",
-    "vlocreset name1 name2 ...\n\t\t  remove object local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocmove",
-    "vlocmove name1 name2 ... name\n\t\t  set local transform to match transform of 'name'",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vloctranslate",
-    "vloctranslate name1 name2 ... dx dy dz\n\t\t  applies translation to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocrotate",
-    "vlocrotate name1 name2 ... x y z dx dy dz angle\n\t\t  applies rotation to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocmirror",
-    "vlocmirror name x y z dx dy dz\n\t\t  applies mirror to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
-  theCommands.Add("vlocscale",
-    "vlocscale name x y z scale\n\t\t  applies scale to local transformation",
-    __FILE__,
-    LocalTransformPresentation, group);
-
   theCommands.Add("vpriority",
     "vpriority [-noupdate|-update] name [value]\n\t\t  prints or sets the display priority for an object",
     __FILE__,
     VPriority, group);
+
+  theCommands.Add ("vnormals",
+                   "vnormals usage:\n"
+                   "vnormals Shape [{on|off}=on] [-length {10}] [-nbAlongU {1}] [-nbAlongV {1}] [-nbAlong {1}]"
+                   "\n\t\t:        [-useMesh] [-oriented {0}1}=0]"
+                   "\n\t\t:  Displays/Hides normals calculated on shape geometry or retrieved from triangulation",
+                   __FILE__, VNormals, group);
 }