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