Salome HOME
a44a47e0b2b43792291f2c30d6930ec3552f059c
[modules/shaper.git] / src / PartSet / PartSet_Tools.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_Tools.cpp
4 // Created:     28 Apr 2014
5 // Author:      Natalia ERMOLAEVA
6
7 #include <PartSet_Tools.h>
8 #include <PartSet_Module.h>
9 #include <PartSet_SketcherMgr.h>
10
11 #include <ModelAPI_Data.h>
12 #include <ModelAPI_AttributeDouble.h>
13 #include <ModelAPI_AttributeRefList.h>
14 #include <ModelAPI_Document.h>
15 #include <ModelAPI_Session.h>
16 #include <ModelAPI_ResultConstruction.h>
17
18 #include <XGUI_ModuleConnector.h>
19 #include <XGUI_Displayer.h>
20 #include <XGUI_Workshop.h>
21 #include <XGUI_SelectionMgr.h>
22 #include <XGUI_Selection.h>
23
24 #include <GeomDataAPI_Point.h>
25 #include <GeomDataAPI_Dir.h>
26 #include <GeomDataAPI_Point2D.h>
27 #include <GeomAPI_Pln.h>
28 #include <GeomAPI_Pnt2d.h>
29 #include <GeomAPI_Pnt.h>
30 #include <GeomAPI_Edge.h>
31 #include <GeomAPI_Vertex.h>
32
33 #include <GeomAPI_Dir.h>
34 #include <GeomAPI_XYZ.h>
35
36 #include <SketchPlugin_Feature.h>
37 #include <SketchPlugin_Sketch.h>
38 #include <SketchPlugin_ConstraintCoincidence.h>
39 #include <SketchPlugin_ConstraintDistance.h>
40 #include <SketchPlugin_ConstraintLength.h>
41 #include <SketchPlugin_ConstraintRadius.h>
42 #include <SketchPlugin_ConstraintRigid.h>
43 #include <SketchPlugin_Constraint.h>
44 #include <SketchPlugin_Circle.h>
45 #include <SketchPlugin_Arc.h>
46 #include <SketchPlugin_Line.h>
47 #include <SketchPlugin_Point.h>
48
49 #include <ModuleBase_IWorkshop.h>
50 #include <ModuleBase_ViewerPrs.h>
51
52 #include <V3d_View.hxx>
53 #include <gp_Pln.hxx>
54 #include <gp_Circ.hxx>
55 #include <ProjLib.hxx>
56 #include <ElSLib.hxx>
57 #include <Geom_Line.hxx>
58 #include <GeomAPI_ProjectPointOnCurve.hxx>
59 #include <BRep_Tool.hxx>
60 #include <TopoDS.hxx>
61 #include <TopoDS_Edge.hxx>
62 #include <TopoDS_Vertex.hxx>
63 #include <AIS_InteractiveObject.hxx>
64 #include <StdSelect_BRepOwner.hxx>
65 #include <SelectMgr_IndexedMapOfOwner.hxx>
66
67 #ifdef _DEBUG
68 #include <QDebug>
69 #endif
70
71 const double PRECISION_TOLERANCE = 0.000001;
72
73 gp_Pnt PartSet_Tools::convertClickToPoint(QPoint thePoint, Handle(V3d_View) theView)
74 {
75   if (theView.IsNull())
76     return gp_Pnt();
77
78   V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
79   theView->Eye(XEye, YEye, ZEye);
80
81   theView->At(XAt, YAt, ZAt);
82   gp_Pnt EyePoint(XEye, YEye, ZEye);
83   gp_Pnt AtPoint(XAt, YAt, ZAt);
84
85   gp_Vec EyeVector(EyePoint, AtPoint);
86   gp_Dir EyeDir(EyeVector);
87
88   gp_Pln PlaneOfTheView = gp_Pln(AtPoint, EyeDir);
89   Standard_Real X, Y, Z;
90   theView->Convert(thePoint.x(), thePoint.y(), X, Y, Z);
91   gp_Pnt ConvertedPoint(X, Y, Z);
92
93   gp_Pnt2d ConvertedPointOnPlane = ProjLib::Project(PlaneOfTheView, ConvertedPoint);
94   gp_Pnt ResultPoint = ElSLib::Value(ConvertedPointOnPlane.X(), ConvertedPointOnPlane.Y(),
95                                      PlaneOfTheView);
96   return ResultPoint;
97 }
98
99 void PartSet_Tools::convertTo2D(const gp_Pnt& thePoint, FeaturePtr theSketch,
100 Handle(V3d_View) theView,
101                                 double& theX, double& theY)
102 {
103   if (!theSketch)
104     return;
105
106   AttributeDoublePtr anAttr;
107   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
108
109   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
110       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
111
112   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
113       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
114   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
115       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
116   std::shared_ptr<GeomAPI_XYZ> anY = aNorm->xyz()->cross(aX->xyz());
117
118   gp_Pnt anOriginPnt(anOrigin->x(), anOrigin->y(), anOrigin->z());
119   gp_Vec aVec(anOriginPnt, thePoint);
120
121   if (!theView.IsNull()) {
122     V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
123     theView->Eye(XEye, YEye, ZEye);
124
125     theView->At(XAt, YAt, ZAt);
126     gp_Pnt EyePoint(XEye, YEye, ZEye);
127     gp_Pnt AtPoint(XAt, YAt, ZAt);
128
129     gp_Vec anEyeVec(EyePoint, AtPoint);
130     anEyeVec.Normalize();
131
132     std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
133         aData->attribute(SketchPlugin_Sketch::NORM_ID()));
134     gp_Vec aNormalVec(aNormal->x(), aNormal->y(), aNormal->z());
135
136     double aDen = anEyeVec * aNormalVec;
137     double aLVec = aDen != 0 ? aVec * aNormalVec / aDen : DBL_MAX;
138
139     gp_Vec aDeltaVec = anEyeVec * aLVec;
140     aVec = aVec - aDeltaVec;
141   }
142   theX = aVec.X() * aX->x() + aVec.Y() * aX->y() + aVec.Z() * aX->z();
143   theY = aVec.X() * anY->x() + aVec.Y() * anY->y() + aVec.Z() * anY->z();
144 }
145
146 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::convertTo2D(FeaturePtr theSketch, 
147                                                     const std::shared_ptr<GeomAPI_Pnt>& thePnt)
148 {
149   std::shared_ptr<GeomAPI_Pnt2d> aRes;
150   if (theSketch->getKind() != SketchPlugin_Sketch::ID())
151     return aRes;
152   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
153       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
154   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
155       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
156   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
157       theSketch->data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
158   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
159   return thePnt->to2D(aC->pnt(), aX->dir(), aY);
160 }
161
162
163 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::convertTo3D(const double theX, const double theY, FeaturePtr theSketch)
164 {
165   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
166
167   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
168       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
169   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
170       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
171   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
172       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
173   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
174
175   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d = 
176     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
177
178   return aPnt2d->to3D(aC->pnt(), aX->dir(), aY);
179 }
180
181 ObjectPtr PartSet_Tools::nearestFeature(QPoint thePoint, Handle_V3d_View theView,
182                                         FeaturePtr theSketch,
183                                         const QList<ModuleBase_ViewerPrs>& theSelected,
184                                         const QList<ModuleBase_ViewerPrs>& theHighlighted)
185 {
186   // firstly it finds the feature in the list of highlight
187   ObjectPtr aDeltaObject  = nearestFeature(thePoint, theView, theSketch, theHighlighted);
188   if (!aDeltaObject)
189     // secondly it finds the feature in the list of selected objects
190     aDeltaObject  = nearestFeature(thePoint, theView, theSketch, theSelected);
191
192   return aDeltaObject;
193 }
194
195 ObjectPtr PartSet_Tools::nearestFeature(QPoint thePoint, Handle_V3d_View theView,
196                                         FeaturePtr theSketch,
197                                         const QList<ModuleBase_ViewerPrs>& thePresentations)
198 {
199   ObjectPtr aDeltaObject;
200
201   CompositeFeaturePtr aSketch = 
202       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theSketch);
203   // 1. find it in the selected list by the selected point
204   if (!aDeltaObject) {
205     double aX, anY;
206     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(thePoint, theView);
207     PartSet_Tools::convertTo2D(aPoint, theSketch, theView, aX, anY);
208
209     FeaturePtr aFeature;
210     double aMinDelta = -1;
211     ModuleBase_ViewerPrs aPrs;
212     foreach (ModuleBase_ViewerPrs aPrs, thePresentations) {
213       if (!aPrs.object())
214         continue;
215       FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs.object());
216       std::shared_ptr<SketchPlugin_Feature> aSketchFeature = std::dynamic_pointer_cast<
217           SketchPlugin_Feature>(aFeature);
218       if (!aSketchFeature || !aSketch->isSub(aSketchFeature))
219         continue;
220
221       double aDelta = aSketchFeature->distanceToPoint(
222           std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(aX, anY)));
223       if (aMinDelta < 0 || aMinDelta > aDelta) {
224         aMinDelta = aDelta;
225         // TODO aDeltaObject = aPrs.result();
226       }
227     }
228   }
229   // 2. if the object is not found, returns the first selected sketch feature
230   if (!aDeltaObject && thePresentations.size() > 0) {
231     // there can be some highlighted objects, e.g. a result of boolean operation and a sketch point
232     foreach (ModuleBase_ViewerPrs aPrs, thePresentations) {
233       if (!aPrs.object())
234         continue;
235       FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs.object());
236       if (aFeature && aSketch->isSub(aFeature))
237         aDeltaObject = aPrs.object();
238     }
239   }
240   return aDeltaObject;
241 }
242
243 std::shared_ptr<ModelAPI_Document> PartSet_Tools::document()
244 {
245   return ModelAPI_Session::get()->moduleDocument();
246 }
247
248 /*std::shared_ptr<GeomDataAPI_Point2D> PartSet_Tools::getFeaturePoint(FeaturePtr theFeature,
249                                                                       double theX, double theY)
250 {
251   std::shared_ptr<GeomAPI_Pnt2d> aClickedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
252                                                                  new GeomAPI_Pnt2d(theX, theY));
253   std::list<std::shared_ptr<ModelAPI_Attribute> > anAttiributes =
254                                     theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
255   std::list<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anIt = anAttiributes.begin(),
256                                                                     aLast = anAttiributes.end();
257   std::shared_ptr<GeomDataAPI_Point2D> aFPoint;
258   for (; anIt != aLast && !aFPoint; anIt++) {
259     std::shared_ptr<GeomDataAPI_Point2D> aCurPoint = std::dynamic_pointer_cast<
260         GeomDataAPI_Point2D>(*anIt);
261     if (aCurPoint && aCurPoint->pnt()->distance(aClickedPoint) < Precision::Confusion())
262       aFPoint = aCurPoint;
263   }
264
265   return aFPoint;
266 }*/
267
268 void PartSet_Tools::setFeatureValue(FeaturePtr theFeature, double theValue,
269                                     const std::string& theAttribute)
270 {
271   if (!theFeature)
272     return;
273   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
274   AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
275       aData->attribute(theAttribute));
276   if (anAttribute)
277     anAttribute->setValue(theValue);
278 }
279
280 double PartSet_Tools::featureValue(FeaturePtr theFeature, const std::string& theAttribute,
281                                    bool& isValid)
282 {
283   isValid = false;
284   double aValue = 0;
285   if (theFeature) {
286     std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
287     AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
288         aData->attribute(theAttribute));
289     if (anAttribute) {
290       aValue = anAttribute->value();
291       isValid = true;
292     }
293   }
294   return aValue;
295 }
296
297 FeaturePtr PartSet_Tools::feature(FeaturePtr theFeature, const std::string& theAttribute,
298                                   const std::string& theKind)
299 {
300   FeaturePtr aFeature;
301   if (!theFeature)
302     return aFeature;
303
304   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
305   std::shared_ptr<ModelAPI_AttributeRefAttr> anAttr = std::dynamic_pointer_cast<
306       ModelAPI_AttributeRefAttr>(aData->attribute(theAttribute));
307   if (anAttr) {
308     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->object());
309     if (!theKind.empty() && aFeature && aFeature->getKind() != theKind) {
310       aFeature = FeaturePtr();
311     }
312   }
313   return aFeature;
314 }
315
316 void PartSet_Tools::createConstraint(CompositeFeaturePtr theSketch,
317                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint1,
318                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint2)
319 {
320   FeaturePtr aFeature;
321   if (theSketch) {
322     aFeature = theSketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
323   } else {
324     std::shared_ptr<ModelAPI_Document> aDoc = document();
325     aFeature = aDoc->addFeature(SketchPlugin_ConstraintCoincidence::ID());
326   }
327
328   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
329
330   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
331       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
332   aRef1->setAttr(thePoint1);
333
334   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
335       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
336   aRef2->setAttr(thePoint2);
337
338   if (aFeature)  // TODO: generate an error if feature was not created
339     aFeature->execute();
340 }
341
342 /*std::shared_ptr<GeomDataAPI_Point2D> PartSet_Tools::
343   findAttributePoint(CompositeFeaturePtr theSketch, double theX, double theY,
344   double theTolerance, const QList<FeaturePtr>& theIgnore)
345 {
346   std::shared_ptr<GeomAPI_Pnt2d> aClickedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
347       new GeomAPI_Pnt2d(theX, theY));
348
349   std::list<std::shared_ptr<ModelAPI_Attribute> > anAttiributes;
350   for (int i = 0; i < theSketch->numberOfSubs(); i++) {
351     FeaturePtr aFeature = theSketch->subFeature(i);
352     if (!theIgnore.contains(aFeature)) {
353       anAttiributes = aFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
354
355       std::list<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anIt;
356       for (anIt = anAttiributes.cbegin(); anIt != anAttiributes.cend(); ++anIt) {
357         std::shared_ptr<GeomDataAPI_Point2D> aCurPoint = 
358           std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIt);
359         double x = aCurPoint->x();
360         double y = aCurPoint->y();
361         if (aCurPoint && (aCurPoint->pnt()->distance(aClickedPoint) < theTolerance)) {
362           return aCurPoint;
363         }
364       }
365     }
366   }
367   return std::shared_ptr<GeomDataAPI_Point2D>();
368 }*/
369
370
371 void PartSet_Tools::setConstraints(CompositeFeaturePtr theSketch, FeaturePtr theFeature,
372                                    const std::string& theAttribute, double theClickedX,
373                                    double theClickedY)
374 {
375   // find a feature point by the selection mode
376   //std::shared_ptr<GeomDataAPI_Point2D> aPoint = featurePoint(theMode);
377   std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint = std::dynamic_pointer_cast<
378       GeomDataAPI_Point2D>(theFeature->data()->attribute(theAttribute));
379   if (!aFeaturePoint)
380     return;
381
382   // get all sketch features. If the point with the given coordinates belong to any sketch feature,
383   // the constraint is created between the feature point and the found sketch point
384   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
385   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
386       ModelAPI_AttributeRefList>(aData->attribute(SketchPlugin_Sketch::FEATURES_ID()));
387
388   std::list<ObjectPtr> aFeatures = aRefList->list();
389   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
390   std::list<std::shared_ptr<ModelAPI_Attribute> > anAttiributes;
391   std::shared_ptr<GeomAPI_Pnt2d> aClickedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
392       new GeomAPI_Pnt2d(theClickedX, theClickedY));
393   for (; anIt != aLast; anIt++) {
394     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
395     if (!aFeature.get() || theFeature == aFeature)
396       continue;
397     // find the given point in the feature attributes
398     anAttiributes = aFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
399     std::list<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anIt = anAttiributes.begin(),
400         aLast = anAttiributes.end();
401     std::shared_ptr<GeomDataAPI_Point2D> aFPoint;
402     for (; anIt != aLast && !aFPoint; anIt++) {
403       std::shared_ptr<GeomDataAPI_Point2D> aCurPoint = 
404         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIt);
405       if (aCurPoint && (aCurPoint->pnt()->distance(aClickedPoint) < Precision::Confusion())) {
406         aFPoint = aCurPoint;
407         break;
408       }
409     }
410     if (aFPoint)
411       PartSet_Tools::createConstraint(theSketch, aFPoint, aFeaturePoint);
412   }
413 }
414
415 std::shared_ptr<GeomAPI_Pln> PartSet_Tools::sketchPlane(CompositeFeaturePtr theSketch)
416 {
417   std::shared_ptr<GeomAPI_Pln> aPlane;
418
419   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
420   if (aData) {
421     std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
422         aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
423     std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
424         aData->attribute(SketchPlugin_Sketch::NORM_ID()));
425     if (aNormal && anOrigin) {
426       double adX = aNormal->x();
427       double adY = aNormal->y();
428       double adZ = aNormal->z();
429
430       if ( (adX != 0) || (adY != 0) || (adZ != 0) ) { // Plane is valid
431         double aX = anOrigin->x();
432         double aY = anOrigin->y();
433         double aZ = anOrigin->z();
434         gp_Pln aPln(gp_Pnt(aX, aY, aZ), gp_Dir(adX, adY, adZ));
435         double aA, aB, aC, aD;
436         aPln.Coefficients(aA, aB, aC, aD);
437         aPlane = std::shared_ptr<GeomAPI_Pln>(new GeomAPI_Pln(aA, aB, aC, aD));
438       }
439     }
440   }
441   return aPlane;
442 }
443
444 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::point3D(std::shared_ptr<GeomAPI_Pnt2d> thePoint2D,
445                                                       CompositeFeaturePtr theSketch)
446 {
447   std::shared_ptr<GeomAPI_Pnt> aPoint;
448   if (!theSketch || !thePoint2D)
449     return aPoint;
450
451   DataPtr aData = theSketch->data();
452   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
453       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
454   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
455       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
456   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
457       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
458   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
459
460   return thePoint2D->to3D(aC->pnt(), aX->dir(), aY);
461 }
462
463 ResultPtr PartSet_Tools::findFixedObjectByExternal(const TopoDS_Shape& theShape,
464                                                    const ObjectPtr& theObject,
465                                                    CompositeFeaturePtr theSketch)
466 {
467   ResultPtr aResult;
468   if (theShape.ShapeType() == TopAbs_EDGE) {
469     // Check that we already have such external edge
470     std::shared_ptr<GeomAPI_Edge> aInEdge = std::shared_ptr<GeomAPI_Edge>(new GeomAPI_Edge());
471     aInEdge->setImpl(new TopoDS_Shape(theShape));
472     aResult = findExternalEdge(theSketch, aInEdge);
473   }
474   if (theShape.ShapeType() == TopAbs_VERTEX) {
475     std::shared_ptr<GeomAPI_Vertex> aInVert = std::shared_ptr<GeomAPI_Vertex>(new GeomAPI_Vertex());
476     aInVert->setImpl(new TopoDS_Shape(theShape));
477     aResult = findExternalVertex(theSketch, aInVert);
478   }
479   return aResult;
480 }
481
482 ResultPtr PartSet_Tools::createFixedObjectByExternal(const TopoDS_Shape& theShape, 
483                                                      const ObjectPtr& theObject, 
484                                                      CompositeFeaturePtr theSketch,
485                                                      const bool theTemporary)
486 {
487   if (theShape.ShapeType() == TopAbs_EDGE) {
488     Standard_Real aStart, aEnd;
489     Handle(V3d_View) aNullView;
490     FeaturePtr aMyFeature;
491
492     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(TopoDS::Edge(theShape), aStart, aEnd);
493     GeomAdaptor_Curve aAdaptor(aCurve);
494     if (aAdaptor.GetType() == GeomAbs_Line) {
495       // Create line
496       aMyFeature = theSketch->addFeature(SketchPlugin_Line::ID());
497     } else if (aAdaptor.GetType() == GeomAbs_Circle) {
498       std::shared_ptr<GeomAPI_Edge> anEdge = std::shared_ptr<GeomAPI_Edge>(new GeomAPI_Edge);
499       anEdge->setImpl(new TopoDS_Shape(theShape));
500       if (anEdge->isArc()) {
501         // Create arc
502         aMyFeature = theSketch->addFeature(SketchPlugin_Arc::ID());
503       }
504       else {
505         // Create circle
506         aMyFeature = theSketch->addFeature(SketchPlugin_Circle::ID());
507       }
508     }
509     if (aMyFeature) {
510       DataPtr aData = aMyFeature->data();
511       AttributeSelectionPtr anAttr = 
512         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
513         (aData->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID()));
514
515       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
516       if (anAttr && aRes) {
517         std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
518         anEdge->setImpl(new TopoDS_Shape(theShape));
519
520         anAttr->setValue(aRes, anEdge);
521         //if (!theTemporary) {
522           aMyFeature->execute();
523
524           // fix this edge
525           FeaturePtr aFix = theSketch->addFeature(SketchPlugin_ConstraintRigid::ID());
526           aFix->data()->refattr(SketchPlugin_Constraint::ENTITY_A())->
527             setObject(aMyFeature->lastResult());
528         //}
529         return aMyFeature->lastResult();
530       }
531     }
532   }
533   if (theShape.ShapeType() == TopAbs_VERTEX) {
534     FeaturePtr aMyFeature = theSketch->addFeature(SketchPlugin_Point::ID());
535
536     if (aMyFeature) {
537       DataPtr aData = aMyFeature->data();
538       AttributeSelectionPtr anAttr = 
539         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
540         (aData->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID()));
541
542       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
543       if (anAttr && aRes) {
544         std::shared_ptr<GeomAPI_Shape> aVert(new GeomAPI_Shape);
545         aVert->setImpl(new TopoDS_Shape(theShape));
546
547         anAttr->setValue(aRes, aVert);
548         //if (theTemporary) {
549           aMyFeature->execute();
550
551           // fix this edge
552           FeaturePtr aFix = theSketch->addFeature(SketchPlugin_ConstraintRigid::ID());
553           aFix->data()->refattr(SketchPlugin_Constraint::ENTITY_A())->
554             setObject(aMyFeature->lastResult());
555         //}
556         return aMyFeature->lastResult();
557       }
558     }
559   }
560   return ResultPtr();
561 }
562
563 bool PartSet_Tools::isContainPresentation(const QList<ModuleBase_ViewerPrs>& theSelected,
564                                           const ModuleBase_ViewerPrs& thePrs)
565 {
566   foreach (ModuleBase_ViewerPrs aPrs, theSelected) {
567     if (aPrs.object() == thePrs.object())
568       return true;
569   }
570   return false;
571 }
572
573 ResultPtr PartSet_Tools::findExternalEdge(CompositeFeaturePtr theSketch, std::shared_ptr<GeomAPI_Edge> theEdge)
574 {
575   for (int i = 0; i < theSketch->numberOfSubs(); i++) {
576     FeaturePtr aFeature = theSketch->subFeature(i);
577     std::shared_ptr<SketchPlugin_Feature> aSketchFea = 
578       std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
579     if (aSketchFea) {
580       if (aSketchFea->isExternal()) {
581         std::list<ResultPtr> aResults = aSketchFea->results();
582         std::list<ResultPtr>::const_iterator aIt;
583         for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
584           ResultConstructionPtr aRes = 
585             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aIt);
586           if (aRes) {
587             std::shared_ptr<GeomAPI_Shape> aShape = aRes->shape();
588             if (aShape) {
589               if (theEdge->isEqual(aShape))
590                 return aRes;
591             }
592           }
593         }
594       }
595     }
596   }
597   return ResultPtr();
598 }
599
600
601 ResultPtr PartSet_Tools::findExternalVertex(CompositeFeaturePtr theSketch, std::shared_ptr<GeomAPI_Vertex> theVert)
602 {
603   for (int i = 0; i < theSketch->numberOfSubs(); i++) {
604     FeaturePtr aFeature = theSketch->subFeature(i);
605     std::shared_ptr<SketchPlugin_Feature> aSketchFea = 
606       std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
607     if (aSketchFea) {
608       if (aSketchFea->isExternal()) {
609         std::list<ResultPtr> aResults = aSketchFea->results();
610         std::list<ResultPtr>::const_iterator aIt;
611         for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
612           ResultConstructionPtr aRes = 
613             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aIt);
614           if (aRes) {
615             std::shared_ptr<GeomAPI_Shape> aShape = aRes->shape();
616             if (aShape) {
617               if (theVert->isEqual(aShape))
618                 return aRes;
619             }
620           }
621         }
622       }
623     }
624   }
625   return ResultPtr();
626 }
627
628
629 bool PartSet_Tools::hasVertexShape(const ModuleBase_ViewerPrs& thePrs, FeaturePtr theSketch,
630                                    Handle_V3d_View theView, double& theX, double& theY)
631 {
632   bool aHasVertex = false;
633
634   const TopoDS_Shape& aShape = thePrs.shape();
635   if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_VERTEX)
636   {
637     const TopoDS_Vertex& aVertex = TopoDS::Vertex(aShape);
638     if (!aVertex.IsNull())
639     {
640       gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
641       PartSet_Tools::convertTo2D(aPoint, theSketch, theView, theX, theY);
642       aHasVertex = true;
643     }
644   }
645
646   return aHasVertex;
647 }
648
649 GeomShapePtr PartSet_Tools::findShapeBy2DPoint(const AttributePtr& theAttribute,
650                                                ModuleBase_IWorkshop* theWorkshop)
651 {
652   // 1. find an attribute value in attribute reference attribute value
653   GeomShapePtr aShape;
654   AttributeRefAttrPtr aRefAttr =
655     std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
656   if (aRefAttr) {
657     if (!aRefAttr->isObject()) {
658       AttributePtr theAttribute = aRefAttr->attr();
659       if (theAttribute.get()) {
660         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
661         XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
662
663         // 2. find visualized vertices of the attribute and if the attribute of the vertex is
664         // the same, return it
665         FeaturePtr anAttributeFeature = ModelAPI_Feature::feature(theAttribute->owner());
666         // 2.1 get visualized results of the feature
667         const std::list<ResultPtr>& aResList = anAttributeFeature->results();
668         std::list<ResultPtr>::const_iterator anIt = aResList.begin(), aLast = aResList.end();
669         for (; anIt != aLast; anIt++) {
670           AISObjectPtr aAISObj = aDisplayer->getAISObject(*anIt);
671           if (aAISObj.get() != NULL) {
672             Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
673             // 2.2 find selected owners of a visualizedd object
674             SelectMgr_IndexedMapOfOwner aSelectedOwners;
675             aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
676             for (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
677               Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
678               if (!anOwner.IsNull()) {
679                 Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
680                 if (!aBRepOwner.IsNull() && aBRepOwner->HasShape()) {
681                   const TopoDS_Shape& aBRepShape = aBRepOwner->Shape();
682                   if (aBRepShape.ShapeType() == TopAbs_VERTEX) {
683                     // 2.3 if the owner is vertex and an attribute of the vertex is equal to the initial
684                     // attribute, returns the shape
685                     PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(theWorkshop->module());
686                     PartSet_SketcherMgr* aSketchMgr = aModule->sketchMgr();
687                     AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(anAttributeFeature,
688                                                              aBRepShape, aSketchMgr->activeSketch());
689                     if (aPntAttr.get() != NULL && aPntAttr == theAttribute) {
690                       aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
691                       aShape->setImpl(new TopoDS_Shape(aBRepShape));
692                       break;
693                     }
694                   }
695                 }
696               }
697             }
698           }
699         }
700       }
701     }
702   }
703   return aShape;
704 }
705
706 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPoint(std::shared_ptr<ModelAPI_Feature>& theFeature,
707                                                        const std::string& theAttribute)
708 {
709   std::shared_ptr<GeomDataAPI_Point2D> aPointAttr;
710
711   if (!theFeature->data())
712     return std::shared_ptr<GeomAPI_Pnt2d>();
713
714   FeaturePtr aFeature;
715   std::shared_ptr<ModelAPI_AttributeRefAttr> anAttr = std::dynamic_pointer_cast<
716       ModelAPI_AttributeRefAttr>(theFeature->data()->attribute(theAttribute));
717   if (anAttr)
718     aFeature = ModelAPI_Feature::feature(anAttr->object());
719
720   if (aFeature && aFeature->getKind() == SketchPlugin_Point::ID())
721     aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
722         aFeature->data()->attribute(SketchPlugin_Point::COORD_ID()));
723
724   else if (anAttr->attr()) {
725     aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr->attr());
726   }
727   if (aPointAttr.get() != NULL)
728     return aPointAttr->pnt();
729   return std::shared_ptr<GeomAPI_Pnt2d>();
730 }
731
732 void PartSet_Tools::findCoincidences(FeaturePtr theStartCoin, QList<FeaturePtr>& theList,
733                                      std::string theAttr)
734 {
735   AttributeRefAttrPtr aPnt = theStartCoin->refattr(theAttr);
736   FeaturePtr aObj = ModelAPI_Feature::feature(aPnt->object());
737   if (!theList.contains(aObj)) {
738     std::shared_ptr<GeomAPI_Pnt2d> aOrig = getPoint(theStartCoin, theAttr);
739     if (aOrig.get() == NULL)
740       return;
741     theList.append(aObj);
742     const std::set<AttributePtr>& aRefsList = aObj->data()->refsToMe();
743     std::set<AttributePtr>::const_iterator aIt;
744     for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
745       std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
746       FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
747       if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) { 
748         std::shared_ptr<GeomAPI_Pnt2d> aPnt = getPoint(aConstrFeature, theAttr);
749         if (aPnt.get() && aOrig->isEqual(aPnt)) {
750           findCoincidences(aConstrFeature, theList, SketchPlugin_ConstraintCoincidence::ENTITY_A());
751           findCoincidences(aConstrFeature, theList, SketchPlugin_ConstraintCoincidence::ENTITY_B());
752         }
753       }
754     }
755   }
756 }
757
758 AttributePtr PartSet_Tools::findAttributeBy2dPoint(ObjectPtr theObj, 
759                                                    const TopoDS_Shape theShape, 
760                                                    FeaturePtr theSketch)
761 {
762
763   AttributePtr anAttribute;
764   FeaturePtr aFeature = ModelAPI_Feature::feature(theObj);
765   if (aFeature) {
766     if (theShape.ShapeType() == TopAbs_VERTEX) {
767       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
768       if (!aVertex.IsNull())  {
769         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
770         std::shared_ptr<GeomAPI_Pnt> aValue = std::shared_ptr<GeomAPI_Pnt>(
771             new GeomAPI_Pnt(aPoint.X(), aPoint.Y(), aPoint.Z()));
772
773         // find the given point in the feature attributes
774         std::list<AttributePtr> anAttiributes = 
775           aFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
776         std::list<AttributePtr>::const_iterator anIt = anAttiributes.begin(), 
777                                                 aLast = anAttiributes.end();
778         for (; anIt != aLast && !anAttribute; anIt++) {
779           std::shared_ptr<GeomDataAPI_Point2D> aCurPoint = 
780             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIt);
781
782           std::shared_ptr<GeomAPI_Pnt> aPnt = convertTo3D(aCurPoint->x(), aCurPoint->y(), theSketch);
783           if (aPnt && (aPnt->distance(aValue) < Precision::Confusion())) {
784             anAttribute = aCurPoint;
785             break;
786           }
787         }
788       }
789     }
790   }
791   return anAttribute;
792 }