0029109: Visualization, AIS_Trihedron - add option hiding arrows tips
[occt.git] / src / ViewerTest / ViewerTest_ObjectCommands.cxx
1 // Created on: 1998-11-12
2 // Created by: Robert COUBLANC
3 // Copyright (c) 1998-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 #include <ViewerTest.hxx>
18
19 #include <AIS_PlaneTrihedron.hxx>
20
21 #include <Quantity_NameOfColor.hxx>
22 #include <Draw_Interpretor.hxx>
23 #include <Draw.hxx>
24 #include <Draw_Appli.hxx>
25 #include <DBRep.hxx>
26 #include <DBRep_DrawableShape.hxx>
27
28 #include <Font_BRepFont.hxx>
29 #include <Font_BRepTextBuilder.hxx>
30 #include <Font_FontMgr.hxx>
31
32 #include <NCollection_List.hxx>
33
34 #include <OSD_Chronometer.hxx>
35 #include <TCollection_AsciiString.hxx>
36 #include <V3d_Viewer.hxx>
37 #include <V3d_View.hxx>
38 #include <V3d.hxx>
39
40 #include <AIS_Shape.hxx>
41 #include <AIS_DisplayMode.hxx>
42 #include <AIS_PointCloud.hxx>
43 #include <TColStd_MapOfInteger.hxx>
44 #include <AIS_MapOfInteractive.hxx>
45 #include <ViewerTest_AutoUpdater.hxx>
46 #include <ViewerTest_DoubleMapOfInteractiveAndName.hxx>
47 #include <ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName.hxx>
48 #include <ViewerTest_EventManager.hxx>
49
50 #include <TopoDS_Solid.hxx>
51 #include <BRepTools.hxx>
52 #include <BRep_Builder.hxx>
53 #include <TopAbs_ShapeEnum.hxx>
54
55 #include <TopoDS.hxx>
56 #include <BRep_Tool.hxx>
57 #include <TopExp_Explorer.hxx>
58
59 #include <BRepAdaptor_Curve.hxx>
60 #include <BRepAdaptor_Surface.hxx>
61
62 #include <TopAbs.hxx>
63 #include <TopExp.hxx>
64 #include <TopoDS_Vertex.hxx>
65 #include <TopoDS_Shape.hxx>
66 #include <TopoDS_Face.hxx>
67
68 #include <Draw_Window.hxx>
69 #include <AIS_ListIteratorOfListOfInteractive.hxx>
70 #include <AIS_ListOfInteractive.hxx>
71 #include <AIS_DisplayMode.hxx>
72 #include <AIS_Shape.hxx>
73
74 #include <AIS_InteractiveContext.hxx>
75 #include <Geom_Plane.hxx>
76 #include <gp_Pln.hxx>
77 #include <TCollection_ExtendedString.hxx>
78 #include <TCollection_HAsciiString.hxx>
79 #include <GC_MakePlane.hxx>
80 #include <gp_Circ.hxx>
81 #include <AIS_Axis.hxx>
82 #include <Geom_Axis2Placement.hxx>
83 #include <Geom_Axis1Placement.hxx>
84 #include <AIS_Trihedron.hxx>
85 #include <AIS_Axis.hxx>
86 #include <gp_Trsf.hxx>
87 #include <gp_Quaternion.hxx>
88 #include <TopLoc_Location.hxx>
89
90 #include <HLRAlgo_Projector.hxx>
91 #include <HLRBRep_PolyAlgo.hxx>
92 #include <HLRBRep_PolyHLRToShape.hxx>
93 #include <Aspect_Window.hxx>
94
95 #include <Graphic3d_ArrayOfPoints.hxx>
96 #include <Graphic3d_ArrayOfSegments.hxx>
97 #include <Graphic3d_ArrayOfPolylines.hxx>
98 #include <Graphic3d_ArrayOfTriangles.hxx>
99 #include <Graphic3d_ArrayOfTriangleFans.hxx>
100 #include <Graphic3d_ArrayOfTriangleStrips.hxx>
101 #include <Graphic3d_ArrayOfQuadrangles.hxx>
102 #include <Graphic3d_ArrayOfQuadrangleStrips.hxx>
103 #include <Graphic3d_ArrayOfPolygons.hxx>
104 #include <Graphic3d_AspectMarker3d.hxx>
105 #include <Graphic3d_Group.hxx>
106 #include <Standard_Real.hxx>
107
108 #include <AIS_Circle.hxx>
109 #include <BRepBuilderAPI_MakeEdge.hxx>
110 #include <BRepBuilderAPI_MakeFace.hxx>
111 #include <BRepBuilderAPI_MakeWire.hxx>
112 #include <Geom_Circle.hxx>
113 #include <GC_MakeCircle.hxx>
114 #include <Select3D_SensitiveCircle.hxx>
115 #include <SelectMgr_EntityOwner.hxx>
116 #include <SelectMgr_Selection.hxx>
117 #include <StdFail_NotDone.hxx>
118 #include <StdPrs_ShadedShape.hxx>
119 #include <TopoDS_Wire.hxx>
120
121 #include <AIS_MultipleConnectedInteractive.hxx>
122 #include <AIS_ConnectedInteractive.hxx>
123 #include <AIS_TextLabel.hxx>
124 #include <TopLoc_Location.hxx>
125 #include <TColStd_ListOfInteger.hxx>
126 #include <TColStd_ListIteratorOfListOfInteger.hxx>
127
128 #include <Select3D_SensitiveTriangle.hxx>
129 #include <Select3D_SensitiveCurve.hxx>
130 #include <Select3D_SensitivePoint.hxx>
131 #include <BRepAdaptor_Curve.hxx>
132 #include <StdPrs_Curve.hxx>
133
134 #include <BRepExtrema_ExtPC.hxx>
135 #include <BRepExtrema_ExtPF.hxx>
136
137 #include <Prs3d_Arrow.hxx>
138 #include <Prs3d_ArrowAspect.hxx>
139 #include <Prs3d_DatumAttribute.hxx>
140 #include <Prs3d_DatumAspect.hxx>
141 #include <Prs3d_Drawer.hxx>
142 #include <Prs3d_VertexDrawMode.hxx>
143 #include <Prs3d_LineAspect.hxx>
144 #include <Prs3d_PointAspect.hxx>
145 #include <Prs3d_Presentation.hxx>
146 #include <Prs3d_TextAspect.hxx>
147
148 #include <Image_AlienPixMap.hxx>
149 #include <TColStd_HArray1OfAsciiString.hxx>
150 #include <TColStd_HSequenceOfAsciiString.hxx>
151
152 extern ViewerTest_DoubleMapOfInteractiveAndName& GetMapOfAIS();
153 extern Standard_Boolean VDisplayAISObject (const TCollection_AsciiString& theName,
154                                            const Handle(AIS_InteractiveObject)& theAISObj,
155                                            Standard_Boolean theReplaceIfExists = Standard_True);
156 extern int ViewerMainLoop(Standard_Integer argc, const char** argv);
157 extern Handle(AIS_InteractiveContext)& TheAISContext();
158
159 namespace
160 {
161   static bool convertToColor (const Handle(TColStd_HSequenceOfAsciiString)& theColorValues,
162                               Quantity_Color& theColor)
163   {
164     const char* anArgs[3] =
165     {
166       theColorValues->Size() >= 1 ? theColorValues->Value (1).ToCString() : "",
167       theColorValues->Size() >= 2 ? theColorValues->Value (2).ToCString() : "",
168       theColorValues->Size() >= 3 ? theColorValues->Value (3).ToCString() : ""
169     };
170     return ViewerTest::ParseColor (theColorValues->Size(), anArgs, theColor) != 0;
171   }
172
173   static bool convertToDatumPart (const TCollection_AsciiString& theValue,
174                                   Prs3d_DatumParts& theDatumPart)
175   {
176     TCollection_AsciiString aValue = theValue;
177     aValue.LowerCase();
178     if      (aValue == "origin")  theDatumPart = Prs3d_DP_Origin;
179     else if (aValue == "xaxis")   theDatumPart = Prs3d_DP_XAxis;
180     else if (aValue == "yaxis")   theDatumPart = Prs3d_DP_YAxis;
181     else if (aValue == "zaxis")   theDatumPart = Prs3d_DP_ZAxis;
182     else if (aValue == "xarrow")  theDatumPart = Prs3d_DP_XArrow;
183     else if (aValue == "yarrow")  theDatumPart = Prs3d_DP_YArrow;
184     else if (aValue == "zarrow")  theDatumPart = Prs3d_DP_ZArrow;
185     else if (aValue == "xoyaxis") theDatumPart = Prs3d_DP_XOYAxis;
186     else if (aValue == "yozaxis") theDatumPart = Prs3d_DP_YOZAxis;
187     else if (aValue == "xozaxis") theDatumPart = Prs3d_DP_XOZAxis;
188     else if (aValue == "whole")   theDatumPart = Prs3d_DP_None;
189     else
190     {
191       return false;
192     }
193     return true;
194   }
195
196   static void convertToDatumParts (const TCollection_AsciiString& theValue,
197                                    NCollection_List<Prs3d_DatumParts>& theParts)
198   {
199     TCollection_AsciiString aValue = theValue;
200     const Standard_Integer aSplitPos = theValue.Search ("|");
201     Prs3d_DatumParts aPart = Prs3d_DP_None;
202     if (aSplitPos > 0)
203     {
204       convertToDatumParts (theValue.SubString (aSplitPos + 1, theValue.Length()), theParts);
205       if (aSplitPos == 1) // first symbol
206       {
207         return;
208       }
209       aValue = theValue.SubString (1, aSplitPos - 1);
210     }
211     if (convertToDatumPart (aValue, aPart))
212     {
213       theParts.Append (aPart);
214     }
215   }
216
217   static bool convertToDatumAttribute (const TCollection_AsciiString& theValue,
218                                        Prs3d_DatumAttribute& theAttribute)
219   {
220     TCollection_AsciiString aValue = theValue;
221     aValue.LowerCase();
222     if      (aValue == "xaxislength")       theAttribute = Prs3d_DA_XAxisLength;
223     else if (aValue == "yaxislength")       theAttribute = Prs3d_DA_YAxisLength;
224     else if (aValue == "zaxislength")       theAttribute = Prs3d_DA_ZAxisLength;
225     else if (aValue == "tuberadiuspercent") theAttribute = Prs3d_DP_ShadingTubeRadiusPercent;
226     else if (aValue == "coneradiuspercent") theAttribute = Prs3d_DP_ShadingConeRadiusPercent;
227     else if (aValue == "conelengthpercent") theAttribute = Prs3d_DP_ShadingConeLengthPercent;
228     else if (aValue == "originradiuspercent") theAttribute = Prs3d_DP_ShadingOriginRadiusPercent;
229     else if (aValue == "shadingnumberoffacettes") theAttribute = Prs3d_DP_ShadingNumberOfFacettes;
230     else
231       return false;
232     return true;
233   }
234
235   static void convertToDatumAttributes (const TCollection_AsciiString& theValue,
236                                         NCollection_List<Prs3d_DatumAttribute>& theAttributes)
237   {
238     TCollection_AsciiString aValue = theValue;
239     const Standard_Integer aSplitPos = theValue.Search ("|");
240     Prs3d_DatumAttribute anAttribute = Prs3d_DA_XAxisLength;
241     if (aSplitPos > 0)
242     {
243       convertToDatumAttributes (theValue.SubString (aSplitPos + 1, theValue.Length()), theAttributes);
244       if (aSplitPos == 1) // first symbol
245       {
246         return;
247       }
248       aValue = theValue.SubString (1, aSplitPos - 1);
249     }
250     if (convertToDatumAttribute (aValue, anAttribute))
251     {
252       theAttributes.Append (anAttribute);
253     }
254   }
255
256   static bool convertToDatumAxes (const TCollection_AsciiString& theValue,
257                                   Prs3d_DatumAxes& theDatumAxes)
258   {
259     TCollection_AsciiString aValue = theValue;
260     aValue.LowerCase();
261     if      (aValue == "x")   theDatumAxes = Prs3d_DA_XAxis;
262     else if (aValue == "y")   theDatumAxes = Prs3d_DA_YAxis;
263     else if (aValue == "z")   theDatumAxes = Prs3d_DA_ZAxis;
264     else if (aValue == "xy")  theDatumAxes = Prs3d_DA_XYAxis;
265     else if (aValue == "zy")  theDatumAxes = Prs3d_DA_YZAxis;
266     else if (aValue == "xz")  theDatumAxes = Prs3d_DA_XZAxis;
267     else if (aValue == "xyz") theDatumAxes = Prs3d_DA_XYZAxis;
268     else
269     {
270       return false;
271     }
272     return true;
273   }
274
275   static Standard_Boolean setTrihedronParams (Standard_Integer  theArgsNb,
276                                               const char** theArgVec,
277                                               Handle(AIS_Trihedron) theTrihedron)
278   {
279     NCollection_DataMap<TCollection_AsciiString, Handle(TColStd_HSequenceOfAsciiString)> aMapOfArgs;
280     TCollection_AsciiString aParseKey;
281     for (Standard_Integer anArgIt = 1; anArgIt < theArgsNb; ++anArgIt)
282     {
283       TCollection_AsciiString anArg (theArgVec [anArgIt]);
284       if (anArg.Value (1) == '-'
285       && !anArg.IsRealValue())
286       {
287         aParseKey = anArg;
288         aParseKey.Remove (1);
289         aParseKey.LowerCase();
290         std::string aKey = aParseKey.ToCString();
291         aMapOfArgs.Bind (aParseKey, new TColStd_HSequenceOfAsciiString());
292         continue;
293       }
294
295       if (aParseKey.IsEmpty())
296       {
297         continue;
298       }
299
300       aMapOfArgs (aParseKey)->Append (anArg);
301     }
302
303     // Check parameters
304     if ((aMapOfArgs.IsBound ("xaxis") && !aMapOfArgs.IsBound ("zaxis"))
305     || (!aMapOfArgs.IsBound ("xaxis") &&  aMapOfArgs.IsBound ("zaxis")))
306     {
307       std::cout << "Syntax error: -xaxis and -zaxis parameters are to set together.\n";
308       return Standard_False;
309     }
310
311     Handle(TColStd_HSequenceOfAsciiString) aValues;
312     Handle(Geom_Axis2Placement) aComponent = theTrihedron->Component();
313     if (aMapOfArgs.Find ("origin", aValues))
314     {
315       aComponent->SetLocation (gp_Pnt (aValues->Value (1).RealValue(),
316                                        aValues->Value (2).RealValue(),
317                                        aValues->Value (3).RealValue()));
318     }
319     Handle(TColStd_HSequenceOfAsciiString) aXValues, aZValues;
320     if (aMapOfArgs.Find ("xaxis", aXValues) && aMapOfArgs.Find ("zaxis", aZValues))
321     {
322       gp_Dir aXDir (aXValues->Value (1).RealValue(),
323                     aXValues->Value (2).RealValue(),
324                     aXValues->Value (3).RealValue());
325
326       gp_Dir aZDir (aZValues->Value (1).RealValue(),
327                     aZValues->Value (2).RealValue(),
328                     aZValues->Value (3).RealValue());
329
330       if (!aZDir.IsNormal (aXDir, M_PI / 180.0))
331       {
332         std::cout << "Syntax error - parameters 'xaxis' and 'zaxis' are not applied as VectorX is not normal to VectorZ\n";
333         return Standard_False;
334       }
335
336       aComponent->SetXDirection(aXDir);
337       aComponent->SetDirection (aZDir);
338     }
339
340     if (aMapOfArgs.Find ("dispmode", aValues))
341     {
342       TCollection_AsciiString aValue (aValues->Value (1));
343       bool isWireframe = true;
344       if (aValue.IsEqual ("sh") || aValue.IsEqual ("shading"))
345         isWireframe = false;
346       theTrihedron->SetDatumDisplayMode (isWireframe ? Prs3d_DM_WireFrame
347                                                      : Prs3d_DM_Shaded);
348     }
349
350     if (aMapOfArgs.Find ("hidelabels", aValues))
351     {
352       Standard_Boolean toHideLabels = Standard_True;
353       if (aValues->Size() == 1)
354       {
355         ViewerTest::ParseOnOff (aValues->First().ToCString(), toHideLabels);
356       }
357       else if (aValues->Size() != 0)
358       {
359         std::cout << "Syntax error: -hidelabels expects parameter 'on' or 'off' after.\n";
360         return Standard_False;
361       }
362
363       if (!theTrihedron->Attributes()->HasOwnDatumAspect())
364       {
365         theTrihedron->Attributes()->SetDatumAspect (new Prs3d_DatumAspect());
366       }
367       theTrihedron->Attributes()->DatumAspect()->SetDrawLabels (!toHideLabels);
368     }
369
370     if (aMapOfArgs.Find ("hidearrows", aValues))
371     {
372       Standard_Boolean toHideArrows = Standard_True;
373       if (aValues->Size() == 1)
374       {
375         ViewerTest::ParseOnOff (aValues->First().ToCString(), toHideArrows);
376       }
377       else if (aValues->Size() != 0)
378       {
379         std::cout << "Syntax error: -hidearrows expects parameter 'on' or 'off' after.\n";
380         return Standard_False;
381       }
382
383       if (!theTrihedron->Attributes()->HasOwnDatumAspect())
384       {
385         theTrihedron->Attributes()->SetDatumAspect (new Prs3d_DatumAspect());
386       }
387       theTrihedron->Attributes()->DatumAspect()->SetDrawArrows (!toHideArrows);
388     }
389
390     if (aMapOfArgs.Find ("color", aValues))
391     {
392       NCollection_List<Prs3d_DatumParts> aParts;
393       if (aValues->Size() < 2)
394       {
395         std::cout << "Syntax error: -color wrong parameters.\n";
396         return Standard_False;
397       }
398
399       convertToDatumParts (aValues->Value(1), aParts);
400       aValues->Remove (1); // datum part is processed
401       Quantity_Color aColor;
402       if (!convertToColor (aValues, aColor))
403       {
404         std::cout << "Syntax error: -color wrong parameters.\n";
405         return Standard_False;
406       }
407
408       for (NCollection_List<Prs3d_DatumParts>::Iterator anIterator (aParts); anIterator.More(); anIterator.Next())
409       {
410         Prs3d_DatumParts aDatumPart = anIterator.Value();
411         if (aDatumPart == Prs3d_DP_None)
412         {
413           theTrihedron->SetColor (aColor);
414         }
415         else
416         {
417           theTrihedron->SetDatumPartColor (aDatumPart, aColor);
418         }
419       }
420     }
421
422     if (aMapOfArgs.Find ("textcolor", aValues))
423     {
424       Quantity_Color aColor;
425       if (!convertToColor (aValues, aColor))
426       {
427         std::cout << "Syntax error: -textcolor wrong parameters.\n";
428         return Standard_False;
429       }
430       theTrihedron->SetTextColor (aColor);
431     }
432
433     if (aMapOfArgs.Find ("arrowcolor", aValues))
434     {
435       Quantity_Color aColor;
436       if (!convertToColor (aValues, aColor))
437       {
438         std::cout << "Syntax error: -arrowcolor wrong parameters.\n";
439         return Standard_False;
440       }
441       theTrihedron->SetArrowColor (aColor);
442     }
443
444     if (aMapOfArgs.Find ("attribute", aValues))
445     {
446       NCollection_List<Prs3d_DatumAttribute> anAttributes;
447       if (aValues->Size() != 2)
448       {
449         std::cout << "Syntax error: -attribute wrong parameters.\n";
450         return Standard_False;
451       }
452
453       convertToDatumAttributes (aValues->Value (1), anAttributes);
454       if (!theTrihedron->Attributes()->HasOwnDatumAspect())
455         theTrihedron->Attributes()->SetDatumAspect(new Prs3d_DatumAspect());
456       for (NCollection_List<Prs3d_DatumAttribute>::Iterator anIterator (anAttributes); anIterator.More(); anIterator.Next())
457       {
458         theTrihedron->Attributes()->DatumAspect()->SetAttribute (anIterator.Value(), aValues->Value (2).RealValue());
459       }
460     }
461
462     if (aMapOfArgs.Find ("priority", aValues))
463     {
464       Prs3d_DatumParts aDatumPart;
465       if (aValues->Size() < 2
466       || !convertToDatumPart (aValues->Value (1), aDatumPart))
467       {
468         std::cout << "Syntax error: -priority wrong parameters.\n";
469         return Standard_False;
470       }
471       theTrihedron->SetSelectionPriority (aDatumPart, aValues->Value (2).IntegerValue());
472     }
473
474     if (aMapOfArgs.Find ("labels", aValues))
475     {
476       Prs3d_DatumParts aDatumPart = Prs3d_DP_None;
477       if (aValues->Size() > 2
478        && convertToDatumPart(aValues->Value(1), aDatumPart)
479        && aDatumPart >= Prs3d_DP_XAxis
480        && aDatumPart <= Prs3d_DP_ZAxis) // labels are set to axes only
481       {
482         theTrihedron->SetLabel (aDatumPart, aValues->Value (2));
483       }
484       else
485       {
486         std::cout << "Syntax error: -labels wrong parameters.\n";
487         return Standard_False;
488       }
489     }
490
491     if (aMapOfArgs.Find ("drawaxes", aValues))
492     {
493       Prs3d_DatumAxes aDatumAxes = Prs3d_DA_XAxis;
494       if (aValues->Size() < 1
495       || !convertToDatumAxes (aValues->Value (1), aDatumAxes))
496       {
497         std::cout << "Syntax error: -drawaxes wrong parameters.\n";
498         return Standard_False;
499       }
500       if (!theTrihedron->Attributes()->HasOwnDatumAspect())
501         theTrihedron->Attributes()->SetDatumAspect(new Prs3d_DatumAspect());
502       theTrihedron->Attributes()->DatumAspect()->SetDrawDatumAxes (aDatumAxes);
503     }
504     return Standard_True;
505   }
506 }
507
508 //==============================================================================
509 //function : Vtrihedron 2d
510 //purpose  : Create a plane with a 2D  trihedron from a faceselection
511 //Draw arg : vtri2d  name
512 //==============================================================================
513 static int VTrihedron2D (Draw_Interpretor& /*theDI*/,
514                          Standard_Integer  theArgsNum,
515                          const char**      theArgVec)
516 {
517   if (theArgsNum != 2)
518   {
519     std::cerr << theArgVec[0]<< " error.\n";
520     return 1;
521   }
522
523   TopTools_ListOfShape aShapes;
524   ViewerTest::GetSelectedShapes (aShapes);
525
526   if (aShapes.Extent() != 1)
527   {
528     std::cerr << "Error: wrong number of selected shapes.\n";
529     return 1;
530   }
531
532   const TopoDS_Shape& aShape = aShapes.First();
533
534   TopoDS_Face     aFace = TopoDS::Face (aShape);
535   TopExp_Explorer aFaceExp (aFace, TopAbs_EDGE);
536   TopoDS_Edge     anEdge0 = TopoDS::Edge (aFaceExp.Current());
537
538   gp_Pnt A,B,C;
539   if (aFaceExp.More())
540   {
541     aFaceExp.Next();
542     TopoDS_Edge anEdge1 = TopoDS::Edge (aFaceExp.Current() );
543     BRepAdaptor_Curve aCurve0 (anEdge0);
544     BRepAdaptor_Curve aCurve1 (anEdge1);
545     A = aCurve1.Value (0.1);
546     B = aCurve1.Value (0.9);
547     C = aCurve0.Value (0.5);
548   }
549   else
550   {
551     BRepAdaptor_Curve aCurve0 (anEdge0);
552     A = aCurve0.Value (0.1);
553     B = aCurve0.Value (0.9);
554     C = aCurve0.Value (0.5);
555   }
556
557   GC_MakePlane aMkPlane (A,B,C);
558
559   Handle(AIS_PlaneTrihedron) anAISPlaneTri = new AIS_PlaneTrihedron (aMkPlane.Value());
560   TCollection_AsciiString aName (theArgVec[1]);
561
562   VDisplayAISObject (aName, anAISPlaneTri);
563
564   return 0;
565 }
566
567 //=======================================================================
568 //function : VTrihedron
569 //purpose  :
570 //=======================================================================
571 static int VTrihedron (Draw_Interpretor& ,
572                        Standard_Integer theArgsNb,
573                        const char** theArgVec)
574 {
575   if (theArgsNb < 2)
576   {
577     std::cout << "Syntax error: the wrong number of input parameters.\n";
578     return 1;
579   }
580
581   TCollection_AsciiString aName (theArgVec[1]);
582   gp_Pln aWorkingPlane;
583   Standard_Boolean toUpdate = Standard_True;
584
585   NCollection_DataMap<TCollection_AsciiString, Standard_Real> aRealParams;
586   NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString> aStringParams;
587
588   Handle(AIS_Trihedron) aTrihedron;
589   if (GetMapOfAIS().IsBound2 (aName))
590   {
591     Handle(AIS_InteractiveObject) anObject = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aName));
592     aTrihedron = Handle(AIS_Trihedron)::DownCast (anObject);
593     if (aTrihedron.IsNull())
594     {
595       std::cout << "Syntax error: no trihedron with this name.\n";
596       return 1;
597     }
598   }
599   else
600   {
601     Handle(Geom_Axis2Placement) aPlacement = new Geom_Axis2Placement (gp_Pnt (0.0, 0.0, 0.0),
602                                                                       gp::DZ(), gp::DX());
603     aTrihedron = new AIS_Trihedron (aPlacement);
604   }
605
606   if (!setTrihedronParams (theArgsNb, theArgVec, aTrihedron))
607   {
608     return 1;
609   }
610
611   // Redisplay a dimension after parameter changing.
612   if (ViewerTest::GetAISContext()->IsDisplayed (aTrihedron))
613   {
614     ViewerTest::GetAISContext()->Redisplay (aTrihedron, toUpdate);
615   }
616   else
617   {
618     VDisplayAISObject (theArgVec[1], aTrihedron);
619   }
620
621   return 0;
622 }
623
624 //==============================================================================
625 //function : VSize
626 //author   : ege
627 //purpose  : Change the size of a named or selected trihedron
628 //           if no name : it affects the trihedrons witch are selected otherwise nothing is donne
629 //           if no value, the value is set at 100 by default
630 //Draw arg : vsize [name] [size]
631 //==============================================================================
632
633 static int VSize (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
634
635 {
636   // Declaration de booleens
637   Standard_Boolean             ThereIsName;
638   Standard_Boolean             ThereIsCurrent;
639   Standard_Real                value;
640   Standard_Boolean             hascol;
641
642   Quantity_Color col = Quantity_NOC_BLACK;
643
644   // Verification des arguments
645   if ( argc>3 ) {di<<argv[0]<<" Syntaxe error\n"; return 1;}
646
647   // Verification du nombre d'arguments
648   if (argc==1)      {ThereIsName=Standard_False;value=100;}
649   else if (argc==2) {ThereIsName=Standard_False;value=Draw::Atof(argv[1]);}
650   else              {ThereIsName=Standard_True;value=Draw::Atof(argv[2]);}
651
652   // On set le booleen ThereIsCurrent
653   if (TheAISContext() -> NbSelected() > 0) {ThereIsCurrent=Standard_True;}
654   else {ThereIsCurrent=Standard_False;}
655
656
657
658   //===============================================================
659   // Il n'y a pas de nom  mais des objets selectionnes
660   //===============================================================
661   if (!ThereIsName && ThereIsCurrent)
662   {
663
664     ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName
665       it (GetMapOfAIS());
666
667     while ( it.More() ) {
668
669       Handle(AIS_InteractiveObject) aShape=
670         Handle(AIS_InteractiveObject)::DownCast(it.Key1());
671
672       if (!aShape.IsNull() &&  TheAISContext()->IsSelected(aShape) )
673       {
674
675         // On verifie que l'AIS InteraciveObject selectionne est bien
676         // un AIS_Trihedron
677         if (aShape->Type()==AIS_KOI_Datum && aShape->Signature()==3) {
678
679           if (aShape->HasColor())
680           {
681             hascol = Standard_True;
682
683             // On recupere la couleur de aShape
684             aShape->Color (col);
685           }
686           else
687           {
688             hascol = Standard_False;
689           }
690
691           // On downcast aShape  de AIS_InteractiveObject a AIS_Trihedron
692           // pour lui appliquer la methode SetSize()
693           Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast (aShape);
694
695           // C'est bien un triedre,on chage sa valeur!
696           aTrihedron->SetSize(value);
697
698           // On donne la couleur au Trihedron
699           if(hascol)   aTrihedron->SetColor(col);
700           else         aTrihedron->UnsetColor();
701
702
703           // The trihedron hasn't be errased from the map
704           // so you just have to redisplay it
705           TheAISContext() ->Redisplay(aTrihedron,Standard_False);
706
707         }
708
709       }
710
711       it.Next();
712     }
713
714     TheAISContext() ->UpdateCurrentViewer();
715   }
716
717   //===============================================================
718   // Il n'y a pas d'arguments et aucuns objets selectionne Rien A Faire!
719   //===============================================================
720
721
722
723   //===============================================================
724   // Il y a un nom de triedre passe en argument
725   //===============================================================
726   if (ThereIsName) {
727     TCollection_AsciiString name=argv[1];
728
729     // on verifie que ce nom correspond bien a une shape
730     Standard_Boolean IsBound= GetMapOfAIS().IsBound2(name);
731
732     if (IsBound) {
733
734       // on recupere la shape dans la map des objets displayes
735       Handle(AIS_InteractiveObject) aShape =
736         Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(name));
737
738       // On verifie que l'AIS InteraciveObject est bien
739       // un AIS_Trihedron
740       if (!aShape.IsNull() &&
741         aShape->Type()==AIS_KOI_Datum && aShape->Signature()==3)
742       {
743         if (aShape->HasColor())
744         {
745           hascol=Standard_True;
746
747           // On recupere la couleur de aShape
748           aShape->Color (col);
749         }
750         else
751         {
752           hascol = Standard_False;
753         }
754
755         // On downcast aShape de AIS_InteractiveObject a AIS_Trihedron
756         // pour lui appliquer la methode SetSize()
757         Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast (aShape);
758
759         // C'est bien un triedre,on chage sa valeur
760         aTrihedron->SetSize(value);
761
762         // On donne la couleur au Trihedron
763         if(hascol)   aTrihedron->SetColor(col);
764         else         aTrihedron->UnsetColor();
765
766         // The trihedron hasn't be errased from the map
767         // so you just have to redisplay it
768         TheAISContext() ->Redisplay(aTrihedron,Standard_False);
769
770         TheAISContext() ->UpdateCurrentViewer();
771       }
772     }
773   }
774   return 0;
775 }
776
777
778 //==============================================================================
779
780 //==============================================================================
781 //function : VPlaneTrihedron
782 //purpose  : Create a plane from a trihedron selection. If no arguments are set, the default
783 //Draw arg : vplanetri  name
784 //==============================================================================
785 #include <AIS_Plane.hxx>
786
787
788
789 static int VPlaneTrihedron (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
790
791 {
792   // Verification des arguments
793   if ( argc!=2) {di<<argv[0]<<" error\n"; return 1;}
794
795   if (TheAISContext()->NbSelected() != 1)
796   {
797     std::cerr << "Error: Wrong number of selected shapes.\n";
798     return 1;
799   }
800
801   TheAISContext()->InitSelected();
802   Handle(AIS_InteractiveObject) aTest = TheAISContext()->SelectedInteractive();
803   Handle(AIS_Plane) aPlane = Handle(AIS_Plane)::DownCast (aTest);
804   if (aPlane.IsNull())
805   {
806     std::cerr << "Error: Selected shape is not a plane.\n";
807     return 1;
808   }
809
810   VDisplayAISObject (argv[1], aPlane);
811
812   return 0;
813 }
814
815
816
817 //==============================================================================
818 // Fonction        First click      2de click
819 //
820 // vaxis           vertex           vertex
821 //                 edge             None
822 // vaxispara       edge             vertex
823 // vaxisortho      edge             Vertex
824 // vaxisinter      Face             Face
825 //==============================================================================
826
827 //==============================================================================
828 //function : VAxisBuilder
829 //purpose  :
830 //Draw arg : vaxis AxisName Xa Ya Za Xb Yb Zb
831 //==============================================================================
832 #include <TopoDS_Edge.hxx>
833 #include <TopoDS_Vertex.hxx>
834 #include <TopExp.hxx>
835 #include <Geom_Line.hxx>
836
837 static int VAxisBuilder(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
838 {
839   // Declarations
840   Standard_Boolean HasArg;
841   TCollection_AsciiString name;
842
843   // Verification
844   if (argc<2 || argc>8 ) {di<<" Syntaxe error\n";return 1;}
845   if (argc==8) HasArg=Standard_True;
846   else HasArg=Standard_False;
847
848   name=argv[1];
849
850   TopTools_ListOfShape aShapes;
851   ViewerTest::GetSelectedShapes (aShapes);
852
853   // Cas ou il y a des arguments
854   // Purpose: Teste le constructeur AIS_Axis::AIS_Axis(x: Line from Geom)
855   if (HasArg) {
856     Standard_Real coord[6];
857     for(Standard_Integer i=0;i<=5;i++){
858       coord[i]=Draw::Atof(argv[2+i]);
859     }
860     gp_Pnt p1(coord[0],coord[1],coord[2]), p2(coord[3],coord[4],coord[5]) ;
861
862     gp_Vec myVect (p1,p2);
863     Handle(Geom_Line) myLine=new Geom_Line (p1 ,myVect );
864     Handle(AIS_Axis) TheAxis=new AIS_Axis (myLine );
865     GetMapOfAIS().Bind (TheAxis,name);
866     TheAISContext()->Display(TheAxis, Standard_True);
867   }
868
869   // Pas d'arguments
870   else {
871     // fonction vaxis
872     // Purpose: Teste le constructeur AIS_Axis::AIS_Axis (x:Axis1Placement from Geom)
873     if ( !strcasecmp(argv[0], "vaxis")) {
874       if (aShapes.Extent() != 2 && aShapes.Extent() != 1)
875       {
876         std::cerr << "Error: Wrong number of selected shapes.\n";
877         return 1;
878       }
879
880       const TopoDS_Shape& aShapeA = aShapes.First();
881       if (aShapeA.ShapeType() == TopAbs_VERTEX)
882       {
883         if (aShapes.Extent() != 2)
884         {
885           std::cerr << "Error: Wron number of selected shapes.\n";
886           return 1;
887         }
888
889         const TopoDS_Shape& aShapeB = aShapes.Last();
890         if (aShapeB.ShapeType() != TopAbs_VERTEX)
891         {
892           std::cerr << "Syntax error: You should select two vertices or one edge.\n";
893           return 1;
894         }
895
896         // Construction de l'axe
897         gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
898         gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
899         gp_Vec V (A,B);
900         gp_Dir D (V);
901         Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (A,D);
902         Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
903         GetMapOfAIS().Bind (TheAxis,name);
904         TheAISContext()->Display (TheAxis, Standard_True);
905       }
906       else
907       {
908         TopoDS_Edge    ed =TopoDS::Edge (aShapeA);
909         TopoDS_Vertex  Va,Vb;
910         TopExp::Vertices(ed,Va,Vb );
911         gp_Pnt A=BRep_Tool::Pnt(Va);
912         gp_Pnt B=BRep_Tool::Pnt(Vb);
913         gp_Vec  V (A,B);
914         gp_Dir   D (V);
915         Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (A,D);
916         Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
917         GetMapOfAIS().Bind (TheAxis,name);
918         TheAISContext()->Display (TheAxis, Standard_True);
919       }
920
921     }
922
923     // Fonction axispara
924     // Purpose: Teste le constructeur AIS_Axis::AIS_Axis(x: Axis2Placement from Geom, y: TypeOfAxis from AIS)
925     else if ( !strcasecmp(argv[0], "vaxispara"))
926     {
927       if (aShapes.Extent() != 2)
928       {
929         std::cerr << "Error: Wrong number of selected shapes.\n";
930         return 1;
931       }
932
933       const TopoDS_Shape& aShapeA = aShapes.First();
934       const TopoDS_Shape& aShapeB = aShapes.Last();
935       if (!(aShapeA.ShapeType() == TopAbs_EDGE
936          && aShapeB.ShapeType() == TopAbs_VERTEX))
937       {
938         std::cerr << "Syntax error: You should select face and then vertex.\n";
939         return 1;
940       }
941
942       TopoDS_Edge    ed=TopoDS::Edge (aShapeA);
943       gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
944       TopoDS_Vertex  Va,Vc;
945       TopExp::Vertices(ed,Va,Vc );
946       gp_Pnt A=BRep_Tool::Pnt(Va);
947       gp_Pnt C=BRep_Tool::Pnt(Vc);
948       gp_Vec  V (A,C);
949       gp_Dir   D (V);
950       Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (B,D);
951       Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
952       GetMapOfAIS().Bind (TheAxis,name);
953       TheAISContext()->Display (TheAxis, Standard_True);
954
955     }
956
957     // Fonction axisortho
958     else
959     {
960       if (aShapes.Extent() != 2)
961       {
962         std::cerr << "Error: Wrong number of selected shapes.\n";
963         return 1;
964       }
965
966       const TopoDS_Shape& aShapeA = aShapes.First();
967       const TopoDS_Shape& aShapeB = aShapes.Last();
968       if (!(aShapeA.ShapeType() == TopAbs_EDGE
969          && aShapeB.ShapeType() == TopAbs_VERTEX))
970       {
971         std::cerr << "Syntax error: You should select face and then vertex.\n";
972         return 1;
973       }
974
975       // Construction de l'axe
976       TopoDS_Edge    ed=TopoDS::Edge(aShapeA) ;
977       gp_Pnt B=BRep_Tool::Pnt(TopoDS::Vertex(aShapeB) );
978       TopoDS_Vertex  Va,Vc;
979       TopExp::Vertices(ed,Va,Vc );
980       gp_Pnt A=BRep_Tool::Pnt(Va);
981       gp_Pnt C=BRep_Tool::Pnt(Vc);
982       gp_Pnt E(A.Y()+A.Z()-C.Y()-C.Z()  ,C.X()-A.X() ,C.X()-A.X() );
983       gp_Vec  V (A,E);
984       gp_Dir   D (V);
985       Handle(Geom_Axis1Placement) OrigineAndVect=new Geom_Axis1Placement (B,D);
986       Handle(AIS_Axis) TheAxis=new AIS_Axis (OrigineAndVect);
987       GetMapOfAIS().Bind (TheAxis,name);
988       TheAISContext()->Display (TheAxis, Standard_True);
989
990     }
991
992   }
993   return 0;
994 }
995
996
997 //==============================================================================
998 // Fonction        First click      Result
999 //
1000 // vpoint          vertex           AIS_Point=Vertex
1001 //                 edge             AIS_Point=Middle of the edge
1002 //==============================================================================
1003
1004 //==============================================================================
1005 //function : VPointBuilder
1006 //purpose  : Build an AIS_Point from coordinates or with a selected vertex or edge
1007 //Draw arg : vpoint PoinName [Xa] [Ya] [Za]
1008 //==============================================================================
1009 #include <TopoDS_Edge.hxx>
1010 #include <TopoDS_Vertex.hxx>
1011 #include <TopExp.hxx>
1012 #include <AIS_Point.hxx>
1013 #include <Geom_CartesianPoint.hxx>
1014
1015 static int VPointBuilder(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1016 {
1017   // Declarations
1018   Standard_Boolean HasArg;
1019   TCollection_AsciiString name;
1020
1021   // Verification
1022   if (argc<2 || argc>5 ) {di<<" Syntaxe error\n";return 1;}
1023   if (argc==5) HasArg=Standard_True;
1024   else HasArg=Standard_False;
1025
1026   name=argv[1];
1027
1028   // Il y a des arguments: teste l'unique constructeur AIS_Pnt::AIS_Pnt(Point from Geom)
1029   if (HasArg) {
1030     Standard_Real thecoord[3];
1031     for(Standard_Integer i=0;i<=2;i++)
1032       thecoord[i]=Draw::Atof(argv[2+i]);
1033     Handle(Geom_CartesianPoint )  myGeomPoint= new Geom_CartesianPoint (thecoord[0],thecoord[1],thecoord[2]);
1034     Handle(AIS_Point)  myAISPoint=new AIS_Point(myGeomPoint );
1035     GetMapOfAIS().Bind (myAISPoint,name);
1036     TheAISContext()->Display (myAISPoint, Standard_True);
1037   }
1038
1039   // Il n'a pas d'arguments
1040   else
1041   {
1042     TopTools_ListOfShape aShapes;
1043     ViewerTest::GetSelectedShapes (aShapes);
1044
1045     if (aShapes.Extent() != 1)
1046     {
1047       std::cerr << "Error: Wrong number of selected shapes.\n";
1048       std::cerr << "\tYou should select one edge or vertex.\n";
1049       return 1;
1050     }
1051
1052     const TopoDS_Shape& aShapeA = aShapes.First();
1053
1054     if (aShapeA.ShapeType()==TopAbs_VERTEX )
1055     {
1056       gp_Pnt A=BRep_Tool::Pnt(TopoDS::Vertex(aShapeA ) );
1057       Handle(Geom_CartesianPoint) myGeomPoint= new Geom_CartesianPoint (A );
1058       Handle(AIS_Point)  myAISPoint = new AIS_Point  (myGeomPoint );
1059       GetMapOfAIS().Bind(myAISPoint,name);
1060       TheAISContext()->Display (myAISPoint, Standard_True);
1061     }
1062     else
1063     {
1064       TopoDS_Edge myEdge=TopoDS::Edge(aShapeA);
1065       TopoDS_Vertex myVertexA,myVertexB;
1066       TopExp::Vertices (myEdge ,myVertexA ,myVertexB );
1067       gp_Pnt A=BRep_Tool::Pnt(myVertexA );
1068       gp_Pnt B=BRep_Tool::Pnt(myVertexB );
1069       // M est le milieu de [AB]
1070       Handle(Geom_CartesianPoint) myGeomPointM= new Geom_CartesianPoint ( (A.X()+B.X())/2  , (A.Y()+B.Y())/2  , (A.Z()+B.Z())/2  );
1071       Handle(AIS_Point)  myAISPointM = new AIS_Point  (myGeomPointM );
1072       GetMapOfAIS().Bind(myAISPointM,name);
1073       TheAISContext()->Display (myAISPointM, Standard_True);
1074     }
1075
1076   }
1077   return 0;
1078
1079 }
1080
1081 //==============================================================================
1082 // Function        1st click   2de click  3de click
1083 // vplane          Vertex      Vertex     Vertex
1084 //                 Vertex      Edge
1085 //                 Edge        Vertex
1086 //                 Face
1087 // vplanepara      Face        Vertex
1088 //                 Vertex      Face
1089 // vplaneortho     Face        Edge
1090 //                 Edge        Face
1091 //==============================================================================
1092
1093 //==============================================================================
1094 //function : VPlaneBuilder
1095 //purpose  : Build an AIS_Plane from selected entities or Named AIS components
1096 //Draw arg : vplane PlaneName [AxisName]  [PointName] [TypeOfSensitivity]
1097 //                            [PointName] [PointName] [PointName] [TypeOfSensitivity]
1098 //                            [PlaneName] [PointName] [TypeOfSensitivity]
1099 //==============================================================================
1100
1101 static Standard_Integer VPlaneBuilder (Draw_Interpretor& /*di*/,
1102                                        Standard_Integer argc,
1103                                        const char** argv)
1104 {
1105   // Declarations
1106   Standard_Boolean hasArg;
1107   TCollection_AsciiString aName;
1108
1109   // Verification
1110   if (argc<2 || argc>6 )
1111   {
1112     std::cout<<" Syntax error\n";
1113     return 1;
1114   }
1115   if (argc == 6 || argc==5 || argc==4)
1116     hasArg=Standard_True;
1117   else 
1118     hasArg=Standard_False;
1119
1120   aName=argv[1];
1121
1122   // There are some arguments
1123   if (hasArg)
1124   {
1125     if (!GetMapOfAIS().IsBound2(argv[2] ))
1126     {
1127       std::cout<<"vplane: error 1st name doesn't exist in the GetMapOfAIS()\n";
1128       return 1;
1129     }
1130     // Get shape from map
1131     Handle(AIS_InteractiveObject) aShapeA =
1132       Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[2] ));
1133
1134     // The first argument is an AIS_Point
1135     if (!aShapeA.IsNull() &&
1136         aShapeA->Type()==AIS_KOI_Datum &&
1137         aShapeA->Signature()==1)
1138     {
1139         // The second argument must also be an AIS_Point
1140         if (argc<5 || !GetMapOfAIS().IsBound2(argv[3]))
1141         {
1142           std::cout<<"vplane: error 2nd name doesn't exist in the GetMapOfAIS()\n";
1143           return 1;
1144         }
1145         // Get shape from map
1146         Handle(AIS_InteractiveObject) aShapeB =
1147           Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
1148         // If B is not an AIS_Point
1149         if (aShapeB.IsNull() ||
1150           (!(aShapeB->Type()==AIS_KOI_Datum && aShapeB->Signature()==1)))
1151         {
1152           std::cout<<"vplane: error 2nd object is expected to be an AIS_Point.\n";
1153           return 1;
1154         }
1155         // The third object is an AIS_Point
1156         if (!GetMapOfAIS().IsBound2(argv[4]) ) 
1157         {
1158           std::cout<<"vplane: error 3d name doesn't exist in the GetMapOfAIS().\n";
1159           return 1; 
1160         }
1161         // Get shape from map
1162         Handle(AIS_InteractiveObject) aShapeC =
1163           Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[4]));
1164         // If C is not an AIS_Point
1165         if (aShapeC.IsNull() ||
1166           (!(aShapeC->Type()==AIS_KOI_Datum && aShapeC->Signature()==1)))
1167         {
1168           std::cout<<"vplane: error 3d object is expected to be an AIS_Point.\n";
1169           return 1;
1170         }
1171
1172         // Treatment of objects A, B, C
1173         // Downcast an AIS_IO to AIS_Point
1174         Handle(AIS_Point) anAISPointA = Handle(AIS_Point)::DownCast( aShapeA);
1175         Handle(AIS_Point) anAISPointB = Handle(AIS_Point)::DownCast( aShapeB);
1176         Handle(AIS_Point) anAISPointC = Handle(AIS_Point)::DownCast( aShapeC);
1177
1178         Handle(Geom_CartesianPoint ) aCartPointA = 
1179           Handle(Geom_CartesianPoint)::DownCast( anAISPointA->Component());
1180
1181         Handle(Geom_CartesianPoint ) aCartPointB = 
1182           Handle(Geom_CartesianPoint)::DownCast( anAISPointB->Component());
1183
1184         Handle(Geom_CartesianPoint ) aCartPointC = 
1185           Handle(Geom_CartesianPoint)::DownCast( anAISPointC->Component());
1186
1187         // Verification that the three points are different
1188         if(Abs(aCartPointB->X()-aCartPointA->X())<=Precision::Confusion() &&
1189            Abs(aCartPointB->Y()-aCartPointA->Y())<=Precision::Confusion() &&
1190            Abs(aCartPointB->Z()-aCartPointA->Z())<=Precision::Confusion())
1191         {
1192           // B=A
1193           std::cout<<"vplane error: same points\n";return 1;
1194         }
1195         if(Abs(aCartPointC->X()-aCartPointA->X())<=Precision::Confusion() &&
1196            Abs(aCartPointC->Y()-aCartPointA->Y())<=Precision::Confusion() &&
1197            Abs(aCartPointC->Z()-aCartPointA->Z())<=Precision::Confusion())
1198         {
1199           // C=A
1200           std::cout<<"vplane error: same points\n";return 1;
1201         }
1202         if(Abs(aCartPointC->X()-aCartPointB->X())<=Precision::Confusion() &&
1203            Abs(aCartPointC->Y()-aCartPointB->Y())<=Precision::Confusion() &&
1204            Abs(aCartPointC->Z()-aCartPointB->Z())<=Precision::Confusion())
1205         {
1206           // C=B
1207           std::cout<<"vplane error: same points\n";return 1;
1208         }
1209
1210         gp_Pnt A = aCartPointA->Pnt();
1211         gp_Pnt B = aCartPointB->Pnt();
1212         gp_Pnt C = aCartPointC->Pnt();
1213
1214         // Construction of AIS_Plane
1215         GC_MakePlane MkPlane (A,B,C);
1216         Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
1217         Handle(AIS_Plane)  anAISPlane = new AIS_Plane(aGeomPlane );
1218         GetMapOfAIS().Bind (anAISPlane,aName );
1219         if (argc == 6)
1220         {
1221           Standard_Integer aType = Draw::Atoi (argv[5]);
1222           if (aType != 0 && aType != 1)
1223           {
1224             std::cout << "vplane error: wrong type of sensitivity!\n"
1225                       << "Should be one of the following values:\n"
1226                       << "0 - Interior\n"
1227                       << "1 - Boundary"
1228                       << std::endl;
1229             return 1;
1230           }
1231           else
1232           {
1233             anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
1234           }
1235         }
1236         TheAISContext()->Display (anAISPlane, Standard_True);
1237       }
1238
1239       // The first argument is an AIS_Axis
1240       // Creation of a plane orthogonal to the axis through a point
1241     else if (aShapeA->Type()==AIS_KOI_Datum && aShapeA->Signature()==2 ) {
1242       // The second argument should be an AIS_Point
1243       if (argc!=4 || !GetMapOfAIS().IsBound2(argv[3] ) )
1244       {
1245         std::cout<<"vplane: error 2d name doesn't exist in the GetMapOfAIS()\n";
1246         return 1;
1247       }
1248       // Get shape from map
1249       Handle(AIS_InteractiveObject) aShapeB =
1250         Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
1251       // If B is not an AIS_Point
1252       if (aShapeB.IsNull() ||
1253         (!(aShapeB->Type()==AIS_KOI_Datum && aShapeB->Signature()==1)))
1254       {
1255         std::cout<<"vplane: error 2d object is expected to be an AIS_Point\n";
1256         return 1;
1257       }
1258
1259       // Treatment of objects A and B
1260       Handle(AIS_Axis) anAISAxisA = Handle(AIS_Axis)::DownCast(aShapeA);
1261       Handle(AIS_Point) anAISPointB = Handle(AIS_Point)::DownCast(aShapeB);
1262
1263       Handle(Geom_Line ) aGeomLineA = anAISAxisA ->Component();
1264       Handle(Geom_Point) aGeomPointB = anAISPointB->Component()  ;
1265
1266       gp_Ax1 anAxis = aGeomLineA->Position();
1267       Handle(Geom_CartesianPoint) aCartPointB = 
1268         Handle(Geom_CartesianPoint)::DownCast(aGeomPointB);
1269
1270       gp_Dir D =anAxis.Direction();
1271       gp_Pnt B = aCartPointB->Pnt();
1272
1273       // Construction of AIS_Plane
1274       Handle(Geom_Plane) aGeomPlane = new Geom_Plane(B,D);
1275       Handle(AIS_Plane) anAISPlane = new AIS_Plane(aGeomPlane,B );
1276       GetMapOfAIS().Bind (anAISPlane,aName );
1277       if (argc == 5)
1278       {
1279         Standard_Integer aType = Draw::Atoi (argv[4]);
1280         if (aType != 0 && aType != 1)
1281         {
1282           std::cout << "vplane error: wrong type of sensitivity!\n"
1283                     << "Should be one of the following values:\n"
1284                     << "0 - Interior\n"
1285                     << "1 - Boundary"
1286                     << std::endl;
1287           return 1;
1288         }
1289         else
1290         {
1291           anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
1292         }
1293       }
1294       TheAISContext()->Display (anAISPlane, Standard_True);
1295
1296     }
1297     // The first argumnet is an AIS_Plane
1298     // Creation of a plane parallel to the plane passing through the point
1299     else if (aShapeA->Type()==AIS_KOI_Datum && aShapeA->Signature()==7)
1300     {
1301       // The second argument should be an AIS_Point
1302       if (argc!=4 || !GetMapOfAIS().IsBound2(argv[3]))
1303       {
1304         std::cout<<"vplane: error 2d name doesn't exist in the GetMapOfAIS()\n";
1305         return 1;
1306       }
1307       // Get shape from map
1308       Handle(AIS_InteractiveObject) aShapeB =
1309         Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
1310       // B should be an AIS_Point
1311       if (aShapeB.IsNull() ||
1312          (!(aShapeB->Type()==AIS_KOI_Datum && aShapeB->Signature()==1)))
1313       {
1314         std::cout<<"vplane: error 2d object is expected to be an AIS_Point\n";
1315         return 1;
1316       }
1317
1318       // Treatment of objects A and B
1319       Handle(AIS_Plane) anAISPlaneA = Handle(AIS_Plane)::DownCast(aShapeA);
1320       Handle(AIS_Point) anAISPointB = Handle(AIS_Point)::DownCast(aShapeB);
1321
1322       Handle(Geom_Plane) aNewGeomPlane= anAISPlaneA->Component();
1323       Handle(Geom_Point) aGeomPointB = anAISPointB->Component();
1324
1325       Handle(Geom_CartesianPoint) aCartPointB = 
1326         Handle(Geom_CartesianPoint)::DownCast(aGeomPointB);
1327       gp_Pnt B= aCartPointB->Pnt();
1328
1329       // Construction of an AIS_Plane
1330       Handle(AIS_Plane) anAISPlane = new AIS_Plane(aNewGeomPlane, B);
1331       GetMapOfAIS().Bind (anAISPlane, aName);
1332       if (argc == 5)
1333       {
1334         Standard_Integer aType = Draw::Atoi (argv[4]);
1335         if (aType != 0 && aType != 1)
1336         {
1337           std::cout << "vplane error: wrong type of sensitivity!\n"
1338                     << "Should be one of the following values:\n"
1339                     << "0 - Interior\n"
1340                     << "1 - Boundary"
1341                     << std::endl;
1342           return 1;
1343         }
1344         else
1345         {
1346           anAISPlane->SetTypeOfSensitivity (Select3D_TypeOfSensitivity (aType));
1347         }
1348       }
1349       TheAISContext()->Display (anAISPlane, Standard_True);
1350     }
1351     // Error
1352     else
1353     {
1354       std::cout<<"vplane: error 1st object is not an AIS\n";
1355       return 1;
1356     }
1357   }
1358   // There are no arguments
1359   else 
1360   {
1361     TopTools_ListOfShape aShapes;
1362     ViewerTest::GetSelectedShapes (aShapes);
1363
1364     // Function vplane
1365     // Test the constructor AIS_Plane::AIS_Plane(Geom_Plane, Standard_Boolean )
1366     if (!strcasecmp(argv[0], "vplane"))
1367     {
1368       if (aShapes.Extent() < 1 || aShapes.Extent() > 3)
1369       {
1370         std::cerr << "Error: Wront number of selected shapes.\n";
1371         std::cerr << "\tYou should one of variant: face, edge and vertex or three vertices.\n";
1372         return 1;
1373       }
1374
1375       const TopoDS_Shape& aShapeA = aShapes.First();
1376       if (aShapeA.ShapeType() == TopAbs_VERTEX)
1377       {
1378         if (aShapes.Extent() == 2)
1379         {
1380           const TopoDS_Shape& aShapeB = aShapes.Last();
1381           if (aShapeB.ShapeType() != TopAbs_EDGE)
1382           {
1383             std::cerr << "Syntax error: Together with vertex should be edge.\n";
1384             return 1;
1385           }
1386
1387           // Verify that the vertex is not on the edge ShapeB
1388           TopoDS_Edge anEdgeB = TopoDS::Edge(aShapeB);
1389           TopoDS_Vertex aVertA = TopoDS::Vertex(aShapeA);
1390
1391           BRepExtrema_ExtPC OrthoProj(aVertA, anEdgeB);
1392           if (OrthoProj.SquareDistance(1)<Precision::Approximation())
1393           {
1394             // The vertex is on the edge
1395             std::cout<<" vplane: error point is on the edge\n";
1396             return 1;
1397           }
1398           else
1399           {
1400             gp_Pnt A = BRep_Tool::Pnt(aVertA);
1401             TopoDS_Vertex aVBa, aVBb;
1402             TopExp::Vertices(anEdgeB ,aVBa ,aVBb);
1403             gp_Pnt aBa = BRep_Tool::Pnt(aVBa);
1404             gp_Pnt aBb = BRep_Tool::Pnt(aVBb);
1405             GC_MakePlane MkPlane (A, aBa, aBb);
1406             Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
1407             Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
1408             GetMapOfAIS().Bind (anAISPlane, aName);
1409             TheAISContext()->Display (anAISPlane, Standard_True);
1410           }
1411         }
1412         else if (aShapes.Extent() == 3)
1413         {
1414           TopTools_ListOfShape::Iterator anIter (aShapes);
1415
1416           anIter.Next();
1417           const TopoDS_Shape& aShapeB = anIter.Value();
1418
1419           anIter.Next();
1420           const TopoDS_Shape& aShapeC = anIter.Value();
1421
1422           if (!(aShapeB.ShapeType() == TopAbs_VERTEX
1423              && aShapeC.ShapeType() == TopAbs_VERTEX))
1424           {
1425             std::cerr << "Syntax error: You should one of variant: face, edge and vertex or three vertices.\n";
1426             return 1;
1427           }
1428
1429           gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(aShapeA));
1430           gp_Pnt B = BRep_Tool::Pnt(TopoDS::Vertex(aShapeB));
1431           gp_Pnt C = BRep_Tool::Pnt(TopoDS::Vertex(aShapeC));
1432           GC_MakePlane MkPlane(A, B, C);
1433           Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
1434           Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
1435           GetMapOfAIS().Bind (anAISPlane, aName);
1436           TheAISContext()->Display (anAISPlane, Standard_True);
1437         }
1438         else
1439         {
1440           std::cerr << "Syntax error: You should one of variant: face, edge and vertex or three vertices.\n";
1441           return 1;
1442         }
1443       }
1444       else if (aShapeA.ShapeType() == TopAbs_EDGE)
1445       {
1446         if (aShapes.Extent() != 2)
1447         {
1448           std::cerr << "Error: wrong number of selected shapes.\n";
1449           return 1;
1450         }
1451
1452         const TopoDS_Shape& aShapeB = aShapes.Last();
1453         if (aShapeB.ShapeType() != TopAbs_VERTEX)
1454         {
1455           std::cerr << "Syntax error: Together with edge should be vertex.\n";
1456           return 1;
1457         }
1458
1459         // Check that the vertex aShapeB is not on the edge
1460         TopoDS_Edge anEdgeA = TopoDS::Edge(aShapeA);
1461         TopoDS_Vertex aVertB = TopoDS::Vertex(aShapeB);
1462
1463         BRepExtrema_ExtPC OrthoProj (aVertB, anEdgeA);
1464         if (OrthoProj.SquareDistance(1)<Precision::Approximation())
1465         {
1466           // The vertex is on the edge
1467           std::cout<<" vplane: error point is on the edge\n";
1468           return 1;
1469         }
1470
1471         gp_Pnt B = BRep_Tool::Pnt(aVertB);
1472         TopoDS_Vertex aVAa, aVAb;
1473         TopExp::Vertices(anEdgeA, aVAa, aVAb);
1474         gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
1475         gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
1476         GC_MakePlane MkPlane (B,Aa,Ab);
1477         Handle(Geom_Plane) aGeomPlane = MkPlane.Value();
1478         Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane);
1479         GetMapOfAIS().Bind (anAISPlane ,aName);
1480         TheAISContext()->Display (anAISPlane, Standard_True);
1481       }
1482       else if (aShapeA.ShapeType() == TopAbs_FACE)
1483       {
1484         TopoDS_Face aFace = TopoDS::Face(aShapeA);
1485         BRepAdaptor_Surface aSurface (aFace, Standard_False);
1486         if (aSurface.GetType()==GeomAbs_Plane)
1487         {
1488           gp_Pln aPlane = aSurface.Plane();
1489           Handle(Geom_Plane) aGeomPlane = new Geom_Plane(aPlane);
1490           Handle(AIS_Plane) anAISPlane = new AIS_Plane(aGeomPlane);
1491           GetMapOfAIS().Bind (anAISPlane, aName);
1492           TheAISContext()->Display (anAISPlane, Standard_True);
1493         }
1494         else
1495         {
1496           std::cout<<" vplane: error\n";
1497           return 1;
1498         }
1499       }
1500       else
1501       {
1502         std::cerr << "Syntax error: You should one of variant: face, edge and vertex or three vertices.\n";
1503         return 1;
1504       }
1505     }
1506
1507     // Function vPlanePara
1508     // ===================
1509     // test the constructor AIS_Plane::AIS_Plane(Geom_Plane,gp_Pnt)
1510     else if (!strcasecmp(argv[0], "vplanepara"))
1511     {
1512       if (aShapes.Extent() != 2)
1513       {
1514         std::cerr << "Error: Wrong number of selected shapes.\n";
1515         return 1;
1516       }
1517
1518       const TopoDS_Shape* aShapeA = &aShapes.First();
1519       const TopoDS_Shape* aShapeB = &aShapes.Last();
1520       if (aShapeA->ShapeType() != TopAbs_VERTEX)
1521       {
1522         std::swap (aShapeA, aShapeB);
1523       }
1524
1525       if (!(aShapeA->ShapeType() == TopAbs_VERTEX
1526          && aShapeB->ShapeType() == TopAbs_FACE))
1527       {
1528         std::cerr << "Syntax error: you should select face and vertex.\n";
1529         return 1;
1530       }
1531
1532       gp_Pnt A = BRep_Tool::Pnt(TopoDS::Vertex(*aShapeA));
1533
1534       TopoDS_Face aFace = TopoDS::Face(*aShapeB);
1535       BRepAdaptor_Surface aSurface (aFace, Standard_False);
1536       if (aSurface.GetType() == GeomAbs_Plane)
1537       {
1538         gp_Pln aPlane = aSurface.Plane();
1539         // Construct a plane parallel to aGeomPlane through A
1540         aPlane.SetLocation(A);
1541         Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
1542         Handle(AIS_Plane) aAISPlane = new AIS_Plane (aGeomPlane, A);
1543         GetMapOfAIS().Bind (aAISPlane ,aName);
1544         TheAISContext()->Display (aAISPlane, Standard_True);
1545       }
1546       else
1547       {
1548         std::cerr << "Error: Builded surface is not a plane.\n";
1549         return 1;
1550       }
1551     }
1552
1553     // Function vplaneortho
1554     // ====================
1555     // test the constructor AIS_Plane::AIS_Plane(Geom_Plane,gp_Pnt,gp_Pnt,gp_Pnt)
1556     else
1557     {
1558       if (aShapes.Extent() != 2)
1559       {
1560         std::cerr << "Error: wrong number of selected shapes.\n";
1561         return 1;
1562       }
1563
1564       const TopoDS_Shape* aShapeA = &aShapes.First();
1565       const TopoDS_Shape* aShapeB = &aShapes.Last();
1566
1567       if (aShapeA->ShapeType() != TopAbs_EDGE)
1568       {
1569         std::swap (aShapeA, aShapeB);
1570       }
1571
1572       if (!(aShapeA->ShapeType() == TopAbs_EDGE
1573          && aShapeB->ShapeType() == TopAbs_FACE))
1574       {
1575         std::cerr << "Error: you should select edge and face.\n";
1576         return 1;
1577       }
1578
1579       // Construction of plane
1580       TopoDS_Edge anEdgeA = TopoDS::Edge(*aShapeA);
1581       TopoDS_Vertex aVAa, aVAb;
1582       TopExp::Vertices(anEdgeA, aVAa, aVAb);
1583       gp_Pnt Aa = BRep_Tool::Pnt(aVAa);
1584       gp_Pnt Ab = BRep_Tool::Pnt(aVAb);
1585       gp_Vec ab (Aa,Ab);
1586
1587       gp_Dir Dab (ab);
1588       // Creation of rotation axis
1589       gp_Ax1 aRotAxis (Aa,Dab);
1590
1591       TopoDS_Face aFace = TopoDS::Face(*aShapeB);
1592       // The edge must be parallel to the face
1593       BRepExtrema_ExtPF aHeightA (aVAa, aFace);
1594       BRepExtrema_ExtPF aHeightB (aVAb, aFace);
1595       // Compare to heights
1596       if (fabs(sqrt(aHeightA.SquareDistance(1)) - sqrt(aHeightB.SquareDistance(1)))
1597           >Precision::Confusion())
1598       {
1599         // the edge is not parallel to the face
1600         std::cout<<" vplaneortho error: the edge is not parallel to the face\n";
1601         return 1;
1602       }
1603       // the edge is OK
1604       BRepAdaptor_Surface aSurface (aFace, Standard_False);
1605       if (aSurface.GetType()==GeomAbs_Plane)
1606       {
1607         gp_Pln aPlane = aSurface.Plane();
1608         // It rotates a half turn round the axis of rotation
1609         aPlane.Rotate(aRotAxis , M_PI/2);
1610
1611         Handle(Geom_Plane) aGeomPlane = new Geom_Plane (aPlane);
1612         // constructed aGeomPlane parallel to a plane containing the edge (center mid-edge)
1613         gp_Pnt aMiddle ((Aa.X()+Ab.X() )/2 ,(Aa.Y()+Ab.Y() )/2 ,(Aa.Z()+Ab.Z() )/2 );
1614         Handle(AIS_Plane) anAISPlane = new AIS_Plane (aGeomPlane, aMiddle);
1615         GetMapOfAIS().Bind (anAISPlane, aName);
1616         TheAISContext()->Display (anAISPlane, Standard_True);
1617       }
1618       else
1619       {
1620         std::cout<<" vplaneortho: error\n";
1621         return 1;
1622       }
1623     }
1624   }
1625   return 0;
1626 }
1627
1628 //===============================================================================================
1629 //function : VChangePlane
1630 //purpose  :
1631 //===============================================================================================
1632 static int VChangePlane (Draw_Interpretor& /*theDi*/, Standard_Integer theArgsNb, const char** theArgVec)
1633 {
1634   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
1635   if (aContextAIS.IsNull())
1636   {
1637     std::cout << theArgVec[0] << "AIS context is not available.\n";
1638     return 1;
1639   }
1640
1641   if (theArgsNb < 3 || theArgsNb > 11)
1642   {
1643     std::cerr << theArgVec[0] 
1644               << ": incorrect number of command arguments.\n"
1645               << "Type help for more information.\n";
1646     return 1;
1647   }
1648
1649   TCollection_AsciiString aName (theArgVec[1]);
1650
1651   Handle(AIS_Plane) aPlane = GetMapOfAIS().IsBound2(aName)
1652     ? Handle(AIS_Plane)::DownCast (GetMapOfAIS().Find2 (aName))
1653     : NULL;
1654
1655   if ( aPlane.IsNull() )
1656   {
1657     std::cout << theArgVec[0] 
1658               << ": there is no interactive plane with the given name."
1659               << "Type help for more information.\n";
1660     return 1;
1661   }
1662
1663   Standard_Real aCenterX = aPlane->Center().X();
1664   Standard_Real aCenterY = aPlane->Center().Y();
1665   Standard_Real aCenterZ = aPlane->Center().Z();
1666
1667   Standard_Real aDirX = aPlane->Component()->Axis().Direction().X();
1668   Standard_Real aDirY = aPlane->Component()->Axis().Direction().Y();
1669   Standard_Real aDirZ = aPlane->Component()->Axis().Direction().Z();
1670
1671   Standard_Real aSizeX = 0.0;
1672   Standard_Real aSizeY = 0.0;
1673   aPlane->Size (aSizeX, aSizeY);
1674   Standard_Boolean isUpdate = Standard_True;
1675
1676   TCollection_AsciiString aPName, aPValue;
1677   for (Standard_Integer anArgIt = 1; anArgIt < theArgsNb; ++anArgIt)
1678   {
1679     const TCollection_AsciiString anArg = theArgVec[anArgIt];
1680     TCollection_AsciiString anArgCase = anArg;
1681     anArgCase.UpperCase();
1682     if (ViewerTest::SplitParameter (anArg, aPName, aPValue))
1683     {
1684       aPName.UpperCase();
1685       if (aPName.IsEqual ("X"))
1686       {
1687         aCenterX = aPValue.RealValue();
1688       }
1689       else if (aPName.IsEqual ("Y"))
1690       {
1691         aCenterY = aPValue.RealValue();
1692       }
1693       else if (aPName.IsEqual ("Z"))
1694       {
1695         aCenterZ = aPValue.RealValue();
1696       }
1697       else if (aPName.IsEqual ("DX"))
1698       {
1699         aDirX = aPValue.RealValue();
1700       }
1701       else if (aPName.IsEqual ("DY"))
1702       {
1703         aDirY = aPValue.RealValue();
1704       }
1705       else if (aPName.IsEqual ("DZ"))
1706       {
1707         aDirZ = aPValue.RealValue();
1708       }
1709       else if (aPName.IsEqual ("SX"))
1710       {
1711         aSizeX = aPValue.RealValue();
1712       }
1713       else if (aPName.IsEqual ("SY"))
1714       {
1715         aSizeY = aPValue.RealValue();
1716       }
1717     }
1718     else if (anArg.IsEqual ("NOUPDATE"))
1719     {
1720       isUpdate = Standard_False;
1721     }
1722   }
1723
1724   gp_Dir aDirection (aDirX, aDirY, aDirZ);
1725   gp_Pnt aCenterPnt (aCenterX, aCenterY, aCenterZ);
1726   aPlane->SetCenter (aCenterPnt);
1727   aPlane->SetComponent (new Geom_Plane (aCenterPnt, aDirection));
1728   aPlane->SetSize (aSizeX, aSizeY);
1729
1730   aContextAIS->Update (aPlane, isUpdate);
1731
1732   return 0;
1733 }
1734
1735 //==============================================================================
1736 // Fonction  vline
1737 // ---------------  Uniquement par parametre. Pas de selection dans le viewer.
1738 //==============================================================================
1739
1740 //==============================================================================
1741 //function : VLineBuilder
1742 //purpose  : Build an AIS_Line
1743 //Draw arg : vline LineName  [AIS_PointName] [AIS_PointName]
1744 //                           [Xa] [Ya] [Za]   [Xb] [Yb] [Zb]
1745 //==============================================================================
1746 #include <Geom_CartesianPoint.hxx>
1747 #include <AIS_Line.hxx>
1748
1749
1750 static int VLineBuilder(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1751 {
1752   // Verifications
1753   if (argc!=4 && argc!=8 && argc!=2 )  {di<<"vline error: number of arguments not correct \n";return 1; }
1754
1755   // On recupere les parametres
1756   Handle(AIS_InteractiveObject) theShapeA;
1757   Handle(AIS_InteractiveObject) theShapeB;
1758
1759   // Parametres: AIS_Point AIS_Point
1760   // ===============================
1761   if (argc==4) {
1762     theShapeA=
1763       Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[2]));
1764     // On verifie que c'est bien une AIS_Point
1765     if (!theShapeA.IsNull() &&
1766       theShapeA->Type()==AIS_KOI_Datum && theShapeA->Signature()==1) {
1767         // on recupere le deuxieme AIS_Point
1768         theShapeB=
1769           Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(argv[3]));
1770         if (theShapeA.IsNull() ||
1771           (!(theShapeB->Type()==AIS_KOI_Datum && theShapeB->Signature()==1)))
1772         {
1773           di <<"vline error: wrong type of 2de argument.\n";
1774           return 1;
1775         }
1776       }
1777     else {di <<"vline error: wrong type of 1st argument.\n";return 1; }
1778     // Les deux parametres sont du bon type. On verifie que les points ne sont pas confondus
1779     Handle(AIS_Point) theAISPointA= Handle(AIS_Point)::DownCast (theShapeA);
1780     Handle(AIS_Point) theAISPointB= Handle(AIS_Point)::DownCast (theShapeB);
1781
1782     Handle(Geom_Point ) myGeomPointBA=  theAISPointA->Component();
1783     Handle(Geom_CartesianPoint ) myCartPointA= Handle(Geom_CartesianPoint)::DownCast (myGeomPointBA);
1784     //    Handle(Geom_CartesianPoint ) myCartPointA= *(Handle(Geom_CartesianPoint)*)& (theAISPointA->Component() ) ;
1785
1786     Handle(Geom_Point ) myGeomPointB=  theAISPointB->Component();
1787     Handle(Geom_CartesianPoint ) myCartPointB= Handle(Geom_CartesianPoint)::DownCast (myGeomPointB);
1788     //    Handle(Geom_CartesianPoint ) myCartPointB= *(Handle(Geom_CartesianPoint)*)& (theAISPointB->Component() ) ;
1789
1790     if (myCartPointB->X()==myCartPointA->X() && myCartPointB->Y()==myCartPointA->Y() && myCartPointB->Z()==myCartPointA->Z() ) {
1791       // B=A
1792       di<<"vline error: same points\n";return 1;
1793     }
1794     // Les deux points sont OK...Construction de l'AIS_Line (en faite, le segment AB)
1795     Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
1796     GetMapOfAIS().Bind(theAISLine,argv[1] );
1797     TheAISContext()->Display (theAISLine, Standard_True);
1798
1799   }
1800
1801   // Parametres 6 Reals
1802   // ==================
1803
1804   else if (argc==8) {
1805     // On verifie que les deux points ne sont pas confondus
1806
1807     Standard_Real coord[6];
1808     for(Standard_Integer i=0;i<=2;i++){
1809       coord[i]=Draw::Atof(argv[2+i]);
1810       coord[i+3]=Draw::Atof(argv[5+i]);
1811     }
1812
1813     Handle(Geom_CartesianPoint ) myCartPointA=new Geom_CartesianPoint (coord[0],coord[1],coord[2] );
1814     Handle(Geom_CartesianPoint ) myCartPointB=new Geom_CartesianPoint (coord[3],coord[4],coord[5] );
1815
1816     Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
1817     GetMapOfAIS().Bind(theAISLine,argv[1] );
1818     TheAISContext()->Display (theAISLine, Standard_True);
1819
1820   }
1821
1822   // Pas de parametres: Selection dans le viewer.
1823   // ============================================
1824
1825   else
1826   {
1827     TopTools_ListOfShape aShapes;
1828     ViewerTest::GetSelectedShapes (aShapes);
1829     if (aShapes.Extent() != 2)
1830     {
1831       std::cerr << "Error: wrong number of selected shapes.\n";
1832       return 1;
1833     }
1834
1835     const TopoDS_Shape& aShapeA = aShapes.First();
1836     const TopoDS_Shape& aShapeB = aShapes.Last();
1837
1838     if (!(aShapeA.ShapeType() == TopAbs_VERTEX
1839        && aShapeB.ShapeType() == TopAbs_VERTEX))
1840     {
1841       std::cerr << "Error: you should select two different vertex.\n";
1842       return 1;
1843     }
1844
1845     // Construction de la line
1846     gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
1847     gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
1848
1849     Handle(Geom_CartesianPoint ) myCartPointA=new Geom_CartesianPoint(A);
1850     Handle(Geom_CartesianPoint ) myCartPointB=new Geom_CartesianPoint(B);
1851
1852     Handle(AIS_Line) theAISLine= new AIS_Line(myCartPointA,myCartPointB );
1853     GetMapOfAIS().Bind(theAISLine,argv[1] );
1854     TheAISContext()->Display (theAISLine, Standard_True);
1855   }
1856
1857   return 0;
1858 }
1859
1860 //==============================================================================
1861 // class   : FilledCircle
1862 // purpose : creates filled circle based on AIS_InteractiveObject 
1863 //           and Geom_Circle.
1864 //           This class is used to check method Matches() of class 
1865 //           Select3D_SensitiveCircle with member myFillStatus = Standard_True, 
1866 //           because none of AIS classes provides creation of 
1867 //           Select3D_SensitiveCircle with member myFillStatus = Standard_True 
1868 //           (look method ComputeSelection() )
1869 //============================================================================== 
1870
1871 Handle(Geom_Circle) CreateCircle(gp_Pnt theCenter, Standard_Real theRadius) 
1872 {
1873   gp_Ax2 anAxes(theCenter, gp_Dir(gp_Vec(0., 0., 1.))); 
1874   gp_Circ aCirc(anAxes, theRadius);
1875   Handle(Geom_Circle) aCircle = new Geom_Circle(aCirc);
1876   return aCircle;
1877 }
1878
1879 class FilledCircle : public AIS_InteractiveObject 
1880 {
1881 public:
1882     // CASCADE RTTI
1883     DEFINE_STANDARD_RTTI_INLINE(FilledCircle,AIS_InteractiveObject); 
1884
1885     FilledCircle(gp_Pnt theCenter, Standard_Real theRadius);
1886     FilledCircle(Handle(Geom_Circle) theCircle);
1887
1888 private:
1889     TopoDS_Face ComputeFace();
1890
1891     // Virtual methods implementation
1892     void Compute (  const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
1893                   const Handle(Prs3d_Presentation)& thePresentation,
1894                   const Standard_Integer theMode) Standard_OVERRIDE;
1895
1896     void ComputeSelection (  const Handle(SelectMgr_Selection)& theSelection, 
1897                            const Standard_Integer theMode) Standard_OVERRIDE;
1898
1899 protected:
1900     Handle(Geom_Circle) myCircle;
1901     Standard_Boolean myFilledStatus;
1902
1903 }; 
1904
1905
1906 FilledCircle::FilledCircle(gp_Pnt theCenter, Standard_Real theRadius) 
1907 {
1908   myCircle = CreateCircle(theCenter, theRadius);
1909   myFilledStatus = Standard_True;
1910 }
1911
1912 FilledCircle::FilledCircle(Handle(Geom_Circle) theCircle) 
1913 {
1914   myCircle = theCircle;
1915   myFilledStatus = Standard_True;
1916 }
1917
1918 TopoDS_Face FilledCircle::ComputeFace() 
1919 {
1920   // Create edge from myCircle 
1921   BRepBuilderAPI_MakeEdge anEdgeMaker(myCircle->Circ());
1922   TopoDS_Edge anEdge = anEdgeMaker.Edge(); 
1923
1924   // Create wire from anEdge 
1925   BRepBuilderAPI_MakeWire aWireMaker(anEdge);
1926   TopoDS_Wire aWire = aWireMaker.Wire();
1927
1928   // Create face from aWire
1929   BRepBuilderAPI_MakeFace aFaceMaker(aWire);
1930   TopoDS_Face aFace = aFaceMaker.Face();
1931
1932   return aFace;
1933 }
1934
1935 void FilledCircle::Compute(const Handle(PrsMgr_PresentationManager3d) &/*thePresentationManager*/, 
1936                            const Handle(Prs3d_Presentation) &thePresentation, 
1937                            const Standard_Integer theMode) 
1938 {
1939   thePresentation->Clear();
1940
1941   TopoDS_Face aFace = ComputeFace();
1942
1943   if (aFace.IsNull()) return;
1944   if (theMode != 0) return;
1945
1946   StdPrs_ShadedShape::Add(thePresentation, aFace, myDrawer);
1947 }
1948
1949 void FilledCircle::ComputeSelection(const Handle(SelectMgr_Selection) &theSelection, 
1950                                     const Standard_Integer /*theMode*/)
1951 {
1952   Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner(this);
1953   Handle(Select3D_SensitiveCircle) aSensitiveCircle = new Select3D_SensitiveCircle(anEntityOwner, 
1954       myCircle, myFilledStatus);
1955   theSelection->Add(aSensitiveCircle);
1956 }
1957
1958 //==============================================================================
1959 // Fonction  vcircle
1960 // -----------------  Uniquement par parametre. Pas de selection dans le viewer.
1961 //==============================================================================
1962
1963 //==============================================================================
1964 //function : VCircleBuilder
1965 //purpose  : Build an AIS_Circle
1966 //Draw arg : vcircle CircleName PlaneName PointName Radius IsFilled
1967 //                              PointName PointName PointName IsFilled
1968 //==============================================================================
1969
1970 void DisplayCircle (Handle (Geom_Circle) theGeomCircle,
1971                     TCollection_AsciiString theName, 
1972                     Standard_Boolean isFilled) 
1973 {
1974   Handle(AIS_InteractiveObject) aCircle;
1975   if (isFilled) 
1976   {
1977     aCircle = new FilledCircle(theGeomCircle);
1978   }
1979   else
1980   {
1981     aCircle = new AIS_Circle(theGeomCircle);
1982     Handle(AIS_Circle)::DownCast (aCircle)->SetFilledCircleSens (Standard_False);
1983   }
1984
1985   // Check if there is an object with given name
1986   // and remove it from context
1987   if (GetMapOfAIS().IsBound2(theName)) 
1988   {
1989     Handle(Standard_Transient) anObj = GetMapOfAIS().Find2(theName);
1990     Handle(AIS_InteractiveObject) anInterObj = 
1991          Handle(AIS_InteractiveObject)::DownCast(anObj);
1992     TheAISContext()->Remove(anInterObj, Standard_False);
1993     GetMapOfAIS().UnBind2(theName);
1994    }
1995
1996    // Bind the circle to its name
1997    GetMapOfAIS().Bind(aCircle, theName);
1998
1999    // Display the circle
2000    TheAISContext()->Display (aCircle, Standard_True);
2001   
2002 }
2003
2004 static int VCircleBuilder(Draw_Interpretor& /*di*/, Standard_Integer argc, const char** argv)
2005 {
2006   // Verification of the arguments
2007   if (argc>6 || argc<2) 
2008   { 
2009     std::cout << "vcircle error: expect 4 arguments.\n"; 
2010     return 1; // TCL_ERROR 
2011   }
2012
2013   // There are all arguments
2014   if (argc == 6) 
2015   {
2016     // Get arguments
2017     TCollection_AsciiString aName(argv[1]);
2018     Standard_Boolean isFilled = Draw::Atoi(argv[5]) != 0;
2019
2020     Handle(AIS_InteractiveObject) theShapeA;
2021     Handle(AIS_InteractiveObject) theShapeB;
2022
2023     theShapeA =
2024       Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(argv[2]));
2025     theShapeB =
2026       Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(argv[3]));
2027
2028
2029     // Arguments: AIS_Point AIS_Point AIS_Point
2030     // ========================================
2031     if (!theShapeA.IsNull() && !theShapeB.IsNull() &&
2032       theShapeA->Type()==AIS_KOI_Datum && theShapeA->Signature()==1)
2033     {
2034       if (theShapeB->Type()!=AIS_KOI_Datum || theShapeB->Signature()!=1 ) 
2035       {
2036         std::cout << "vcircle error: 2d argument is unexpected to be a point.\n";
2037         return 1; // TCL_ERROR 
2038       }
2039       // The third object must be a point
2040       Handle(AIS_InteractiveObject) theShapeC =
2041         Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(argv[4]));
2042       if (theShapeC.IsNull() ||
2043         theShapeC->Type()!=AIS_KOI_Datum || theShapeC->Signature()!=1 ) 
2044       {
2045         std::cout << "vcircle error: 3d argument is unexpected to be a point.\n";
2046         return 1; // TCL_ERROR 
2047       }
2048         // tag
2049         // Verify that the three points are different
2050         Handle(AIS_Point) theAISPointA = Handle(AIS_Point)::DownCast(theShapeA);
2051         Handle(AIS_Point) theAISPointB = Handle(AIS_Point)::DownCast(theShapeB);
2052         Handle(AIS_Point) theAISPointC = Handle(AIS_Point)::DownCast(theShapeC);
2053         
2054         Handle(Geom_Point) myGeomPointA = theAISPointA->Component();
2055         Handle(Geom_CartesianPoint) myCartPointA = 
2056           Handle(Geom_CartesianPoint)::DownCast(myGeomPointA);
2057
2058         Handle(Geom_Point) myGeomPointB = theAISPointB->Component();
2059         Handle(Geom_CartesianPoint) myCartPointB =
2060           Handle(Geom_CartesianPoint)::DownCast(myGeomPointB);
2061
2062         Handle(Geom_Point) myGeomPointC = theAISPointC->Component();
2063         Handle(Geom_CartesianPoint) myCartPointC =
2064           Handle(Geom_CartesianPoint)::DownCast(myGeomPointC);
2065
2066         // Test A=B
2067         if (Abs(myCartPointA->X()-myCartPointB->X()) <= Precision::Confusion() && 
2068             Abs(myCartPointA->Y()-myCartPointB->Y()) <= Precision::Confusion() && 
2069             Abs(myCartPointA->Z()-myCartPointB->Z()) <= Precision::Confusion() ) 
2070         {
2071           std::cout << "vcircle error: Same points.\n"; 
2072           return 1; // TCL_ERROR 
2073         }
2074         // Test A=C
2075         if (Abs(myCartPointA->X()-myCartPointC->X()) <= Precision::Confusion() &&
2076             Abs(myCartPointA->Y()-myCartPointC->Y()) <= Precision::Confusion() && 
2077             Abs(myCartPointA->Z()-myCartPointC->Z()) <= Precision::Confusion() ) 
2078         {
2079           std::cout << "vcircle error: Same points.\n"; 
2080           return 1; // TCL_ERROR 
2081         }
2082         // Test B=C
2083         if (Abs(myCartPointB->X()-myCartPointC->X()) <= Precision::Confusion() && 
2084             Abs(myCartPointB->Y()-myCartPointC->Y()) <= Precision::Confusion() && 
2085             Abs(myCartPointB->Z()-myCartPointC->Z()) <= Precision::Confusion() ) 
2086         {
2087           std::cout << "vcircle error: Same points.\n"; 
2088           return 1;// TCL_ERROR 
2089         }
2090         // Construction of the circle
2091         GC_MakeCircle Cir = GC_MakeCircle (myCartPointA->Pnt(), 
2092           myCartPointB->Pnt(), myCartPointC->Pnt() );
2093         Handle (Geom_Circle) theGeomCircle;
2094         try 
2095         {
2096           theGeomCircle = Cir.Value();
2097         }
2098         catch (StdFail_NotDone)
2099         {
2100           std::cout << "vcircle error: can't create circle\n";
2101           return -1; // TCL_ERROR
2102         }
2103         
2104         DisplayCircle(theGeomCircle, aName, isFilled);
2105     }
2106
2107     // Arguments: AIS_Plane AIS_Point Real
2108     // ===================================
2109     else if (theShapeA->Type() == AIS_KOI_Datum && 
2110       theShapeA->Signature() == 7 ) 
2111     {
2112       if (theShapeB->Type() != AIS_KOI_Datum || 
2113         theShapeB->Signature() != 1 ) 
2114       {
2115         std::cout << "vcircle error: 2d element is a unexpected to be a point.\n"; 
2116         return 1; // TCL_ERROR 
2117       }
2118       // Check that the radius is >= 0
2119       if (Draw::Atof(argv[4]) <= 0 ) 
2120       {
2121         std::cout << "vcircle error: the radius must be >=0.\n"; 
2122         return 1; // TCL_ERROR 
2123       }
2124
2125       // Recover the normal to the plane
2126       Handle(AIS_Plane) theAISPlane = Handle(AIS_Plane)::DownCast(theShapeA);
2127       Handle(AIS_Point) theAISPointB = Handle(AIS_Point)::DownCast(theShapeB); 
2128
2129       Handle(Geom_Plane) myGeomPlane = theAISPlane->Component();
2130       Handle(Geom_Point) myGeomPointB = theAISPointB->Component();
2131       Handle(Geom_CartesianPoint) myCartPointB = 
2132         Handle(Geom_CartesianPoint)::DownCast(myGeomPointB);
2133
2134       gp_Pln mygpPlane = myGeomPlane->Pln();
2135       gp_Ax1 thegpAxe = mygpPlane.Axis();
2136       gp_Dir theDir = thegpAxe.Direction();
2137       gp_Pnt theCenter = myCartPointB->Pnt();
2138       Standard_Real TheR = Draw::Atof(argv[4]);
2139       GC_MakeCircle Cir = GC_MakeCircle (theCenter, theDir ,TheR);
2140       Handle (Geom_Circle) theGeomCircle;
2141       try 
2142       {
2143         theGeomCircle = Cir.Value();
2144       }
2145       catch (StdFail_NotDone)
2146       {
2147         std::cout << "vcircle error: can't create circle\n";
2148         return -1; // TCL_ERROR
2149       }
2150
2151       DisplayCircle(theGeomCircle, aName, isFilled);
2152
2153     }
2154
2155     // Error
2156     else
2157     {
2158       std::cout << "vcircle error: 1st argument is a unexpected type.\n"; 
2159       return 1; // TCL_ERROR 
2160     }
2161
2162   }
2163   // No arguments: selection in the viewer
2164   // =========================================
2165   else 
2166   {
2167     // Get the name of the circle 
2168     TCollection_AsciiString aName(argv[1]);
2169
2170     TopTools_ListOfShape aShapes;
2171     ViewerTest::GetSelectedShapes (aShapes);
2172     if (aShapes.Extent() != 3 && aShapes.Extent() != 2)
2173     {
2174       std::cerr << "Error: Wrong number of selected shapes.\n";
2175       return 1;
2176     }
2177
2178     const TopoDS_Shape& aShapeA = aShapes.First();
2179     if (aShapeA.ShapeType() == TopAbs_VERTEX ) 
2180     {
2181       if (aShapes.Extent() != 3)
2182       {
2183         std::cerr << "Error: wrong number of selected shapes.\n";
2184         return 1;
2185       }
2186
2187       TopTools_ListOfShape::Iterator anIter (aShapes);
2188
2189       anIter.Next();
2190       const TopoDS_Shape& aShapeB = anIter.Value();
2191
2192       anIter.Next();
2193       const TopoDS_Shape& aShapeC = anIter.Value();
2194       
2195       // Get isFilled
2196       Standard_Boolean isFilled;
2197       std::cout << "Enter filled status (0 or 1)\n";
2198       cin >> isFilled;
2199
2200       // Construction of the circle
2201       gp_Pnt A = BRep_Tool::Pnt (TopoDS::Vertex (aShapeA));
2202       gp_Pnt B = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
2203       gp_Pnt C = BRep_Tool::Pnt (TopoDS::Vertex (aShapeC));
2204
2205       GC_MakeCircle Cir = GC_MakeCircle (A, B, C);
2206       Handle (Geom_Circle) theGeomCircle;
2207       try 
2208       {
2209         theGeomCircle = Cir.Value();
2210       }
2211       catch (StdFail_NotDone)
2212       {
2213         std::cout << "vcircle error: can't create circle\n";
2214         return -1; // TCL_ERROR
2215       }
2216
2217       DisplayCircle(theGeomCircle, aName, isFilled);
2218
2219     }
2220     else if (aShapeA.ShapeType() == TopAbs_FACE)
2221     {
2222       const TopoDS_Shape& aShapeB = aShapes.Last();
2223
2224       // Recover the radius 
2225       Standard_Real theRad;
2226       do 
2227       {
2228         std::cout << " Enter the value of the radius:\n";
2229         cin >> theRad;
2230       } while (theRad <= 0);
2231       
2232       // Get filled status
2233       Standard_Boolean isFilled;
2234       std::cout << "Enter filled status (0 or 1)\n";
2235       cin >> isFilled;
2236
2237       // Recover the normal to the plane. tag
2238       TopoDS_Face myFace = TopoDS::Face(aShapeA);
2239       BRepAdaptor_Surface mySurface (myFace, Standard_False);
2240       gp_Pln myPlane = mySurface.Plane();
2241       Handle(Geom_Plane) theGeomPlane = new Geom_Plane (myPlane);
2242       gp_Pln mygpPlane = theGeomPlane->Pln();
2243       gp_Ax1 thegpAxe = mygpPlane.Axis();
2244       gp_Dir theDir = thegpAxe.Direction();
2245
2246       // Recover the center
2247       gp_Pnt theCenter = BRep_Tool::Pnt (TopoDS::Vertex (aShapeB));
2248
2249       // Construct the circle
2250       GC_MakeCircle Cir = GC_MakeCircle (theCenter, theDir ,theRad);
2251       Handle (Geom_Circle) theGeomCircle;
2252       try 
2253       {
2254         theGeomCircle = Cir.Value();
2255       }
2256       catch (StdFail_NotDone)
2257       {
2258         std::cout << "vcircle error: can't create circle\n";
2259         return -1; // TCL_ERROR
2260       }
2261
2262       DisplayCircle(theGeomCircle, aName, isFilled);
2263     }
2264     else
2265     {
2266       std::cerr << "Error: You should select face and vertex or three vertices.\n";
2267       return 1;
2268     }
2269   }
2270
2271   return 0;
2272 }
2273
2274 //=======================================================================
2275 //function : VDrawText
2276 //purpose  :
2277 //=======================================================================
2278 static int VDrawText (Draw_Interpretor& theDI,
2279                       Standard_Integer  theArgsNb,
2280                       const char**      theArgVec)
2281 {
2282   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
2283   if (theArgsNb < 3)
2284   {
2285     std::cout << "Error: wrong number of arguments! See usage:\n";
2286     theDI.PrintHelp (theArgVec[0]);
2287     return 1;
2288   }
2289   else if (aContext.IsNull())
2290   {
2291     std::cout << "Error: no active view!\n";
2292     return 1;
2293   }
2294
2295   Standard_Integer           anArgIt = 1;
2296   TCollection_ExtendedString aName (theArgVec[anArgIt++], Standard_True);
2297   TCollection_ExtendedString aText (theArgVec[anArgIt++], Standard_True);
2298   Handle(AIS_TextLabel)      aTextPrs;
2299   ViewerTest_AutoUpdater     anAutoUpdater (aContext, ViewerTest::CurrentView());
2300
2301   Standard_Boolean isNewPrs = Standard_False;
2302   if (GetMapOfAIS().IsBound2 (aName))
2303   {
2304     aTextPrs = Handle(AIS_TextLabel)::DownCast (GetMapOfAIS().Find2 (aName));
2305   }
2306
2307   if (aTextPrs.IsNull())
2308   {
2309     isNewPrs = Standard_True;
2310     aTextPrs = new AIS_TextLabel();
2311     aTextPrs->SetFont ("Courier");
2312   }
2313
2314   aTextPrs->SetText (aText);
2315
2316   Handle(Graphic3d_TransformPers) aTrsfPers;
2317   Aspect_TypeOfDisplayText aDisplayType = Aspect_TODT_NORMAL;
2318
2319   Standard_Boolean aHasPlane = Standard_False;
2320   gp_Dir           aNormal;
2321   gp_Dir           aDirection;
2322   gp_Pnt           aPos;
2323
2324   for (; anArgIt < theArgsNb; ++anArgIt)
2325   {
2326     TCollection_AsciiString aParam (theArgVec[anArgIt]);
2327     aParam.LowerCase();
2328
2329     if (anAutoUpdater.parseRedrawMode (aParam))
2330     {
2331       continue;
2332     }
2333     else if (aParam == "-pos"
2334           || aParam == "-position")
2335     {
2336       if (anArgIt + 3 >= theArgsNb)
2337       {
2338         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2339         return 1;
2340       }
2341
2342       aPos.SetX (Draw::Atof (theArgVec[++anArgIt]));
2343       aPos.SetY (Draw::Atof (theArgVec[++anArgIt]));
2344       aPos.SetZ (Draw::Atof (theArgVec[++anArgIt]));
2345       aTextPrs->SetPosition (aPos);
2346     }
2347     else if (aParam == "-color")
2348     {
2349       if (anArgIt + 1 >= theArgsNb)
2350       {
2351         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2352         return 1;
2353       }
2354
2355       TCollection_AsciiString aColor (theArgVec[anArgIt + 1]);
2356       Quantity_NameOfColor aNameOfColor = Quantity_NOC_BLACK;
2357       if (Quantity_Color::ColorFromName (aColor.ToCString(), aNameOfColor))
2358       {
2359         anArgIt += 1;
2360         aTextPrs->SetColor (aNameOfColor);
2361         continue;
2362       }
2363       else if (anArgIt + 3 >= theArgsNb)
2364       {
2365         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2366         return 1;
2367       }
2368
2369       TCollection_AsciiString aGreen (theArgVec[anArgIt + 2]);
2370       TCollection_AsciiString aBlue  (theArgVec[anArgIt + 3]);
2371       if (!aColor.IsRealValue()
2372        || !aGreen.IsRealValue()
2373        || !aBlue.IsRealValue())
2374       {
2375         std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
2376         return 1;
2377       }
2378
2379       const Graphic3d_Vec3d anRGB (aColor.RealValue(),
2380                                    aGreen.RealValue(),
2381                                    aBlue.RealValue());
2382
2383       aTextPrs->SetColor (Quantity_Color (anRGB.r(), anRGB.g(), anRGB.b(), Quantity_TOC_RGB));
2384       anArgIt += 3;
2385     }
2386     else if (aParam == "-halign")
2387     {
2388       if (++anArgIt >= theArgsNb)
2389       {
2390         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2391         return 1;
2392       }
2393
2394       TCollection_AsciiString aType (theArgVec[anArgIt]);
2395       aType.LowerCase();
2396       if (aType == "left")
2397       {
2398         aTextPrs->SetHJustification (Graphic3d_HTA_LEFT);
2399       }
2400       else if (aType == "center")
2401       {
2402         aTextPrs->SetHJustification (Graphic3d_HTA_CENTER);
2403       }
2404       else if (aType == "right")
2405       {
2406         aTextPrs->SetHJustification (Graphic3d_HTA_RIGHT);
2407       }
2408       else
2409       {
2410         std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
2411         return 1;
2412       }
2413     }
2414     else if (aParam == "-valign")
2415     {
2416       if (++anArgIt >= theArgsNb)
2417       {
2418         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2419         return 1;
2420       }
2421
2422       TCollection_AsciiString aType (theArgVec[anArgIt]);
2423       aType.LowerCase();
2424       if (aType == "top")
2425       {
2426         aTextPrs->SetVJustification (Graphic3d_VTA_TOP);
2427       }
2428       else if (aType == "center")
2429       {
2430         aTextPrs->SetVJustification (Graphic3d_VTA_CENTER);
2431       }
2432       else if (aType == "bottom")
2433       {
2434         aTextPrs->SetVJustification (Graphic3d_VTA_BOTTOM);
2435       }
2436       else if (aType == "topfirstline")
2437       {
2438         aTextPrs->SetVJustification (Graphic3d_VTA_TOPFIRSTLINE);
2439       }
2440       else
2441       {
2442         std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
2443         return 1;
2444       }
2445     }
2446     else if (aParam == "-angle")
2447     {
2448       if (++anArgIt >= theArgsNb)
2449       {
2450         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2451         return 1;
2452       }
2453
2454       aTextPrs->SetAngle (Draw::Atof (theArgVec[anArgIt]) * (M_PI / 180.0));
2455     }
2456     else if (aParam == "-zoom")
2457     {
2458       if (++anArgIt >= theArgsNb)
2459       {
2460         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2461         return 1;
2462       }
2463
2464       aTextPrs->SetZoomable (Draw::Atoi (theArgVec[anArgIt]) == 1);
2465     }
2466     else if (aParam == "-height")
2467     {
2468       if (++anArgIt >= theArgsNb)
2469       {
2470         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2471         return 1;
2472       }
2473
2474       aTextPrs->SetHeight (Draw::Atof(theArgVec[anArgIt]));
2475     }
2476     else if (aParam == "-aspect")
2477     {
2478       if (++anArgIt >= theArgsNb)
2479       {
2480         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2481         return 1;
2482       }
2483
2484       TCollection_AsciiString anOption (theArgVec[anArgIt]);
2485       anOption.LowerCase();
2486       if (anOption.IsEqual ("regular"))
2487       {
2488         aTextPrs->SetFontAspect (Font_FA_Regular);
2489       }
2490       else if (anOption.IsEqual ("bold"))
2491       {
2492         aTextPrs->SetFontAspect (Font_FA_Bold);
2493       }
2494       else if (anOption.IsEqual ("italic"))
2495       {
2496         aTextPrs->SetFontAspect (Font_FA_Italic);
2497       }
2498       else if (anOption.IsEqual ("bolditalic"))
2499       {
2500         aTextPrs->SetFontAspect (Font_FA_BoldItalic);
2501       }
2502     }
2503     else if (aParam == "-font")
2504     {
2505       if (++anArgIt >= theArgsNb)
2506       {
2507         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2508         return 1;
2509       }
2510
2511       aTextPrs->SetFont (theArgVec[anArgIt]);
2512     }
2513     else if (aParam == "-plane")
2514     {
2515       if (anArgIt + 6 >= theArgsNb)
2516       {
2517         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2518         return 1;
2519       }
2520
2521       Standard_Real aX = Draw::Atof (theArgVec[++anArgIt]);
2522       Standard_Real aY = Draw::Atof (theArgVec[++anArgIt]);
2523       Standard_Real aZ = Draw::Atof (theArgVec[++anArgIt]);
2524       aNormal.SetCoord (aX, aY, aZ);
2525
2526       aX = Draw::Atof (theArgVec[++anArgIt]);
2527       aY = Draw::Atof (theArgVec[++anArgIt]);
2528       aZ = Draw::Atof (theArgVec[++anArgIt]);
2529       aDirection.SetCoord (aX, aY, aZ);
2530
2531       aHasPlane = Standard_True;
2532     }
2533     else if (aParam == "-flipping")
2534     {
2535       aTextPrs->SetFlipping (Standard_True);
2536     }
2537     else if (aParam == "-disptype"
2538           || aParam == "-displaytype")
2539     {
2540       if (++anArgIt >= theArgsNb)
2541       {
2542         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2543         return 1;
2544       }
2545       TCollection_AsciiString aType (theArgVec[anArgIt]);
2546       aType.LowerCase();
2547       if (aType == "subtitle")
2548         aDisplayType = Aspect_TODT_SUBTITLE;
2549       else if (aType == "decal")
2550         aDisplayType = Aspect_TODT_DEKALE;
2551       else if (aType == "blend")
2552         aDisplayType = Aspect_TODT_BLEND;
2553       else if (aType == "dimension")
2554         aDisplayType = Aspect_TODT_DIMENSION;
2555       else if (aType == "normal")
2556         aDisplayType = Aspect_TODT_NORMAL;
2557       else
2558       {
2559         std::cout << "Error: wrong display type '" << aType << "'.\n";
2560         return 1;
2561       }
2562     }
2563     else if (aParam == "-subcolor"
2564           || aParam == "-subtitlecolor")
2565     {
2566       if (anArgIt + 1 >= theArgsNb)
2567       {
2568         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2569         return 1;
2570       }
2571
2572       TCollection_AsciiString aColor (theArgVec[anArgIt + 1]);
2573       Quantity_NameOfColor aNameOfColor = Quantity_NOC_BLACK;
2574       if (Quantity_Color::ColorFromName (aColor.ToCString(), aNameOfColor))
2575       {
2576         anArgIt += 1;
2577         aTextPrs->SetColorSubTitle (aNameOfColor);
2578         continue;
2579       }
2580       else if (anArgIt + 3 >= theArgsNb)
2581       {
2582         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2583         return 1;
2584       }
2585
2586       TCollection_AsciiString aGreen (theArgVec[anArgIt + 2]);
2587       TCollection_AsciiString aBlue  (theArgVec[anArgIt + 3]);
2588       if (!aColor.IsRealValue()
2589        || !aGreen.IsRealValue()
2590        || !aBlue.IsRealValue())
2591       {
2592         std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
2593         return 1;
2594       }
2595
2596       const Graphic3d_Vec3d anRGB (aColor.RealValue(),
2597                                    aGreen.RealValue(),
2598                                    aBlue.RealValue());
2599
2600       aTextPrs->SetColorSubTitle (Quantity_Color (anRGB.r(), anRGB.g(), anRGB.b(), Quantity_TOC_RGB));
2601       anArgIt += 3;
2602     }
2603     else if (aParam == "-2d")
2604     {
2605       aTrsfPers = new Graphic3d_TransformPers (Graphic3d_TMF_2d);
2606     }
2607     else if (aParam == "-trsfperspos"
2608           || aParam == "-perspos")
2609     {
2610       if (anArgIt + 2 >= theArgsNb)
2611       {
2612         std::cerr << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
2613         return 1;
2614       }
2615
2616       TCollection_AsciiString aX (theArgVec[++anArgIt]);
2617       TCollection_AsciiString aY (theArgVec[++anArgIt]);
2618       TCollection_AsciiString aZ = "0";
2619       if (!aX.IsIntegerValue()
2620        || !aY.IsIntegerValue())
2621       {
2622         std::cerr << "Error: wrong syntax at '" << aParam << "'.\n";
2623         return 1;
2624       }
2625       if (anArgIt + 1 < theArgsNb)
2626       {
2627         TCollection_AsciiString aTemp = theArgVec[anArgIt + 1];
2628         if (aTemp.IsIntegerValue())
2629         {
2630           aZ = aTemp;
2631           ++anArgIt;
2632         }
2633       }
2634
2635       aTrsfPers = Graphic3d_TransformPers::FromDeprecatedParams (Graphic3d_TMF_2d, gp_Pnt (aX.IntegerValue(), aY.IntegerValue(), aZ.IntegerValue()));
2636     }
2637     else
2638     {
2639       std::cout << "Error: unknown argument '" << aParam << "'\n";
2640       return 1;
2641     }
2642   }
2643
2644   if (aHasPlane)
2645   {
2646     aTextPrs->SetOrientation3D (gp_Ax2 (aPos, aNormal, aDirection));
2647   }
2648
2649   aTextPrs->SetDisplayType (aDisplayType);
2650
2651   if (!aTrsfPers.IsNull())
2652   {
2653     aContext->SetTransformPersistence (aTextPrs, aTrsfPers);
2654     aTextPrs->SetZLayer(Graphic3d_ZLayerId_TopOSD);
2655     if (aTextPrs->Position().Z() != 0)
2656     {
2657       aTextPrs->SetPosition (gp_Pnt(aTextPrs->Position().X(), aTextPrs->Position().Y(), 0));
2658     }
2659   }
2660   else if (!aTextPrs->TransformPersistence().IsNull())
2661   {
2662     aContext->SetTransformPersistence (aTextPrs, Handle(Graphic3d_TransformPers)());
2663   }
2664
2665   if (isNewPrs)
2666   {
2667     ViewerTest::Display (aName, aTextPrs, Standard_False);
2668   }
2669   else
2670   {
2671     aContext->Redisplay (aTextPrs, Standard_False, Standard_True);
2672   }
2673   return 0;
2674 }
2675
2676 #include <math.h>
2677 #include <gp_Pnt.hxx>
2678 #include <Graphic3d_ArrayOfPoints.hxx>
2679 #include <Graphic3d_ArrayOfPrimitives.hxx>
2680 #include <Graphic3d_ArrayOfTriangles.hxx>
2681 #include <Poly_Array1OfTriangle.hxx>
2682 #include <Poly_Triangle.hxx>
2683 #include <Poly_Triangulation.hxx>
2684 #include <TColgp_Array1OfPnt.hxx>
2685 #include <TShort_Array1OfShortReal.hxx>
2686 #include <TShort_HArray1OfShortReal.hxx>
2687
2688 #include <AIS_Triangulation.hxx>
2689 #include <StdPrs_ToolTriangulatedShape.hxx>
2690 #include <Poly_Connect.hxx>
2691 #include <TColgp_Array1OfDir.hxx>
2692 #include <Graphic3d_GraphicDriver.hxx>
2693
2694 #include <TColStd_Array1OfInteger.hxx>
2695 #include <TColStd_HArray1OfInteger.hxx>
2696 #include <Prs3d_ShadingAspect.hxx>
2697 #include <Graphic3d_MaterialAspect.hxx>
2698 #include <Graphic3d_AspectFillArea3d.hxx>
2699
2700 #include <BRepPrimAPI_MakeCylinder.hxx>
2701 #include <TopoDS_Shape.hxx>
2702 #include <TopExp_Explorer.hxx>
2703 #include <TopAbs.hxx>
2704 #include <StdSelect_ShapeTypeFilter.hxx>
2705 #include <AIS_InteractiveObject.hxx>
2706
2707
2708 //===============================================================================================
2709 //function : CalculationOfSphere
2710 //author   : psn
2711 //purpose  : Create a Sphere
2712 //===============================================================================================
2713
2714 Handle( Poly_Triangulation ) CalculationOfSphere( double X , double Y , double Z ,
2715                                                   int res ,
2716                                                   double Radius ){
2717   double mRadius = Radius;
2718   double mCenter[3] = {X,Y,Z};
2719   int mThetaResolution;
2720   int mPhiResolution;
2721   double mStartTheta = 0;//StartTheta;
2722   double mEndTheta = 360;//EndTheta;
2723   double mStartPhi = 0;//StartPhi;
2724   double mEndPhi = 180;//EndPhi;
2725   res = res < 4 ? 4 : res;
2726
2727   mThetaResolution = res;
2728   mPhiResolution = res;
2729
2730   int i, j;
2731   int jStart, jEnd, numOffset;
2732   double x[3], n[3], deltaPhi, deltaTheta, phi, theta, radius;
2733   double startTheta, endTheta, startPhi, endPhi;
2734   int base, numPoles=0, thetaResolution, phiResolution;
2735
2736   int pts[3];
2737   int piece = -1;
2738   int numPieces = 1;
2739   if ( numPieces > mThetaResolution ) {
2740     numPieces = mThetaResolution;
2741   }
2742
2743   int localThetaResolution =  mThetaResolution;
2744   double localStartTheta =  mStartTheta;
2745   double localEndTheta =  mEndTheta;
2746
2747   while ( localEndTheta < localStartTheta ) {
2748     localEndTheta += 360.0;
2749   }
2750
2751   deltaTheta = (localEndTheta - localStartTheta) / localThetaResolution;
2752
2753   // Change the ivars based on pieces.
2754   int start, end;
2755   start = piece * localThetaResolution / numPieces;
2756   end = (piece+1) * localThetaResolution / numPieces;
2757   localEndTheta = localStartTheta + (double)(end) * deltaTheta;
2758   localStartTheta = localStartTheta + (double)(start) * deltaTheta;
2759   localThetaResolution = end - start;
2760
2761   // Create north pole if needed
2762   int number_point = 0;
2763   int number_pointArray = 0;
2764
2765   if ( mStartPhi <= 0.0 ) {
2766     number_pointArray++;
2767     numPoles++;
2768   }
2769   if ( mEndPhi >= 180.0 ) {
2770     number_pointArray++;
2771     numPoles++;
2772   }
2773
2774   // Check data, determine increments, and convert to radians
2775   startTheta = (localStartTheta < localEndTheta ? localStartTheta : localEndTheta);
2776   startTheta *= M_PI  / 180.0;
2777   endTheta = (localEndTheta > localStartTheta ? localEndTheta : localStartTheta);
2778   endTheta *= M_PI  / 180.0;
2779
2780
2781   startPhi = ( mStartPhi <  mEndPhi ?  mStartPhi :  mEndPhi);
2782   startPhi *= M_PI  / 180.0;
2783   endPhi = ( mEndPhi >  mStartPhi ?  mEndPhi :  mStartPhi);
2784   endPhi *= M_PI  / 180.0;
2785
2786   phiResolution =  mPhiResolution - numPoles;
2787   deltaPhi = (endPhi - startPhi) / ( mPhiResolution - 1);
2788   thetaResolution = localThetaResolution;
2789   if ( fabs(localStartTheta - localEndTheta) < 360.0 ) {
2790     ++localThetaResolution;
2791   }
2792   deltaTheta = (endTheta - startTheta) / thetaResolution;
2793
2794   jStart = ( mStartPhi <= 0.0 ? 1 : 0);
2795   jEnd = ( mEndPhi >= 180.0 ?  mPhiResolution - 1 :  mPhiResolution);
2796
2797   // Create intermediate points
2798   for ( i = 0; i < localThetaResolution; i++ ) {
2799     for ( j = jStart; j < jEnd; j++ ) {
2800         number_pointArray++;
2801     }
2802   }
2803
2804   //Generate mesh connectivity
2805   base = phiResolution * localThetaResolution;
2806
2807   int number_triangle = 0 ;
2808   if ( mStartPhi <= 0.0 ) { // around north pole
2809     number_triangle += localThetaResolution;
2810   }
2811
2812   if ( mEndPhi >= 180.0 ) { // around south pole
2813     number_triangle += localThetaResolution;
2814   }
2815
2816   // bands in-between poles
2817   for ( i=0; i < localThetaResolution; i++){
2818     for ( j=0; j < (phiResolution-1); j++){
2819        number_triangle +=2;
2820     }
2821   }
2822
2823   Handle( Poly_Triangulation ) polyTriangulation = new Poly_Triangulation(number_pointArray, number_triangle, false);
2824   TColgp_Array1OfPnt& PointsOfArray = polyTriangulation->ChangeNodes();
2825   Poly_Array1OfTriangle& pArrayTriangle = polyTriangulation->ChangeTriangles();
2826
2827   if (  mStartPhi <= 0.0 ){
2828       x[0] =  mCenter[0];
2829       x[1] =  mCenter[1];
2830       x[2] =  mCenter[2] +  mRadius;
2831       PointsOfArray.SetValue(1,gp_Pnt(x[0],x[1],x[2]));
2832   }
2833
2834   // Create south pole if needed
2835   if (  mEndPhi >= 180.0 ){
2836       x[0] =  mCenter[0];
2837       x[1] =  mCenter[1];
2838       x[2] =  mCenter[2] -  mRadius;
2839       PointsOfArray.SetValue(2,gp_Pnt(x[0],x[1],x[2]));
2840   }
2841
2842   number_point = 3;
2843   for ( i=0; i < localThetaResolution; i++){
2844     theta = localStartTheta * M_PI / 180.0 + i*deltaTheta;
2845     for ( j = jStart; j < jEnd; j++){
2846         phi = startPhi + j*deltaPhi;
2847         radius =  mRadius * sin((double)phi);
2848         n[0] = radius * cos((double)theta);
2849         n[1] = radius * sin((double)theta);
2850         n[2] =  mRadius * cos((double)phi);
2851         x[0] = n[0] +  mCenter[0];
2852         x[1] = n[1] +  mCenter[1];
2853         x[2] = n[2] +  mCenter[2];
2854         PointsOfArray.SetValue(number_point,gp_Pnt(x[0],x[1],x[2]));
2855         number_point++;
2856       }
2857     }
2858
2859   numPoles = 3;
2860   number_triangle = 1;
2861   if ( mStartPhi <= 0.0 ){// around north pole
2862     for (i=0; i < localThetaResolution; i++){
2863         pts[0] = phiResolution*i + numPoles;
2864         pts[1] = (phiResolution*(i+1) % base) + numPoles;
2865         pts[2] = 1;
2866         pArrayTriangle.SetValue(number_triangle,Poly_Triangle(pts[0],pts[1],pts[2]));
2867         number_triangle++;
2868       }
2869     }
2870
2871   if (  mEndPhi >= 180.0 ){ // around south pole
2872     numOffset = phiResolution - 1 + numPoles;
2873     for (i=0; i < localThetaResolution; i++){
2874         pts[0] = phiResolution*i + numOffset;
2875         pts[2] = ((phiResolution*(i+1)) % base) + numOffset;
2876         pts[1] = numPoles - 1;
2877         pArrayTriangle.SetValue(number_triangle,Poly_Triangle(pts[0],pts[1],pts[2]));
2878         number_triangle++;
2879       }
2880     }
2881
2882   // bands in-between poles
2883
2884   for (i=0; i < localThetaResolution; i++){
2885     for (j=0; j < (phiResolution-1); j++){
2886         pts[0] = phiResolution*i + j + numPoles;
2887         pts[1] = pts[0] + 1;
2888         pts[2] = ((phiResolution*(i+1)+j) % base) + numPoles + 1;
2889         pArrayTriangle.SetValue(number_triangle,Poly_Triangle(pts[0],pts[1],pts[2]));
2890         number_triangle++;
2891         pts[1] = pts[2];
2892         pts[2] = pts[1] - 1;
2893         pArrayTriangle.SetValue(number_triangle,Poly_Triangle(pts[0],pts[1],pts[2]));
2894         number_triangle++;
2895       }
2896     }
2897
2898   Poly_Connect* pc = new Poly_Connect(polyTriangulation);
2899
2900   Handle(TShort_HArray1OfShortReal) Normals = new TShort_HArray1OfShortReal(1, polyTriangulation->NbNodes() * 3);
2901
2902   Standard_Integer index[3];
2903   Standard_Real Tol = Precision::Confusion();
2904
2905   gp_Dir Nor;
2906   for (i = PointsOfArray.Lower(); i <= PointsOfArray.Upper(); i++) {
2907       gp_XYZ eqPlan(0, 0, 0);
2908       for ( pc->Initialize(i); pc->More(); pc->Next()) {
2909         pArrayTriangle(pc->Value()).Get(index[0], index[1], index[2]);
2910         gp_XYZ v1(PointsOfArray(index[1]).Coord()-PointsOfArray(index[0]).Coord());
2911         gp_XYZ v2(PointsOfArray(index[2]).Coord()-PointsOfArray(index[1]).Coord());
2912         gp_XYZ vv = v1^v2;
2913         Standard_Real mod = vv.Modulus();
2914         if(mod < Tol) continue;
2915         eqPlan += vv/mod;
2916       }
2917
2918       Standard_Real modmax = eqPlan.Modulus();
2919
2920       if(modmax > Tol)
2921         Nor = gp_Dir(eqPlan);
2922       else
2923         Nor = gp_Dir(0., 0., 1.);
2924       
2925       Standard_Integer k = (i - PointsOfArray.Lower()) * 3;
2926       Normals->SetValue(k + 1, (Standard_ShortReal)Nor.X());
2927       Normals->SetValue(k + 2, (Standard_ShortReal)Nor.Y());
2928       Normals->SetValue(k + 3, (Standard_ShortReal)Nor.Z());
2929   }
2930
2931   delete pc;
2932   polyTriangulation->SetNormals(Normals);
2933
2934   return polyTriangulation;
2935 }
2936
2937 //===============================================================================================
2938 //function : VDrawSphere
2939 //author   : psn
2940 //purpose  : Create an AIS shape.
2941 //===============================================================================================
2942 static int VDrawSphere (Draw_Interpretor& /*di*/, Standard_Integer argc, const char** argv)
2943 {
2944   // check for errors
2945   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
2946   if (aContextAIS.IsNull())
2947   {
2948     std::cout << "Call vinit before!\n";
2949     return 1;
2950   }
2951   else if (argc < 3)
2952   {
2953     std::cout << "Use: " << argv[0]
2954               << " shapeName Fineness [X=0.0 Y=0.0 Z=0.0] [Radius=100.0] [ToShowEdges=0]\n";
2955     return 1;
2956   }
2957
2958   // read the arguments
2959   TCollection_AsciiString aShapeName (argv[1]);
2960   Standard_Integer aResolution = Draw::Atoi (argv[2]);
2961   Standard_Real aCenterX = (argc > 5) ? Draw::Atof (argv[3]) : 0.0;
2962   Standard_Real aCenterY = (argc > 5) ? Draw::Atof (argv[4]) : 0.0;
2963   Standard_Real aCenterZ = (argc > 5) ? Draw::Atof (argv[5]) : 0.0;
2964   Standard_Real aRadius =  (argc > 6) ? Draw::Atof (argv[6]) : 100.0;
2965   Standard_Boolean toShowEdges = (argc > 7) ? Draw::Atoi (argv[7]) == 1 : Standard_False;
2966   Standard_Boolean toPrintInfo = (argc > 8) ? Draw::Atoi (argv[8]) == 1 : Standard_True;
2967
2968   // remove AIS object with given name from map
2969   VDisplayAISObject (aShapeName, Handle(AIS_InteractiveObject)());
2970
2971   if (toPrintInfo)
2972     std::cout << "Compute Triangulation...\n";
2973   Handle(AIS_Triangulation) aShape
2974     = new AIS_Triangulation (CalculationOfSphere (aCenterX, aCenterY, aCenterZ,
2975                                                   aResolution,
2976                                                   aRadius));
2977   Standard_Integer aNumberPoints    = aShape->GetTriangulation()->Nodes().Length();
2978   Standard_Integer aNumberTriangles = aShape->GetTriangulation()->Triangles().Length();
2979
2980   // stupid initialization of Green color in RGBA space as integer
2981   // probably wrong for big-endian CPUs
2982   const Graphic3d_Vec4ub aColor (0, 255, 0, 0);
2983
2984   // setup colors array per vertex
2985   Handle(TColStd_HArray1OfInteger) aColorArray = new TColStd_HArray1OfInteger (1, aNumberPoints);
2986   for (Standard_Integer aNodeId = 1; aNodeId <= aNumberPoints; ++aNodeId)
2987   {
2988     aColorArray->SetValue (aNodeId, *reinterpret_cast<const Standard_Integer*> (aColor.GetData()));
2989   }
2990   aShape->SetColors (aColorArray);
2991
2992   // show statistics
2993   Standard_Integer aPointsSize      = aNumberPoints * 3 * sizeof(float);  // 3x GLfloat
2994   Standard_Integer aNormalsSize     = aNumberPoints * 3 * sizeof(float);  // 3x GLfloat
2995   Standard_Integer aColorsSize      = aNumberPoints * 3 * sizeof(float);  // 3x GLfloat without alpha
2996   Standard_Integer aTrianglesSize   = aNumberTriangles * 3 * sizeof(int); // 3x GLint
2997   Standard_Integer aPolyConnectSize = aNumberPoints * 4 + aNumberTriangles * 6 * 4;
2998   Standard_Integer aTotalSize       = aPointsSize + aNormalsSize + aColorsSize + aTrianglesSize;
2999   aTotalSize >>= 20; //MB
3000   aNormalsSize >>= 20;
3001   aColorsSize >>= 20;
3002   aTrianglesSize >>= 20;
3003   aPolyConnectSize >>= 20;
3004   if (toPrintInfo)
3005   {
3006     std::cout << "NumberOfPoints:    " << aNumberPoints << "\n"
3007       << "NumberOfTriangles: " << aNumberTriangles << "\n"
3008       << "Amount of memory required for PolyTriangulation without Normals: " << (aTotalSize - aNormalsSize) << " Mb\n"
3009       << "Amount of memory for colors: " << aColorsSize << " Mb\n"
3010       << "Amount of memory for PolyConnect: " << aPolyConnectSize << " Mb\n"
3011       << "Amount of graphic card memory required: " << aTotalSize << " Mb\n";
3012   }
3013
3014   // Setting material properties, very important for desirable visual result!
3015   Graphic3d_MaterialAspect aMat (Graphic3d_NOM_PLASTIC);
3016   aMat.SetAmbient  (0.2f);
3017   aMat.SetSpecular (0.5f);
3018   Handle(Graphic3d_AspectFillArea3d) anAspect
3019     = new Graphic3d_AspectFillArea3d (Aspect_IS_SOLID,
3020                                       Quantity_NOC_RED,
3021                                       Quantity_NOC_YELLOW,
3022                                       Aspect_TOL_SOLID,
3023                                       1.0,
3024                                       aMat,
3025                                       aMat);
3026   Handle(Prs3d_ShadingAspect) aShAsp = new Prs3d_ShadingAspect();
3027   if (toShowEdges)
3028   {
3029     anAspect->SetEdgeOn();
3030   }
3031   else
3032   {
3033     anAspect->SetEdgeOff();
3034   }
3035   aShAsp->SetAspect (anAspect);
3036   aShape->Attributes()->SetShadingAspect (aShAsp);
3037
3038   VDisplayAISObject (aShapeName, aShape);
3039   return 0;
3040 }
3041
3042 //=============================================================================
3043 //function : VComputeHLR
3044 //purpose  :
3045 //=============================================================================
3046
3047 static int VComputeHLR (Draw_Interpretor& di,
3048                         Standard_Integer argc,
3049                         const char** argv)
3050 {
3051   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext ();
3052
3053   if (aContextAIS.IsNull ())
3054   {
3055     di << "Please call vinit before\n";
3056     return 1;
3057   }
3058
3059   if ( argc != 3 &&  argc != 12 )
3060   {
3061     di << "Usage: " << argv[0] << " ShapeName HlrName "
3062        << "[ eye_x eye_y eye_z dir_x dir_y dir_z upx upy upz ]\n"
3063        << "                    ShapeName - name of the initial shape\n"
3064        << "                    HlrName - result hlr object from initial shape\n"
3065        << "                    eye, dir are eye position and look direction\n"
3066        << "                    up is the look up direction vector\n"
3067        << "                    Use vtop to see projected hlr shape\n";
3068     return 1;
3069   }
3070
3071   // shape and new object name
3072   TCollection_AsciiString aShapeName (argv[1]);
3073   TCollection_AsciiString aHlrName (argv[2]);
3074
3075   TopoDS_Shape aSh = DBRep::Get (argv[1]);
3076   if (aSh.IsNull()) 
3077   {
3078     BRep_Builder aBrepBuilder;
3079     BRepTools::Read (aSh, argv[1], aBrepBuilder);
3080     if (aSh.IsNull ())
3081     {
3082       di << "No shape with name " << argv[1] << " found\n";
3083       return 1;
3084     }
3085   }
3086
3087   if (GetMapOfAIS ().IsBound2 (aHlrName))
3088   {
3089     di << "Presentable object with name " << argv[2] << " already exists\n";
3090     return 1;
3091   }
3092
3093   Handle(HLRBRep_PolyAlgo) aPolyAlgo = new HLRBRep_PolyAlgo();
3094   HLRBRep_PolyHLRToShape aHLRToShape;
3095
3096   gp_Pnt anEye;
3097   gp_Dir aDir;
3098   gp_Ax2 aProjAx;
3099   if (argc == 9)
3100   {
3101     gp_Dir anUp;
3102
3103     anEye.SetCoord (Draw::Atof (argv[3]), Draw::Atof (argv[4]), Draw::Atof (argv[5]));
3104     aDir.SetCoord (Draw::Atof (argv[6]), Draw::Atof (argv[7]), Draw::Atof (argv[8]));
3105     anUp.SetCoord (Draw::Atof (argv[9]), Draw::Atof (argv[10]), Draw::Atof (argv[11]));
3106     aProjAx.SetLocation (anEye);
3107     aProjAx.SetDirection (aDir);
3108     aProjAx.SetYDirection (anUp);
3109   }
3110   else
3111   {
3112     gp_Dir aRight;
3113
3114     Handle(V3d_Viewer) aViewer = ViewerTest::GetViewerFromContext();
3115     Handle(V3d_View)   aView   = ViewerTest::CurrentView();
3116     Standard_Integer aWidth, aHeight;
3117     Standard_Real aCentX, aCentY, aCentZ, aDirX, aDirY, aDirZ;
3118     Standard_Real aRightX, aRightY, aRightZ;
3119     aView->Window()->Size (aWidth, aHeight);
3120
3121     aView->ConvertWithProj (aWidth, aHeight/2, 
3122                             aRightX, aRightY, aRightZ,
3123                             aDirX, aDirY, aDirZ);
3124
3125     aView->ConvertWithProj (aWidth/2, aHeight/2, 
3126                             aCentX, aCentY, aCentZ,
3127                             aDirX, aDirY, aDirZ);
3128
3129     anEye.SetCoord (-aCentX, -aCentY, -aCentZ);
3130     aDir.SetCoord (-aDirX, -aDirY, -aDirZ);
3131     aRight.SetCoord (aRightX - aCentX, aRightY - aCentY, aRightZ - aCentZ);
3132     aProjAx.SetLocation (anEye);
3133     aProjAx.SetDirection (aDir);
3134     aProjAx.SetXDirection (aRight);
3135   }
3136
3137   HLRAlgo_Projector aProjector (aProjAx);
3138   aPolyAlgo->Projector (aProjector);
3139   aPolyAlgo->Load (aSh);
3140   aPolyAlgo->Update ();
3141
3142   aHLRToShape.Update (aPolyAlgo);
3143
3144   // make hlr shape from input shape
3145   TopoDS_Compound aHlrShape;
3146   BRep_Builder aBuilder;
3147   aBuilder.MakeCompound (aHlrShape);
3148
3149   TopoDS_Shape aCompound = aHLRToShape.VCompound();
3150   if (!aCompound.IsNull ())
3151   {
3152     aBuilder.Add (aHlrShape, aCompound);
3153   }
3154   
3155   // extract visible outlines
3156   aCompound = aHLRToShape.OutLineVCompound();
3157   if (!aCompound.IsNull ())
3158   {
3159     aBuilder.Add (aHlrShape, aCompound);
3160   }
3161
3162   // create an AIS shape and display it
3163   Handle(AIS_Shape) anObject = new AIS_Shape (aHlrShape);
3164   GetMapOfAIS().Bind (anObject, aHlrName);
3165   aContextAIS->Display (anObject, Standard_False);
3166
3167   aContextAIS->UpdateCurrentViewer ();
3168
3169   return 0;
3170 }
3171
3172 // This class is a wrap for Graphic3d_ArrayOfPrimitives; it is used for
3173 // manipulating and displaying such an array with AIS context
3174
3175 class MyPArrayObject : public AIS_InteractiveObject
3176 {
3177
3178 public:
3179
3180   MyPArrayObject (Handle(TColStd_HArray1OfAsciiString) theArrayDescription,
3181                   Handle(Graphic3d_AspectMarker3d) theMarkerAspect = NULL)
3182   {
3183     myArrayDescription = theArrayDescription;
3184     myMarkerAspect = theMarkerAspect;
3185   }
3186
3187   DEFINE_STANDARD_RTTI_INLINE(MyPArrayObject,AIS_InteractiveObject);
3188
3189 private:
3190
3191   void Compute (const Handle(PrsMgr_PresentationManager3d)& aPresentationManager,
3192                 const Handle(Prs3d_Presentation)& aPresentation,
3193                 const Standard_Integer aMode) Standard_OVERRIDE;
3194
3195   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
3196                          const Standard_Integer /*theMode*/) Standard_OVERRIDE;
3197
3198   bool CheckInputCommand (const TCollection_AsciiString theCommand,
3199                           const Handle(TColStd_HArray1OfAsciiString) theArgsArray,
3200                           Standard_Integer &theArgIndex,
3201                           Standard_Integer theArgCount,
3202                           Standard_Integer theMaxArgs);
3203
3204 protected:
3205
3206   Handle(TColStd_HArray1OfAsciiString) myArrayDescription;
3207   Handle(Graphic3d_AspectMarker3d) myMarkerAspect;
3208
3209 };
3210
3211
3212 void MyPArrayObject::Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPresentationManager*/,
3213                               const Handle(Prs3d_Presentation)& aPresentation,
3214                               const Standard_Integer /*aMode*/)
3215 {
3216
3217   // Parsing array description
3218   Standard_Integer aVertexNum = 0, aBoundNum = 0, aEdgeNum = 0;
3219   Standard_Boolean hasVColors, hasBColors, hasNormals, hasTexels;
3220   hasVColors = hasNormals = hasBColors = hasTexels = Standard_False;
3221
3222   Standard_Integer anArgIndex = 0;
3223   Standard_Integer anArgsCount = myArrayDescription->Length();
3224   TCollection_AsciiString anArrayType = myArrayDescription->Value (anArgIndex++);
3225
3226   TCollection_AsciiString aCommand;
3227   while (anArgIndex < anArgsCount)
3228   {
3229     aCommand = myArrayDescription->Value (anArgIndex);
3230     aCommand.LowerCase();
3231
3232     // vertex command
3233     if (CheckInputCommand ("v", myArrayDescription, anArgIndex, 3, anArgsCount))
3234     {
3235       // vertex has a normal or normal with color or texel
3236       if (CheckInputCommand ("n", myArrayDescription, anArgIndex, 3, anArgsCount))
3237         hasNormals = Standard_True;
3238
3239       // vertex has a color
3240       if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
3241         hasVColors = Standard_True;
3242
3243       // vertex has a texel
3244       if (CheckInputCommand ("t", myArrayDescription, anArgIndex, 2, anArgsCount))
3245         hasTexels = Standard_True;
3246
3247       aVertexNum++;
3248     }
3249     // bound command
3250     else if (CheckInputCommand ("b", myArrayDescription, anArgIndex, 1, anArgsCount))
3251     {
3252       // bound has color
3253       if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
3254         hasBColors = Standard_True;
3255
3256       aBoundNum++;
3257     }
3258     // edge command
3259     else if (CheckInputCommand ("e", myArrayDescription, anArgIndex, 1, anArgsCount))
3260     {
3261       aEdgeNum++;
3262     }
3263     // unknown command
3264     else
3265       anArgIndex++;
3266   }
3267
3268   Handle(Graphic3d_ArrayOfPrimitives) anArray;
3269   if (anArrayType == "points")
3270   {
3271     anArray = new Graphic3d_ArrayOfPoints (aVertexNum);
3272   }
3273   else if (anArrayType == "segments")
3274     anArray = new Graphic3d_ArrayOfSegments (aVertexNum, aEdgeNum, hasVColors);
3275   else if (anArrayType == "polylines")
3276     anArray = new Graphic3d_ArrayOfPolylines (aVertexNum, aBoundNum, aEdgeNum,
3277                                               hasVColors, hasBColors);
3278   else if (anArrayType == "triangles")
3279     anArray = new Graphic3d_ArrayOfTriangles (aVertexNum, aEdgeNum, hasNormals,
3280                                               hasVColors, hasTexels);
3281   else if (anArrayType == "trianglefans")
3282     anArray = new Graphic3d_ArrayOfTriangleFans (aVertexNum, aBoundNum,
3283                                                  hasNormals, hasVColors,
3284                                                  hasBColors, hasTexels);
3285   else if (anArrayType == "trianglestrips")
3286     anArray = new Graphic3d_ArrayOfTriangleStrips (aVertexNum, aBoundNum,
3287                                                    hasNormals, hasVColors,
3288                                                    hasBColors, hasTexels);
3289   else if (anArrayType == "quads")
3290     anArray = new Graphic3d_ArrayOfQuadrangles (aVertexNum, aEdgeNum,
3291                                                 hasNormals, hasVColors,
3292                                                 hasTexels);
3293   else if (anArrayType == "quadstrips")
3294     anArray = new Graphic3d_ArrayOfQuadrangleStrips (aVertexNum, aBoundNum,
3295                                                      hasNormals, hasVColors,
3296                                                      hasBColors, hasTexels);
3297   else if (anArrayType == "polygons")
3298     anArray = new Graphic3d_ArrayOfPolygons (aVertexNum, aBoundNum, aEdgeNum,
3299                                              hasNormals, hasVColors, hasBColors,
3300                                              hasTexels);
3301
3302   anArgIndex = 1;
3303   while (anArgIndex < anArgsCount)
3304   {
3305     aCommand = myArrayDescription->Value (anArgIndex);
3306     aCommand.LowerCase();
3307     if (!aCommand.IsAscii())
3308       break;
3309
3310     // vertex command
3311     if (CheckInputCommand ("v", myArrayDescription, anArgIndex, 3, anArgsCount))
3312     {
3313       anArray->AddVertex (myArrayDescription->Value (anArgIndex - 3).RealValue(),
3314                           myArrayDescription->Value (anArgIndex - 2).RealValue(),
3315                           myArrayDescription->Value (anArgIndex - 1).RealValue());
3316       const Standard_Integer aVertIndex = anArray->VertexNumber();
3317
3318       // vertex has a normal or normal with color or texel
3319       if (CheckInputCommand ("n", myArrayDescription, anArgIndex, 3, anArgsCount))
3320         anArray->SetVertexNormal (aVertIndex,
3321                                   myArrayDescription->Value (anArgIndex - 3).RealValue(),
3322                                   myArrayDescription->Value (anArgIndex - 2).RealValue(),
3323                                   myArrayDescription->Value (anArgIndex - 1).RealValue());
3324       
3325       if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
3326         anArray->SetVertexColor (aVertIndex,
3327                                  myArrayDescription->Value (anArgIndex - 3).RealValue(),
3328                                  myArrayDescription->Value (anArgIndex - 2).RealValue(),
3329                                  myArrayDescription->Value (anArgIndex - 1).RealValue());
3330       
3331       if (CheckInputCommand ("t", myArrayDescription, anArgIndex, 2, anArgsCount))
3332         anArray->SetVertexTexel (aVertIndex,
3333                                  myArrayDescription->Value (anArgIndex - 2).RealValue(),
3334                                  myArrayDescription->Value (anArgIndex - 1).RealValue());
3335     }
3336     // bounds command
3337     else if (CheckInputCommand ("b", myArrayDescription, anArgIndex, 1, anArgsCount))
3338     {
3339       Standard_Integer aVertCount = myArrayDescription->Value (anArgIndex - 1).IntegerValue();
3340
3341       if (CheckInputCommand ("c", myArrayDescription, anArgIndex, 3, anArgsCount))
3342         anArray->AddBound (aVertCount,
3343                            myArrayDescription->Value (anArgIndex - 3).RealValue(),
3344                            myArrayDescription->Value (anArgIndex - 2).RealValue(),
3345                            myArrayDescription->Value (anArgIndex - 1).RealValue());
3346
3347       else
3348         anArray->AddBound (aVertCount);
3349     }
3350     // edge command
3351     else if (CheckInputCommand ("e", myArrayDescription, anArgIndex, 1, anArgsCount))
3352     {
3353       const Standard_Integer aVertIndex = myArrayDescription->Value (anArgIndex - 1).IntegerValue();
3354       anArray->AddEdge (aVertIndex);
3355     }
3356     // unknown command
3357     else
3358       anArgIndex++;
3359   }
3360
3361   aPresentation->Clear();
3362   if (!myMarkerAspect.IsNull())
3363   {
3364     Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myMarkerAspect);
3365   }
3366   Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myDrawer->LineAspect()->Aspect());
3367   Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myDrawer->ShadingAspect()->Aspect());
3368   Prs3d_Root::CurrentGroup (aPresentation)->AddPrimitiveArray (anArray);
3369 }
3370
3371 void MyPArrayObject::ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
3372                                        const Standard_Integer /*theMode*/)
3373 {
3374   Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner (this);
3375
3376   Standard_Integer anArgIndex = 1;
3377   while (anArgIndex < myArrayDescription->Length())
3378   {
3379     if (CheckInputCommand ("v", myArrayDescription, anArgIndex, 3, myArrayDescription->Length()))
3380     {
3381       gp_Pnt aPoint (myArrayDescription->Value (anArgIndex - 3).RealValue(),
3382                      myArrayDescription->Value (anArgIndex - 2).RealValue(),
3383                      myArrayDescription->Value (anArgIndex - 1).RealValue());
3384       Handle(Select3D_SensitivePoint) aSensetivePoint = new Select3D_SensitivePoint (anEntityOwner, aPoint);
3385       theSelection->Add (aSensetivePoint);
3386     }
3387     else
3388     {
3389       anArgIndex++;
3390     }
3391   }
3392 }
3393
3394 bool MyPArrayObject::CheckInputCommand (const TCollection_AsciiString theCommand,
3395                                        const Handle(TColStd_HArray1OfAsciiString) theArgsArray,
3396                                        Standard_Integer &theArgIndex,
3397                                        Standard_Integer theArgCount,
3398                                        Standard_Integer theMaxArgs)
3399 {
3400   // check if there is more elements than expected
3401   if (theArgIndex >= theMaxArgs)
3402     return false;
3403
3404   TCollection_AsciiString aStrCommand = theArgsArray->Value (theArgIndex);
3405   aStrCommand.LowerCase();
3406   if (aStrCommand.Search(theCommand) != 1 ||
3407       theArgIndex + (theArgCount - 1) >= theMaxArgs)
3408     return false;
3409
3410   // go to the first data element
3411   theArgIndex++;
3412
3413   // check data if it can be converted to numeric
3414   for (int aElement = 0; aElement < theArgCount; aElement++, theArgIndex++)
3415   {
3416     aStrCommand = theArgsArray->Value (theArgIndex);
3417     if (!aStrCommand.IsRealValue())
3418       return false;
3419   }
3420
3421   return true;
3422 }
3423
3424 //=============================================================================
3425 //function : VDrawPArray
3426 //purpose  : Draws primitives array from list of vertexes, bounds, edges
3427 //=============================================================================
3428
3429 static int VDrawPArray (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
3430 {
3431   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
3432   if (aContextAIS.IsNull())
3433   {
3434     di << "Call vinit before!\n";
3435     return 1;
3436   }
3437   else if (argc < 3)
3438   {
3439     di << "Use: " << argv[0] << " Name TypeOfArray"
3440        << " [vertex] ... [bounds] ... [edges]\n"
3441        << "  TypeOfArray={ points | segments | polylines | triangles |\n"
3442        << "                trianglefans | trianglestrips | quads |\n"
3443        << "                quadstrips | polygons }\n"
3444        << "  vertex={ 'v' x y z [normal={ 'n' nx ny nz }] [color={ 'c' r g b }]"
3445        << " [texel={ 't' tx ty }] } \n"
3446        << "  bounds={ 'b' verticies_count [color={ 'c' r g b }] }\n"
3447        << "  edges={ 'e' vertex_id }\n";
3448     return 1;
3449   }
3450
3451   // read the arguments
3452   Standard_Integer aArgIndex = 1;
3453   TCollection_AsciiString aName (argv[aArgIndex++]);
3454   TCollection_AsciiString anArrayType (argv[aArgIndex++]);
3455
3456   Standard_Boolean hasVertex = Standard_False;
3457
3458   Handle(TColStd_HArray1OfAsciiString) anArgsArray = new TColStd_HArray1OfAsciiString (0, argc - 2);
3459   anArgsArray->SetValue (0, anArrayType);
3460
3461   if (anArrayType != "points"         &&
3462       anArrayType != "segments"       &&
3463       anArrayType != "polylines"      &&
3464       anArrayType != "triangles"      &&
3465       anArrayType != "trianglefans"   &&
3466       anArrayType != "trianglestrips" &&
3467       anArrayType != "quads"          &&
3468       anArrayType != "quadstrips"     &&
3469       anArrayType != "polygons")
3470   {
3471     di << "Unexpected type of primitives array\n";
3472     return 1;
3473   }
3474
3475   TCollection_AsciiString aCommand;
3476   for (Standard_Integer anArgIndex = 3; anArgIndex < argc; anArgIndex++)
3477   {
3478     aCommand = argv[anArgIndex];
3479     aCommand.LowerCase();
3480     if (!aCommand.IsAscii())
3481     {
3482       di << "Unexpected argument: #" << aArgIndex - 1 << " , "
3483          << "should be an array element: 'v', 'b', 'e' \n";
3484       break;
3485     }
3486
3487     if (aCommand == "v")
3488     {
3489       hasVertex = Standard_True;
3490     }
3491
3492     anArgsArray->SetValue (anArgIndex - 2, aCommand);
3493   }
3494
3495   if (!hasVertex)
3496   {
3497     di << "You should pass any verticies in the list of array elements\n";
3498     return 1;
3499   }
3500
3501   Handle(Graphic3d_AspectMarker3d)    anAspPoints;
3502   if (anArrayType == "points")
3503   {
3504     anAspPoints = new Graphic3d_AspectMarker3d (Aspect_TOM_POINT, Quantity_NOC_YELLOW, 1.0f);
3505   }
3506
3507   // create primitives array object
3508   Handle(MyPArrayObject) aPObject = new MyPArrayObject (anArgsArray, anAspPoints);
3509
3510   // register the object in map
3511   VDisplayAISObject (aName, aPObject);
3512
3513   return 0;
3514 }
3515
3516 namespace
3517 {
3518   //! Auxiliary function for parsing translation vector - either 2D or 3D.
3519   static Standard_Integer parseTranslationVec (Standard_Integer theArgNb,
3520                                                const char**     theArgVec,
3521                                                gp_Vec&          theVec)
3522   {
3523     if (theArgNb < 2)
3524     {
3525       return 0;
3526     }
3527
3528     TCollection_AsciiString anX (theArgVec[0]);
3529     TCollection_AsciiString anY (theArgVec[1]);
3530     if (!anX.IsRealValue()
3531      || !anY.IsRealValue())
3532     {
3533       return 0;
3534     }
3535
3536     theVec.SetX (anX.RealValue());
3537     theVec.SetY (anY.RealValue());
3538     if (theArgNb >= 3)
3539     {
3540       TCollection_AsciiString anZ (theArgVec[2]);
3541       if (anZ.IsRealValue())
3542       {
3543         theVec.SetZ (anZ.RealValue());
3544         return 3;
3545       }
3546     }
3547     return 2;
3548   }
3549 }
3550
3551 //=======================================================================
3552 //function : VSetLocation
3553 //purpose  : Change location of AIS interactive object
3554 //=======================================================================
3555
3556 static Standard_Integer VSetLocation (Draw_Interpretor& theDI,
3557                                       Standard_Integer  theArgNb,
3558                                       const char**      theArgVec)
3559 {
3560   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
3561   ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
3562   if (aContext.IsNull())
3563   {
3564     std::cout << "Error: no active view!\n";
3565     return 1;
3566   }
3567
3568   Standard_Boolean toPrintInfo = Standard_True;
3569   Handle(AIS_InteractiveObject) anObj;
3570   TCollection_AsciiString aCmdName (theArgVec[0]);
3571   aCmdName.LowerCase();
3572   for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
3573   {
3574     TCollection_AsciiString anArg = theArgVec[anArgIter];
3575     anArg.LowerCase();
3576     if (anUpdateTool.parseRedrawMode (anArg))
3577     {
3578       continue;
3579     }
3580     else if (anObj.IsNull())
3581     {
3582       const TCollection_AsciiString aName (theArgVec[anArgIter]);
3583       const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
3584       if (aMap.IsBound2 (aName))
3585       {
3586         anObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (aName));
3587       }
3588       if (anObj.IsNull())
3589       {
3590         std::cout << "Error: object '" << aName << "' is not displayed!\n";
3591         return 1;
3592       }
3593     }
3594     else if (anArg == "-reset")
3595     {
3596       toPrintInfo = Standard_False;
3597       aContext->SetLocation (anObj, gp_Trsf());
3598     }
3599     else if (anArg == "-copyfrom"
3600           || anArg == "-copy")
3601     {
3602       if (anArgIter + 1 >= theArgNb)
3603       {
3604         std::cout << "Syntax error at '" << anArg << "'\n";
3605         return 1;
3606       }
3607
3608       const TCollection_AsciiString aName2 (theArgVec[anArgIter + 1]);
3609       const ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
3610       Handle(AIS_InteractiveObject) anObj2;
3611       if (aMap.IsBound2 (aName2))
3612       {
3613         anObj2 = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (aName2));
3614       }
3615       if (anObj2.IsNull())
3616       {
3617         std::cout << "Error: object '" << aName2 << "' is not displayed!\n";
3618         return 1;
3619       }
3620
3621       ++anArgIter;
3622       aContext->SetLocation (anObj, anObj2->LocalTransformation());
3623     }
3624     else if (anArg == "-rotate")
3625     {
3626       toPrintInfo = Standard_False;
3627       if (anArgIter + 7 >= theArgNb)
3628       {
3629         std::cout << "Syntax error at '" << anArg << "'\n";
3630         return 1;
3631       }
3632
3633       gp_Trsf aTrsf;
3634       aTrsf.SetRotation (gp_Ax1 (gp_Pnt (Draw::Atof (theArgVec[anArgIter + 1]),
3635                                          Draw::Atof (theArgVec[anArgIter + 2]),
3636                                          Draw::Atof (theArgVec[anArgIter + 3])),
3637                                  gp_Vec (Draw::Atof (theArgVec[anArgIter + 4]),
3638                                          Draw::Atof (theArgVec[anArgIter + 5]),
3639                                          Draw::Atof (theArgVec[anArgIter + 6]))),
3640                                          Draw::Atof (theArgVec[anArgIter + 7]) * (M_PI / 180.0));
3641       anArgIter += 7;
3642
3643       aTrsf = anObj->LocalTransformation() * aTrsf;
3644       aContext->SetLocation (anObj, aTrsf);
3645     }
3646     else if (anArg == "-translate")
3647     {
3648       toPrintInfo = Standard_False;
3649       gp_Vec aLocVec;
3650       Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter - 1, theArgVec + anArgIter + 1, aLocVec);
3651       anArgIter += aNbParsed;
3652       if (aNbParsed == 0)
3653       {
3654         std::cout << "Syntax error at '" << anArg << "'\n";
3655         return 1;
3656       }
3657
3658       gp_Trsf aTrsf;
3659       aTrsf.SetTranslationPart (aLocVec);
3660       aTrsf = anObj->LocalTransformation() * aTrsf;
3661       aContext->SetLocation (anObj, aTrsf);
3662     }
3663     else if (anArg == "-scale"
3664           || anArg == "-setscale")
3665     {
3666       toPrintInfo = Standard_False;
3667       gp_XYZ aScaleLoc;
3668       Standard_Real aScale = 1.0;
3669       Standard_Boolean toPrintScale = Standard_True;
3670       Standard_Boolean hasScaleLoc  = Standard_False;
3671       if (anArgIter + 4 < theArgNb)
3672       {
3673         TCollection_AsciiString aScaleArgs[4] =
3674         {
3675           TCollection_AsciiString (theArgVec[anArgIter + 1]),
3676           TCollection_AsciiString (theArgVec[anArgIter + 2]),
3677           TCollection_AsciiString (theArgVec[anArgIter + 3]),
3678           TCollection_AsciiString (theArgVec[anArgIter + 4])
3679         };
3680         Standard_Integer aScaleArgIter = 0;
3681         for (; aScaleArgIter < 4; ++aScaleArgIter)
3682         {
3683           if (!aScaleArgs[aScaleArgIter].IsRealValue())
3684           {
3685             break;
3686           }
3687         }
3688         if (aScaleArgIter == 4)
3689         {
3690           aScaleLoc.SetCoord (aScaleArgs[0].RealValue(), aScaleArgs[1].RealValue(), aScaleArgs[2].RealValue());
3691           aScale = aScaleArgs[3].RealValue();
3692           anArgIter += 4;
3693           toPrintScale = Standard_False;
3694           hasScaleLoc  = Standard_True;
3695         }
3696         else if (aScaleArgIter >= 1)
3697         {
3698           aScale = aScaleArgs[0].RealValue();
3699           ++anArgIter;
3700           toPrintScale = Standard_False;
3701         }
3702       }
3703       else if (anArgIter + 1 < theArgNb)
3704       {
3705         TCollection_AsciiString aScaleArg (theArgVec[anArgIter + 1]);
3706         if (aScaleArg.IsRealValue())
3707         {
3708           aScale = aScaleArg.RealValue();
3709           ++anArgIter;
3710           toPrintScale = Standard_False;
3711         }
3712       }
3713
3714       if (toPrintScale)
3715       {
3716         if (anArg == "-setscale")
3717         {
3718           std::cout << "Syntax error at '" << anArg << "'\n";
3719           return 1;
3720         }
3721
3722         char aText[1024];
3723         Sprintf (aText, "%g ", anObj->LocalTransformation().ScaleFactor());
3724         theDI << aText;
3725         continue;
3726       }
3727
3728       if (anArg == "-setscale")
3729       {
3730         gp_Trsf aTrsf = anObj->LocalTransformation();
3731         if (hasScaleLoc)
3732         {
3733           aTrsf.SetScale (aScaleLoc, aScale);
3734         }
3735         else
3736         {
3737           aTrsf.SetScaleFactor (aScale);
3738         }
3739         aContext->SetLocation (anObj, aTrsf);
3740       }
3741       else
3742       {
3743         gp_Trsf aTrsf;
3744         if (hasScaleLoc)
3745         {
3746           aTrsf.SetScale (aScaleLoc, aScale);
3747           aTrsf = anObj->LocalTransformation() * aTrsf;
3748         }
3749         else
3750         {
3751           aTrsf = anObj->LocalTransformation();
3752           aTrsf.SetScaleFactor (aTrsf.ScaleFactor() * aScale);
3753         }
3754         aContext->SetLocation (anObj, aTrsf);
3755       }
3756     }
3757     else if (anArg == "-mirror")
3758     {
3759       toPrintInfo = Standard_False;
3760       if (anArgIter + 6 >= theArgNb)
3761       {
3762         std::cout << "Syntax error at '" << anArg << "'\n";
3763         return 1;
3764       }
3765
3766       gp_Trsf aTrsf;
3767       aTrsf.SetMirror (gp_Ax2 (gp_Pnt (Draw::Atof(theArgVec[theArgNb - 6]),
3768                                        Draw::Atof(theArgVec[theArgNb - 5]),
3769                                        Draw::Atof(theArgVec[theArgNb - 4])),
3770                                gp_Vec (Draw::Atof(theArgVec[theArgNb - 3]),
3771                                        Draw::Atof(theArgVec[theArgNb - 2]),
3772                                        Draw::Atof(theArgVec[theArgNb - 1]))));
3773       anArgIter += 6;
3774       aTrsf = anObj->LocalTransformation() * aTrsf;
3775       aContext->SetLocation (anObj, aTrsf);
3776     }
3777     else if (anArg == "-setrotation"
3778           || anArg == "-rotation")
3779     {
3780       toPrintInfo = Standard_False;
3781       if (anArgIter + 4 < theArgNb)
3782       {
3783         TCollection_AsciiString aQuatArgs[4] =
3784         {
3785           TCollection_AsciiString (theArgVec[anArgIter + 1]),
3786           TCollection_AsciiString (theArgVec[anArgIter + 2]),
3787           TCollection_AsciiString (theArgVec[anArgIter + 3]),
3788           TCollection_AsciiString (theArgVec[anArgIter + 4])
3789         };
3790         Standard_Integer aQuatArgIter = 0;
3791         for (; aQuatArgIter < 4; ++aQuatArgIter)
3792         {
3793           if (!aQuatArgs[aQuatArgIter].IsRealValue())
3794           {
3795             break;
3796           }
3797         }
3798
3799         if (aQuatArgIter == 4)
3800         {
3801           anArgIter += 4;
3802           const gp_Quaternion aQuat (aQuatArgs[0].RealValue(),
3803                                      aQuatArgs[1].RealValue(),
3804                                      aQuatArgs[2].RealValue(),
3805                                      aQuatArgs[3].RealValue());
3806           gp_Trsf aTrsf = anObj->LocalTransformation();
3807           aTrsf.SetRotation (aQuat);
3808           aContext->SetLocation (anObj, aTrsf);
3809           continue;
3810         }
3811         else if (anArg == "-setrotation")
3812         {
3813           std::cout << "Syntax error at '" << anArg << "'\n";
3814           return 1;
3815         }
3816       }
3817
3818       char aText[1024];
3819       const gp_Quaternion aQuat = anObj->LocalTransformation().GetRotation();
3820       Sprintf (aText, "%g %g %g %g ", aQuat.X(), aQuat.Y(), aQuat.Z(), aQuat.W());
3821       theDI << aText;
3822     }
3823     else if (anArg == "-setlocation"
3824           || anArg == "-location")
3825     {
3826       toPrintInfo = Standard_False;
3827       gp_Vec aLocVec;
3828       Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter - 1, theArgVec + anArgIter + 1, aLocVec);
3829       anArgIter += aNbParsed;
3830       if (aNbParsed != 0)
3831       {
3832         gp_Trsf aTrsf = anObj->LocalTransformation();
3833         aTrsf.SetTranslationPart (aLocVec);
3834         aContext->SetLocation (anObj, aTrsf);
3835       }
3836       else if (anArg == "-setlocation")
3837       {
3838         std::cout << "Syntax error at '" << anArg << "'\n";
3839         return 1;
3840       }
3841
3842       char aText[1024];
3843       const gp_XYZ aLoc = anObj->LocalTransformation().TranslationPart();
3844       Sprintf (aText, "%g %g %g ", aLoc.X(), aLoc.Y(), aLoc.Z());
3845       theDI << aText;
3846     }
3847     else if (aCmdName == "vsetlocation")
3848     {
3849       // compatibility with old syntax
3850       gp_Vec aLocVec;
3851       Standard_Integer aNbParsed = parseTranslationVec (theArgNb - anArgIter, theArgVec + anArgIter, aLocVec);
3852       if (aNbParsed == 0)
3853       {
3854         std::cout << "Syntax error at '" << anArg << "'\n";
3855         return 1;
3856       }
3857       anArgIter = anArgIter + aNbParsed - 1;
3858
3859       gp_Trsf aTrsf;
3860       aTrsf.SetTranslationPart (aLocVec);
3861       aContext->SetLocation (anObj, aTrsf);
3862       toPrintInfo = Standard_False;
3863     }
3864     else
3865     {
3866       std::cout << "Error: unknown argument '" << anArg << "'\n";
3867       return 1;
3868     }
3869   }
3870
3871   if (anObj.IsNull())
3872   {
3873     std::cout << "Syntax error - wrong number of arguments\n";
3874     return 1;
3875   }
3876   else if (!toPrintInfo)
3877   {
3878     return 0;
3879   }
3880
3881   const gp_Trsf       aTrsf = anObj->LocalTransformation();
3882   const gp_XYZ        aLoc  = aTrsf.TranslationPart();
3883   const gp_Quaternion aRot  = aTrsf.GetRotation();
3884   char aText[4096];
3885   Sprintf (aText, "Location: %g %g %g\n"
3886                   "Rotation: %g %g %g %g\n"
3887                   "Scale:    %g\n",
3888                   aLoc.X(), aLoc.Y(), aLoc.Z(),
3889                   aRot.X(), aRot.Y(), aRot.Z(), aRot.W(),
3890                   aTrsf.ScaleFactor());
3891   theDI << aText;
3892   return 0;
3893 }
3894
3895 //===============================================================================================
3896 //function : VConnect
3897 //purpose  : Creates and displays AIS_ConnectedInteractive object from input object and location 
3898 //Draw arg : vconnect name Xo Yo Zo object1 object2 ... [color=NAME]
3899 //===============================================================================================
3900
3901 static Standard_Integer VConnect (Draw_Interpretor& /*di*/, 
3902                                   Standard_Integer argc, 
3903                                   const char ** argv) 
3904 {
3905   // Check the viewer
3906   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
3907   if (aContext.IsNull())
3908   {
3909     std::cout << "vconnect error : call vinit before\n";
3910     return 1; // TCL_ERROR
3911   }
3912   // Check argumnets 
3913   if (argc < 6)
3914   {
3915     std::cout << "vconnect error: expect at least 5 arguments\n";
3916     return 1; // TCL_ERROR
3917   }
3918
3919   // Get values
3920   Standard_Integer anArgIter = 1;
3921   TCollection_AsciiString aName (argv[anArgIter++]);
3922   Handle(AIS_MultipleConnectedInteractive) anOriginObject;
3923   TCollection_AsciiString aColorString (argv[argc-1]);
3924   Standard_CString aColorName = "";
3925   Standard_Boolean hasColor = Standard_False;
3926   if (aColorString.Search ("color=") != -1)
3927   {
3928     hasColor = Standard_True;
3929     aColorString.Remove (1, 6);
3930     aColorName = aColorString.ToCString();
3931   }
3932   Handle(AIS_InteractiveObject) anObject;
3933
3934   // AIS_MultipleConnectedInteractive
3935   const Standard_Integer aNbShapes = hasColor ? (argc - 1) : argc;
3936   for (Standard_Integer i = 5; i < aNbShapes; ++i)
3937   {
3938     TCollection_AsciiString anOriginObjectName (argv[i]);
3939     if (aName.IsEqual (anOriginObjectName))
3940     {
3941       std::cout << "vconnect error: equal names for connected objects\n";
3942       continue;
3943     }
3944     if (GetMapOfAIS().IsBound2 (anOriginObjectName))
3945     {
3946       Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (anOriginObjectName);
3947       anObject = Handle(AIS_InteractiveObject)::DownCast(anObj);
3948       if (anObject.IsNull())
3949       {
3950         std::cout << "Object " << anOriginObjectName << " is used for non AIS viewer\n";
3951         continue;
3952       }
3953     }
3954     else
3955     {
3956       Standard_CString aOriginName = anOriginObjectName.ToCString();
3957       TopoDS_Shape aTDShape = DBRep::Get (aOriginName);
3958       if (aTDShape.IsNull())
3959       {
3960         std::cout << "vconnect error: object " << anOriginObjectName << " doesn't exist\n";
3961         continue;
3962       }
3963       anObject = new AIS_Shape (aTDShape);
3964       aContext->Load (anObject);
3965       anObject->SetColor (ViewerTest::GetColorFromName (aColorName));
3966     }
3967
3968     if (anOriginObject.IsNull())
3969     {
3970       anOriginObject = new AIS_MultipleConnectedInteractive();
3971     }
3972
3973     anOriginObject->Connect (anObject);
3974   }
3975   if (anOriginObject.IsNull())
3976   {
3977     std::cout << "vconect error : can't connect input objects\n";
3978     return 1; // TCL_ERROR
3979   }
3980
3981   // Get location data
3982   Standard_Real aXo = Draw::Atof (argv[anArgIter++]);
3983   Standard_Real aYo = Draw::Atof (argv[anArgIter++]);
3984   Standard_Real aZo = Draw::Atof (argv[anArgIter++]);
3985
3986   // Create transformation
3987   gp_Vec aTranslation (aXo, aYo, aZo);
3988
3989   gp_Trsf aTrsf; 
3990   aTrsf.SetTranslationPart (aTranslation);
3991   TopLoc_Location aLocation (aTrsf);
3992
3993   anOriginObject->SetLocalTransformation (aTrsf);
3994
3995   // Check if there is another object with given name
3996   // and remove it from context
3997   if(GetMapOfAIS().IsBound2(aName))
3998   {
3999     Handle(AIS_InteractiveObject) anObj = 
4000       Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(aName));
4001     TheAISContext()->Remove(anObj, Standard_False);
4002     GetMapOfAIS().UnBind2(aName);
4003   }
4004
4005   // Bind connected object to its name
4006   GetMapOfAIS().Bind (anOriginObject, aName);
4007
4008   // Display connected object
4009   TheAISContext()->Display (anOriginObject, Standard_True);
4010
4011   return 0;
4012 }
4013
4014 //===============================================================================================
4015 //function : VConnectTo
4016 //purpose  : Creates and displays AIS_ConnectedInteractive object from input object and location 
4017 //Draw arg : vconnectto name Xo Yo Zo object [-nodisplay|-noupdate|-update]
4018 //===============================================================================================
4019
4020 static Standard_Integer VConnectTo (Draw_Interpretor& /*di*/, 
4021                                     Standard_Integer argc, 
4022                                     const char ** argv) 
4023 {
4024   // Check the viewer
4025   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4026   ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
4027   if (aContext.IsNull())
4028   {
4029     std::cout << "vconnect error : call vinit before\n";
4030     return 1; // TCL_ERROR
4031   }
4032   // Check argumnets 
4033   if (argc != 6 && argc != 7)
4034   {
4035     std::cout << "vconnect error: expect at least 5 arguments\n";
4036     return 1; // TCL_ERROR
4037   }
4038
4039   // Get values
4040   Standard_Integer anArgIter = 1;
4041   TCollection_AsciiString aName (argv[anArgIter++]);
4042   Handle(AIS_InteractiveObject) anOriginObject;
4043
4044   TCollection_AsciiString anOriginObjectName(argv[5]);
4045   if (aName.IsEqual (anOriginObjectName))
4046   {
4047     std::cout << "vconnect error: equal names for connected objects\n"; 
4048     return 1; // TCL_ERROR
4049   }
4050   if (GetMapOfAIS().IsBound2 (anOriginObjectName))
4051   {
4052     Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (anOriginObjectName);
4053     anOriginObject = Handle(AIS_InteractiveObject)::DownCast(anObj);
4054     if (anOriginObject.IsNull())
4055     {
4056       std::cout << "Object " << anOriginObjectName << " is used for non AIS viewer\n";
4057       return 1; // TCL_ERROR
4058     }
4059   }
4060   else
4061   {
4062     Standard_CString aOriginName = anOriginObjectName.ToCString();
4063     TopoDS_Shape aTDShape = DBRep::Get (aOriginName);
4064     if (aTDShape.IsNull())
4065     {
4066       std::cout << "vconnect error: object " << anOriginObjectName << " doesn't exist\n";
4067       return 1; // TCL_ERROR
4068     }
4069     anOriginObject = new AIS_Shape (aTDShape);
4070     GetMapOfAIS().Bind (anOriginObject, anOriginObjectName);
4071   }
4072  
4073   // Get location data
4074   Standard_Real aXo = Draw::Atof (argv[anArgIter++]);
4075   Standard_Real aYo = Draw::Atof (argv[anArgIter++]);
4076   Standard_Real aZo = Draw::Atof (argv[anArgIter++]);
4077
4078   // Create transformation
4079   gp_Vec aTranslation (aXo, aYo, aZo);
4080
4081   gp_Trsf aTrsf; 
4082   aTrsf.SetTranslationPart (aTranslation);
4083  
4084   Handle(AIS_ConnectedInteractive) aConnected;
4085
4086   aConnected = new AIS_ConnectedInteractive();
4087
4088   aConnected->Connect (anOriginObject, aTrsf);
4089
4090   // Check if there is another object with given name
4091   // and remove it from context
4092   if(GetMapOfAIS().IsBound2(aName))
4093   {
4094     Handle(AIS_InteractiveObject) anObj = 
4095       Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(aName));
4096     TheAISContext()->Remove(anObj, Standard_False);
4097     GetMapOfAIS().UnBind2(aName);
4098   }
4099
4100   // Bind connected object to its name
4101   GetMapOfAIS().Bind (aConnected, aName);
4102
4103   if (argc == 7)
4104   {
4105     TCollection_AsciiString anArg = argv[6];
4106     anArg.LowerCase();
4107     if (anArg == "-nodisplay")
4108       return 0;
4109
4110     if (!anUpdateTool.parseRedrawMode (anArg))
4111     {
4112       std::cout << "Warning! Unknown argument '" << anArg << "' passed, -nodisplay|-noupdate|-update expected at this point.\n";
4113     }
4114   }
4115
4116   // Display connected object
4117   TheAISContext()->Display (aConnected, Standard_False);
4118
4119   return 0;
4120 }
4121
4122 //=======================================================================
4123 //function : VDisconnect
4124 //purpose  :
4125 //=======================================================================
4126 static Standard_Integer VDisconnect (Draw_Interpretor& di,
4127                                      Standard_Integer argc,
4128                                      const char ** argv)
4129 {
4130   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4131   if (aContext.IsNull())
4132   {
4133     std::cout << argv[0] << "ERROR : use 'vinit' command before \n";
4134     return 1;
4135   }
4136   
4137   if (argc != 3)
4138   {
4139     std::cout << "ERROR : Usage : " << argv[0] << " name object\n";
4140     return 1;
4141   }
4142
4143   TCollection_AsciiString aName (argv[1]);
4144   TCollection_AsciiString anObject (argv[2]);
4145   Standard_Integer anObjectNumber = Draw::Atoi (argv[2]);
4146
4147   // find objects
4148   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
4149   Handle(AIS_MultipleConnectedInteractive) anAssembly;
4150   if (!aMap.IsBound2 (aName) )
4151   {
4152     std::cout << "Use 'vdisplay' before\n";
4153     return 1;
4154   }
4155
4156   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
4157   if (anAssembly.IsNull())
4158   {
4159     di << "Not an assembly\n";
4160     return 1;
4161   }
4162
4163   Handle(AIS_InteractiveObject) anIObj;
4164   if (!aMap.IsBound2 (anObject))
4165   {
4166     // try to interpret second argument as child number
4167     if (anObjectNumber > 0 && anObjectNumber <= anAssembly->Children().Size())
4168     {
4169       Standard_Integer aCounter = 1;
4170       for (PrsMgr_ListOfPresentableObjectsIter anIter (anAssembly->Children()); anIter.More(); anIter.Next())
4171       {
4172         if (aCounter == anObjectNumber)
4173         {
4174           anIObj = Handle(AIS_InteractiveObject)::DownCast (anIter.Value());
4175           break;
4176         }
4177         ++aCounter;
4178       }
4179     }
4180     else
4181     {
4182       std::cout << "Use 'vdisplay' before\n";
4183       return 1;
4184     }    
4185   }
4186
4187   // if object was found by name
4188   if (anIObj.IsNull())
4189   {
4190     anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (anObject));
4191   }
4192
4193   aContext->Disconnect (anAssembly, anIObj);
4194   aContext->UpdateCurrentViewer();
4195
4196   return 0;
4197 }
4198
4199 //=======================================================================
4200 //function : VAddConnected
4201 //purpose  :
4202 //=======================================================================
4203 static Standard_Integer VAddConnected (Draw_Interpretor& di,
4204                                        Standard_Integer argc,
4205                                        const char ** argv)
4206 {
4207   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4208   if (aContext.IsNull())
4209   {
4210     std::cout << argv[0] << "error : use 'vinit' command before \n";
4211     return 1;
4212   }
4213   
4214   if (argc != 6)
4215   {
4216     std::cout << argv[0] << " error: expect 5 arguments\n";
4217     return 1;
4218   }
4219
4220   TCollection_AsciiString aName (argv[1]);
4221   TCollection_AsciiString anObject (argv[5]);
4222   Standard_Real aX = Draw::Atof (argv[2]);
4223   Standard_Real aY = Draw::Atof (argv[3]);
4224   Standard_Real aZ = Draw::Atof (argv[4]);
4225
4226   // find object
4227   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
4228   Handle(AIS_MultipleConnectedInteractive) anAssembly;
4229   if (!aMap.IsBound2 (aName) )
4230   {
4231     std::cout << "Use 'vdisplay' before\n";
4232     return 1;
4233   }
4234
4235   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
4236   if (anAssembly.IsNull())
4237   {
4238     di << "Not an assembly\n";
4239     return 1;
4240   }
4241
4242   Handle(AIS_InteractiveObject) anIObj;
4243   if (!aMap.IsBound2 (anObject))
4244   {
4245       std::cout << "Use 'vdisplay' before\n";
4246       return 1; 
4247   }
4248
4249   anIObj = Handle(AIS_InteractiveObject)::DownCast (aMap.Find2 (anObject));
4250
4251   gp_Trsf aTrsf;
4252   aTrsf.SetTranslation (gp_Vec (aX, aY, aZ));
4253  
4254   anAssembly->Connect (anIObj, aTrsf);
4255   TheAISContext()->Display (anAssembly, Standard_False);
4256   TheAISContext()->RecomputeSelectionOnly (anAssembly);
4257   aContext->UpdateCurrentViewer();
4258
4259   return 0;
4260 }
4261
4262 //=======================================================================
4263 //function : VListConnected
4264 //purpose  :
4265 //=======================================================================
4266 static Standard_Integer VListConnected (Draw_Interpretor& /*di*/,
4267                                         Standard_Integer argc,
4268                                         const char ** argv)
4269 {
4270   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4271   if (aContext.IsNull())
4272   {
4273     std::cout << argv[0] << "ERROR : use 'vinit' command before \n";
4274     return 1;
4275   }
4276   
4277   if (argc != 2)
4278   {
4279     std::cout << "ERROR : Usage : " << argv[0] << " name\n";
4280     return 1;
4281   }
4282
4283   TCollection_AsciiString aName (argv[1]);
4284
4285   // find object
4286   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
4287   Handle(AIS_MultipleConnectedInteractive) anAssembly;
4288   if (!aMap.IsBound2 (aName) )
4289   {
4290     std::cout << "Use 'vdisplay' before\n";
4291     return 1;
4292   }
4293
4294   anAssembly = Handle(AIS_MultipleConnectedInteractive)::DownCast (aMap.Find2 (aName));
4295   if (anAssembly.IsNull())
4296   {
4297     std::cout << "Not an assembly\n";
4298     return 1;
4299   }
4300
4301   std::cout << "Children of " << aName << ":\n";
4302
4303   Standard_Integer aCounter = 1;
4304   for (PrsMgr_ListOfPresentableObjectsIter anIter (anAssembly->Children()); anIter.More(); anIter.Next())
4305   {
4306     if (GetMapOfAIS().IsBound1 (anIter.Value()))
4307     {
4308       TCollection_AsciiString aCuurrentName = GetMapOfAIS().Find1 (anIter.Value());
4309       std::cout << aCounter << ")  " << aCuurrentName << "    (" << anIter.Value()->DynamicType()->Name() << ")";
4310     }
4311
4312     std::cout << aCounter << ")  " << anIter.Value()->DynamicType()->Name();
4313
4314     Handle(AIS_ConnectedInteractive) aConnected = Handle(AIS_ConnectedInteractive)::DownCast (anIter.Value());
4315     if (!aConnected.IsNull() && !aConnected->ConnectedTo().IsNull() && aMap.IsBound1 (aConnected->ConnectedTo()))
4316     {
4317       std::cout << " connected to " << aMap.Find1 (aConnected->ConnectedTo());
4318     }
4319     std::cout << std::endl;
4320     
4321     ++aCounter;
4322   }
4323
4324   return 0;
4325 }
4326
4327 namespace
4328 {
4329   //! Checks if theMode is already turned on for theObj.
4330   static Standard_Boolean InList (const Handle(AIS_InteractiveContext)& theAISContext,
4331                                   const Handle(AIS_InteractiveObject)&  theObj,
4332                                   const Standard_Integer                theMode)
4333   {
4334     TColStd_ListOfInteger anActiveModes;
4335     theAISContext->ActivatedModes (theObj, anActiveModes);
4336     for (TColStd_ListIteratorOfListOfInteger aModeIt (anActiveModes); aModeIt.More(); aModeIt.Next())
4337     {
4338       if (aModeIt.Value() == theMode)
4339       {
4340         return Standard_True;
4341       }
4342     }
4343     return Standard_False;
4344   }
4345 }
4346
4347 //===============================================================================================
4348 //function : VSetSelectionMode
4349 //purpose  : Sets input selection mode for input object or for all displayed objects 
4350 //Draw arg : vselmode [object] mode On/Off (1/0)
4351 //===============================================================================================
4352 static Standard_Integer VSetSelectionMode (Draw_Interpretor& /*di*/,
4353                                            Standard_Integer  theArgc,
4354                                            const char**      theArgv)
4355 {
4356   // Check errors
4357   Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
4358   if (anAISContext.IsNull())
4359   {
4360     std::cerr << "Call vinit before!" << std::endl;
4361     return 1;
4362   }
4363
4364   // Check the arguments
4365   if (theArgc < 3 && theArgc > 5)
4366   {
4367     std::cerr << "vselmode error : expects at least 2 arguments.\n"
4368               << "Type help "<< theArgv[0] <<" for more information." << std::endl;
4369     return 1;
4370   }
4371
4372   TCollection_AsciiString aLastArg (theArgv[theArgc - 1]);
4373   aLastArg.LowerCase();
4374   Standard_Boolean isToOpenLocalCtx = aLastArg == "-local";
4375
4376   // get objects to change selection mode
4377   AIS_ListOfInteractive aTargetIOs;
4378   Standard_Integer anArgNb = isToOpenLocalCtx ? theArgc - 1 : theArgc;
4379   if (anArgNb == 3)
4380   {
4381     anAISContext->DisplayedObjects (aTargetIOs);
4382   }
4383   else
4384   {
4385     // Check if there is an object with given name in context
4386     const TCollection_AsciiString aNameIO (theArgv[1]);
4387     if (GetMapOfAIS().IsBound2 (aNameIO))
4388     {
4389       Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aNameIO));
4390       if (anIO.IsNull())
4391       {
4392         std::cerr << "vselmode error : object name is used for non AIS viewer" << std::endl;
4393         return 1;
4394       }
4395       aTargetIOs.Append (anIO);
4396     }
4397   }
4398
4399   Standard_Integer aSelectionMode = -1;
4400   Standard_Boolean toTurnOn = Standard_True;
4401   {
4402     const TCollection_AsciiString aSelModeString (theArgv[anArgNb == 3 ? 1 : 2]);
4403     TopAbs_ShapeEnum aShapeType = TopAbs_SHAPE;
4404     if (aSelModeString.IsIntegerValue())
4405     {
4406       aSelectionMode = aSelModeString.IntegerValue();
4407     }
4408     else if (TopAbs::ShapeTypeFromString (aSelModeString.ToCString(), aShapeType))
4409     {
4410       aSelectionMode = AIS_Shape::SelectionMode (aShapeType);
4411     }
4412     else
4413     {
4414       std::cout << "Syntax error: unknown selection mode '" << aSelModeString  << "'\n";
4415       return 1;
4416     }
4417   }
4418   if (!ViewerTest::ParseOnOff (theArgv[anArgNb == 3 ? 2 : 3], toTurnOn))
4419   {
4420     std::cout << "Syntax error: on/off is expected by found '" << theArgv[anArgNb == 3 ? 2 : 3] << "'\n";
4421     return 1;
4422   }
4423
4424   Standard_DISABLE_DEPRECATION_WARNINGS
4425   if (aSelectionMode == 0 && anAISContext->HasOpenedContext())
4426   {
4427     anAISContext->CloseLocalContext();
4428   }
4429   Standard_ENABLE_DEPRECATION_WARNINGS
4430
4431   if (aSelectionMode == 0)
4432   {
4433     if (toTurnOn)
4434     {
4435       for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
4436       {
4437         const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
4438         TColStd_ListOfInteger anActiveModes;
4439         anAISContext->ActivatedModes (anIO, anActiveModes);
4440         if (!anActiveModes.IsEmpty())
4441         {
4442           anAISContext->Deactivate (anIO);
4443         }
4444         if (!InList (anAISContext, anIO, aSelectionMode))
4445         {
4446           anAISContext->Activate (anIO);
4447         }
4448       }
4449     }
4450     else
4451     {
4452       for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
4453       {
4454         const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
4455         if (InList (anAISContext, anIO, aSelectionMode))
4456         {
4457           anAISContext->Deactivate (anIO);
4458         }
4459       }
4460     }
4461   }
4462
4463   if (aSelectionMode != 0 && toTurnOn) // Turn on specified mode
4464   {
4465     Standard_DISABLE_DEPRECATION_WARNINGS
4466     if (!anAISContext->HasOpenedContext() && isToOpenLocalCtx)
4467     {
4468       anAISContext->OpenLocalContext (Standard_False);
4469     }
4470     Standard_ENABLE_DEPRECATION_WARNINGS
4471
4472     for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
4473     {
4474       const Handle(AIS_InteractiveObject)& anIO = aTargetIt.Value();
4475       anAISContext->Deactivate (anIO, 0);
4476       anAISContext->Load (anIO, -1, Standard_True);
4477       anAISContext->Activate (anIO, aSelectionMode);
4478     }
4479   }
4480
4481   if (aSelectionMode != 0 && !toTurnOn) // Turn off specified mode
4482   {
4483     for (AIS_ListIteratorOfListOfInteractive aTargetIt (aTargetIOs); aTargetIt.More(); aTargetIt.Next())
4484     {
4485       anAISContext->Deactivate (aSelectionMode);
4486     }
4487   }
4488
4489   return 0;
4490 }
4491
4492 //===============================================================================================
4493 //function : VSelectionNext
4494 //purpose  : 
4495 //===============================================================================================
4496 static Standard_Integer VSelectionNext(Draw_Interpretor& /*theDI*/,
4497                                  Standard_Integer /*theArgsNb*/,
4498                                  const char** /*theArgVec*/)
4499 {
4500   // Check errors
4501   Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
4502   Handle(V3d_View) aView = ViewerTest::CurrentView();
4503
4504   if (anAISContext.IsNull())
4505   {
4506     std::cerr << "Call vinit before!" << std::endl;
4507     return 1;
4508   }
4509
4510   anAISContext->HilightNextDetected (aView);
4511   return 0;
4512 }
4513
4514 //===============================================================================================
4515 //function : VSelectionPrevious
4516 //purpose  : 
4517 //===============================================================================================
4518 static Standard_Integer VSelectionPrevious(Draw_Interpretor& /*theDI*/,
4519                                  Standard_Integer /*theArgsNb*/,
4520                                  const char** /*theArgVec*/)
4521 {
4522   // Check errors
4523   Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
4524   Handle(V3d_View) aView = ViewerTest::CurrentView();
4525
4526   if (anAISContext.IsNull())
4527   {
4528     std::cerr << "Call vinit before!" << std::endl;
4529     return 1;
4530   }
4531
4532   anAISContext->HilightPreviousDetected (aView);
4533   return 0;
4534 }
4535
4536
4537 //==========================================================================
4538 //class   : Triangle 
4539 //purpose : creates Triangle based on AIS_InteractiveObject. 
4540 //          This class was implemented for testing Select3D_SensitiveTriangle
4541 //===========================================================================
4542
4543 class Triangle: public AIS_InteractiveObject 
4544 {
4545 public: 
4546   // CASCADE RTTI
4547   DEFINE_STANDARD_RTTI_INLINE(Triangle,AIS_InteractiveObject);
4548   Triangle (const gp_Pnt& theP1, 
4549             const gp_Pnt& theP2, 
4550             const gp_Pnt& theP3);
4551 protected:
4552   void Compute (  const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
4553                   const Handle(Prs3d_Presentation)& thePresentation,
4554                   const Standard_Integer theMode) Standard_OVERRIDE;
4555
4556   void ComputeSelection (  const Handle(SelectMgr_Selection)& theSelection, 
4557                            const Standard_Integer theMode) Standard_OVERRIDE;
4558 private: 
4559   gp_Pnt myPoint1;
4560   gp_Pnt myPoint2;
4561   gp_Pnt myPoint3;
4562 };
4563
4564
4565 Triangle::Triangle (const gp_Pnt& theP1,
4566                     const gp_Pnt& theP2,
4567                     const gp_Pnt& theP3)
4568 {
4569   myPoint1 = theP1;
4570   myPoint2 = theP2;
4571   myPoint3 = theP3;
4572 }
4573
4574 void Triangle::Compute(const Handle(PrsMgr_PresentationManager3d)& /*thePresentationManager*/,
4575                        const Handle(Prs3d_Presentation)& thePresentation,
4576                        const Standard_Integer /*theMode*/)
4577 {
4578   thePresentation->Clear();
4579
4580   BRepBuilderAPI_MakeEdge anEdgeMaker1(myPoint1, myPoint2),
4581                           anEdgeMaker2(myPoint2, myPoint3),
4582                           anEdgeMaker3(myPoint3, myPoint1);
4583
4584   TopoDS_Edge anEdge1 = anEdgeMaker1.Edge(),
4585               anEdge2 = anEdgeMaker2.Edge(),
4586               anEdge3 = anEdgeMaker3.Edge();
4587   if(anEdge1.IsNull() || anEdge2.IsNull() || anEdge3.IsNull())
4588     return;
4589
4590   BRepBuilderAPI_MakeWire aWireMaker(anEdge1, anEdge2, anEdge3);
4591   TopoDS_Wire aWire = aWireMaker.Wire();
4592   if(aWire.IsNull()) return;
4593
4594   BRepBuilderAPI_MakeFace aFaceMaker(aWire);
4595   TopoDS_Face aFace = aFaceMaker.Face();
4596   if(aFace.IsNull()) return;
4597
4598   StdPrs_ShadedShape::Add(thePresentation, aFace, myDrawer);
4599 }
4600
4601 void Triangle::ComputeSelection(const Handle(SelectMgr_Selection)& theSelection, 
4602                                 const Standard_Integer /*theMode*/)
4603 {
4604   Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner(this);
4605   Handle(Select3D_SensitiveTriangle) aSensTriangle = 
4606     new Select3D_SensitiveTriangle(anEntityOwner, myPoint1, myPoint2, myPoint3);
4607   theSelection->Add(aSensTriangle);
4608 }
4609
4610 //===========================================================================
4611 //function : VTriangle 
4612 //Draw arg : vtriangle Name PointName PointName PointName
4613 //purpose  : creates and displays Triangle
4614 //===========================================================================
4615
4616 //function: IsPoint
4617 //purpose : checks if the object with theName is AIS_Point, 
4618 //          if yes initialize thePoint from MapOfAIS
4619 Standard_Boolean IsPoint (const TCollection_AsciiString& theName,
4620                           Handle(AIS_Point)& thePoint)
4621 {
4622   Handle(AIS_InteractiveObject) anObject = 
4623     Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(theName));
4624   if(anObject.IsNull() || 
4625      anObject->Type() != AIS_KOI_Datum || 
4626      anObject->Signature() != 1)
4627   {
4628     return Standard_False;
4629   }
4630   thePoint = Handle(AIS_Point)::DownCast(anObject);
4631   if(thePoint.IsNull())
4632     return Standard_False;
4633   return Standard_True;
4634 }
4635
4636 //function: IsMatch
4637 //purpose: checks if thePoint1 is equal to thePoint2
4638 Standard_Boolean IsMatch (const Handle(Geom_CartesianPoint)& thePoint1,
4639                           const Handle(Geom_CartesianPoint)& thePoint2)
4640 {
4641   if(Abs(thePoint1->X()-thePoint2->X()) <= Precision::Confusion() &&
4642      Abs(thePoint1->Y()-thePoint2->Y()) <= Precision::Confusion() &&
4643      Abs(thePoint1->Z()-thePoint2->Z()) <= Precision::Confusion())
4644   {
4645     return Standard_True;
4646   }
4647   return Standard_False;
4648 }
4649
4650 static Standard_Integer VTriangle (Draw_Interpretor& /*di*/,
4651                                    Standard_Integer argc,
4652                                    const char ** argv)
4653 {
4654   // Check arguments
4655   if (argc != 5)
4656   {
4657     std::cout<<"vtriangle error: expects 4 argumnets\n";
4658     return 1; // TCL_ERROR
4659   }
4660
4661   // Get and check values
4662   TCollection_AsciiString aName(argv[1]);
4663
4664   Handle(AIS_Point) aPoint1, aPoint2, aPoint3;
4665   if (!IsPoint(argv[2], aPoint1))
4666   {
4667     std::cout<<"vtriangle error: the 2nd argument must be a point\n";
4668     return 1; // TCL_ERROR
4669   }
4670   if (!IsPoint(argv[3], aPoint2))
4671   {
4672     std::cout<<"vtriangle error: the 3d argument must be a point\n";
4673     return 1; // TCL_ERROR
4674   }
4675   if (!IsPoint(argv[4], aPoint3))
4676   {
4677     std::cout<<"vtriangle error: the 4th argument must be a point\n";
4678     return 1; // TCL_ERROR
4679   }
4680
4681   // Check that points are different
4682   Handle(Geom_CartesianPoint) aCartPoint1 = 
4683     Handle(Geom_CartesianPoint)::DownCast(aPoint1->Component());
4684   Handle(Geom_CartesianPoint) aCartPoint2 = 
4685     Handle(Geom_CartesianPoint)::DownCast(aPoint2->Component());
4686   // Test aPoint1 = aPoint2
4687   if (IsMatch(aCartPoint1, aCartPoint2))
4688   {
4689     std::cout<<"vtriangle error: the 1st and the 2nd points are equal\n";
4690     return 1; // TCL_ERROR
4691   }
4692   // Test aPoint2 = aPoint3
4693   Handle(Geom_CartesianPoint) aCartPoint3 = 
4694     Handle(Geom_CartesianPoint)::DownCast(aPoint3->Component());
4695   if (IsMatch(aCartPoint2, aCartPoint3))
4696   {
4697     std::cout<<"vtriangle error: the 2nd and the 3d points are equal\n";
4698     return 1; // TCL_ERROR
4699   }
4700   // Test aPoint3 = aPoint1
4701   if (IsMatch(aCartPoint1, aCartPoint3))
4702   {
4703     std::cout<<"vtriangle error: the 1st and the 3d points are equal\n";
4704     return 1; // TCL_ERROR
4705   }
4706
4707   // Create triangle
4708   Handle(Triangle) aTriangle = new Triangle(aCartPoint1->Pnt(),
4709                                             aCartPoint2->Pnt(),
4710                                             aCartPoint3->Pnt());
4711
4712   // Check if there is an object with given name
4713   // and remove it from context
4714   if (GetMapOfAIS().IsBound2(aName))
4715   {
4716     Handle(Standard_Transient) anObj = GetMapOfAIS().Find2(aName);
4717     Handle(AIS_InteractiveObject) anInterObj = 
4718          Handle(AIS_InteractiveObject)::DownCast(anObj);
4719     TheAISContext()->Remove(anInterObj, Standard_False);
4720     GetMapOfAIS().UnBind2(aName);
4721   }
4722
4723   // Bind triangle to its name
4724   GetMapOfAIS().Bind(aTriangle, aName);
4725
4726   // Display triangle
4727   TheAISContext()->Display (aTriangle, Standard_True);
4728   return 0;
4729 }
4730
4731 //class  : SegmentObject
4732 //purpose: creates segment based on AIS_InteractiveObject.
4733 //         This class was implemented for testing Select3D_SensitiveCurve
4734
4735 class SegmentObject: public AIS_InteractiveObject
4736 {
4737 public:
4738   // CASCADE RTTI
4739   DEFINE_STANDARD_RTTI_INLINE(SegmentObject,AIS_InteractiveObject); 
4740   SegmentObject (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2);
4741 protected:
4742   void Compute (const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
4743                 const Handle(Prs3d_Presentation)& thePresentation,
4744                 const Standard_Integer theMode) Standard_OVERRIDE;
4745
4746   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection, 
4747                          const Standard_Integer theMode) Standard_OVERRIDE;
4748 private:
4749   gp_Pnt myPoint1;
4750   gp_Pnt myPoint2;
4751 };
4752
4753
4754 SegmentObject::SegmentObject (const gp_Pnt& thePnt1, const gp_Pnt& thePnt2)
4755 {
4756   myPoint1 = thePnt1;
4757   myPoint2 = thePnt2;
4758 }
4759
4760 void SegmentObject::Compute (const Handle(PrsMgr_PresentationManager3d) &/*thePresentationManager*/,
4761                              const Handle(Prs3d_Presentation) &thePresentation,
4762                              const Standard_Integer /*theMode*/)
4763 {
4764   thePresentation->Clear();
4765   BRepBuilderAPI_MakeEdge anEdgeMaker(myPoint1, myPoint2);
4766   TopoDS_Edge anEdge = anEdgeMaker.Edge();
4767   if (anEdge.IsNull())
4768     return;
4769   BRepAdaptor_Curve aCurveAdaptor(anEdge);
4770   StdPrs_Curve::Add(thePresentation, aCurveAdaptor, myDrawer);
4771 }
4772
4773 void SegmentObject::ComputeSelection (const Handle(SelectMgr_Selection) &theSelection,
4774                                       const Standard_Integer /*theMode*/)
4775 {
4776   Handle(SelectMgr_EntityOwner) anOwner = new SelectMgr_EntityOwner(this);
4777   Handle(TColgp_HArray1OfPnt) anArray = new TColgp_HArray1OfPnt(1, 2);
4778   anArray->SetValue(1, myPoint1);
4779   anArray->SetValue(2, myPoint2);
4780   Handle(Select3D_SensitiveCurve) aSensCurve = 
4781     new Select3D_SensitiveCurve(anOwner, anArray);
4782   theSelection->Add(aSensCurve);
4783 }
4784
4785 //=======================================================================
4786 //function  : VSegment
4787 //Draw args : vsegment Name PointName PointName
4788 //purpose   : creates and displays Segment
4789 //=======================================================================
4790 static Standard_Integer VSegment (Draw_Interpretor& /*di*/,
4791                                   Standard_Integer argc,
4792                                   const char ** argv)
4793 {
4794   // Check arguments
4795   if(argc!=4)
4796   {
4797     std::cout<<"vsegment error: expects 3 arguments\n";
4798     return 1; // TCL_ERROR
4799   }
4800
4801   // Get and check arguments
4802   TCollection_AsciiString aName(argv[1]);
4803   Handle(AIS_Point) aPoint1, aPoint2;
4804   if (!IsPoint(argv[2], aPoint1))
4805   {
4806     std::cout<<"vsegment error: the 2nd argument should be a point\n";
4807     return 1; // TCL_ERROR
4808   }
4809   if (!IsPoint(argv[3], aPoint2))
4810   {
4811     std::cout<<"vsegment error: the 3d argument should be a point\n";
4812     return 1; // TCL_ERROR
4813   }
4814   //Check that points are different
4815   Handle(Geom_CartesianPoint) aCartPoint1 = 
4816     Handle(Geom_CartesianPoint)::DownCast(aPoint1->Component());
4817   Handle(Geom_CartesianPoint) aCartPoint2 = 
4818     Handle(Geom_CartesianPoint)::DownCast(aPoint2->Component());
4819   if(IsMatch(aCartPoint1, aCartPoint2))
4820   {
4821     std::cout<<"vsegment error: equal points\n";
4822     return 1; // TCL_ERROR
4823   }
4824   
4825   // Create segment
4826   Handle(SegmentObject) aSegment = new SegmentObject(aCartPoint1->Pnt(), aCartPoint2->Pnt());
4827   // Check if there is an object with given name
4828   // and remove it from context
4829   if (GetMapOfAIS().IsBound2(aName))
4830   {
4831     Handle(Standard_Transient) anObj = GetMapOfAIS().Find2(aName);
4832     Handle(AIS_InteractiveObject) anInterObj = 
4833          Handle(AIS_InteractiveObject)::DownCast(anObj);
4834     TheAISContext()->Remove(anInterObj, Standard_False);
4835     GetMapOfAIS().UnBind2(aName);
4836   }
4837
4838   // Bind segment to its name
4839   GetMapOfAIS().Bind(aSegment, aName);
4840
4841   // Display segment
4842   TheAISContext()->Display (aSegment, Standard_True);
4843   return 0;
4844 }
4845
4846 //=======================================================================
4847 //function : VObjZLayer
4848 //purpose  : Set or get z layer id for presentable object
4849 //=======================================================================
4850
4851 static Standard_Integer VObjZLayer (Draw_Interpretor& di,
4852                                     Standard_Integer argc,
4853                                     const char ** argv)
4854 {
4855   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4856   if (aContext.IsNull())
4857   {
4858     di << argv[0] << "Call 'vinit' before!\n";
4859     return 1;
4860   }
4861
4862   // get operation
4863   TCollection_AsciiString aOperation;
4864   if (argc >= 2)
4865     aOperation = TCollection_AsciiString (argv [1]);
4866
4867   // check for correct arguments
4868   if (!(argc == 4 && aOperation.IsEqual ("set")) &&
4869       !(argc == 3 && aOperation.IsEqual ("get")))
4870   {
4871     di << "Usage : " << argv[0] << " set/get object [layerid]\n";
4872     di << " set - set layer id for interactive object, layerid - z layer id\n";
4873     di << " get - get layer id of interactive object\n";
4874     di << " argument layerid should be passed for set operation only\n";
4875     return 1;
4876   }
4877
4878   // find object
4879   TCollection_AsciiString aName (argv[2]);
4880   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
4881   if (!aMap.IsBound2 (aName))
4882   {
4883     di << "Use 'vdisplay' before\n";
4884     return 1;
4885   }
4886
4887   // find interactive object
4888   Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (aName);
4889   Handle(AIS_InteractiveObject) anInterObj =
4890     Handle(AIS_InteractiveObject)::DownCast (anObj);
4891   if (anInterObj.IsNull())
4892   {
4893     di << "Not an AIS interactive object!\n";
4894     return 1;
4895   }
4896
4897   // process operation
4898   if (aOperation.IsEqual ("set"))
4899   {
4900     Standard_Integer aLayerId = Draw::Atoi (argv [3]);
4901     aContext->SetZLayer (anInterObj, aLayerId);
4902   }
4903   else if (aOperation.IsEqual ("get"))
4904   {
4905     di << "Z layer id: " << aContext->GetZLayer (anInterObj);
4906   }
4907   
4908   return 0;
4909 }
4910
4911 //=======================================================================
4912 //function : VPolygonOffset
4913 //purpose  : Set or get polygon offset parameters
4914 //=======================================================================
4915 static Standard_Integer VPolygonOffset(Draw_Interpretor& /*di*/,
4916                                        Standard_Integer argc,
4917                                        const char ** argv)
4918 {
4919   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4920   if (aContext.IsNull())
4921   {
4922     std::cout << argv[0] << " Call 'vinit' before!\n";
4923     return 1;
4924   }
4925
4926   if (argc > 2 && argc != 5)
4927   {
4928     std::cout << "Usage : " << argv[0] << " [object [mode factor units]] - sets/gets polygon offset parameters for an object,"
4929       "without arguments prints the default values" << std::endl;
4930     return 1;
4931   }
4932
4933   // find object
4934   Handle(AIS_InteractiveObject) anInterObj;
4935   if (argc >= 2)
4936   {
4937     TCollection_AsciiString aName (argv[1]);
4938     ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
4939     if (!aMap.IsBound2 (aName))
4940     {
4941       std::cout << "Use 'vdisplay' before" << std::endl;
4942       return 1;
4943     }
4944
4945     // find interactive object
4946     Handle(Standard_Transient) anObj = GetMapOfAIS().Find2 (aName);
4947     anInterObj = Handle(AIS_InteractiveObject)::DownCast (anObj);
4948     if (anInterObj.IsNull())
4949     {
4950       std::cout << "Not an AIS interactive object!" << std::endl;
4951       return 1;
4952     }
4953   }
4954
4955   Standard_Integer aMode;
4956   Standard_ShortReal    aFactor, aUnits;
4957   if (argc == 5)
4958   {
4959     aMode   = Draw::Atoi(argv[2]);
4960     aFactor = (Standard_ShortReal) Draw::Atof(argv[3]);
4961     aUnits  = (Standard_ShortReal) Draw::Atof(argv[4]);
4962
4963     anInterObj->SetPolygonOffsets(aMode, aFactor, aUnits);
4964     aContext->UpdateCurrentViewer();
4965     return 0;
4966   }
4967   else if (argc == 2)
4968   {
4969     if (anInterObj->HasPolygonOffsets())
4970     {
4971       anInterObj->PolygonOffsets(aMode, aFactor, aUnits);
4972       std::cout << "Current polygon offset parameters for " << argv[1] << ":" << std::endl;
4973       std::cout << "\tMode: "   << aMode   << std::endl;
4974       std::cout << "\tFactor: " << aFactor << std::endl;
4975       std::cout << "\tUnits: "  << aUnits  << std::endl;
4976       return 0;
4977     }
4978     else
4979     {
4980       std::cout << "Specific polygon offset parameters are not set for " << argv[1] << std::endl;
4981     }
4982   }
4983
4984   std::cout << "Default polygon offset parameters:" << std::endl;
4985   aContext->DefaultDrawer()->ShadingAspect()->Aspect()->PolygonOffsets(aMode, aFactor, aUnits);
4986   std::cout << "\tMode: "   << aMode   << std::endl;
4987   std::cout << "\tFactor: " << aFactor << std::endl;
4988   std::cout << "\tUnits: "  << aUnits  << std::endl;
4989
4990   return 0;
4991 }
4992
4993 //=======================================================================
4994 //function : VShowFaceBoundaries
4995 //purpose  : Set face boundaries drawing on/off for ais object
4996 //=======================================================================
4997 static Standard_Integer VShowFaceBoundary (Draw_Interpretor& /*di*/,
4998                                            Standard_Integer argc,
4999                                            const char ** argv)
5000 {
5001   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext ();
5002   if (aContext.IsNull ())
5003   {
5004     std::cout << argv[0] << " Call 'vinit' before!\n";
5005     return 1;
5006   }
5007
5008   if ((argc != 3 && argc < 6) || argc > 8)
5009   {
5010     std::cout << "Usage :\n " << argv[0]
5011               << " ObjectName isOn [R G B [LineWidth [LineStyle]]]\n"
5012               << "   ObjectName - name of AIS interactive object. \n"
5013               << "                if ObjectName = \"\", then set as default\n"
5014               << "                settings for all newly displayed objects\n"
5015               << "   isOn       - flag indicating whether the boundaries\n"
5016               << "                should be turned on or off (can be set\n"
5017               << "                to 0 (off) or 1 (on)).\n"
5018               << "   R, G, B    - red, green and blue components of boundary\n"
5019               << "                color in range (0 - 255).\n"
5020               << "                (default is (0, 0, 0)\n"
5021               << "   LineWidth  - line width\n"
5022               << "                (default is 1)\n"
5023               << "   LineStyle  - line fill style :\n"
5024               << "                 0 - solid  \n"
5025               << "                 1 - dashed \n"
5026               << "                 2 - dot    \n"
5027               << "                 3 - dashdot\n"
5028               << "                 (default is solid)";
5029     return 1;
5030   }
5031
5032   TCollection_AsciiString aName (argv[1]);
5033
5034   Standard_Real aRed   = 0.0;
5035   Standard_Real aGreen = 0.0;
5036   Standard_Real aBlue  = 0.0;
5037   Standard_Real aWidth = 1.0;
5038   Aspect_TypeOfLine aLineType = Aspect_TOL_SOLID;
5039   
5040   // find object
5041   Handle(AIS_InteractiveObject) anInterObj;
5042
5043   // if name is empty - apply attributes for default aspect
5044   if (!aName.IsEmpty ())
5045   {
5046     ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS ();
5047     if (!aMap.IsBound2 (aName))
5048     {
5049       std::cout << "Use 'vdisplay' on " << aName << " before" << std::endl;
5050       return 1;
5051     }
5052
5053     // find interactive object
5054     Handle(Standard_Transient) anObj = GetMapOfAIS ().Find2 (aName);
5055     anInterObj = Handle(AIS_InteractiveObject)::DownCast (anObj);
5056     if (anInterObj.IsNull ())
5057     {
5058       std::cout << "Not an AIS interactive object!" << std::endl;
5059       return 1;
5060     }
5061   }
5062   
5063   const Handle(Prs3d_Drawer)& aDrawer = (aName.IsEmpty ()) ?
5064     TheAISContext ()->DefaultDrawer () : anInterObj->Attributes ();
5065
5066   // turn boundaries on/off
5067   Standard_Boolean isBoundaryDraw = (Draw::Atoi (argv[2]) == 1);
5068   aDrawer->SetFaceBoundaryDraw (isBoundaryDraw);
5069   
5070   // set boundary line color
5071   if (argc >= 6)
5072   {
5073     // Text color
5074     aRed   = Draw::Atof (argv[3])/255.;
5075     aGreen = Draw::Atof (argv[4])/255.;
5076     aBlue  = Draw::Atof (argv[5])/255.;
5077   }
5078
5079   // set line width
5080   if (argc >= 7)
5081   {
5082     aWidth = (Standard_Real)Draw::Atof (argv[6]);
5083   }
5084
5085   // select appropriate line type
5086   if (argc == 8)
5087   {
5088     if (!ViewerTest::ParseLineType (argv[7], aLineType))
5089     {
5090       std::cout << "Syntax error: unknown line type '" << argv[7] << "'\n";
5091       return 1;
5092     }
5093   }
5094
5095   Quantity_Color aColor (aRed, aGreen, aBlue, Quantity_TOC_RGB);
5096
5097   Handle(Prs3d_LineAspect) aBoundaryAspect = 
5098     new Prs3d_LineAspect (aColor, aLineType, aWidth);
5099
5100   aDrawer->SetFaceBoundaryAspect (aBoundaryAspect);
5101
5102   TheAISContext()->Redisplay (anInterObj, Standard_True);
5103   
5104   return 0;
5105 }
5106
5107 // This class is used for testing markers.
5108
5109 class ViewerTest_MarkersArrayObject : public AIS_InteractiveObject
5110 {
5111
5112 public:
5113
5114   ViewerTest_MarkersArrayObject (const gp_XYZ& theStartPoint,
5115                                  const Standard_Integer& thePointsOnSide,
5116                                  Handle(Graphic3d_AspectMarker3d) theMarkerAspect = NULL)
5117   {
5118     myStartPoint = theStartPoint;
5119     myPointsOnSide = thePointsOnSide;
5120     myMarkerAspect = theMarkerAspect;
5121   }
5122
5123   DEFINE_STANDARD_RTTI_INLINE(ViewerTest_MarkersArrayObject,AIS_InteractiveObject);
5124
5125 private:
5126
5127   void Compute (const Handle(PrsMgr_PresentationManager3d)& aPresentationManager,
5128                 const Handle(Prs3d_Presentation)& aPresentation,
5129                 const Standard_Integer aMode) Standard_OVERRIDE;
5130
5131   void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
5132                          const Standard_Integer /*theMode*/) Standard_OVERRIDE;
5133
5134 protected:
5135
5136   gp_XYZ myStartPoint;
5137   Standard_Integer myPointsOnSide;
5138   Handle(Graphic3d_AspectMarker3d) myMarkerAspect;
5139 };
5140
5141
5142 void ViewerTest_MarkersArrayObject::Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPresentationManager*/,
5143                               const Handle(Prs3d_Presentation)& aPresentation,
5144                               const Standard_Integer /*aMode*/)
5145 {
5146   Handle(Graphic3d_ArrayOfPrimitives) anArray = new Graphic3d_ArrayOfPoints ((Standard_Integer )Pow (myPointsOnSide, 3), myPointsOnSide != 1);
5147   if (myPointsOnSide == 1)
5148   {
5149     anArray->AddVertex (myStartPoint);
5150   }
5151   else
5152   {
5153     for (Standard_Real i = 1; i <= myPointsOnSide; i++)
5154     {
5155       for (Standard_Real j = 1; j <= myPointsOnSide; j++)
5156       {
5157         for (Standard_Real k = 1; k <= myPointsOnSide; k++)
5158         {
5159           anArray->AddVertex (myStartPoint.X() + i, myStartPoint.Y() + j, myStartPoint.Z() + k);
5160           anArray->SetVertexColor (anArray->VertexNumber(),
5161                                    i / myPointsOnSide,
5162                                    j / myPointsOnSide,
5163                                    k / myPointsOnSide);
5164         }
5165       }
5166     }
5167   }
5168
5169   aPresentation->Clear();
5170   if (!myMarkerAspect.IsNull())
5171   {
5172     Prs3d_Root::CurrentGroup (aPresentation)->SetGroupPrimitivesAspect (myMarkerAspect);
5173   }
5174   Prs3d_Root::CurrentGroup (aPresentation)->AddPrimitiveArray (anArray);
5175 }
5176
5177 void ViewerTest_MarkersArrayObject::ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
5178                                        const Standard_Integer /*theMode*/)
5179 {
5180   Handle(SelectMgr_EntityOwner) anEntityOwner = new SelectMgr_EntityOwner (this);
5181
5182   if (myPointsOnSide == 1)
5183   {
5184     gp_Pnt aPoint (myStartPoint);
5185     Handle(Select3D_SensitivePoint) aSensetivePoint = new Select3D_SensitivePoint (anEntityOwner, aPoint);
5186     theSelection->Add (aSensetivePoint);
5187   }
5188   else
5189   {
5190     for (Standard_Real i = 1; i <= myPointsOnSide; i++)
5191     {
5192       for (Standard_Real j = 1; j <= myPointsOnSide; j++)
5193       {
5194         for (Standard_Real k = 1; k <= myPointsOnSide; k++)
5195         {
5196           gp_Pnt aPoint (myStartPoint.X() + i, myStartPoint.Y() + j, myStartPoint.Z() + k);
5197           Handle(Select3D_SensitivePoint) aSensetivePoint = new Select3D_SensitivePoint (anEntityOwner, aPoint);
5198           theSelection->Add (aSensetivePoint);
5199         }
5200       }
5201     }
5202   }
5203 }
5204 //=======================================================================
5205 //function : VMarkersTest
5206 //purpose  : Draws an array of markers for testing purposes.
5207 //=======================================================================
5208 static Standard_Integer VMarkersTest (Draw_Interpretor&,
5209                                       Standard_Integer  theArgNb,
5210                                       const char**      theArgVec)
5211 {
5212   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
5213   if (aContext.IsNull())
5214   {
5215     std::cerr << "Call 'vinit' before!\n";
5216     return 1;
5217   }
5218
5219   if (theArgNb < 5)
5220   {
5221     std::cerr << "Usage :\n " << theArgVec[0]
5222               << "name X Y Z [PointsOnSide=10] [MarkerType=0] [Scale=1.0] [FileName=ImageFile]\n";
5223     return 1;
5224   }
5225
5226   Standard_Integer anArgIter = 1;
5227
5228   TCollection_AsciiString aName (theArgVec[anArgIter++]);
5229   TCollection_AsciiString aFileName;
5230   gp_XYZ aPnt (Atof (theArgVec[anArgIter]),
5231                Atof (theArgVec[anArgIter + 1]),
5232                Atof (theArgVec[anArgIter + 2]));
5233   anArgIter += 3;
5234
5235   Standard_Integer aPointsOnSide = 10;
5236   Standard_Integer aMarkerType   = -1;
5237   Standard_Real    aScale        = 1.0;
5238   for (; anArgIter < theArgNb; ++anArgIter)
5239   {
5240     const TCollection_AsciiString anArg (theArgVec[anArgIter]);
5241     if (anArg.Search ("PointsOnSide=") > -1)
5242     {
5243       aPointsOnSide = anArg.Token ("=", 2).IntegerValue();
5244     }
5245     else if (anArg.Search ("MarkerType=") > -1)
5246     {
5247       aMarkerType = anArg.Token ("=", 2).IntegerValue();
5248     }
5249     else if (anArg.Search ("Scale=") > -1)
5250     {
5251       aScale = anArg.Token ("=", 2).RealValue();
5252     }
5253     else if (anArg.Search ("FileName=") > -1)
5254     {
5255       aFileName = anArg.Token ("=", 2);
5256     }
5257     else
5258     {
5259       std::cerr << "Wrong argument: " << anArg << "\n";
5260       return 1;
5261     }
5262   }
5263
5264   Handle(Graphic3d_AspectMarker3d) anAspect;
5265   Handle(Image_AlienPixMap) anImage;
5266   Quantity_Color aColor (Quantity_NOC_GREEN1);
5267   if ((aMarkerType == Aspect_TOM_USERDEFINED || aMarkerType < 0)
5268    && !aFileName.IsEmpty())
5269   {
5270     anImage = new Image_AlienPixMap();
5271     if (!anImage->Load (aFileName))
5272     {
5273       std::cerr << "Could not load image from file '" << aFileName << "'!\n";
5274       return 1;
5275     }
5276     if (anImage->Format() == Image_Format_Gray)
5277     {
5278       anImage->SetFormat (Image_Format_Alpha);
5279     }
5280     else if (anImage->Format() == Image_Format_GrayF)
5281     {
5282       anImage->SetFormat (Image_Format_AlphaF);
5283     }
5284     anAspect = new Graphic3d_AspectMarker3d (anImage);
5285   }
5286   else
5287   {
5288     anAspect = new Graphic3d_AspectMarker3d (aMarkerType >= 0 ? (Aspect_TypeOfMarker )aMarkerType : Aspect_TOM_POINT, aColor, aScale);
5289   }
5290
5291   Handle(ViewerTest_MarkersArrayObject) aMarkersArray = new ViewerTest_MarkersArrayObject (aPnt, aPointsOnSide, anAspect);
5292   VDisplayAISObject (aName, aMarkersArray);
5293
5294   return 0;
5295 }
5296
5297 //! Auxiliary function to parse font aspect style argument
5298 static Standard_Boolean parseFontStyle (const TCollection_AsciiString& theArg,
5299                                         Font_FontAspect&               theAspect)
5300 {
5301   if (theArg == "regular"
5302    || *theArg.ToCString() == 'r')
5303   {
5304     theAspect = Font_FA_Regular;
5305     return Standard_True;
5306   }
5307   else if (theArg == "bolditalic")
5308   {
5309     theAspect = Font_FA_BoldItalic;
5310     return Standard_True;
5311   }
5312   else if (theArg == "bold"
5313         || *theArg.ToCString() == 'b')
5314   {
5315     theAspect = Font_FA_Bold;
5316     return Standard_True;
5317   }
5318   else if (theArg == "italic"
5319         || *theArg.ToCString() == 'i')
5320   {
5321     theAspect = Font_FA_Italic;
5322     return Standard_True;
5323   }
5324   return Standard_False;
5325 }
5326
5327 //! Auxiliary function
5328 static TCollection_AsciiString fontStyleString (const Font_FontAspect theAspect)
5329 {
5330   switch (theAspect)
5331   {
5332     case Font_FA_Regular:    return "regular";
5333     case Font_FA_BoldItalic: return "bolditalic";
5334     case Font_FA_Bold:       return "bold";
5335     case Font_FA_Italic:     return "italic";
5336     default:                 return "undefined";
5337   }
5338 }
5339
5340 //=======================================================================
5341 //function : TextToBrep
5342 //purpose  : Tool for conversion text to occt-shapes
5343 //=======================================================================
5344 static int TextToBRep (Draw_Interpretor& /*theDI*/,
5345                        Standard_Integer  theArgNb,
5346                        const char**      theArgVec)
5347 {
5348   // Check arguments
5349   if (theArgNb < 3)
5350   {
5351     std::cerr << "Error: " << theArgVec[0] << " - invalid syntax\n";
5352     return 1;
5353   }
5354
5355   Standard_Integer anArgIt = 1;
5356   Standard_CString aName   = theArgVec[anArgIt++];
5357   Standard_CString aText   = theArgVec[anArgIt++];
5358
5359   Font_BRepFont           aFont;
5360   TCollection_AsciiString aFontName ("Courier");
5361   Standard_Real           aTextHeight        = 16.0;
5362   Font_FontAspect         aFontAspect        = Font_FA_Regular;
5363   Standard_Boolean        anIsCompositeCurve = Standard_False;
5364   gp_Ax3                  aPenAx3    (gp::XOY());
5365   gp_Dir                  aNormal    (0.0, 0.0, 1.0);
5366   gp_Dir                  aDirection (1.0, 0.0, 0.0);
5367   gp_Pnt                  aPenLoc;
5368
5369   Graphic3d_HorizontalTextAlignment aHJustification = Graphic3d_HTA_LEFT;
5370   Graphic3d_VerticalTextAlignment   aVJustification = Graphic3d_VTA_BOTTOM;
5371
5372   for (; anArgIt < theArgNb; ++anArgIt)
5373   {
5374     TCollection_AsciiString aParam (theArgVec[anArgIt]);
5375     aParam.LowerCase();
5376
5377     if (aParam == "-pos"
5378      || aParam == "-position")
5379     {
5380       if (anArgIt + 3 >= theArgNb)
5381       {
5382         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5383         return 1;
5384       }
5385
5386       aPenLoc.SetX (Draw::Atof(theArgVec[++anArgIt]));
5387       aPenLoc.SetY (Draw::Atof(theArgVec[++anArgIt]));
5388       aPenLoc.SetZ (Draw::Atof(theArgVec[++anArgIt]));
5389     }
5390     else if (aParam == "-halign")
5391     {
5392       if (++anArgIt >= theArgNb)
5393       {
5394         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5395         return 1;
5396       }
5397
5398       TCollection_AsciiString aType (theArgVec[anArgIt]);
5399       aType.LowerCase();
5400       if (aType == "left")
5401       {
5402         aHJustification = Graphic3d_HTA_LEFT;
5403       }
5404       else if (aType == "center")
5405       {
5406         aHJustification = Graphic3d_HTA_CENTER;
5407       }
5408       else if (aType == "right")
5409       {
5410         aHJustification = Graphic3d_HTA_RIGHT;
5411       }
5412       else
5413       {
5414         std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
5415         return 1;
5416       }
5417     }
5418     else if (aParam == "-valign")
5419     {
5420       if (++anArgIt >= theArgNb)
5421       {
5422         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5423         return 1;
5424       }
5425
5426       TCollection_AsciiString aType (theArgVec[anArgIt]);
5427       aType.LowerCase();
5428       if (aType == "top")
5429       {
5430         aVJustification = Graphic3d_VTA_TOP;
5431       }
5432       else if (aType == "center")
5433       {
5434         aVJustification = Graphic3d_VTA_CENTER;
5435       }
5436       else if (aType == "bottom")
5437       {
5438         aVJustification = Graphic3d_VTA_BOTTOM;
5439       }
5440       else if (aType == "topfirstline")
5441       {
5442         aVJustification = Graphic3d_VTA_TOPFIRSTLINE;
5443       }
5444       else
5445       {
5446         std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
5447         return 1;
5448       }
5449     }
5450     else if (aParam == "-height")
5451     {
5452       if (++anArgIt >= theArgNb)
5453       {
5454         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5455         return 1;
5456       }
5457
5458       aTextHeight = Draw::Atof(theArgVec[anArgIt]);
5459     }
5460     else if (aParam == "-aspect")
5461     {
5462       if (++anArgIt >= theArgNb)
5463       {
5464         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5465         return 1;
5466       }
5467
5468       TCollection_AsciiString anOption (theArgVec[anArgIt]);
5469       anOption.LowerCase();
5470
5471       if (anOption.IsEqual ("regular"))
5472       {
5473         aFontAspect = Font_FA_Regular;
5474       }
5475       else if (anOption.IsEqual ("bold"))
5476       {
5477         aFontAspect = Font_FA_Bold;
5478       }
5479       else if (anOption.IsEqual ("italic"))
5480       {
5481         aFontAspect = Font_FA_Italic;
5482       }
5483       else if (anOption.IsEqual ("bolditalic"))
5484       {
5485         aFontAspect = Font_FA_BoldItalic;
5486       }
5487       else
5488       {
5489         std::cout << "Error: wrong syntax at '" << aParam.ToCString() << "'.\n";
5490         return 1;
5491       }
5492     }
5493     else if (aParam == "-font")
5494     {
5495       if (++anArgIt >= theArgNb)
5496       {
5497         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5498         return 1;
5499       }
5500
5501       aFontName = theArgVec[anArgIt];
5502     }
5503     else if (aParam == "-composite")
5504     {
5505       if (++anArgIt >= theArgNb)
5506       {
5507         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5508         return 1;
5509       }
5510
5511       ViewerTest::ParseOnOff (theArgVec[anArgIt], anIsCompositeCurve);
5512     }
5513     else if (aParam == "-plane")
5514     {
5515       if (anArgIt + 6 >= theArgNb)
5516       {
5517         std::cout << "Error: wrong number of values for parameter '" << aParam.ToCString() << "'.\n";
5518         return 1;
5519       }
5520
5521       Standard_Real aX = Draw::Atof (theArgVec[++anArgIt]);
5522       Standard_Real aY = Draw::Atof (theArgVec[++anArgIt]);
5523       Standard_Real aZ = Draw::Atof (theArgVec[++anArgIt]);
5524       aNormal.SetCoord (aX, aY, aZ);
5525
5526       aX = Draw::Atof (theArgVec[++anArgIt]);
5527       aY = Draw::Atof (theArgVec[++anArgIt]);
5528       aZ = Draw::Atof (theArgVec[++anArgIt]);
5529       aDirection.SetCoord (aX, aY, aZ);
5530     }
5531     else
5532     {
5533       std::cerr << "Warning! Unknown argument '" << aParam << "'\n";
5534     }
5535   }
5536
5537   aFont.SetCompositeCurveMode (anIsCompositeCurve);
5538   if (!aFont.Init (aFontName.ToCString(), aFontAspect, aTextHeight))
5539   {
5540     std::cerr << "Font initialization error\n";
5541     return 1;
5542   }
5543
5544   aPenAx3 = gp_Ax3 (aPenLoc, aNormal, aDirection);
5545
5546   Font_BRepTextBuilder aBuilder;
5547   DBRep::Set (aName, aBuilder.Perform (aFont, aText, aPenAx3, aHJustification, aVJustification));
5548   return 0;
5549 }
5550
5551 //=======================================================================
5552 //function : VFont
5553 //purpose  : Font management
5554 //=======================================================================
5555
5556 static int VFont (Draw_Interpretor& theDI,
5557                   Standard_Integer  theArgNb,
5558                   const char**      theArgVec)
5559 {
5560   Handle(Font_FontMgr) aMgr = Font_FontMgr::GetInstance();
5561   if (theArgNb < 2)
5562   {
5563     // just print the list of available fonts
5564     Standard_Boolean isFirst = Standard_True;
5565     for (Font_NListOfSystemFont::Iterator anIter (aMgr->GetAvailableFonts());
5566          anIter.More(); anIter.Next())
5567     {
5568       const Handle(Font_SystemFont)& aFont = anIter.Value();
5569       if (!isFirst)
5570       {
5571         theDI << "\n";
5572       }
5573
5574       theDI << aFont->FontName()->String()
5575             << " " << fontStyleString (aFont->FontAspect())
5576             << " " << aFont->FontPath()->String();
5577       isFirst = Standard_False;
5578     }
5579     return 0;
5580   }
5581
5582   for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
5583   {
5584     const TCollection_AsciiString anArg (theArgVec[anArgIter]);
5585     TCollection_AsciiString anArgCase (anArg);
5586     anArgCase.LowerCase();
5587     if (anArgCase == "find")
5588     {
5589       if (++anArgIter >= theArgNb)
5590       {
5591         std::cerr << "Wrong syntax at argument '" << anArg.ToCString() << "'!\n";
5592         return 1;
5593       }
5594
5595       Standard_CString aFontName   = theArgVec[anArgIter];
5596       Font_FontAspect  aFontAspect = Font_FA_Undefined;
5597       if (++anArgIter < theArgNb)
5598       {
5599         anArgCase = theArgVec[anArgIter];
5600         anArgCase.LowerCase();
5601         if (!parseFontStyle (anArgCase, aFontAspect))
5602         {
5603           --anArgIter;
5604         }
5605       }
5606       Handle(Font_SystemFont) aFont = aMgr->FindFont (new TCollection_HAsciiString (aFontName), aFontAspect, -1);
5607       if (aFont.IsNull())
5608       {
5609         std::cerr << "Error: font '" << aFontName << "' is not found!\n";
5610         continue;
5611       }
5612
5613       theDI << aFont->FontName()->String()
5614             << " " << fontStyleString (aFont->FontAspect())
5615             << " " << aFont->FontPath()->String();
5616     }
5617     else if (anArgCase == "add"
5618           || anArgCase == "register")
5619     {
5620       if (++anArgIter >= theArgNb)
5621       {
5622         std::cerr << "Error: wrong syntax at argument '" << anArg << "'!\n";
5623         return 1;
5624       }
5625
5626       Standard_CString aFontPath = theArgVec[anArgIter++];
5627       TCollection_AsciiString aFontName;
5628       Font_FontAspect  aFontAspect = Font_FA_Undefined;
5629       Standard_Integer isSingelStroke = -1;
5630       for (; anArgIter < theArgNb; ++anArgIter)
5631       {
5632         anArgCase = theArgVec[anArgIter];
5633         anArgCase.LowerCase();
5634         if (aFontAspect == Font_FA_Undefined
5635          && parseFontStyle (anArgCase, aFontAspect))
5636         {
5637           continue;
5638         }
5639         else if (anArgCase == "singlestroke"
5640               || anArgCase == "singleline"
5641               || anArgCase == "oneline")
5642         {
5643           isSingelStroke = 1;
5644         }
5645         else if (aFontName.IsEmpty())
5646         {
5647           aFontName = theArgVec[anArgIter];
5648         }
5649         else
5650         {
5651           --anArgIter;
5652           break;
5653         }
5654       }
5655
5656       Handle(Font_SystemFont) aFont = aMgr->CheckFont (aFontPath);
5657       if (aFont.IsNull())
5658       {
5659         std::cerr << "Error: font '" << aFontPath << "' is not found!\n";
5660         continue;
5661       }
5662
5663       if (aFontAspect != Font_FA_Undefined
5664       || !aFontName.IsEmpty())
5665       {
5666         if (aFontAspect == Font_FA_Undefined)
5667         {
5668           aFontAspect = aFont->FontAspect();
5669         }
5670         Handle(TCollection_HAsciiString) aName = aFont->FontName();
5671         if (!aFontName.IsEmpty())
5672         {
5673           aName = new TCollection_HAsciiString (aFontName);
5674         }
5675         aFont = new Font_SystemFont (aName, aFontAspect, new TCollection_HAsciiString (aFontPath));
5676       }
5677       if (isSingelStroke != -1)
5678       {
5679         aFont->SetSingleStrokeFont (isSingelStroke == 1);
5680       }
5681
5682       aMgr->RegisterFont (aFont, Standard_True);
5683       theDI << aFont->FontName()->String()
5684             << " " << fontStyleString (aFont->FontAspect())
5685             << " " << aFont->FontPath()->String();
5686     }
5687     else
5688     {
5689       std::cerr << "Warning! Unknown argument '" << anArg << "'\n";
5690     }
5691   }
5692
5693   return 0;
5694 }
5695
5696 //=======================================================================
5697 //function : VSetEdgeType
5698 //purpose  : Edges type management
5699 //=======================================================================
5700
5701 static int VSetEdgeType (Draw_Interpretor& theDI,
5702                          Standard_Integer  theArgNum,
5703                          const char**      theArgs)
5704 {
5705   if (theArgNum < 4 || theArgNum > 9)
5706   {
5707     theDI << theArgs[0] << " error: wrong number of parameters. Type 'help "
5708           << theArgs[0] << "' for more information.\n";
5709     return 1;
5710   }
5711
5712   Standard_Boolean isForceRedisplay = Standard_False;
5713
5714   // Get shape name
5715   TCollection_AsciiString aName(theArgs[1]);
5716   if (!GetMapOfAIS().IsBound2 (aName))
5717   {
5718     theDI <<  theArgs[0] << " error: wrong object name.\n";
5719     return 1;
5720   }
5721   
5722   Handle(AIS_InteractiveObject) anObject = 
5723     Handle(AIS_InteractiveObject)::DownCast(GetMapOfAIS().Find2(aName));
5724   
5725   // Enable triangle edge mode
5726   if (!anObject->Attributes()->HasOwnShadingAspect())
5727   {
5728     anObject->Attributes()->SetShadingAspect (new Prs3d_ShadingAspect());
5729     *anObject->Attributes()->ShadingAspect()->Aspect() = *anObject->Attributes()->Link()->ShadingAspect()->Aspect();
5730   }
5731   const Handle(Prs3d_ShadingAspect)& aFillAreaAspect = anObject->Attributes()->ShadingAspect();
5732   aFillAreaAspect->Aspect()->SetEdgeOn();
5733
5734   // Parse parameters
5735   for (Standard_Integer anIt = 2; anIt < theArgNum; ++anIt)
5736   {
5737     TCollection_AsciiString aParam ((theArgs[anIt]));
5738     if (aParam.Value (1) == '-' && !aParam.IsRealValue())
5739     {
5740       if (aParam.IsEqual ("-type"))
5741       {
5742         if (theArgNum <= anIt + 1)
5743         {
5744           theDI <<  theArgs[0] << " error: wrong number of values for parameter '"
5745                 << aParam.ToCString() << "'.\n";
5746           return 1;
5747         }
5748
5749         ++anIt;
5750         Aspect_TypeOfLine aTypeEnum = Aspect_TOL_SOLID;
5751         if (!ViewerTest::ParseLineType (theArgs[anIt], aTypeEnum))
5752         {
5753           std::cout << "Syntax error: wrong line type: '" << theArgs[anIt] << "'.\n";
5754           return 1;
5755         }
5756         anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeLineType (aTypeEnum);
5757       }
5758       else if (aParam.IsEqual ("-color"))
5759       {
5760         if (theArgNum <= anIt + 3)
5761         {
5762           theDI <<  theArgs[0] << " error: wrong number of values for parameter '"
5763                 << aParam.ToCString() << "'.\n";
5764           return 1;
5765         }
5766
5767         Standard_Real aR = Draw::Atof(theArgs[++anIt]);
5768         Standard_Real aG = Draw::Atof(theArgs[++anIt]);
5769         Standard_Real aB = Draw::Atof(theArgs[++anIt]);
5770         Quantity_Color aColor = Quantity_Color (aR > 1 ? aR / 255.0 : aR,
5771                                                 aG > 1 ? aG / 255.0 : aG,
5772                                                 aB > 1 ? aB / 255.0 : aB,
5773                                                 Quantity_TOC_RGB);
5774
5775         aFillAreaAspect->Aspect()->SetEdgeColor (aColor);
5776       }
5777       else if (aParam.IsEqual ("-force"))
5778       {
5779         isForceRedisplay = Standard_True;
5780       }
5781       else
5782       {
5783         theDI <<  theArgs[0] << " error: unknown parameter '"
5784               << aParam.ToCString() << "'.\n";
5785         return 1;
5786       }
5787     }
5788   }
5789
5790   // Update shape presentation as aspect parameters were changed
5791   if (isForceRedisplay)
5792   {
5793     ViewerTest::GetAISContext()->Redisplay (anObject, Standard_False);
5794   }
5795   else
5796   {
5797     anObject->SetAspect (aFillAreaAspect);
5798   }
5799
5800   //Update view
5801   ViewerTest::CurrentView()->Redraw();
5802
5803   return 0;
5804 }
5805
5806 //=======================================================================
5807 //function : VUnsetEdgeType
5808 //purpose  : Unsets edges visibility in shading mode
5809 //=======================================================================
5810
5811 static int VUnsetEdgeType (Draw_Interpretor& theDI,
5812                          Standard_Integer  theArgNum,
5813                          const char**      theArgs)
5814 {
5815   if (theArgNum != 2 && theArgNum != 3)
5816   {
5817     theDI << theArgs[0] << " error: wrong number of parameters. Type 'help "
5818           << theArgs[0] << "' for more information.\n";
5819     return 1;
5820   }
5821
5822   Standard_Boolean isForceRedisplay = Standard_False;
5823
5824   // Get shape name
5825   TCollection_AsciiString aName (theArgs[1]);
5826   if (!GetMapOfAIS().IsBound2 (aName))
5827   {
5828     theDI <<  theArgs[0] << " error: wrong object name.\n";
5829     return 1;
5830   }
5831
5832   Handle(AIS_InteractiveObject) anObject = 
5833     Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(aName));
5834
5835   // Enable trianle edge mode
5836   anObject->Attributes()->ShadingAspect()->Aspect()->SetEdgeOff();
5837
5838   // Parse parameters
5839   if (theArgNum == 3)
5840   {
5841     TCollection_AsciiString aParam ((theArgs[2]));
5842     if (aParam.IsEqual ("-force"))
5843     {
5844       isForceRedisplay = Standard_True;
5845     }
5846     else
5847     {
5848        theDI <<  theArgs[0] << " error: unknown parameter '"
5849               << aParam.ToCString() << "'.\n";
5850        return 1;
5851     }
5852   }
5853
5854   // Update shape presentation as aspect parameters were changed
5855   if (isForceRedisplay)
5856   {
5857     ViewerTest::GetAISContext()->Redisplay (anObject, Standard_False);
5858   }
5859   else
5860   {
5861     anObject->SetAspect (anObject->Attributes()->ShadingAspect());
5862   }
5863
5864   //Update view
5865   ViewerTest::CurrentView()->Redraw();
5866
5867   return 0;
5868 }
5869
5870
5871 //=======================================================================
5872 //function : VVertexMode
5873 //purpose  : Switches vertex display mode for AIS_Shape or displays the current value
5874 //=======================================================================
5875
5876 static int VVertexMode (Draw_Interpretor& theDI,
5877                          Standard_Integer  theArgNum,
5878                          const char**      theArgs)
5879 {
5880   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
5881   if (aContext.IsNull())
5882   {
5883     std::cout << "Error: no view available, call 'vinit' before!" << std::endl;
5884     return 1;
5885   }
5886
5887   // No arguments --> print the current default vertex draw mode
5888   if (theArgNum == 1)
5889   {
5890     Prs3d_VertexDrawMode aCurrMode = aContext->DefaultDrawer()->VertexDrawMode();
5891     theDI <<  "Default vertex draw mode: " << (aCurrMode == Prs3d_VDM_Isolated ? "'isolated'" : "'all'") << "\n";
5892     return 0;
5893   }
5894
5895   // -set argument --> change the default vertex draw mode and the mode for all displayed or given object(s)
5896   TCollection_AsciiString aParam (theArgs[1]);
5897   if (aParam == "-set")
5898   {
5899     if (theArgNum == 2)
5900     {
5901       std::cout << "Error: '-set' option not followed by the mode and optional object name(s)" << std::endl;
5902       std::cout << "Type 'help vvertexmode' for usage hints" << std::endl;
5903       return 1;
5904     }
5905
5906     TCollection_AsciiString aModeStr (theArgs[2]);
5907     Prs3d_VertexDrawMode aNewMode =
5908        aModeStr == "isolated" ? Prs3d_VDM_Isolated :
5909       (aModeStr == "all"      ? Prs3d_VDM_All :
5910                                 Prs3d_VDM_Inherited);
5911
5912     Standard_Boolean aRedrawNeeded = Standard_False;
5913     AIS_ListOfInteractive anObjs;
5914
5915     // No object(s) specified -> use all displayed
5916     if (theArgNum == 3)
5917     {
5918       theDI << "Setting the default vertex draw mode and updating all displayed objects...\n";
5919       aContext->DisplayedObjects (anObjs);
5920       aContext->DefaultDrawer()->SetVertexDrawMode (aNewMode);
5921       aRedrawNeeded = Standard_True;
5922     }
5923
5924     Handle(AIS_InteractiveObject) anObject;
5925     for (Standard_Integer aCount = 3; aCount < theArgNum; aCount++)
5926     {
5927       TCollection_AsciiString aName (theArgs[aCount]);
5928       if (!GetMapOfAIS().IsBound2 (aName))
5929       {
5930         theDI << "Warning: wrong object name ignored - " << theArgs[0] << "\n";
5931         continue;
5932       }
5933       anObject = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2(aName));
5934       anObjs.Append (anObject);
5935     }
5936
5937     for (AIS_ListIteratorOfListOfInteractive anIt (anObjs); anIt.More(); anIt.Next())
5938     {
5939       anObject = anIt.Value();
5940       anObject->Attributes()->SetVertexDrawMode (aNewMode);
5941       aContext->Redisplay (anObject, Standard_False);
5942       aRedrawNeeded = Standard_True;
5943     }
5944
5945     if (aRedrawNeeded)
5946       ViewerTest::CurrentView()->Redraw();
5947
5948     return 0;
5949   }
5950
5951   if (theArgNum > 2)
5952   {
5953     std::cout << "Error: invalid number of arguments" << std::endl;
5954     std::cout << "Type 'help vvertexmode' for usage hints" << std::endl;
5955     return 1;
5956   }
5957
5958   // One argument (object name) --> print the current vertex draw mode for the object
5959   Handle(AIS_InteractiveObject) anObject =
5960     Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aParam));
5961   Prs3d_VertexDrawMode aCurrMode = anObject->Attributes()->VertexDrawMode();
5962   theDI <<  "Object's vertex draw mode: " << (aCurrMode == Prs3d_VDM_Isolated ? "'isolated'" : "'all'") << "\n";
5963   return 0;
5964 }
5965
5966 //=======================================================================
5967 //function : VPointCloud
5968 //purpose  : Create interactive object for arbitary set of points.
5969 //=======================================================================
5970 static Standard_Integer VPointCloud (Draw_Interpretor& theDI,
5971                                      Standard_Integer  theArgNum,
5972                                      const char**      theArgs)
5973 {
5974   Handle(AIS_InteractiveContext) anAISContext = ViewerTest::GetAISContext();
5975   if (anAISContext.IsNull())
5976   {
5977     std::cerr << "Error: no active view!\n";
5978     return 1;
5979   }
5980
5981   // command to execute
5982   enum Command
5983   {
5984     CloudForShape, // generate point cloud for shape
5985     CloudSphere,   // generate point cloud for generic sphere
5986     Unknow
5987   };
5988
5989   // count number of non-optional command arguments
5990   Command aCmd = Unknow;
5991   Standard_Integer aCmdArgs = 0;
5992   for (Standard_Integer anArgIter = 1; anArgIter < theArgNum; ++anArgIter)
5993   {
5994     Standard_CString anArg = theArgs[anArgIter];
5995     TCollection_AsciiString aFlag (anArg);
5996     aFlag.LowerCase();
5997     if (aFlag.IsRealValue() || aFlag.Search ("-") != 1)
5998     {
5999       aCmdArgs++;
6000     }
6001   }
6002   switch (aCmdArgs)
6003   {
6004     case 2  : aCmd = CloudForShape; break;
6005     case 7  : aCmd = CloudSphere; break;
6006     default :
6007       std::cout << "Error: wrong number of arguments! See usage:\n";
6008       theDI.PrintHelp (theArgs[0]);
6009       return 1;
6010   }
6011
6012   // parse options
6013   Standard_Boolean toRandColors = Standard_False;
6014   Standard_Boolean hasNormals   = Standard_True;
6015   Standard_Boolean isSetArgNorm = Standard_False;
6016   for (Standard_Integer anArgIter = 1; anArgIter < theArgNum; ++anArgIter)
6017   {
6018     Standard_CString anArg = theArgs[anArgIter];
6019     TCollection_AsciiString aFlag (anArg);
6020     aFlag.LowerCase();
6021     if (aFlag == "-randcolors"
6022      || aFlag == "-randcolor")
6023     {
6024       if (isSetArgNorm && hasNormals)
6025       {
6026         std::cout << "Error: wrong syntax - normals can not be enabled with colors at the same time\n";
6027         return 1;
6028       }
6029       toRandColors = Standard_True;
6030       hasNormals   = Standard_False;
6031     }
6032     else if (aFlag == "-normals"
6033           || aFlag == "-normal")
6034     {
6035       if (toRandColors)
6036       {
6037         std::cout << "Error: wrong syntax - normals can not be enabled with colors at the same time\n";
6038         return 1;
6039       }
6040       isSetArgNorm = Standard_True;
6041       hasNormals   = Standard_True;
6042     }
6043     else if (aFlag == "-nonormals"
6044           || aFlag == "-nonormal")
6045     {
6046       isSetArgNorm = Standard_True;
6047       hasNormals   = Standard_False;
6048     }
6049   }
6050
6051   Standard_CString aName = theArgs[1];
6052
6053   // generate arbitrary set of points
6054   Handle(Graphic3d_ArrayOfPoints) anArrayPoints;
6055   if (aCmd == CloudForShape)
6056   {
6057     Standard_CString aShapeName = theArgs[2];
6058     TopoDS_Shape     aShape     = DBRep::Get (aShapeName);
6059
6060     if (aShape.IsNull())
6061     {
6062       std::cout << "Error: no shape with name '" << aShapeName << "' found\n";
6063       return 1;
6064     }
6065
6066     // calculate number of points
6067     TopLoc_Location  aLocation;
6068     Standard_Integer aNbPoints = 0;
6069     for (TopExp_Explorer aFaceIt (aShape, TopAbs_FACE); aFaceIt.More(); aFaceIt.Next())
6070     {
6071       const TopoDS_Face& aFace = TopoDS::Face (aFaceIt.Current());
6072       Handle(Poly_Triangulation) aTriangulation = BRep_Tool::Triangulation (aFace, aLocation);
6073       if (!aTriangulation.IsNull())
6074       {
6075         aNbPoints += aTriangulation->NbNodes();
6076       }
6077     }
6078     if (aNbPoints < 3)
6079     {
6080       std::cout << "Error: shape should be triangulated!\n";
6081       return 1;
6082     }
6083
6084     anArrayPoints = new Graphic3d_ArrayOfPoints (aNbPoints, toRandColors, hasNormals);
6085     for (TopExp_Explorer aFaceIt (aShape, TopAbs_FACE); aFaceIt.More(); aFaceIt.Next())
6086     {
6087       const TopoDS_Face& aFace = TopoDS::Face (aFaceIt.Current());
6088       Handle(Poly_Triangulation) aTriangulation = BRep_Tool::Triangulation (aFace, aLocation);
6089       if (aTriangulation.IsNull())
6090       {
6091         continue;
6092       }
6093
6094       const TColgp_Array1OfPnt& aNodes = aTriangulation->Nodes();
6095       const gp_Trsf&            aTrsf  = aLocation.Transformation();
6096
6097       // extract normals from nodes
6098       TColgp_Array1OfDir aNormals (aNodes.Lower(), hasNormals ? aNodes.Upper() : aNodes.Lower());
6099       if (hasNormals)
6100       {
6101         Poly_Connect aPolyConnect (aTriangulation);
6102         StdPrs_ToolTriangulatedShape::Normal (aFace, aPolyConnect, aNormals);
6103       }
6104
6105       for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter)
6106       {
6107         gp_Pnt aPoint = aNodes (aNodeIter);
6108         if (!aLocation.IsIdentity())
6109         {
6110           aPoint.Transform (aTrsf);
6111           if (hasNormals)
6112           {
6113             aNormals (aNodeIter).Transform (aTrsf);
6114           }
6115         }
6116
6117         // add vertex into array of points
6118         const Standard_Integer anIndexOfPoint = anArrayPoints->AddVertex (aPoint);
6119         if (toRandColors)
6120         {
6121           Quantity_Color aColor (360.0 * Standard_Real(anIndexOfPoint) / Standard_Real(aNbPoints),
6122                                  1.0, 0.5, Quantity_TOC_HLS);
6123           anArrayPoints->SetVertexColor (anIndexOfPoint, aColor);
6124         }
6125
6126         if (hasNormals)
6127         {
6128           anArrayPoints->SetVertexNormal (anIndexOfPoint, aNormals (aNodeIter));
6129         }
6130       }
6131     }
6132   }
6133   else if (aCmd == CloudSphere)
6134   {
6135     Standard_Real aCenterX       = Draw::Atof (theArgs[2]);
6136     Standard_Real aCenterY       = Draw::Atof (theArgs[3]);
6137     Standard_Real aCenterZ       = Draw::Atof (theArgs[4]);
6138     Standard_Real aRadius        = Draw::Atof (theArgs[5]);
6139     Standard_Integer aNbPoints   = Draw::Atoi (theArgs[6]);
6140
6141     TCollection_AsciiString aDistribution = TCollection_AsciiString(theArgs[7]);
6142     aDistribution.LowerCase();
6143     if ( aDistribution != "surface" && aDistribution != "volume" )
6144     {
6145       std::cout << "Error: wrong arguments! See usage:\n";
6146       theDI.PrintHelp (theArgs[0]);
6147       return 1;
6148     }
6149     Standard_Boolean isSurface = aDistribution == "surface";
6150
6151     gp_Pnt aCenter(aCenterX, aCenterY, aCenterZ);
6152
6153     anArrayPoints = new Graphic3d_ArrayOfPoints (aNbPoints, toRandColors, hasNormals);
6154     for (Standard_Integer aPntIt = 0; aPntIt < aNbPoints; ++aPntIt)
6155     {
6156       Standard_Real anAlpha   = (Standard_Real (rand() % 2000) / 1000.0) * M_PI;
6157       Standard_Real aBeta     = (Standard_Real (rand() % 2000) / 1000.0) * M_PI;
6158       Standard_Real aDistance = isSurface ?
6159         aRadius : (Standard_Real (rand() % aNbPoints) / aNbPoints) * aRadius;
6160
6161       gp_Dir aDir (Cos (anAlpha) * Sin (aBeta),
6162                    Sin (anAlpha),
6163                    Cos (anAlpha) * Cos (aBeta));
6164       gp_Pnt aPoint = aCenter.Translated (aDir.XYZ() * aDistance);
6165
6166       const Standard_Integer anIndexOfPoint = anArrayPoints->AddVertex (aPoint);
6167       if (toRandColors)
6168       {
6169         Quantity_Color aColor (360.0 * Standard_Real (anIndexOfPoint) / Standard_Real (aNbPoints),
6170                                1.0, 0.5, Quantity_TOC_HLS);
6171         anArrayPoints->SetVertexColor (anIndexOfPoint, aColor);
6172       }
6173
6174       if (hasNormals)
6175       {
6176         anArrayPoints->SetVertexNormal (anIndexOfPoint, aDir);
6177       }
6178     }
6179   }
6180
6181   // set array of points in point cloud object
6182   Handle(AIS_PointCloud) aPointCloud = new AIS_PointCloud();
6183   aPointCloud->SetPoints (anArrayPoints);
6184   VDisplayAISObject (aName, aPointCloud);
6185   return 0;
6186 }
6187
6188 //=======================================================================
6189 //function : VPriority
6190 //purpose  : Prints or sets the display priority for an object
6191 //=======================================================================
6192
6193 static int VPriority (Draw_Interpretor& theDI,
6194                       Standard_Integer  theArgNum,
6195                       const char**      theArgs)
6196 {
6197   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
6198   ViewerTest_AutoUpdater anUpdateTool (aContext, ViewerTest::CurrentView());
6199   if (aContext.IsNull())
6200   {
6201     std::cout << "Error: no view available, call 'vinit' before!" << std::endl;
6202     return 1;
6203   }
6204
6205   TCollection_AsciiString aLastArg (theArgs[theArgNum - 1]);
6206   Standard_Integer aPriority = -1;
6207   Standard_Integer aNbArgs   = theArgNum;
6208   if (aLastArg.IsIntegerValue())
6209   {
6210     aPriority = aLastArg.IntegerValue();
6211     --aNbArgs;
6212     if (aPriority < 0 || aPriority > 10)
6213     {
6214       std::cout << "Error: the specified display priority value '" << aLastArg
6215                 << "' is outside the valid range [0..10]" << std::endl;
6216       return 1;
6217     }
6218   }
6219   else
6220   {
6221     anUpdateTool.Invalidate();
6222   }
6223
6224   if (aNbArgs < 2)
6225   {
6226     std::cout << "Error: wrong number of arguments! See usage:\n";
6227     theDI.PrintHelp (theArgs[0]);
6228     return 1;
6229   }
6230
6231   for (Standard_Integer anArgIter = 1; anArgIter < aNbArgs; ++anArgIter)
6232   {
6233     if (anUpdateTool.parseRedrawMode (theArgs[anArgIter]))
6234     {
6235       continue;
6236     }
6237
6238     TCollection_AsciiString aName (theArgs[anArgIter]);
6239     Handle(AIS_InteractiveObject) anIObj;
6240     if (GetMapOfAIS().IsBound2 (aName))
6241     {
6242       anIObj = Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (aName));
6243     }
6244
6245     if (anIObj.IsNull())
6246     {
6247       std::cout << "Error: the object '" << theArgs[1] << "' is not displayed" << std::endl;
6248       return 1;
6249     }
6250
6251     if (aPriority < 1)
6252     {
6253       theDI << aContext->DisplayPriority (anIObj) << " ";
6254     }
6255     else
6256     {
6257       aContext->SetDisplayPriority (anIObj, aPriority);
6258     }
6259   }
6260   return 0;
6261 }
6262
6263 //! Auxiliary class for command vnormals.
6264 class MyShapeWithNormals : public AIS_Shape
6265 {
6266   DEFINE_STANDARD_RTTI_INLINE(MyShapeWithNormals, AIS_Shape);
6267 public:
6268
6269   Standard_Real    NormalLength;
6270   Standard_Integer NbAlongU;
6271   Standard_Integer NbAlongV;
6272   Standard_Boolean ToUseMesh;
6273   Standard_Boolean ToOrient;
6274
6275 public:
6276
6277   //! Main constructor.
6278   MyShapeWithNormals (const TopoDS_Shape& theShape)
6279   : AIS_Shape   (theShape),
6280     NormalLength(10),
6281     NbAlongU  (1),
6282     NbAlongV  (1),
6283     ToUseMesh (Standard_False),
6284     ToOrient  (Standard_False) {}
6285
6286 protected:
6287
6288   //! Comnpute presentation.
6289   virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr,
6290                         const Handle(Prs3d_Presentation)&           thePrs,
6291                         const Standard_Integer                      theMode) Standard_OVERRIDE
6292   {
6293     AIS_Shape::Compute (thePrsMgr, thePrs, theMode);
6294
6295     NCollection_DataMap<TopoDS_Face, NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> > > aNormalMap;
6296     if (ToUseMesh)
6297     {
6298       DBRep_DrawableShape::addMeshNormals (aNormalMap, myshape, NormalLength);
6299     }
6300     else
6301     {
6302       DBRep_DrawableShape::addSurfaceNormals (aNormalMap, myshape, NormalLength, NbAlongU, NbAlongV);
6303     }
6304
6305     Handle(Graphic3d_Group) aPrsGroup = Prs3d_Root::NewGroup (thePrs);
6306     aPrsGroup->SetGroupPrimitivesAspect (myDrawer->ArrowAspect()->Aspect());
6307
6308     const Standard_Real aArrowAngle  = myDrawer->ArrowAspect()->Angle();
6309     const Standard_Real aArrowLength = myDrawer->ArrowAspect()->Length();
6310     for (NCollection_DataMap<TopoDS_Face, NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> > >::Iterator aFaceIt (aNormalMap);
6311          aFaceIt.More(); aFaceIt.Next())
6312     {
6313       const Standard_Boolean toReverse = ToOrient && aFaceIt.Key().Orientation() == TopAbs_REVERSED;
6314       Handle(Graphic3d_ArrayOfSegments) aSegments = new Graphic3d_ArrayOfSegments (2 * aFaceIt.Value().Size());
6315       for (NCollection_Vector<std::pair<gp_Pnt, gp_Pnt> >::Iterator aPntIt (aFaceIt.Value()); aPntIt.More(); aPntIt.Next())
6316       {
6317         std::pair<gp_Pnt, gp_Pnt> aPair = aPntIt.Value();
6318         if (toReverse)
6319         {
6320           const gp_Vec aDir = aPair.first.XYZ() - aPair.second.XYZ();
6321           aPair.second = aPair.first.XYZ() + aDir.XYZ();
6322         }
6323
6324         aSegments->AddVertex (aPair.first);
6325         aSegments->AddVertex (aPair.second);
6326         Prs3d_Arrow::Draw (aPrsGroup, aPair.second, gp_Vec(aPair.first, aPair.second), aArrowAngle, aArrowLength);
6327       }
6328
6329       aPrsGroup->AddPrimitiveArray (aSegments);
6330     }
6331   }
6332
6333 };
6334
6335 //=======================================================================
6336 //function : VNormals
6337 //purpose  : Displays/Hides normals calculated on shape geometry or retrieved from triangulation
6338 //=======================================================================
6339 static int VNormals (Draw_Interpretor& theDI,
6340                      Standard_Integer  theArgNum,
6341                      const char**      theArgs)
6342 {
6343   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
6344   if (aContext.IsNull())
6345   {
6346     std::cout << "Error: no view available, call 'vinit' before!\n";
6347     return 1;
6348   }
6349   else if (theArgNum < 2)
6350   {
6351     std::cout << "Error: wrong number of arguments! See usage:\n";
6352     theDI.PrintHelp (theArgs[0]);
6353     return 1;
6354   }
6355
6356   Standard_Integer anArgIter = 1;
6357   Standard_CString aShapeName = theArgs[anArgIter++];
6358   TopoDS_Shape     aShape     = DBRep::Get (aShapeName);
6359   Standard_Boolean isOn = Standard_True;
6360   if (aShape.IsNull())
6361   {
6362     std::cout << "Error: shape with name '" << aShapeName << "' is not found\n";
6363     return 1;
6364   }
6365
6366   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
6367   Handle(MyShapeWithNormals) aShapePrs;
6368   if (aMap.IsBound2 (aShapeName))
6369   {
6370     aShapePrs = Handle(MyShapeWithNormals)::DownCast (aMap.Find2 (aShapeName));
6371   }
6372
6373   Standard_Boolean isUseMesh = Standard_False;
6374   Standard_Real    aLength = 10.0;
6375   Standard_Integer aNbAlongU = 1, aNbAlongV = 1;
6376   Standard_Boolean isOriented = Standard_False;
6377   for (; anArgIter < theArgNum; ++anArgIter)
6378   {
6379     TCollection_AsciiString aParam (theArgs[anArgIter]);
6380     aParam.LowerCase();
6381     if (anArgIter == 2
6382      && ViewerTest::ParseOnOff (aParam.ToCString(), isOn))
6383     {
6384       continue;
6385     }
6386     else if (aParam == "-usemesh"
6387           || aParam == "-mesh")
6388     {
6389       isUseMesh = Standard_True;
6390     }
6391     else if (aParam == "-length"
6392           || aParam == "-len")
6393     {
6394       ++anArgIter;
6395       aLength = anArgIter < theArgNum ? Draw::Atof (theArgs[anArgIter]) : 0.0;
6396       if (Abs (aLength) <= gp::Resolution())
6397       {
6398         std::cout << "Syntax error: length should not be zero\n";
6399         return 1;
6400       }
6401     }
6402     else if (aParam == "-orient"
6403           || aParam == "-oriented")
6404     {
6405       isOriented = Standard_True;
6406       if (anArgIter + 1 < theArgNum
6407         && ViewerTest::ParseOnOff (theArgs[anArgIter + 1], isOriented))
6408       {
6409         ++anArgIter;
6410       }
6411     }
6412     else if (aParam == "-nbalongu"
6413           || aParam == "-nbu")
6414     {
6415       ++anArgIter;
6416       aNbAlongU = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
6417       if (aNbAlongU < 1)
6418       {
6419         std::cout << "Syntax error: NbAlongU should be >=1\n";
6420         return 1;
6421       }
6422     }
6423     else if (aParam == "-nbalongv"
6424           || aParam == "-nbv")
6425     {
6426       ++anArgIter;
6427       aNbAlongV = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
6428       if (aNbAlongV < 1)
6429       {
6430         std::cout << "Syntax error: NbAlongV should be >=1\n";
6431         return 1;
6432       }
6433     }
6434     else if (aParam == "-nbalong"
6435           || aParam == "-nbuv")
6436     {
6437       ++anArgIter;
6438       aNbAlongU = anArgIter < theArgNum ? Draw::Atoi (theArgs[anArgIter]) : 0;
6439       aNbAlongV = aNbAlongU;
6440       if (aNbAlongU < 1)
6441       {
6442         std::cout << "Syntax error: NbAlong should be >=1\n";
6443         return 1;
6444       }
6445     }
6446     else
6447     {
6448       std::cout << "Syntax error: unknwon argument '" << aParam << "'\n";
6449       return 1;
6450     }
6451   }
6452
6453   if (isOn)
6454   {
6455     if (aShapePrs.IsNull())
6456     {
6457       aShapePrs = new MyShapeWithNormals (aShape);
6458     }
6459     aShapePrs->ToUseMesh    = isUseMesh;
6460     aShapePrs->ToOrient     = isOriented;
6461     aShapePrs->NormalLength = aLength;
6462     aShapePrs->NbAlongU     = aNbAlongU;
6463     aShapePrs->NbAlongV     = aNbAlongV;
6464     VDisplayAISObject (aShapeName, aShapePrs);
6465   }
6466   else if (!aShapePrs.IsNull())
6467   {
6468     VDisplayAISObject (aShapeName, new AIS_Shape (aShape));
6469   }
6470
6471   return 0;
6472 }
6473
6474 //=======================================================================
6475 //function : ObjectsCommands
6476 //purpose  :
6477 //=======================================================================
6478
6479 void ViewerTest::ObjectCommands(Draw_Interpretor& theCommands)
6480 {
6481   const char *group ="AISObjects";
6482
6483   theCommands.Add ("vtrihedron",
6484                    "vtrihedron : vtrihedron name"
6485                    "\n\t\t: [-dispMode {wireframe|shading} ]"
6486                    "\n\t\t: [-origin x y z ]"
6487                    "\n\t\t: [-zaxis u v w -xaxis u v w ]"
6488                    "\n\t\t: [-drawAxes {X|Y|Z|XY|YZ|XZ|XYZ}]"
6489                    "\n\t\t: [-hideLabels {on|off}]"
6490                    "\n\t\t: [-hideArrows {on|off}]"
6491                    "\n\t\t: [-label {XAxis|YAxis|ZAxis} value]"
6492                    "\n\t\t: [-attribute {XAxisLength|YAxisLength|ZAxisLength"
6493                    "\n\t\t:             |TubeRadiusPercent|ConeRadiusPercent"
6494                    "\n\t\t:             |ConeLengthPercent|OriginRadiusPercent"
6495                    "\n\t\t:             |ShadingNumberOfFacettes} value]"
6496                    "\n\t\t: [-color {Origin|XAxis|YAxis|ZAxis|XOYAxis|YOZAxis"
6497                    "\n\t\t:         |XOZAxis|Whole} {r g b | colorName}]"
6498                    "\n\t\t: [-textColor {r g b | colorName}]"
6499                    "\n\t\t: [-arrowColor {r g b | colorName}]"
6500                    "\n\t\t: [-priority {Origin|XAxis|YAxis|ZAxis|XArrow"
6501                    "\n\t\t:            |YArrow|ZArrow|XOYAxis|YOZAxis"
6502                    "\n\t\t:            |XOZAxis|Whole} value]"
6503                    "\n\t\t:"
6504                    "\n\t\t: Creates a new *AIS_Trihedron* object or changes parameters of "
6505                    "\n\t\t: existing trihedron. If no argument is set,"
6506                    "\n\t\t: the default trihedron (0XYZ) is created."
6507                    "\n\t\t: -dispMode mode of visualization: wf - wireframe,"
6508                    "\n\t\t:                                  sh - shading."
6509                    "\n\t\t:               Default value is wireframe."
6510                    "\n\t\t: -origin allows to set trihedron location."
6511                    "\n\t\t: -zaxis/-xaxis allows to set trihedron X and Z"
6512                    "\n\t\t:               directions. The directions should"
6513                    "\n\t\t:               be orthogonal. Y direction is calculated."
6514                    "\n\t\t: -drawAxes allows to set what axes are drawn in the"
6515                    "\n\t\t:           trihedron, default state is XYZ"
6516                    "\n\t\t: -hideLabels allows to show/hide trihedron labels"
6517                    "\n\t\t: -hideArrows allows to show/hide trihedron arrows"
6518                    "\n\t\t: -labels allows to change default X/Y/Z titles of axes"
6519                    "\n\t\t: -attribute sets parameters of trihedron"
6520                    "\n\t\t: -color sets color properties of parts of trihedron"
6521                    "\n\t\t: -textColor sets color properties of trihedron labels"
6522                    "\n\t\t: -arrowColor sets color properties of trihedron arrows"
6523                    "\n\t\t: -priority allows to change default selection priority"
6524                    "\n\t\t: of trihedron components",
6525                    __FILE__,VTrihedron,group);
6526
6527   theCommands.Add("vtri2d",
6528     "vtri2d Name"
6529     "\n\t\t: Creates a plane with a 2D trihedron from an interactively selected face.",
6530     __FILE__,VTrihedron2D ,group);
6531
6532   theCommands.Add("vplanetri",
6533     "vplanetri name"
6534     "\n\t\t: Create a plane from a trihedron selection. If no arguments are set, the default",
6535     __FILE__,VPlaneTrihedron ,group);
6536
6537   theCommands.Add("vsize",
6538     "vsize       : vsize [name(Default=Current)] [size(Default=100)] "
6539     "\n\t\t: Changes the size of a named or selected trihedron."
6540     "\n\t\t: If the name is not defined: it affects the selected trihedrons otherwise nothing is done."
6541     "\n\t\t: If the value is not defined: it is set to 100 by default.",
6542     __FILE__,VSize,group);
6543
6544   theCommands.Add("vaxis",
6545     "vaxis name [Xa] [Ya] [Za] [Xb] [Yb] [Zb]"
6546     "\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",
6547     __FILE__,VAxisBuilder,group);
6548
6549   theCommands.Add("vaxispara",
6550     "vaxispara name "
6551     "\n\t\t: Creates an axis by interactive selection of an edge and a vertex.",
6552     __FILE__,VAxisBuilder,group);
6553
6554   theCommands.Add("vaxisortho",
6555     "vaxisortho name "
6556     "\n\t\t: Creates an axis by interactive selection of an edge and a vertex. The axis will be orthogonal to the selected edge.",
6557     __FILE__,VAxisBuilder,group);
6558
6559   theCommands.Add("vpoint",
6560     "vpoint  PointName [Xa] [Ya] [Za] "
6561     "\n\t\t: Creates a point from coordinates. If the values are not defined,"
6562     "\n\t\t: a point is created by interactive selection of a vertice or an edge (in the center of the edge).",
6563     __FILE__,VPointBuilder,group);
6564
6565   theCommands.Add("vplane",
6566     "vplane  PlaneName [AxisName/PlaneName/PointName] [PointName/PointName/PointName] [Nothing/Nothing/PointName] [TypeOfSensitivity {0|1}]"
6567     "\n\t\t: Creates a plane from named or interactively selected entities."
6568     "\n\t\t: TypeOfSensitivity:"
6569     "\n\t\t:   0 - Interior"
6570     "\n\t\t:   1 - Boundary",
6571     __FILE__,VPlaneBuilder,group);
6572
6573   theCommands.Add ("vchangeplane", "vchangeplane usage: \n"
6574     "   vchangeplane <plane_name>"
6575     " [x=center_x y=center_y z=center_z]"
6576     " [dx=dir_x dy=dir_y dz=dir_z]"
6577     " [sx=size_x sy=size_y]"
6578     " [noupdate]\n"
6579     "   - changes parameters of the plane:\n"
6580     "   - x y z     - center\n"
6581     "   - dx dy dz  - normal\n"
6582     "   - sx sy     - plane sizes\n"
6583     "   - noupdate  - do not update/redisplay the plane in context\n"
6584     "   Please enter coordinates in format \"param=value\" in arbitrary order.",
6585     __FILE__, VChangePlane, group);
6586
6587   theCommands.Add("vplanepara",
6588     "vplanepara  PlaneName  "
6589     "\n\t\t: Creates a plane from interactively selected vertex and face.",
6590     __FILE__,VPlaneBuilder,group);
6591
6592   theCommands.Add("vplaneortho",
6593     "vplaneortho  PlaneName  "
6594     "\n\t\t: Creates a plane from interactive selected face and coplanar edge. ",
6595     __FILE__,VPlaneBuilder,group);
6596
6597   theCommands.Add("vline",
6598     "vline LineName [Xa/PointName] [Ya/PointName] [Za] [Xb] [Yb] [Zb]  "
6599     "\n\t\t: Creates a line from coordinates, named or interactively selected vertices. ",
6600     __FILE__,VLineBuilder,group);
6601
6602   theCommands.Add("vcircle",
6603     "vcircle CircleName [PointName PointName PointName IsFilled]\n\t\t\t\t\t[PlaneName PointName Radius IsFilled]"
6604     "\n\t\t: Creates a circle from named or interactively selected entities."
6605     "\n\t\t: Parameter IsFilled is defined as 0 or 1.",
6606     __FILE__,VCircleBuilder,group);
6607
6608   theCommands.Add ("vdrawtext",
6609                    "vdrawtext name text"
6610                    "\n\t\t: [-pos X=0 Y=0 Z=0]"
6611                    "\n\t\t: [-color {R G B|name}=yellow]"
6612                    "\n\t\t: [-halign {left|center|right}=left]"
6613                    "\n\t\t: [-valign {top|center|bottom|topfirstline}=bottom}]"
6614                    "\n\t\t: [-angle angle=0]"
6615                    "\n\t\t: [-zoom {0|1}=0]"
6616                    "\n\t\t: [-height height=16]"
6617                    "\n\t\t: [-aspect {regular|bold|italic|bolditalic}=regular]"
6618                    "\n\t\t: [-font font=Times]"
6619                    "\n\t\t: [-2d]"
6620                    "\n\t\t: [-perspos {X Y Z}=0 0 0], where"
6621                    "\n\t\t X and Y define the coordinate origin in 2d space relative to the view window"
6622                    "\n\t\t Example: X=0 Y=0 is center, X=1 Y=1 is upper right corner etc..."
6623                    "\n\t\t Z coordinate defines the gap from border of view window (except center position)."
6624                    "\n\t\t: [-disptype {blend|decal|subtitle|dimension|normal}=normal}"
6625                    "\n\t\t: [-subcolor {R G B|name}=white]"
6626                    "\n\t\t: [-noupdate]"
6627                    "\n\t\t: [-plane NormX NormY NormZ DirX DirY DirZ]"
6628                    "\n\t\t: [-flipping]"
6629                    "\n\t\t: Display text label at specified position.",
6630     __FILE__, VDrawText, group);
6631
6632   theCommands.Add("vdrawsphere",
6633     "vdrawsphere: vdrawsphere shapeName Fineness [X=0.0 Y=0.0 Z=0.0] [Radius=100.0] [ToShowEdges=0] [ToPrintInfo=1]\n",
6634     __FILE__,VDrawSphere,group);
6635
6636   theCommands.Add ("vlocation",
6637                 "vlocation name"
6638       "\n\t\t:   [-reset]"
6639       "\n\t\t:   [-copyFrom otherName]"
6640       "\n\t\t:   [-translate X Y [Z]]"
6641       "\n\t\t:   [-rotate x y z dx dy dz angle]"
6642       "\n\t\t:   [-scale [X Y Z] scale]"
6643       "\n\t\t:   [-mirror x y z dx dy dz]"
6644       "\n\t\t:   [-setLocation X Y [Z]]"
6645       "\n\t\t:   [-setRotation QX QY QZ QW]"
6646       "\n\t\t:   [-setScale [X Y Z] scale]"
6647       "\n\t\t: Object local transformation management:"
6648       "\n\t\t:   -reset       reset transformation to identity"
6649       "\n\t\t:   -translate   translate object"
6650       "\n\t\t:   -rotate      applies rotation to local transformation"
6651       "\n\t\t:   -scale       applies scale    to local transformation"
6652       "\n\t\t:   -mirror      applies mirror   to local transformation"
6653       "\n\t\t:   -setLocation assign object location"
6654       "\n\t\t:   -setRotation assign object rotation (quaternion)"
6655       "\n\t\t:   -setScale    assign object scale factor",
6656         __FILE__, VSetLocation, group);
6657   theCommands.Add ("vsetlocation",
6658                    "alias for vlocation",
6659         __FILE__, VSetLocation, group);
6660
6661   theCommands.Add (
6662     "vcomputehlr",
6663     "vcomputehlr: shape hlrname [ eyex eyey eyez lookx looky lookz ]",
6664     __FILE__, VComputeHLR, group);
6665
6666   theCommands.Add("vdrawparray",
6667     "vdrawparray : vdrawparray Name TypeOfArray [vertex = { 'v' x y z [vertex_normal = { 'n' x y z }] [vertex_color = { 'c' r g b }] ] ... [bound = { 'b' vertex_count [bound_color = { 'c' r g b }] ] ... [edge = { 'e' vertex_id ]",
6668     __FILE__,VDrawPArray,group);
6669
6670   theCommands.Add("vconnect", 
6671     "vconnect name Xo Yo Zo object1 object2 ... [color=NAME]"
6672     "\n\t\t: Creates and displays AIS_ConnectedInteractive object from input object and location.",
6673     __FILE__, VConnect, group);
6674
6675   theCommands.Add("vconnectto",
6676     "vconnectto : instance_name Xo Yo Zo object [-nodisplay|-noupdate|-update]"
6677     "  Makes an instance 'instance_name' of 'object' with position (Xo Yo Zo)."
6678     "\n\t\t:   -nodisplay - only creates interactive object, but not displays it",
6679     __FILE__, VConnectTo,group);
6680
6681   theCommands.Add("vdisconnect",
6682     "vdisconnect assembly_name (object_name | object_number | 'all')"
6683     "  Disconnects all objects from assembly or disconnects object by name or number (use vlistconnected to enumerate assembly children).",
6684     __FILE__,VDisconnect,group);
6685
6686   theCommands.Add("vaddconnected",
6687     "vaddconnected assembly_name object_name"
6688     "Adds object to assembly.",
6689     __FILE__,VAddConnected,group);
6690
6691   theCommands.Add("vlistconnected",
6692     "vlistconnected assembly_name"
6693     "Lists objects in assembly.",
6694     __FILE__,VListConnected,group);
6695
6696
6697   theCommands.Add("vselmode", 
6698     "vselmode : [object] mode_number is_turned_on=(1|0)\n"
6699     "  switches selection mode for the determined object or\n"
6700     "  for all objects in context.\n"
6701     "  mode_number is non-negative integer that has different\n"
6702     "    meaning for different interactive object classes.\n"
6703     "    For shapes the following mode_number values are allowed:\n"
6704     "      0 - shape\n"
6705     "      1 - vertex\n"
6706     "      2 - edge\n"
6707     "      3 - wire\n"
6708     "      4 - face\n"
6709     "      5 - shell\n"
6710     "      6 - solid\n"
6711     "      7 - compsolid\n"
6712     "      8 - compound\n"
6713     "  is_turned_on is:\n"
6714     "    1 if mode is to be switched on\n"
6715     "    0 if mode is to be switched off\n", 
6716     __FILE__, VSetSelectionMode, group);
6717
6718   theCommands.Add("vselnext",
6719     "vselnext : hilight next detected",
6720     __FILE__, VSelectionNext, group);
6721
6722   theCommands.Add("vselprev",
6723     "vselnext : hilight previous detected",
6724     __FILE__, VSelectionPrevious, group);
6725
6726   theCommands.Add("vtriangle",
6727     "vtriangle Name PointName PointName PointName"
6728     "\n\t\t: Creates and displays a filled triangle from named points.", 
6729     __FILE__, VTriangle,group);
6730
6731   theCommands.Add("vsegment",
6732     "vsegment Name PointName PointName"
6733     "\n\t\t: Creates and displays a segment from named points.", 
6734     __FILE__, VSegment,group);
6735
6736   theCommands.Add("vobjzlayer",
6737     "vobjzlayer : set/get object [layerid] - set or get z layer id for the interactive object",
6738     __FILE__, VObjZLayer, group);
6739   
6740   theCommands.Add("vpolygonoffset",
6741     "vpolygonoffset : [object [mode factor units]] - sets/gets polygon offset parameters for an object, without arguments prints the default values",
6742     __FILE__, VPolygonOffset, group);
6743
6744   theCommands.Add ("vshowfaceboundary",
6745     "vshowfaceboundary : ObjectName isOn (1/0) [R G B [LineWidth [LineStyle]]]"
6746     "- turns on/off drawing of face boundaries for ais object "
6747     "and defines boundary line style.",
6748     __FILE__, VShowFaceBoundary, group);
6749
6750   theCommands.Add ("vmarkerstest",
6751                    "vmarkerstest: name X Y Z [PointsOnSide=10] [MarkerType=0] [Scale=1.0] [FileName=ImageFile]\n",
6752                    __FILE__, VMarkersTest, group);
6753
6754   theCommands.Add ("text2brep",
6755                    "text2brep: name text"
6756                    "\n\t\t: [-pos X=0 Y=0 Z=0]"
6757                    "\n\t\t: [-halign {left|center|right}=left]"
6758                    "\n\t\t: [-valign {top|center|bottom|topfirstline}=bottom}]"
6759                    "\n\t\t: [-height height=16]"
6760                    "\n\t\t: [-aspect {regular|bold|italic|bolditalic}=regular]"
6761                    "\n\t\t: [-font font=Courier]"
6762                    "\n\t\t: [-composite {on|off}=off]"
6763                    "\n\t\t: [-plane NormX NormY NormZ DirX DirY DirZ]",
6764                    __FILE__, TextToBRep, group);
6765   theCommands.Add ("vfont",
6766                             "vfont [add pathToFont [fontName] [regular,bold,italic,bolditalic=undefined] [singleStroke]]"
6767                    "\n\t\t:        [find fontName [regular,bold,italic,bolditalic=undefined]]",
6768                    __FILE__, VFont, group);
6769   
6770   theCommands.Add ("vsetedgetype",
6771                    "vsetedgetype usage:\n"
6772                    "vsetedgetype ShapeName [-force] [-type {solid, dash, dot}] [-color R G B] "
6773                    "\n\t\t:        Sets edges type and color for input shape",
6774                    __FILE__, VSetEdgeType, group);
6775
6776   theCommands.Add ("vunsetedgetype",
6777                    "vunsetedgetype usage:\n"
6778                    "vunsetedgetype ShapeName [-force]"
6779                    "\n\t\t:        Unsets edges type and color for input shape",
6780                    __FILE__, VUnsetEdgeType, group);
6781
6782   theCommands.Add ("vvertexmode",
6783                    "vvertexmode [name | -set {isolated | all | inherited} [name1 name2 ...]]\n"
6784                    "vvertexmode - prints the default vertex draw mode\n"
6785                    "vvertexmode name - prints the vertex draw mode of the given object\n"
6786                    "vvertexmode -set {isolated | all | inherited} - sets the default vertex draw mode and updates the mode for all displayed objects\n"
6787                    "vvertexmode -set {isolated | all | inherited} name1 name2 ... - sets the vertex draw mode for the specified object(s)\n",
6788                    __FILE__, VVertexMode, group);
6789
6790   theCommands.Add ("vpointcloud",
6791                    "vpointcloud name shape [-randColor] [-normals] [-noNormals]"
6792                    "\n\t\t: Create an interactive object for arbitary set of points"
6793                    "\n\t\t: from triangulated shape."
6794                    "\n"
6795                    "vpointcloud name x y z r npts {surface|volume}\n"
6796                    "            ... [-randColor] [-normals] [-noNormals]"
6797                    "\n\t\t: Create arbitrary set of points (npts) randomly distributed"
6798                    "\n\t\t: on spheric surface or within spheric volume (x y z r)."
6799                    "\n\t\t:"
6800                    "\n\t\t: Additional options:"
6801                    "\n\t\t:  -randColor - generate random color per point"
6802                    "\n\t\t:  -normals   - generate normal per point (default)"
6803                    "\n\t\t:  -noNormals - do not generate normal per point"
6804                    "\n",
6805                    __FILE__, VPointCloud, group);
6806
6807   theCommands.Add("vpriority",
6808     "vpriority [-noupdate|-update] name [value]\n\t\t  prints or sets the display priority for an object",
6809     __FILE__,
6810     VPriority, group);
6811
6812   theCommands.Add ("vnormals",
6813                    "vnormals usage:\n"
6814                    "vnormals Shape [{on|off}=on] [-length {10}] [-nbAlongU {1}] [-nbAlongV {1}] [-nbAlong {1}]"
6815                    "\n\t\t:        [-useMesh] [-oriented {0}1}=0]"
6816                    "\n\t\t:  Displays/Hides normals calculated on shape geometry or retrieved from triangulation",
6817                    __FILE__, VNormals, group);
6818 }