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