Salome HOME
Issue #2923: Change sketch plane
[modules/shaper.git] / src / PartSet / PartSet_Tools.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <PartSet_Tools.h>
21 #include <PartSet_Module.h>
22 #include <PartSet_SketcherMgr.h>
23
24 #include <ModelAPI_Data.h>
25 #include <ModelAPI_AttributeDouble.h>
26 #include <ModelAPI_AttributeRefList.h>
27 #include <ModelAPI_Document.h>
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_ResultConstruction.h>
30 #include <ModelAPI_Events.h>
31 #include <ModelAPI_Validator.h>
32 #include <ModelAPI_Tools.h>
33
34 #include <ModuleBase_IViewWindow.h>
35
36 #include <ModelGeomAlgo_Point2D.h>
37
38 #include <Events_Loop.h>
39
40 #include <SketcherPrs_Tools.h>
41
42 #include <XGUI_ModuleConnector.h>
43 #include <XGUI_Displayer.h>
44 #include <XGUI_Workshop.h>
45 #include <XGUI_SelectionMgr.h>
46 #include <XGUI_Selection.h>
47
48 #include <GeomDataAPI_Point.h>
49 #include <GeomDataAPI_Dir.h>
50 #include <GeomDataAPI_Point2D.h>
51 #include <GeomAPI_Pln.h>
52 #include <GeomAPI_Pnt2d.h>
53 #include <GeomAPI_Pnt.h>
54 #include <GeomAPI_Edge.h>
55 #include <GeomAPI_Vertex.h>
56
57 #include <GeomAPI_Dir.h>
58 #include <GeomAPI_XYZ.h>
59
60 #include <SketchPlugin_Feature.h>
61 #include <SketchPlugin_Sketch.h>
62 #include <SketchPlugin_ConstraintCoincidence.h>
63 #include <SketchPlugin_ConstraintDistance.h>
64 #include <SketchPlugin_ConstraintLength.h>
65 #include <SketchPlugin_ConstraintRadius.h>
66 #include <SketchPlugin_ConstraintRigid.h>
67 #include <SketchPlugin_Constraint.h>
68 #include <SketchPlugin_Circle.h>
69 #include <SketchPlugin_Arc.h>
70 #include <SketchPlugin_Line.h>
71 #include <SketchPlugin_Point.h>
72 #include <SketchPlugin_Projection.h>
73 #include <SketchPlugin_IntersectionPoint.h>
74
75 #include <ModuleBase_IWorkshop.h>
76 #include <ModuleBase_ViewerPrs.h>
77 #include <ModuleBase_Tools.h>
78
79 #include <V3d_View.hxx>
80 #include <gp_Pln.hxx>
81 #include <gp_Circ.hxx>
82 #include <ProjLib.hxx>
83 #include <ElSLib.hxx>
84 #include <Geom_Line.hxx>
85 #include <GeomAPI_ProjectPointOnCurve.hxx>
86 #include <BRep_Tool.hxx>
87 #include <TopoDS.hxx>
88 #include <TopoDS_Edge.hxx>
89 #include <TopoDS_Vertex.hxx>
90 #include <AIS_InteractiveObject.hxx>
91 #include <StdSelect_BRepOwner.hxx>
92 #include <SelectMgr_IndexedMapOfOwner.hxx>
93 #include <V3d_Coordinate.hxx>
94
95 #include <QMouseEvent>
96
97 #ifdef _DEBUG
98 #include <QDebug>
99 #endif
100
101 const double PRECISION_TOLERANCE = 0.000001;
102 const int AIS_DEFAULT_WIDTH = 2;
103 const bool SKETCH_PROJECTION_INCLUDE_INTO_RESULT = false; // by default, it is not presented
104
105 int PartSet_Tools::getAISDefaultWidth()
106 {
107   return AIS_DEFAULT_WIDTH;
108 }
109
110 gp_Pnt PartSet_Tools::convertClickToPoint(QPoint thePoint, Handle(V3d_View) theView)
111 {
112   if (theView.IsNull())
113     return gp_Pnt();
114
115   V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
116   theView->Eye(XEye, YEye, ZEye);
117
118   theView->At(XAt, YAt, ZAt);
119   gp_Pnt EyePoint(XEye, YEye, ZEye);
120   gp_Pnt AtPoint(XAt, YAt, ZAt);
121
122   gp_Vec EyeVector(EyePoint, AtPoint);
123   gp_Dir EyeDir(EyeVector);
124
125   gp_Pln PlaneOfTheView = gp_Pln(AtPoint, EyeDir);
126   Standard_Real X, Y, Z;
127   theView->Convert(thePoint.x(), thePoint.y(), X, Y, Z);
128   gp_Pnt ConvertedPoint(X, Y, Z);
129
130   gp_Pnt2d ConvertedPointOnPlane = ProjLib::Project(PlaneOfTheView, ConvertedPoint);
131   gp_Pnt ResultPoint = ElSLib::Value(ConvertedPointOnPlane.X(), ConvertedPointOnPlane.Y(),
132                                      PlaneOfTheView);
133   return ResultPoint;
134 }
135
136 void PartSet_Tools::convertTo2D(const gp_Pnt& thePoint, FeaturePtr theSketch,
137 Handle(V3d_View) theView,
138                                 double& theX, double& theY)
139 {
140   if (!theSketch)
141     return;
142
143   AttributeDoublePtr anAttr;
144   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
145
146   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
147       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
148
149   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
150       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
151   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
152       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
153   std::shared_ptr<GeomAPI_XYZ> anY = aNorm->xyz()->cross(aX->xyz());
154
155   gp_Pnt anOriginPnt(anOrigin->x(), anOrigin->y(), anOrigin->z());
156   gp_Vec aVec(anOriginPnt, thePoint);
157
158   if (!theView.IsNull()) {
159     V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
160     theView->Eye(XEye, YEye, ZEye);
161
162     theView->At(XAt, YAt, ZAt);
163     gp_Pnt EyePoint(XEye, YEye, ZEye);
164     gp_Pnt AtPoint(XAt, YAt, ZAt);
165
166     gp_Vec anEyeVec(EyePoint, AtPoint);
167     anEyeVec.Normalize();
168
169     std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
170         aData->attribute(SketchPlugin_Sketch::NORM_ID()));
171     gp_Vec aNormalVec(aNormal->x(), aNormal->y(), aNormal->z());
172
173     double aDen = anEyeVec * aNormalVec;
174     double aLVec = aDen != 0 ? aVec * aNormalVec / aDen : DBL_MAX;
175
176     gp_Vec aDeltaVec = anEyeVec * aLVec;
177     aVec = aVec - aDeltaVec;
178   }
179   theX = aVec.X() * aX->x() + aVec.Y() * aX->y() + aVec.Z() * aX->z();
180   theY = aVec.X() * anY->x() + aVec.Y() * anY->y() + aVec.Z() * anY->z();
181 }
182
183 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::convertTo2D(FeaturePtr theSketch,
184                                                     const std::shared_ptr<GeomAPI_Pnt>& thePnt)
185 {
186   std::shared_ptr<GeomAPI_Pnt2d> aRes;
187   if (theSketch->getKind() != SketchPlugin_Sketch::ID())
188     return aRes;
189   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
190       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
191   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
192       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
193   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
194       theSketch->data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
195   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
196   return thePnt->to2D(aC->pnt(), aX->dir(), aY);
197 }
198
199
200 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::convertTo3D(const double theX, const double theY,
201                                                         FeaturePtr theSketch)
202 {
203   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
204
205   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
206       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
207   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
208       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
209   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
210       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
211   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
212
213   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d =
214     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
215
216   return aPnt2d->to3D(aC->pnt(), aX->dir(), aY);
217 }
218
219 std::shared_ptr<ModelAPI_Document> PartSet_Tools::document()
220 {
221   return ModelAPI_Session::get()->moduleDocument();
222 }
223
224 void PartSet_Tools::setFeatureValue(FeaturePtr theFeature, double theValue,
225                                     const std::string& theAttribute)
226 {
227   if (!theFeature)
228     return;
229   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
230   AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
231       aData->attribute(theAttribute));
232   if (anAttribute)
233     anAttribute->setValue(theValue);
234 }
235
236 double PartSet_Tools::featureValue(FeaturePtr theFeature, const std::string& theAttribute,
237                                    bool& isValid)
238 {
239   isValid = false;
240   double aValue = 0;
241   if (theFeature) {
242     std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
243     AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
244         aData->attribute(theAttribute));
245     if (anAttribute) {
246       aValue = anAttribute->value();
247       isValid = true;
248     }
249   }
250   return aValue;
251 }
252
253 FeaturePtr PartSet_Tools::feature(FeaturePtr theFeature, const std::string& theAttribute,
254                                   const std::string& theKind)
255 {
256   FeaturePtr aFeature;
257   if (!theFeature)
258     return aFeature;
259
260   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
261   std::shared_ptr<ModelAPI_AttributeRefAttr> anAttr = std::dynamic_pointer_cast<
262       ModelAPI_AttributeRefAttr>(aData->attribute(theAttribute));
263   if (anAttr) {
264     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->object());
265     if (!theKind.empty() && aFeature && aFeature->getKind() != theKind) {
266       aFeature = FeaturePtr();
267     }
268   }
269   return aFeature;
270 }
271
272 void PartSet_Tools::createConstraint(CompositeFeaturePtr theSketch,
273                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint1,
274                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint2)
275 {
276   FeaturePtr aFeature;
277   if (theSketch) {
278     aFeature = theSketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
279   } else {
280     std::shared_ptr<ModelAPI_Document> aDoc = document();
281     aFeature = aDoc->addFeature(SketchPlugin_ConstraintCoincidence::ID());
282   }
283
284   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
285
286   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
287       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
288   aRef1->setAttr(thePoint1);
289
290   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
291       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
292   aRef2->setAttr(thePoint2);
293
294   // we need to flush created signal in order to coincidence is processed by solver
295   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
296 }
297
298 std::shared_ptr<GeomAPI_Pln> PartSet_Tools::sketchPlane(CompositeFeaturePtr theSketch)
299 {
300   std::shared_ptr<GeomAPI_Pln> aPlane;
301
302   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
303       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
304   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
305       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
306
307   if (aNormal.get() && aNormal->isInitialized() &&
308       anOrigin.get() && anOrigin->isInitialized())
309     aPlane = std::shared_ptr<GeomAPI_Pln>(new GeomAPI_Pln(anOrigin->pnt(), aNormal->dir()));
310
311   return aPlane;
312 }
313
314 void PartSet_Tools::nullifySketchPlane(CompositeFeaturePtr theSketch)
315 {
316   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
317     theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
318   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
319     theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
320
321   aNormal->reset();
322   anOrigin->reset();
323 }
324
325 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::point3D(std::shared_ptr<GeomAPI_Pnt2d> thePoint2D,
326                                                       CompositeFeaturePtr theSketch)
327 {
328   std::shared_ptr<GeomAPI_Pnt> aPoint;
329   if (!theSketch || !thePoint2D)
330     return aPoint;
331
332   DataPtr aData = theSketch->data();
333   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
334       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
335   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
336       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
337   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
338       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
339   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
340
341   return thePoint2D->to3D(aC->pnt(), aX->dir(), aY);
342 }
343
344 ResultPtr PartSet_Tools::findFixedObjectByExternal(const TopoDS_Shape& theShape,
345                                                    const ObjectPtr& theObject,
346                                                    CompositeFeaturePtr theSketch)
347 {
348   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
349   if (!aResult.get())
350     return ResultPtr();
351
352   for (int i = 0, aNbSubs = theSketch->numberOfSubs(); i < aNbSubs; i++) {
353     FeaturePtr aFeature = theSketch->subFeature(i);
354     if (aFeature->getKind() != SketchPlugin_Projection::PROJECTED_FEATURE_ID())
355       continue;
356     if (aFeature->lastResult() == aResult)
357       return aResult;
358   }
359   return ResultPtr();
360 }
361
362 ResultPtr PartSet_Tools::createFixedObjectByExternal(
363                                    const std::shared_ptr<GeomAPI_Shape>& theShape,
364                                    const ObjectPtr& theObject,
365                                    CompositeFeaturePtr theSketch,
366                                    const bool theTemporary,
367                                    FeaturePtr& theCreatedFeature)
368 {
369   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
370   if (!aResult.get())
371     return ResultPtr();
372
373   FeaturePtr aProjectionFeature = theSketch->addFeature(SketchPlugin_Projection::ID());
374   theCreatedFeature = aProjectionFeature;
375   AttributeSelectionPtr anExternalAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(
376                  aProjectionFeature->attribute(SketchPlugin_Projection::EXTERNAL_FEATURE_ID()));
377   anExternalAttr->setValue(aResult, theShape);
378
379   AttributeBooleanPtr anIntoResult = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
380     (aProjectionFeature->data()->attribute(SketchPlugin_Projection::INCLUDE_INTO_RESULT()));
381   anIntoResult->setValue(SKETCH_PROJECTION_INCLUDE_INTO_RESULT);
382   aProjectionFeature->execute();
383
384   // if projection feature has not been created, exit
385   AttributeRefAttrPtr aRefAttr = aProjectionFeature->data()->refattr(
386     SketchPlugin_Projection::PROJECTED_FEATURE_ID());
387   if (!aRefAttr || !aRefAttr->isInitialized())
388   {
389     // remove external feature if the attribute is not filled
390     std::set<FeaturePtr> aFeatures;
391     aFeatures.insert(aProjectionFeature);
392     ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
393     return ResultPtr();
394   }
395
396   FeaturePtr aProjection = ModelAPI_Feature::feature(aRefAttr->object());
397   if (aProjection.get() && aProjection->lastResult().get())
398     return aProjection->lastResult();
399
400   return ResultPtr();
401 }
402
403 bool PartSet_Tools::isContainPresentation(const QList<ModuleBase_ViewerPrsPtr>& theSelected,
404                                           const ModuleBase_ViewerPrsPtr& thePrs)
405 {
406   foreach (ModuleBase_ViewerPrsPtr aPrs, theSelected) {
407     if (aPrs->object() == thePrs->object())
408       return true;
409   }
410   return false;
411 }
412
413 GeomShapePtr PartSet_Tools::findShapeBy2DPoint(const AttributePtr& theAttribute,
414                                                        ModuleBase_IWorkshop* theWorkshop)
415 {
416   GeomShapePtr aShape;
417   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
418   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
419
420   // 2. find visualized vertices of the attribute and if the attribute of the vertex is
421   // the same, return it
422   FeaturePtr anAttributeFeature = ModelAPI_Feature::feature(theAttribute->owner());
423   // 2.1 get visualized results of the feature
424   const std::list<ResultPtr>& aResList = anAttributeFeature->results();
425   std::list<ResultPtr>::const_iterator anIt = aResList.begin(), aLast = aResList.end();
426   for (; anIt != aLast; anIt++) {
427     AISObjectPtr aAISObj = aDisplayer->getAISObject(*anIt);
428     if (aAISObj.get() != NULL) {
429       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
430       // 2.2 find selected owners of a visualizedd object
431       SelectMgr_IndexedMapOfOwner aSelectedOwners;
432       aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
433       for (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
434         Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
435         if (!anOwner.IsNull()) {
436           Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
437           if (!aBRepOwner.IsNull() && aBRepOwner->HasShape()) {
438             const TopoDS_Shape& aBRepShape = aBRepOwner->Shape();
439             if (aBRepShape.ShapeType() == TopAbs_VERTEX) {
440               // 2.3 if the owner is vertex and an attribute of the vertex is equal to the initial
441               // attribute, returns the shape
442               PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(theWorkshop->module());
443               PartSet_SketcherMgr* aSketchMgr = aModule->sketchMgr();
444               AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(anAttributeFeature,
445                                                         aBRepShape, aSketchMgr->activeSketch());
446               if (aPntAttr.get() != NULL && aPntAttr == theAttribute) {
447                 aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
448                 aShape->setImpl(new TopoDS_Shape(aBRepShape));
449                 break;
450               }
451             }
452           }
453         }
454       }
455     }
456   }
457   return aShape;
458 }
459
460 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPoint(
461                                                   std::shared_ptr<ModelAPI_Feature>& theFeature,
462                                                   const std::string& theAttribute)
463 {
464   std::shared_ptr<GeomDataAPI_Point2D> aPointAttr = ModelGeomAlgo_Point2D::getPointOfRefAttr(
465                                           theFeature.get(), theAttribute, SketchPlugin_Point::ID(),
466                                           SketchPlugin_Point::COORD_ID());
467   if (aPointAttr.get() != NULL)
468     return aPointAttr->pnt();
469   return std::shared_ptr<GeomAPI_Pnt2d>();
470 }
471
472 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPnt2d(QMouseEvent* theEvent,
473                                                 ModuleBase_IViewWindow* theWindow,
474                                                 const FeaturePtr& theSketch)
475 {
476   gp_Pnt aPnt = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
477   double aX, anY;
478   Handle(V3d_View) aView = theWindow->v3dView();
479   PartSet_Tools::convertTo2D(aPnt, theSketch, aView, aX, anY);
480
481   return std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(aX, anY));
482 }
483
484 FeaturePtr findFirstCoincidenceByData(const DataPtr& theData,
485                                       std::shared_ptr<GeomAPI_Pnt2d> thePoint)
486 {
487   FeaturePtr aCoincident;
488
489   const std::set<AttributePtr>& aRefsList = theData->refsToMe();
490   std::set<AttributePtr>::const_iterator aIt;
491   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
492     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
493     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
494     if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
495       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
496         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
497       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
498         aCoincident = aConstrFeature;
499         break;
500       } else {
501         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
502                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
503         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
504           aCoincident = aConstrFeature;
505           break;
506         }
507       }
508     }
509   }
510   return aCoincident;
511 }
512
513 FeaturePtr PartSet_Tools::findFirstCoincidence(const FeaturePtr& theFeature,
514                                                std::shared_ptr<GeomAPI_Pnt2d> thePoint)
515 {
516   FeaturePtr aCoincident;
517   if (theFeature.get() == NULL)
518     return aCoincident;
519
520   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
521   std::set<AttributePtr>::const_iterator aIt;
522   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
523     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
524     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
525     if (aConstrFeature && aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
526       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
527         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
528       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
529         aCoincident = aConstrFeature;
530         break;
531       } else {
532         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
533                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
534         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
535           aCoincident = aConstrFeature;
536           break;
537         }
538       }
539     }
540   }
541   /// Find by result
542   if (!aCoincident.get()) {
543     std::list<ResultPtr> aResults = theFeature->results();
544     std::list<ResultPtr>::const_iterator aIt;
545     for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
546       ResultPtr aResult = *aIt;
547       aCoincident = findFirstCoincidenceByData(aResult->data(), thePoint);
548       if (aCoincident.get())
549         break;
550     }
551   }
552   return aCoincident;
553 }
554
555 void PartSet_Tools::findCoincidences(FeaturePtr theStartCoin, QList<FeaturePtr>& theList,
556                                      QList<FeaturePtr>& theCoincidencies,
557                                      std::string theAttr, QList<bool>& theIsAttributes)
558 {
559   std::shared_ptr<GeomAPI_Pnt2d> aOrig = getCoincedencePoint(theStartCoin);
560   if (aOrig.get() == NULL)
561     return;
562
563   AttributeRefAttrPtr aPnt = theStartCoin->refattr(theAttr);
564   if (!aPnt)
565     return;
566   ObjectPtr aObj = aPnt->object();
567   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
568   if (aFeature.get()) {
569     if (!theList.contains(aFeature)) {
570       theList.append(aFeature);
571       theCoincidencies.append(theStartCoin);
572       theIsAttributes.append(true); // point attribute on a feature
573       const std::set<AttributePtr>& aRefsList = aFeature->data()->refsToMe();
574       std::set<AttributePtr>::const_iterator aIt;
575       for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
576         std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
577         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
578         if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
579           if (!theCoincidencies.contains(aConstrFeature)) {
580             std::shared_ptr<GeomAPI_Pnt2d> aPnt = getCoincedencePoint(aConstrFeature);
581             if (aPnt.get() && aOrig->isEqual(aPnt)) {
582               findCoincidences(aConstrFeature, theList, theCoincidencies,
583                 SketchPlugin_ConstraintCoincidence::ENTITY_A(), theIsAttributes);
584               findCoincidences(aConstrFeature, theList, theCoincidencies,
585                 SketchPlugin_ConstraintCoincidence::ENTITY_B(), theIsAttributes);
586             }
587           }
588         }
589       }
590     }
591   } else {
592     // Find by Results
593     ResultConstructionPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
594     if (aResult.get()) {
595       FeaturePtr aFeature = ModelAPI_Feature::feature(aPnt->object());
596       if (!theList.contains(aFeature))
597         theList.append(aFeature);
598       theCoincidencies.append(theStartCoin);
599       theIsAttributes.append(false); // point attribute on a feature
600
601       const std::set<AttributePtr>& aRefsList = aResult->data()->refsToMe();
602       std::set<AttributePtr>::const_iterator aIt;
603       for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
604         std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
605         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
606         if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
607           if (!theCoincidencies.contains(aConstrFeature)) {
608             std::shared_ptr<GeomAPI_Pnt2d> aPnt = getCoincedencePoint(aConstrFeature);
609             if (aPnt.get() && aOrig->isEqual(aPnt)) {
610               findCoincidences(aConstrFeature, theList, theCoincidencies,
611                 SketchPlugin_ConstraintCoincidence::ENTITY_A(), theIsAttributes);
612               findCoincidences(aConstrFeature, theList, theCoincidencies,
613                 SketchPlugin_ConstraintCoincidence::ENTITY_B(), theIsAttributes);
614             }
615           }
616         }
617       }
618     }
619   }
620 }
621
622 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getCoincedencePoint(FeaturePtr theStartCoin)
623 {
624   std::shared_ptr<GeomAPI_Pnt2d> aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(),
625                                                         SketchPlugin_Constraint::ENTITY_A());
626   if (aPnt.get() == NULL)
627     aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(), SketchPlugin_Constraint::ENTITY_B());
628   return aPnt;
629 }
630
631 AttributePtr PartSet_Tools::findAttributeBy2dPoint(ObjectPtr theObj,
632                                                    const TopoDS_Shape theShape,
633                                                    FeaturePtr theSketch)
634 {
635
636   AttributePtr anAttribute;
637   FeaturePtr aFeature = ModelAPI_Feature::feature(theObj);
638   if (aFeature) {
639     if (theShape.ShapeType() == TopAbs_VERTEX) {
640       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
641       if (!aVertex.IsNull())  {
642         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
643         std::shared_ptr<GeomAPI_Pnt> aValue = std::shared_ptr<GeomAPI_Pnt>(
644             new GeomAPI_Pnt(aPoint.X(), aPoint.Y(), aPoint.Z()));
645
646         // find the given point in the feature attributes
647         std::list<AttributePtr> anAttiributes =
648           aFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
649         std::list<AttributePtr>::const_iterator anIt = anAttiributes.begin(),
650                                                 aLast = anAttiributes.end();
651         for (; anIt != aLast && !anAttribute; anIt++) {
652           std::shared_ptr<GeomDataAPI_Point2D> aCurPoint =
653             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIt);
654           if (!aCurPoint->isInitialized())
655             continue;
656
657           std::shared_ptr<GeomAPI_Pnt> aPnt =
658             convertTo3D(aCurPoint->x(), aCurPoint->y(), theSketch);
659           if (aPnt && (aPnt->distance(aValue) < Precision::Confusion())) {
660             anAttribute = aCurPoint;
661             break;
662           }
663         }
664       }
665     }
666   }
667   return anAttribute;
668 }
669
670 void PartSet_Tools::sendSubFeaturesEvent(const CompositeFeaturePtr& theComposite,
671                                          const Events_ID theEventId)
672 {
673   if (!theComposite.get())
674     return;
675
676   static Events_Loop* aLoop = Events_Loop::loop();
677   int aNumberOfSubs = theComposite->numberOfSubs();
678   for (int i = 0; i < aNumberOfSubs; i++) {
679     FeaturePtr aSubFeature = theComposite->subFeature(i);
680     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
681     aECreator->sendUpdated(aSubFeature, theEventId);
682   }
683   Events_Loop::loop()->flush(theEventId);
684 }
685
686 bool PartSet_Tools::isAuxiliarySketchEntity(const ObjectPtr& theObject)
687 {
688   bool isAuxiliaryFeature = false;
689
690   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
691   std::string anAuxiliaryAttribute = SketchPlugin_SketchEntity::AUXILIARY_ID();
692   AttributeBooleanPtr anAuxiliaryAttr = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(
693                                     anObjectFeature->data()->attribute(anAuxiliaryAttribute));
694   if (anAuxiliaryAttr.get())
695     isAuxiliaryFeature = anAuxiliaryAttr->value();
696
697
698   return isAuxiliaryFeature;
699 }
700
701 bool PartSet_Tools::isIncludeIntoSketchResult(const ObjectPtr& theObject)
702 {
703   // check the feature is neither Projection nor IntersectionPoint feature
704   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
705   if (aFeature->getKind() == SketchPlugin_Projection::ID() ||
706       aFeature->getKind() == SketchPlugin_IntersectionPoint::ID())
707     return false;
708
709   // go through the references to the feature to check
710   // if it was created by Projection or Intersection
711   const std::set<AttributePtr>& aRefs = theObject->data()->refsToMe();
712   for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
713        aRefIt != aRefs.end(); ++aRefIt) {
714     AttributePtr anAttr = *aRefIt;
715     std::string anIncludeToResultAttrName;
716     if (anAttr->id() == SketchPlugin_Projection::PROJECTED_FEATURE_ID())
717       anIncludeToResultAttrName = SketchPlugin_Projection::INCLUDE_INTO_RESULT();
718     else if (anAttr->id() == SketchPlugin_IntersectionPoint::INTERSECTION_POINTS_ID())
719       anIncludeToResultAttrName = SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT();
720
721     if (!anIncludeToResultAttrName.empty()) {
722       // check "include into result" flag
723       FeaturePtr aParent = ModelAPI_Feature::feature(anAttr->owner());
724       return aParent->boolean(anIncludeToResultAttrName)->value();
725     }
726   }
727   return true;
728 }
729
730
731 ResultPtr PartSet_Tools::createFixedByExternalCenter(
732     const ObjectPtr& theObject,
733     const std::shared_ptr<GeomAPI_Edge>& theEdge,
734     ModelAPI_AttributeSelection::CenterType theType,
735     const CompositeFeaturePtr& theSketch,
736     bool theTemporary,
737     FeaturePtr& theCreatedFeature)
738 {
739   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
740   if (!aResult.get())
741     return ResultPtr();
742
743   FeaturePtr aProjectionFeature = theSketch->addFeature(SketchPlugin_Projection::ID());
744   theCreatedFeature = aProjectionFeature;
745   AttributeSelectionPtr anExternalAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(
746                  aProjectionFeature->attribute(SketchPlugin_Projection::EXTERNAL_FEATURE_ID()));
747   anExternalAttr->setValueCenter(aResult, theEdge, theType, theTemporary);
748
749   AttributeBooleanPtr anIntoResult = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
750     (aProjectionFeature->data()->attribute(SketchPlugin_Projection::INCLUDE_INTO_RESULT()));
751   anIntoResult->setValue(SKETCH_PROJECTION_INCLUDE_INTO_RESULT);
752   aProjectionFeature->execute();
753
754   // if projection feature has not been created, exit
755   AttributeRefAttrPtr aRefAttr = aProjectionFeature->data()->refattr(
756     SketchPlugin_Projection::PROJECTED_FEATURE_ID());
757   if (!aRefAttr || !aRefAttr->isInitialized())
758     return ResultPtr();
759
760   FeaturePtr aProjection = ModelAPI_Feature::feature(aRefAttr->object());
761   if (aProjection.get() && aProjection->lastResult().get())
762     return aProjection->lastResult();
763
764   return ResultPtr();
765 }
766
767 void PartSet_Tools::getFirstAndLastIndexInFolder(const ObjectPtr& theFolder,
768   int& theFirst, int& theLast)
769 {
770   theFirst = -1;
771   theLast = -1;
772
773   DocumentPtr aDoc = theFolder->document();
774   FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theFolder);
775   if (!aFolder.get())
776     return;
777
778   AttributeReferencePtr aFirstFeatAttr =
779     aFolder->data()->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
780   if (!aFirstFeatAttr.get())
781     return;
782   FeaturePtr aFirstFeatureInFolder = ModelAPI_Feature::feature(aFirstFeatAttr->value());
783   if (!aFirstFeatureInFolder.get())
784     return;
785
786   FeaturePtr aLastFeatureInFolder = aFolder->lastVisibleFeature();
787   if (!aLastFeatureInFolder.get())
788     return;
789
790   theFirst = aDoc->index(aFirstFeatureInFolder);
791   theLast = aDoc->index(aLastFeatureInFolder);
792 }