Salome HOME
Typo-fix by Kunda
[modules/geom.git] / src / MeasureGUI / MeasureGUI_DimensionCreateTool.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // GEOM GEOMGUI : GUI for Geometry component
24 // File   : MeasureGUI_DimensionCreateTool.cxx
25 // Author : Anton POLETAEV, Open CASCADE S.A.S.
26
27 #include "MeasureGUI_DimensionCreateTool.h"
28
29 // GEOM includes
30 #include <GEOMBase.h>
31
32 // GUI includes
33 #include <SalomeApp_Application.h>
34
35 // SUIT includes
36 #include <OCCViewer_ViewModel.h>
37 #include <OCCViewer_ViewManager.h>
38 #include <OCCViewer_ViewWindow.h>
39 #include <OCCViewer_ViewPort3d.h>
40
41 // OCCT includes
42 #include <Adaptor3d_CurveOnSurface.hxx>
43 #include <BRep_Tool.hxx>
44 #include <BRepTools.hxx>
45 #include <BRepAdaptor_Curve.hxx>
46 #include <BRepAdaptor_Surface.hxx>
47 #include <BRepBndLib.hxx>
48 #include <ElCLib.hxx>
49 #include <gp_Pnt.hxx>
50 #include <gp_Circ.hxx>
51 #include <gp_Sphere.hxx>
52 #include <gp_Cone.hxx>
53 #include <gp_Torus.hxx>
54 #include <gce_MakeDir.hxx>
55 #include <gce_MakePln.hxx>
56 #include <gce_MakeCirc.hxx>
57 #include <GC_MakePlane.hxx>
58 #include <Geom_Circle.hxx>
59 #include <Geom_Plane.hxx>
60 #include <Geom_ElementarySurface.hxx>
61 #include <Geom_Surface.hxx>
62 #include <Geom_ConicalSurface.hxx>
63 #include <Geom_SphericalSurface.hxx>
64 #include <Geom_ToroidalSurface.hxx>
65 #include <Geom_TrimmedCurve.hxx>
66 #include <GeomLib.hxx>
67 #include <GeomLib_Tool.hxx>
68 #include <TopoDS_Shape.hxx>
69 #include <TopoDS_Vertex.hxx>
70 #include <TopoDS_Edge.hxx>
71 #include <TopExp.hxx>
72 #include <TopExp_Explorer.hxx>
73 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
74 #include <TopTools_ListOfShape.hxx>
75 #include <TopTools_ListIteratorOfListOfShape.hxx>
76 #include <TColgp_SequenceOfDir.hxx>
77 #include <V3d_View.hxx>
78
79 // plane associated with custom data
80 struct PlaneAndSegment
81 {
82   PlaneAndSegment() {}
83   PlaneAndSegment(const gp_Pln& thePlane, const MeasureGUI_DimensionCreateTool::Segment& theSegment) : pln(thePlane), seg(theSegment) {}
84   operator gp_Pln () const { return pln; }
85   operator MeasureGUI_DimensionCreateTool::Segment () const { return seg; }
86   gp_Pln pln;
87   MeasureGUI_DimensionCreateTool::Segment seg;
88 };
89
90 typedef NCollection_Sequence<PlaneAndSegment> SeqOfPlnsAndSegments;
91
92 //=================================================================================
93 // function : Constructor
94 // purpose  :
95 //=================================================================================
96 MeasureGUI_DimensionCreateTool::MeasureGUI_DimensionCreateTool()
97 {
98   Settings.DefaultFlyout = 0.0;
99   Settings.ActiveView = NULL;
100 }
101
102 //=================================================================================
103 // function : LengthOnEdge
104 // purpose  :
105 //=================================================================================
106 Handle(AIS_LengthDimension) MeasureGUI_DimensionCreateTool::LengthOnEdge( const GEOM::GeomObjPtr& theMeasuredObj ) const
107 {
108   /* ---------------------------------------------------------------- *
109    *                  get the edge and parent shape                   *
110    * ---------------------------------------------------------------- */
111
112   TopoDS_Shape aMeasuredShape;
113   TopoDS_Shape aMainShape;
114   if ( !GEOMBase::GetShape( theMeasuredObj.operator ->(), aMeasuredShape ) )
115   {
116     return NULL;
117   }
118
119   if ( !GEOMBase::GetShape( GetMainShape( theMeasuredObj ).get(), aMainShape ) )
120   {
121     return NULL;
122   }
123
124   /* ------------------------------------------------- */
125   /*            check the input geometry               */
126   /* ------------------------------------------------- */
127
128   TopoDS_Edge anEdge = TopoDS::Edge( aMeasuredShape );
129
130   TopoDS_Vertex aVertex1;
131   TopoDS_Vertex aVertex2;
132   TopExp::Vertices( anEdge, aVertex1, aVertex2 );
133
134   gp_Pnt aPnt1 = BRep_Tool::Pnt( aVertex1 );
135   gp_Pnt aPnt2 = BRep_Tool::Pnt( aVertex2 );
136   if ( aPnt1.Distance( aPnt2 ) <= Precision::Confusion() )
137   {
138     return NULL;
139   }
140
141   /* ------------------------- *
142    *   position the dimension 
143    * ------------------------- */
144
145   Bnd_Box aBnd;
146   BRepBndLib::AddClose( aMainShape, aBnd );
147
148   // get face sides
149   TopTools_IndexedDataMapOfShapeListOfShape aRelationMap;
150   TopExp::MapShapesAndAncestors( aMainShape, TopAbs_EDGE, TopAbs_FACE, aRelationMap );
151   const TopTools_ListOfShape& aRelatedFaces = aRelationMap.FindFromKey( anEdge );
152
153   gp_Vec aFaceN1( gp::Origin(), gp::Origin() );
154   gp_Vec aFaceN2( gp::Origin(), gp::Origin() );
155   gp_Vec aFaceS1( gp::Origin(), gp::Origin() );
156   gp_Vec aFaceS2( gp::Origin(), gp::Origin() );
157
158   gp_Pnt aMiddlePnt = gp_Pnt( ( aPnt1.XYZ() + aPnt2.XYZ() ) * 0.5 );
159
160   TopTools_ListIteratorOfListOfShape aFaceIt( aRelatedFaces );
161
162   // get face side directions
163   if ( aFaceIt.More() )
164   {
165     TopoDS_Face aFace = TopoDS::Face( aFaceIt.Value() );
166
167     gp_Dir aSideDir;
168     if ( GetFaceSide( aFace, anEdge, aSideDir ) )
169     {
170       aFaceS1 = aSideDir;
171     }
172
173     Handle(Geom_Surface) aSurface = BRep_Tool::Surface( aFace );
174
175     Standard_Real aU = 0.0, aV = 0.0;
176     GeomLib_Tool::Parameters( aSurface, aMiddlePnt, Precision::Confusion(), aU, aV );
177
178     gp_Dir aNorm;
179     if ( GeomLib::NormEstim( aSurface, gp_Pnt2d( aU, aV ), Precision::Confusion(), aNorm ) <= 1 )
180     {
181       aFaceN1 = aFace.Orientation() == TopAbs_REVERSED ? -aNorm : aNorm;
182     }
183
184     aFaceIt.Next();
185   }
186
187   if ( aFaceIt.More() )
188   {
189     TopoDS_Face aFace = TopoDS::Face( aFaceIt.Value() );
190
191     gp_Dir aSideDir;
192     if ( GetFaceSide( aFace, anEdge, aSideDir ) )
193     {
194       aFaceS2 = aSideDir;
195     }
196
197     Handle(Geom_Surface) aSurface = BRep_Tool::Surface( aFace );
198
199     Standard_Real aU = 0.0, aV = 0.0;
200     GeomLib_Tool::Parameters( aSurface, aMiddlePnt, Precision::Confusion(), aU, aV );
201
202     gp_Dir aNorm;
203     if ( GeomLib::NormEstim( aSurface, gp_Pnt2d( aU, aV ), Precision::Confusion(), aNorm ) <= 1 )
204     {
205       aFaceN2 = aFace.Orientation() == TopAbs_REVERSED ? -aNorm : aNorm;
206     }
207   }
208
209   gp_Pln aPln;
210   PositionLength( aBnd, aFaceN1, aFaceN2, aFaceS1, aFaceS2, aPnt1, aPnt2, aPln );
211
212   /* --------------------------------------------------------- *
213    *   construct the dimension for the best selected position
214    * --------------------------------------------------------- */
215
216   Handle(AIS_LengthDimension) aDimension = new AIS_LengthDimension( anEdge, aPln );
217
218   aDimension->SetFlyout( Settings.DefaultFlyout );
219
220   if ( !aDimension->IsValid() )
221   {
222     return NULL;
223   }
224
225   return aDimension;
226 }
227
228 //=================================================================================
229 // function : LengthByPoints
230 // purpose  :
231 //=================================================================================
232 Handle(AIS_LengthDimension) MeasureGUI_DimensionCreateTool::LengthByPoints( const GEOM::GeomObjPtr& theMeasuredObj1,
233                                                                             const GEOM::GeomObjPtr& theMeasuredObj2 ) const
234 {
235   /* ---------------------------------------------------------------- *
236    *                  get the edge and parent shape                   *
237    * ---------------------------------------------------------------- */
238
239   TopoDS_Shape aMeasuredShape1;
240   TopoDS_Shape aMeasuredShape2;
241   TopoDS_Shape aMainShape;
242
243   if ( !GEOMBase::GetShape( theMeasuredObj1.operator ->(), aMeasuredShape1 ) )
244   {
245     return NULL;
246   }
247
248   if ( !GEOMBase::GetShape( theMeasuredObj2.operator ->(), aMeasuredShape2 ) )
249   {
250     return NULL;
251   }
252
253   if ( !GEOMBase::GetShape( GetMainShape( theMeasuredObj1 ).get(), aMainShape ) )
254   {
255     return NULL;
256   }
257
258   /* ------------------------------------------------- */
259   /*            check the input geometry               */
260   /* ------------------------------------------------- */
261
262   TopoDS_Vertex aVertex1 = TopoDS::Vertex( aMeasuredShape1 );
263   TopoDS_Vertex aVertex2 = TopoDS::Vertex( aMeasuredShape2 );
264
265   gp_Pnt aPnt1 = BRep_Tool::Pnt( aVertex1 );
266   gp_Pnt aPnt2 = BRep_Tool::Pnt( aVertex2 );
267   if ( aPnt1.Distance( aPnt2 ) <= Precision::Confusion() )
268   {
269     return NULL;
270   }
271
272   /* ------------------------- *
273    *   position the dimension 
274    * ------------------------- */
275
276   Bnd_Box aBnd;
277   BRepBndLib::AddClose( aMainShape, aBnd );
278
279   // check whether the points share same edge
280   TopExp_Explorer anEdgeExp( aMainShape, TopAbs_EDGE, TopAbs_EDGE );
281   for ( ; anEdgeExp.More(); anEdgeExp.Next() )
282   {
283     TopoDS_Vertex anEdgeV1;
284     TopoDS_Vertex anEdgeV2;
285     TopExp::Vertices( TopoDS::Edge( anEdgeExp.Current() ), anEdgeV1, anEdgeV2 );
286     gp_Pnt anEdgePnt1 = BRep_Tool::Pnt( anEdgeV1 );
287     gp_Pnt anEdgePnt2 = BRep_Tool::Pnt( anEdgeV2 );
288
289     if ( aPnt1.Distance( anEdgePnt1 ) <= Precision::Confusion() )
290     {
291       if ( aPnt2.Distance( anEdgePnt2 ) <= Precision::Confusion() )
292       {
293         break;
294       }
295     }
296
297     if ( aPnt2.Distance( anEdgePnt1 ) <= Precision::Confusion() )
298     {
299       if ( aPnt1.Distance( anEdgePnt2 ) <= Precision::Confusion() )
300       {
301         break;
302       }
303     }
304   }
305
306   gp_Vec aFaceN1( gp::Origin(), gp::Origin() );
307   gp_Vec aFaceN2( gp::Origin(), gp::Origin() );
308   gp_Vec aFaceS1( gp::Origin(), gp::Origin() );
309   gp_Vec aFaceS2( gp::Origin(), gp::Origin() );
310
311   // have shared edge
312   if ( anEdgeExp.More() )
313   {
314     TopoDS_Edge anEdge = TopoDS::Edge( anEdgeExp.Current() );
315     TopTools_IndexedDataMapOfShapeListOfShape aRelationMap;
316     TopExp::MapShapesAndAncestors( aMainShape, TopAbs_EDGE, TopAbs_FACE, aRelationMap );
317     const TopTools_ListOfShape& aRelatedFaces = aRelationMap.FindFromKey( anEdge );
318
319     gp_Pnt aMiddlePnt = gp_Pnt( ( aPnt1.XYZ() + aPnt2.XYZ() ) * 0.5 );
320
321     TopTools_ListIteratorOfListOfShape aFaceIt( aRelatedFaces );
322
323     // get face side directions
324     if ( aFaceIt.More() )
325     {
326       TopoDS_Face aFace = TopoDS::Face( aFaceIt.Value() );
327
328       gp_Dir aSideDir;
329       if ( GetFaceSide( aFace, anEdge, aSideDir ) )
330       {
331         aFaceS1 = aSideDir;
332       }
333
334       Handle(Geom_Surface) aSurface = BRep_Tool::Surface( aFace );
335
336       Standard_Real aU = 0.0, aV = 0.0;
337       GeomLib_Tool::Parameters( aSurface, aMiddlePnt, Precision::Confusion(), aU, aV );
338
339       gp_Dir aNorm;
340       if ( GeomLib::NormEstim( aSurface, gp_Pnt2d( aU, aV ), Precision::Confusion(), aNorm ) <= 1 )
341       {
342         aFaceN1 = aFace.Orientation() == TopAbs_REVERSED ? -aNorm : aNorm;
343       }
344
345       aFaceIt.Next();
346     }
347
348     if ( aFaceIt.More() )
349     {
350       TopoDS_Face aFace = TopoDS::Face( aFaceIt.Value() );
351
352       gp_Dir aSideDir;
353       if ( GetFaceSide( aFace, anEdge, aSideDir ) )
354       {
355         aFaceS2 = aSideDir;
356       }
357
358       Handle(Geom_Surface) aSurface = BRep_Tool::Surface( aFace );
359
360       Standard_Real aU = 0.0, aV = 0.0;
361       GeomLib_Tool::Parameters( aSurface, aMiddlePnt, Precision::Confusion(), aU, aV );
362
363       gp_Dir aNorm;
364       if ( GeomLib::NormEstim( aSurface, gp_Pnt2d( aU, aV ), Precision::Confusion(), aNorm ) <= 1 )
365       {
366         aFaceN2 = aFace.Orientation() == TopAbs_REVERSED ? -aNorm : aNorm;
367       }
368     }
369   }
370
371   gp_Pln aPln;
372   PositionLength( aBnd, aFaceN1, aFaceN2, aFaceS1, aFaceS2, aPnt1, aPnt2, aPln );
373
374   /* --------------------------------------------------------- *
375    *   construct the dimension for the best selected position
376    * --------------------------------------------------------- */
377
378   Handle(AIS_LengthDimension) aDimension = new AIS_LengthDimension( aPnt1, aPnt2, aPln );
379
380   aDimension->SetFlyout( Settings.DefaultFlyout );
381
382   if ( !aDimension->IsValid() )
383   {
384     return NULL;
385   }
386
387   return aDimension;
388 }
389
390 //=================================================================================
391 // function : LengthByParallelEdges
392 // purpose  :
393 //=================================================================================
394 Handle(AIS_LengthDimension) MeasureGUI_DimensionCreateTool::LengthByParallelEdges( const GEOM::GeomObjPtr& theEdge1,
395                                                                                    const GEOM::GeomObjPtr& theEdge2 ) const
396 {
397   TopoDS_Shape aFirstSh;
398   if ( !GEOMBase::GetShape( theEdge1.operator ->(), aFirstSh ) )
399   {
400     return NULL;
401   }
402
403   TopoDS_Shape aSecondSh;
404   if ( !GEOMBase::GetShape( theEdge2.operator ->(), aSecondSh ) )
405   {
406     return NULL;
407   }
408
409   if( aFirstSh == aSecondSh )
410     return NULL;
411
412   TopoDS_Edge aFirstEdge  = TopoDS::Edge( aFirstSh );
413   TopoDS_Edge aSecondEdge = TopoDS::Edge( aSecondSh );
414
415   // Build plane through three points
416   BRepAdaptor_Curve aCurve1( aFirstEdge );
417   BRepAdaptor_Curve aCurve2( aSecondEdge );
418
419   gp_Pnt aPnt1 = aCurve1.Value( 0.1 );
420   gp_Pnt aPnt2 = aCurve1.Value( 0.9 );
421   gp_Pnt aPnt3 = aCurve2.Value( 0.5 );
422
423   GC_MakePlane aMkPlane( aPnt1, aPnt2, aPnt3 );
424   Handle(Geom_Plane) aPlane = aMkPlane.Value();
425
426   // check whether it is possible to compute valid dimension
427   Handle(AIS_LengthDimension) aDimension = new AIS_LengthDimension ( aFirstEdge, aSecondEdge, aPlane->Pln() );
428
429   aDimension->SetFlyout( Settings.DefaultFlyout );
430
431   if ( !aDimension->IsValid() )
432   {
433     return NULL;
434   }
435
436   return aDimension;
437 }
438
439 //=================================================================================
440 // function : Diameter
441 // purpose  :
442 //=================================================================================
443 Handle(AIS_DiameterDimension) MeasureGUI_DimensionCreateTool::Diameter( const GEOM::GeomObjPtr& theMeasuredObj ) const
444 {
445   /* ------------------------------------------------ *
446    *     get the shape and its parent (if exist)      *
447    * ------------------------------------------------ */
448
449   TopoDS_Shape aMeasuredShape;
450   TopoDS_Shape aMainShape;
451   if ( !GEOMBase::GetShape( theMeasuredObj.operator ->(), aMeasuredShape ) )
452   {
453     return NULL;
454   }
455
456   if ( !GEOMBase::GetShape( GetMainShape( theMeasuredObj ).get(), aMainShape ) )
457   {
458     return NULL;
459   }
460
461   Bnd_Box aBnd;
462   BRepBndLib::AddClose( aMainShape, aBnd );
463
464   /* ------------------------------------------------ *
465    *    get the dimension construction arguments      *
466    * ------------------------------------------------ */
467
468   Handle(Geom_Circle) aCircle;
469
470   Standard_Real aPmin = 0, aPmax = 2 * M_PI;
471
472   gp_Vec aFaceN( gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(0.0, 0.0, 0.0) );
473
474   switch ( aMeasuredShape.ShapeType() )
475   {
476     case TopAbs_FACE:
477     {
478       TopoDS_Face aMeasuredFace = TopoDS::Face(aMeasuredShape);
479
480       BRepAdaptor_Surface aSurf( aMeasuredFace );
481
482       Standard_Real aUmin = aSurf.FirstUParameter();
483       Standard_Real aUmax = aSurf.LastUParameter();
484       Standard_Real aVmin = aSurf.FirstVParameter();
485       Standard_Real aVmax = aSurf.LastVParameter();
486
487       // get arguments of sphere (the sphere should not be cutted at v-center)
488       if ( aSurf.GetType() == GeomAbs_Sphere )
489       {
490         if ( aVmax <= Precision::PConfusion() || aVmin >= Precision::PConfusion() )
491         {
492           return NULL;
493         }
494
495         Handle(Geom_Surface) aBasisSurface = Handle(Geom_Surface)::DownCast(
496           aSurf.Surface().Surface()->Transformed( aSurf.Trsf() ) );
497
498         Handle(Geom_Curve) aCurve = aBasisSurface->VIso( 0.0 );
499
500         if ( aCurve->IsKind( STANDARD_TYPE( Geom_Circle ) ) )
501         {
502           aPmin = aUmin;
503           aPmax = aUmax;
504           aCircle = Handle(Geom_Circle)::DownCast( aCurve );
505         }
506         else if (  aCurve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve ) ) )
507         {
508           Handle(Geom_TrimmedCurve) aTrimmedCurve = Handle(Geom_TrimmedCurve)::DownCast( aCurve );
509           aPmin = aTrimmedCurve->FirstParameter();
510           aPmax = aTrimmedCurve->LastParameter();
511
512           aCircle = Handle(Geom_Circle)::DownCast( aTrimmedCurve );
513         }
514         break;
515       }
516
517       // get arguments of cone
518       if ( aSurf.GetType() == GeomAbs_Cone )
519       {
520         aPmin = aUmin;
521         aPmax = aUmax;
522
523         gp_Cone aCone = aSurf.Cone();
524         gp_Ax2 anAx2 = aCone.Position().Ax2();
525         aCircle = new Geom_Circle( anAx2, aCone.RefRadius() );
526
527         aFaceN = aCone.SemiAngle() > 0.0 
528           ?  anAx2.Axis().Direction()
529           : -anAx2.Axis().Direction();
530         break;
531       }
532
533       // get arguments of closed torus or cylinder
534       if ( aSurf.GetType() == GeomAbs_Torus || aSurf.GetType() == GeomAbs_Cylinder )
535       {
536         Handle(Geom_Surface) aBasisSurface = Handle(Geom_Surface)::DownCast(
537           aSurf.Surface().Surface()->Transformed( aSurf.Trsf() ) );
538
539         Handle(Geom_Curve) aCurve = aBasisSurface->VIso( (aVmax + aVmin) * 0.5 );
540
541         if ( aCurve->IsKind( STANDARD_TYPE( Geom_Circle ) ) )
542         {
543           aPmin = aUmin;
544           aPmax = aUmax;
545           aCircle = Handle(Geom_Circle)::DownCast( aCurve );
546         }
547         else if (  aCurve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve ) ) )
548         {
549           Handle(Geom_TrimmedCurve) aTrimmedCurve = Handle(Geom_TrimmedCurve)::DownCast( aCurve );
550           aPmin = aTrimmedCurve->FirstParameter();
551           aPmax = aTrimmedCurve->LastParameter();
552
553           aCircle = Handle(Geom_Circle)::DownCast( aTrimmedCurve );
554         }
555
556         break;
557       }
558
559       // face containing edge?
560       TopExp_Explorer anExp( aMeasuredShape, TopAbs_EDGE );
561       if ( !anExp.More() )
562       {
563         return NULL;
564       }
565
566       TopoDS_Shape anExpEdge = anExp.Current();
567       if ( anExpEdge.IsNull() )
568       {
569         return NULL;
570       }
571
572       // only a single edge is expected
573       anExp.Next();
574       if ( anExp.More() )
575       {
576         return NULL;
577       }
578
579       // do not break, go to edge checking
580       aMeasuredShape = anExpEdge;
581     }
582
583     case TopAbs_EDGE:
584     {
585       TopoDS_Edge aMeasureEdge = TopoDS::Edge( aMeasuredShape );
586
587       BRepAdaptor_Curve aCurve(aMeasureEdge);
588
589       if ( aCurve.GetType() != GeomAbs_Circle )
590       {
591         return NULL;
592       }
593
594       aPmin = aCurve.FirstParameter();
595       aPmax = aCurve.LastParameter();
596
597       aCircle = new Geom_Circle( aCurve.Circle() );
598
599       // check if there is an parent face containing the edge
600       TopTools_IndexedDataMapOfShapeListOfShape aShapeMap;
601       TopExp::MapShapesAndAncestors( aMainShape, TopAbs_EDGE, TopAbs_FACE, aShapeMap );
602       const TopTools_ListOfShape& aFaces = aShapeMap.FindFromKey( aMeasureEdge );
603
604       TopTools_ListIteratorOfListOfShape aFaceIt( aFaces );
605       for ( ; aFaceIt.More(); aFaceIt.Next() )
606       {
607         TopoDS_Face aFace = TopoDS::Face( aFaceIt.Value() );
608
609         Handle(Geom_Surface) aSurface = BRep_Tool::Surface( TopoDS::Face( aFace ) );
610
611         gp_Pnt aCircCenter = aCircle->Circ().Location();
612         Standard_Real aCircU = 0.0, aCircV = 0.0;
613         GeomLib_Tool::Parameters( aSurface, aCircCenter, Precision::Confusion(), aCircU, aCircV );
614
615         gp_Dir aNorm;
616         if ( GeomLib::NormEstim( aSurface, gp_Pnt2d( aCircU, aCircV ), Precision::Confusion(), aNorm ) > 1 )
617         {
618           break;
619         }
620
621         if ( aNorm.Angle( aCircle->Circ().Axis().Direction() ) > M_PI * 0.25 )
622         {
623           continue;
624         }
625
626         aFaceN = gp_Vec( aFace.Orientation() == TopAbs_REVERSED ? -aNorm : aNorm );
627       }
628     }
629     break;
630   }
631
632   if ( aCircle.IsNull() )
633   {
634     return NULL;
635   }
636
637   ElCLib::AdjustPeriodic( 0.0, M_PI * 2, Precision::PConfusion(), aPmin, aPmax );
638
639   /* ------------------------- *
640    *   position the dimension 
641    * ------------------------- */
642
643   gp_Pnt aPnt1;
644   gp_Pnt aPnt2;
645   gp_Pln aPln;
646
647   // diameter for closed circle
648   if ( Abs( ( aPmax - aPmin ) - M_PI * 2 ) <= Precision::PConfusion() )
649   {
650     PositionDiameter( aBnd, aFaceN, aCircle->Circ(), aPnt1, aPnt2, aPln );
651   }
652   // diameter for half-closed circle
653   else if ( Abs( aPmax - aPmin ) > M_PI )
654   {
655     Standard_Real anAnchor = aPmin + ( ( aPmax - aPmin ) - M_PI ) * 0.5;
656
657     PositionDiameter( aBnd, aFaceN, aCircle->Circ(), anAnchor, aPln );
658
659     aPnt1 = ElCLib::Value( anAnchor, aCircle->Circ() );
660     aPnt2 = ElCLib::Value( anAnchor + M_PI, aCircle->Circ() );
661   }
662   // diameter for less than half-closed circle
663   else
664   {
665     Standard_Real anAnchor = aPmin + ( aPmax - aPmin ) * 0.5;
666
667     PositionDiameter( aBnd, aFaceN, aCircle->Circ(), anAnchor, aPln );
668
669     aPnt1 = ElCLib::Value( anAnchor, aCircle->Circ() );
670     aPnt2 = ElCLib::Value( anAnchor + M_PI, aCircle->Circ() );
671   }
672
673   /* --------------------------------------------------------- *
674    *   construct the dimension for the best selected position
675    * --------------------------------------------------------- */
676
677   gp_Pnt aCircP = aCircle->Circ().Location();
678   gp_Dir aCircN = aCircle->Circ().Axis().Direction();
679   gp_Dir aCircX = gce_MakeDir( aPnt1, aPnt2 );
680   Standard_Real aCircR = aCircle->Circ().Radius();
681
682   // construct closed circle as base for the diameter dimension
683   Standard_Boolean isReversed = ( ( aPln.Axis().Direction() ^ aCircX ) * aCircN ) < 0.0;
684
685   gp_Circ aRuledCirc = gce_MakeCirc( gp_Ax2( aCircP, isReversed ? -aCircN : aCircN, aCircX ), aCircR );
686
687   Handle(AIS_DiameterDimension) aDimension = new AIS_DiameterDimension( aRuledCirc, aPln );
688
689   // if flyout is extended in tangent direction to circle, the default flyout value is used
690   // if flyout is extended in plane of circle, the zero flyout value is chosen initially
691   Standard_Real aFlyout = aCircN.IsParallel( aPln.Axis().Direction(), Precision::Angular() ) ? 0.0 : Settings.DefaultFlyout;
692
693   aDimension->SetFlyout(aFlyout);
694
695   if ( !aDimension->IsValid() )
696   {
697     return NULL;
698   }
699
700   return aDimension;
701 }
702
703 //=================================================================================
704 // function : AngleByTwoEdges
705 // purpose  :
706 //=================================================================================
707 Handle(AIS_AngleDimension) MeasureGUI_DimensionCreateTool::AngleByTwoEdges( const GEOM::GeomObjPtr& theEdge1,
708                                                                             const GEOM::GeomObjPtr& theEdge2 ) const
709 {
710   /* --------------------------------------------------- */
711   /*         get construction and parent shapes          */
712   /* --------------------------------------------------- */
713
714   TopoDS_Shape aShapeEdge1;
715   TopoDS_Shape aShapeMain1;
716   if ( !GEOMBase::GetShape( theEdge1.get(), aShapeEdge1 ) )
717   {
718     return NULL;
719   }
720   if ( !GEOMBase::GetShape( GetMainShape( theEdge1 ).get(), aShapeMain1 ) )
721   {
722     return NULL;
723   }
724
725   TopoDS_Shape aShapeEdge2;
726   TopoDS_Shape aShapeMain2;
727   if ( !GEOMBase::GetShape( theEdge2.get(), aShapeEdge2 ) )
728   {
729     return NULL;
730   }
731   if ( !GEOMBase::GetShape( GetMainShape( theEdge2 ).get(), aShapeMain2 ) )
732   {
733     return NULL;
734   }
735
736   /* ---------------------------------------------------- */
737   /*             check construction edges                 */
738   /* ---------------------------------------------------- */
739
740   TopoDS_Edge aFirstEdge  = TopoDS::Edge( aShapeEdge1 );
741   TopoDS_Edge aSecondEdge = TopoDS::Edge( aShapeEdge2 );
742
743   // check whether it is possible to compute dimension on the passed edges
744   Handle(AIS_AngleDimension) aDimension = new AIS_AngleDimension( aFirstEdge, aSecondEdge );
745
746   if ( !aDimension->IsValid() )
747   {
748     return NULL;
749   }
750
751   const gp_Pnt& aFirstPoint  = aDimension->FirstPoint();
752   const gp_Pnt& aSecondPoint = aDimension->SecondPoint();
753   const gp_Pnt& aCenterPoint = aDimension->CenterPoint();
754
755   gp_Vec aVec1( aCenterPoint, aFirstPoint );
756   gp_Vec aVec2( aCenterPoint, aSecondPoint );
757
758   Standard_Real anAngle = aVec2.AngleWithRef( aVec1, aDimension->GetPlane().Axis().Direction() );
759
760   if ( anAngle < 0.0 )
761   {
762     aDimension = new AIS_AngleDimension( aSecondPoint, aCenterPoint, aFirstPoint );
763   }
764
765   aDimension->SetFlyout( Settings.DefaultFlyout );
766
767   return aDimension;
768 }
769
770 //=================================================================================
771 // function : AngleByThreePoints
772 // purpose  :
773 //=================================================================================
774 Handle(AIS_AngleDimension) MeasureGUI_DimensionCreateTool::AngleByThreePoints( const GEOM::GeomObjPtr& thePoint1,
775                                                                                const GEOM::GeomObjPtr& thePoint2,
776                                                                                const GEOM::GeomObjPtr& thePoint3 ) const
777 {
778   TopoDS_Shape aFirstSh;
779   if ( !GEOMBase::GetShape( thePoint1.operator ->(), aFirstSh ) )
780   {
781     return NULL;
782   }
783
784   TopoDS_Shape aSecondSh;
785   if ( !GEOMBase::GetShape( thePoint2.operator ->(), aSecondSh ) )
786   {
787     return NULL;
788   }
789
790   TopoDS_Shape aThirdSh;
791   if ( !GEOMBase::GetShape( thePoint3.operator ->(), aThirdSh ) )
792   {
793     return NULL;
794   }
795
796   TopoDS_Vertex aFirstVertex  = TopoDS::Vertex( aFirstSh );
797   TopoDS_Vertex aSecondVertex = TopoDS::Vertex( aSecondSh );
798   TopoDS_Vertex aThirdVertex  = TopoDS::Vertex( aThirdSh );
799
800   gp_Pnt aPnt1 = BRep_Tool::Pnt( aFirstVertex );
801   gp_Pnt aPnt2 = BRep_Tool::Pnt( aSecondVertex );
802   gp_Pnt aPnt3 = BRep_Tool::Pnt( aThirdVertex );
803
804   // check whether it is possible to compute dimension on the passed points
805   Handle(AIS_AngleDimension) aDimension = new AIS_AngleDimension( aPnt1, aPnt2, aPnt3 );
806
807   if ( !aDimension->IsValid() )
808   {
809     return NULL;
810   }
811
812   aDimension->SetFlyout( Settings.DefaultFlyout );
813
814   return aDimension;
815 }
816
817 //=================================================================================
818 // function : PositionLength
819 // purpose  : The method provides preliminary positioning algorithm for
820 //            for length dimensions measuring the length between two points.
821 //            Parameters:
822 //              theBnd [in] - the bounding box of the main shape
823 //              theFaceN1 [in] - the normal to a first face of edge length (if any)
824 //              theFaceN2 [in] - the normal to a second face of edge length (if any)
825 //              theFaceS1 [in] - the side vector from a first face of edge length (if any)
826 //              theFaceS2 [in] - the side vector from a second face of edge length (if any)
827 //              thePnt1 [in] - the first measured point
828 //              thePnt2 [in] - the last measured point
829 //            The method selects flyout plane to best match the current
830 //            view projection. If edge length is constructed, then the flyout
831 //            can go in line with sides of faces, normal to the faces, or
832 //            aligned to XOY, YOZ, ZOX planes.
833 //=================================================================================
834 void MeasureGUI_DimensionCreateTool::PositionLength( const Bnd_Box& theBnd,
835                                                      const gp_Vec& theFaceN1,
836                                                      const gp_Vec& theFaceN2,
837                                                      const gp_Vec& theFaceS1,
838                                                      const gp_Vec& theFaceS2,
839                                                      const gp_Pnt& thePnt1,
840                                                      const gp_Pnt& thePnt2,
841                                                      gp_Pln& thePln ) const
842 {
843   Standard_Boolean isFace1 = theFaceN1.Magnitude() > Precision::Confusion();
844   Standard_Boolean isFace2 = theFaceN2.Magnitude() > Precision::Confusion();
845   gp_Vec anAverageN( gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(0.0, 0.0, 0.0) );
846
847   // get average direction in case of two non-sharp angled faces
848   if ( isFace1 && isFace2 )
849   {
850     Standard_Boolean isSame = theFaceN1.IsParallel( theFaceN2, Precision::Angular() );
851     if ( !isSame )
852     {
853       gp_Dir aReferenceDir = theFaceN1 ^ theFaceN2;
854       // compute angle between face sides [0 - 2PI]
855       Standard_Real aDirAngle = theFaceN1.AngleWithRef( theFaceN2, aReferenceDir );
856       if ( aDirAngle < 0 )
857       {
858         aDirAngle = ( M_PI * 2.0 ) - aDirAngle;
859       }
860
861       // non-sharp angle, use averaged directio
862       if ( aDirAngle > M_PI * 0.5 )
863       {
864         anAverageN = theFaceN1 + theFaceN2;
865       }
866
867       if ( aDirAngle > M_PI )
868       {
869         isFace1 = Standard_False;
870         isFace2 = Standard_False;
871       }
872     }
873   }
874
875   Standard_Boolean isAverage = anAverageN.Magnitude() > Precision::Confusion();
876
877   SeqOfDirs aFlyoutDirs;
878   if ( isFace1 )
879   {
880     aFlyoutDirs.Append( theFaceN1 );
881     aFlyoutDirs.Append( theFaceS1 );
882   }
883   if ( isFace2 )
884   {
885     aFlyoutDirs.Append( theFaceN2 );
886     aFlyoutDirs.Append( theFaceS2 );
887   }
888   if ( isAverage )
889   {
890     aFlyoutDirs.Append( anAverageN );
891   }
892
893   ChooseLengthFlyoutsFromBnd( aFlyoutDirs, thePnt1, thePnt2, theBnd );
894
895   if ( aFlyoutDirs.IsEmpty() )
896   {
897     return;
898   }
899
900   gp_Dir aPointDir = gce_MakeDir( thePnt1, thePnt2 );
901
902   // make planes for dimension presentation according to flyout directions
903   SeqOfPlanes aSeqOfPlanes;
904   for ( Standard_Integer aFlyoutIt = 1; aFlyoutIt <= aFlyoutDirs.Length(); ++aFlyoutIt )
905   {
906     gp_Pln aPlane( thePnt1, aPointDir ^ aFlyoutDirs.Value( aFlyoutIt ) );
907     aSeqOfPlanes.Append( aPlane );
908   }
909
910   Handle(V3d_View) aView = Settings.ActiveView;
911
912   thePln = !aView.IsNull()
913     ? SelectPlaneForProjection( aSeqOfPlanes, aView )
914     : aSeqOfPlanes.First();
915 }
916
917 //=================================================================================
918 // function : PositionDiameter
919 // purpose  : The method provides preliminary positioning algorithm for
920 //            for diameter dimensions measuring the circle.
921 //            Parameters:
922 //              theBnd [in] - the bounding box of the shape
923 //              theFaceN [in] - the circle face normal (can be void)
924 //              theCirc [in] - the measured circle
925 //              thePnt1 [out] - first dimension point
926 //              thePnt2 [out] - second dimension point
927 //              thePln [out] - dimension flyout plane
928 //            The method selects points on the circle for diameter dimension and
929 //            flyout plane to best match the current view projection (if any)
930 //            The points are aligned to XOY, YOZ, ZOX planes.
931 //            The flyout takes into account bounding box of main shape of face normal
932 //            vector. The flyouts tangential to the circle plane are directed in 
933 //            accordance with the face normal (if not-null), otherwise the flyouts
934 //            are turned to direct to the closest border of bounding box.
935 //=================================================================================
936 void MeasureGUI_DimensionCreateTool::PositionDiameter( const Bnd_Box& theBnd,
937                                                        const gp_Vec& theFaceN,
938                                                        const gp_Circ& theCirc,
939                                                        gp_Pnt& thePnt1,
940                                                        gp_Pnt& thePnt2,
941                                                        gp_Pln& thePln ) const
942 {
943   // select list of measured segments aligned to projection planes
944   SeqOfDirs aProjectionDirs;
945   aProjectionDirs.Append( gp::DX() );
946   aProjectionDirs.Append( gp::DY() );
947   aProjectionDirs.Append( gp::DZ() );
948
949   SeqOfSegments aMeasureSegments = GetInPlaneSegments( theCirc, aProjectionDirs );
950
951   SeqOfPlnsAndSegments aSelectedPlanes;
952
953   // select in-circle-plane direction for flyout closest to border of bounding box
954   for ( Standard_Integer aSegmentIt = 1; aSegmentIt <= aMeasureSegments.Length(); ++aSegmentIt )
955   {
956     const Segment& aSegment = aMeasureSegments.Value(aSegmentIt);
957
958     Standard_Real anAnchor = ElCLib::Parameter( theCirc, aSegment.First );
959
960     gp_Pln aSelectedPlane;
961
962     PositionDiameter( theBnd, theFaceN, theCirc, anAnchor, aSelectedPlane );
963
964     aSelectedPlanes.Append( PlaneAndSegment( aSelectedPlane, aSegment ) );
965   }
966
967   Handle(V3d_View) aView = Settings.ActiveView;
968
969   PlaneAndSegment aChoosenParams = !aView.IsNull()
970     ? SelectPlaneForProjection( aSelectedPlanes, aView )
971     : aSelectedPlanes.First();
972
973   thePnt1 = ((Segment)aChoosenParams).First;
974   thePnt2 = ((Segment)aChoosenParams).Last;
975   thePln  = ((gp_Pln)aChoosenParams);
976 }
977
978 //=================================================================================
979 // function : PositionDiameter
980 // purpose  : The method provides preliminary positioning algorithm for
981 //            for diameter dimensions measuring the circle. The diameter
982 //            dimension is bound at anchor point on the circle.
983 //            Parameters:
984 //              theBnd [in] the bounding box of the shape
985 //              theFaceN [in] - the circle face normal (can be void)
986 //              theCirc [in] - the measured circle
987 //              theAnchorAt [in] - the anchoring parameter
988 //              thePln [out] - dimension flyout plane
989 //            The method selects flyout plane to best match the current
990 //            view projection. The flyout plane can be parallel to circle,
991 //            or tangent to it.
992 //=================================================================================
993 void MeasureGUI_DimensionCreateTool::PositionDiameter( const Bnd_Box& theBnd,
994                                                        const gp_Vec& theFaceN,
995                                                        const gp_Circ& theCirc,
996                                                        const Standard_Real& theAnchorAt,
997                                                        gp_Pln& thePln ) const
998 {
999   gp_Dir aCircN = theCirc.Axis().Direction();
1000   gp_Pnt aCircP = theCirc.Location();
1001
1002   // select tangent direction for flyout closest to border of bounding box
1003   gp_Dir aSelectedTanDir;
1004   if ( theFaceN.Magnitude() < Precision::Confusion() )
1005   {
1006     SeqOfDirs aTangentDirs;
1007     aTangentDirs.Append(  aCircN );
1008     aTangentDirs.Append( -aCircN );
1009     aSelectedTanDir = ChooseDirFromBnd( aTangentDirs, aCircP, theBnd );
1010   }
1011   else
1012   {
1013     aSelectedTanDir = gp_Dir( theFaceN );
1014   }
1015
1016   gp_Pnt aPnt1 = ElCLib::Value( theAnchorAt, theCirc );
1017   gp_Pnt aPnt2 = ElCLib::Value( theAnchorAt + M_PI, theCirc );
1018
1019   gp_Dir aSegmentDir = gce_MakeDir( aPnt1, aPnt2 );
1020
1021   SeqOfDirs aSegmentDirs;
1022   aSegmentDirs.Append(  aCircN ^ aSegmentDir );
1023   aSegmentDirs.Append( -aCircN ^ aSegmentDir );
1024   gp_Dir aSelectedSegDir = ChooseDirFromBnd( aSegmentDirs, aCircP, theBnd );
1025
1026   gp_Pln aTangentFlyout( aCircP, aSegmentDir ^ aSelectedTanDir );
1027   gp_Pln aCoplanarFlyout( aCircP, aSegmentDir ^ aSelectedSegDir );
1028
1029   SeqOfPlanes aSelectedPlanes;
1030   aSelectedPlanes.Append( aTangentFlyout );
1031   aSelectedPlanes.Append( aCoplanarFlyout );
1032
1033   Handle(V3d_View) aView = Settings.ActiveView;
1034
1035   thePln = !aView.IsNull()
1036     ? SelectPlaneForProjection( aSelectedPlanes, aView )
1037     : aSelectedPlanes.First();
1038 }
1039
1040 //=================================================================================
1041 // function : ChooseLengthFlyoutsFromBnd
1042 // purpose  :
1043 //=================================================================================
1044 void MeasureGUI_DimensionCreateTool::ChooseLengthFlyoutsFromBnd( SeqOfDirs& theDirs,
1045                                                                  const gp_Pnt& thePnt1,
1046                                                                  const gp_Pnt& thePnt2,
1047                                                                  const Bnd_Box& theBnd ) const
1048 {
1049   // compose a list of axis-aligned planes for lying-in flyouts
1050   NCollection_Sequence<gp_Pln> anAAPlanes;
1051
1052   // the axis-aligned planes for flyouts are built from
1053   // three points (P1, P2, and P1 translated in orthogonal
1054   // direction dx, dy, dz)
1055   gp_Dir anAxes[3] = { gp::DX(), gp::DY(), gp::DZ() };
1056
1057   for ( int anIt = 0; anIt < 3; ++anIt )
1058   {
1059     const gp_Dir& anAxisDir = anAxes[anIt];
1060     gp_Pnt aPnt3 = thePnt1.Translated( gp_Vec( anAxisDir ) );
1061     gce_MakePln aMakePlane( thePnt1, thePnt2, aPnt3 );
1062     if ( !aMakePlane.IsDone() )
1063     {
1064       continue;
1065     }
1066
1067     anAAPlanes.Append( aMakePlane.Value() );
1068   }
1069
1070   // find out what is the closest direction outside of the bounding box
1071   NCollection_Sequence<gp_Pln>::Iterator aPlaneIt( anAAPlanes );
1072
1073   gp_Dir aPointDir = gce_MakeDir( thePnt1, thePnt2 );
1074
1075   for ( ; aPlaneIt.More(); aPlaneIt.Next() )
1076   {
1077     const gp_Pln& aPlane = aPlaneIt.Value();
1078
1079     // transform bounding box to orthogonal coordinates relative to
1080     // dimension points P1, P2 (x-axis) and plane direction (z-axis),
1081     // where y coordinates will correspond to flyout direction against
1082     // the dimension point line
1083     gp_Ax3 aFlyoutSpace( thePnt1, aPlane.Axis().Direction(), aPointDir );
1084
1085     gp_Trsf aRelativeTransform;
1086     aRelativeTransform.SetTransformation( gp_Ax3(), aFlyoutSpace );
1087     Bnd_Box aRelativeBounds = theBnd.Transformed( aRelativeTransform );
1088
1089     Standard_Real aXmin, aXmax, aYmin, aYmax, aZmin, aZmax;
1090     aRelativeBounds.Get( aXmin, aYmin, aZmin, aXmax, aYmax, aZmax );
1091
1092     gp_Dir aPosFlyout = aPlane.Axis().Direction() ^ aPointDir;
1093     gp_Dir aNegFlyout = aPosFlyout.Reversed();
1094
1095     // select positive or negative flyout
1096     theDirs.Append( Abs( aYmax ) < Abs( aYmin ) ? aPosFlyout : aNegFlyout );
1097   }
1098 }
1099
1100 //=================================================================================
1101 // function : ChooseDirFromBnd
1102 // purpose  : The method chooses the best direction from the passed list of
1103 //            directions, which is closest to the bounding box border.
1104 //            Parameters:
1105 //              theCandidates [in] the list of candidate directions
1106 //              thePos [in] the position from where the directions are traced
1107 //              theBnd [in] the bounding box of main shape
1108 //=================================================================================
1109 gp_Dir MeasureGUI_DimensionCreateTool::ChooseDirFromBnd( const SeqOfDirs& theCandidates,
1110                                                          const gp_Pnt& thePos,
1111                                                          const Bnd_Box& theBnd ) const
1112 {
1113   gp_Dir aBestDir;
1114
1115   Standard_Real aBestDistance = RealLast();
1116
1117   SeqOfDirs::Iterator anIt( theCandidates );
1118   for ( ; anIt.More(); anIt.Next() )
1119   {
1120     const gp_Dir& aDir = anIt.Value();
1121
1122     gp_Ax3 aFlyoutSpace( thePos, aDir );
1123
1124     gp_Trsf aRelativeTransform;
1125     aRelativeTransform.SetTransformation( gp_Ax3(), aFlyoutSpace );
1126     Bnd_Box aRelativeBounds = theBnd.Transformed( aRelativeTransform );
1127
1128     Standard_Real aXmin, aXmax, aYmin, aYmax, aZmin, aZmax;
1129     aRelativeBounds.Get( aXmin, aYmin, aZmin, aXmax, aYmax, aZmax );
1130
1131     if ( aYmax < aBestDistance )
1132     {
1133       aBestDir = aDir;
1134       aBestDistance = aYmax;
1135     }
1136   }
1137
1138   return aBestDir;
1139 }
1140
1141 //=================================================================================
1142 // function : SelectPlaneForProjection
1143 // purpose  : Select best matching plane in current view projection
1144 //=================================================================================
1145 template <typename TPlane>
1146 TPlane MeasureGUI_DimensionCreateTool::SelectPlaneForProjection( const NCollection_Sequence<TPlane>& thePlanes,
1147                                                                  const Handle(V3d_View)& theView ) const
1148 {
1149   Standard_Real U[3];
1150   Standard_Real N[3];
1151   theView->Up( U[0], U[1], U[2] );
1152   theView->Proj( N[0], N[1], N[2] );
1153
1154   gp_Dir aViewN( (Standard_Real)N[0], (Standard_Real)N[1], (Standard_Real)N[2] );
1155   gp_Dir aViewU( (Standard_Real)U[0], (Standard_Real)U[1], (Standard_Real)U[2] );
1156
1157   TPlane aBestPlane = thePlanes.First();
1158
1159   Standard_Real aBestDotProduct = RealFirst();
1160
1161   for ( Standard_Integer aPlnIt = 1; aPlnIt <= thePlanes.Length(); ++aPlnIt )
1162   {
1163     const TPlane& aPlane = thePlanes.Value( aPlnIt );
1164
1165     Standard_Real aDotProduct = Abs( ((gp_Pln)aPlane).Axis().Direction() * aViewN );
1166
1167     // preferred plane is "view parallel"
1168     if ( aDotProduct <= aBestDotProduct )
1169     {
1170       continue;
1171     }
1172
1173     aBestPlane = aPlane;
1174
1175     aBestDotProduct = aDotProduct;
1176   }
1177
1178   return aBestPlane;
1179 }
1180
1181 //=================================================================================
1182 // function : GetMainShape
1183 // purpose  :
1184 //=================================================================================
1185 GEOM::GeomObjPtr MeasureGUI_DimensionCreateTool::GetMainShape( const GEOM::GeomObjPtr& theShape ) const
1186 {
1187   // iterate over top-level objects to search for main shape
1188   GEOM::GeomObjPtr aMainShapeIt = theShape;
1189   while ( !aMainShapeIt->IsMainShape() )
1190   {
1191     aMainShapeIt = aMainShapeIt->GetMainShape();
1192   }
1193   return aMainShapeIt;
1194 }
1195
1196 //=================================================================================
1197 // function : GetFaceSide
1198 // purpose  :
1199 //=================================================================================
1200 bool MeasureGUI_DimensionCreateTool::GetFaceSide( const TopoDS_Face& theFace, const TopoDS_Edge& theEdge, gp_Dir& theDir ) const
1201 {
1202   // get correctly oriented edge from main shape
1203   TopoDS_Edge anEdgeFromFace;
1204   TopExp_Explorer anExplorer( theFace.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1205   for ( ; anExplorer.More(); anExplorer.Next() )
1206   {
1207     TopoDS_Edge aCurrentEdge = TopoDS::Edge( anExplorer.Current() );
1208     if ( theEdge.IsSame( aCurrentEdge ) )
1209     {
1210       anEdgeFromFace = aCurrentEdge;
1211       break;
1212     }
1213   }
1214
1215   if ( anEdgeFromFace.IsNull() )
1216   {
1217     return false;
1218   }
1219
1220   // check out the direction of face extensions from its boundaries at the edge location
1221   // made assumption here that for any linear bounding edge the
1222   // normals are same on the whole length of that edge
1223   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( theFace );
1224   if ( aSurface.IsNull() || !aSurface->IsKind( STANDARD_TYPE(Geom_ElementarySurface) ) )
1225   {
1226     return false;
1227   }
1228
1229   BRepAdaptor_Curve aSurfCurve( anEdgeFromFace, theFace );
1230   if ( !aSurfCurve.IsCurveOnSurface() )
1231   {
1232     return false;
1233   }
1234
1235   Standard_Real aHalfRange = ( aSurfCurve.FirstParameter() + aSurfCurve.LastParameter() ) / 2.0;
1236
1237   gp_Pnt aPoint = aSurfCurve.Value( aHalfRange );
1238
1239   Standard_Real aPointU = 0.0;
1240   Standard_Real aPointV = 0.0;
1241   GeomLib_Tool::Parameters( aSurface, aPoint, Precision::Confusion(), aPointU, aPointV );
1242
1243   gp_Dir aNorm;
1244   if ( GeomLib::NormEstim( aSurface, gp_Pnt2d( aPointU, aPointV ), Precision::Confusion(), aNorm ) > 1 )
1245   {
1246     return false;
1247   }
1248
1249   gp_Vec aTangent = aSurfCurve.DN( aHalfRange, 1 );
1250   if ( aTangent.Magnitude() < Precision::Confusion() )
1251   {
1252     return false;
1253   }
1254
1255   TopAbs_Orientation anEdgeOrientation = anEdgeFromFace.Orientation();
1256   if ( anEdgeOrientation == TopAbs_REVERSED )
1257   {
1258     aTangent.Reverse();
1259   }
1260
1261   theDir = gp_Dir( aTangent ) ^ aNorm;
1262   return true;
1263 }
1264
1265 //=================================================================================
1266 // function : GetInPlaneSegments
1267 // purpose  : The method finds segments crossing the passed circle,
1268 //            which lie in the passed planes.
1269 //            Parameters:
1270 //              theCirc [in] the circle to be crossed.
1271 //              thePlanes [in] the projection planes crossing the circle.
1272 //=================================================================================
1273 MeasureGUI_DimensionCreateTool::SeqOfSegments
1274   MeasureGUI_DimensionCreateTool::GetInPlaneSegments( const gp_Circ& theCirc,
1275                                                       const SeqOfDirs& thePlanes ) const
1276 {
1277   SeqOfSegments aResult;
1278
1279   gp_Pnt aCircP = theCirc.Location();
1280   gp_Dir aCircN = theCirc.Axis().Direction();
1281   Standard_Real aCircR = theCirc.Radius();
1282
1283   SeqOfDirs::Iterator anIt( thePlanes );
1284   for ( ; anIt.More(); anIt.Next() )
1285   {
1286     const gp_Dir& aDir = anIt.Value();
1287
1288     if ( aDir.IsParallel( aCircN, Precision::Angular() ) )
1289     {
1290       continue;
1291     }
1292
1293     gp_Dir aIntDir = aDir ^ aCircN;
1294
1295     gp_Pnt aPnt1 = gp_Pnt( aCircP.XYZ() - aIntDir.XYZ() * aCircR );
1296     gp_Pnt aPnt2 = gp_Pnt( aCircP.XYZ() + aIntDir.XYZ() * aCircR );
1297     Segment aSegment;
1298     aSegment.First = aPnt1;
1299     aSegment.Last  = aPnt2;
1300     aResult.Append( aSegment );
1301   }
1302
1303   return aResult;
1304 }