]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_Tools.cpp
Salome HOME
Protect normalization of zero-length vector.
[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 #include <Events_InfoMessage.h>
40
41 #include <SketcherPrs_Tools.h>
42
43 #include <XGUI_ModuleConnector.h>
44 #include <XGUI_Displayer.h>
45 #include <XGUI_Workshop.h>
46 #include <XGUI_SelectionMgr.h>
47 #include <XGUI_Selection.h>
48
49 #include <GeomDataAPI_Point.h>
50 #include <GeomDataAPI_Dir.h>
51 #include <GeomDataAPI_Point2D.h>
52 #include <GeomDataAPI_Point2DArray.h>
53 #include <GeomAPI_Pln.h>
54 #include <GeomAPI_Pnt2d.h>
55 #include <GeomAPI_Pnt.h>
56 #include <GeomAPI_Edge.h>
57 #include <GeomAPI_Vertex.h>
58 #include <GeomAPI_ShapeExplorer.h>
59
60 #include <GeomAPI_Dir.h>
61 #include <GeomAPI_XYZ.h>
62
63 #include <SketchPlugin_Feature.h>
64 #include <SketchPlugin_Sketch.h>
65 #include <SketchPlugin_ConstraintCoincidence.h>
66 #include <SketchPlugin_ConstraintDistance.h>
67 #include <SketchPlugin_ConstraintLength.h>
68 #include <SketchPlugin_ConstraintRadius.h>
69 #include <SketchPlugin_ConstraintRigid.h>
70 #include <SketchPlugin_Constraint.h>
71 #include <SketchPlugin_Circle.h>
72 #include <SketchPlugin_Arc.h>
73 #include <SketchPlugin_Line.h>
74 #include <SketchPlugin_Point.h>
75 #include <SketchPlugin_Projection.h>
76 #include <SketchPlugin_IntersectionPoint.h>
77
78 #include <ModuleBase_IWorkshop.h>
79 #include <ModuleBase_ViewerPrs.h>
80 #include <ModuleBase_Tools.h>
81
82 #include <V3d_View.hxx>
83 #include <gp_Pln.hxx>
84 #include <gp_Circ.hxx>
85 #include <ProjLib.hxx>
86 #include <ElSLib.hxx>
87 #include <Geom_Line.hxx>
88 #include <GeomAPI_ProjectPointOnCurve.hxx>
89 #include <BRep_Tool.hxx>
90 #include <TopoDS.hxx>
91 #include <TopoDS_Edge.hxx>
92 #include <TopoDS_Vertex.hxx>
93 #include <AIS_InteractiveObject.hxx>
94 #include <StdSelect_BRepOwner.hxx>
95 #include <SelectMgr_IndexedMapOfOwner.hxx>
96 #include <V3d_Coordinate.hxx>
97
98 #include <QMouseEvent>
99
100 #ifdef _DEBUG
101 #include <QDebug>
102 #endif
103
104 const double PRECISION_TOLERANCE = 0.000001;
105 const int AIS_DEFAULT_WIDTH = 2;
106 const bool SKETCH_PROJECTION_INCLUDE_INTO_RESULT = false; // by default, it is not presented
107
108 int PartSet_Tools::getAISDefaultWidth()
109 {
110   return AIS_DEFAULT_WIDTH;
111 }
112
113 gp_Pnt PartSet_Tools::convertClickToPoint(QPoint thePoint, Handle(V3d_View) theView)
114 {
115   if (theView.IsNull())
116     return gp_Pnt();
117
118   V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
119   theView->Eye(XEye, YEye, ZEye);
120
121   theView->At(XAt, YAt, ZAt);
122   gp_Pnt EyePoint(XEye, YEye, ZEye);
123   gp_Pnt AtPoint(XAt, YAt, ZAt);
124
125   if (EyePoint.Distance(AtPoint) < Precision::Confusion())
126     return gp_Pnt();
127
128   gp_Vec EyeVector(EyePoint, AtPoint);
129   gp_Dir EyeDir(EyeVector);
130
131   gp_Pln PlaneOfTheView = gp_Pln(AtPoint, EyeDir);
132   Standard_Real X, Y, Z;
133   theView->Convert(thePoint.x(), thePoint.y(), X, Y, Z);
134   gp_Pnt ConvertedPoint(X, Y, Z);
135
136   gp_Pnt2d ConvertedPointOnPlane = ProjLib::Project(PlaneOfTheView, ConvertedPoint);
137   return ElSLib::Value(ConvertedPointOnPlane.X(), ConvertedPointOnPlane.Y(),
138                                      PlaneOfTheView);
139 }
140
141 void PartSet_Tools::convertTo2D(const gp_Pnt& thePoint, FeaturePtr theSketch,
142 Handle(V3d_View) theView,
143                                 double& theX, double& theY)
144 {
145   if (!theSketch)
146     return;
147
148   AttributeDoublePtr anAttr;
149   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
150
151   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
152       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
153
154   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
155       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
156   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
157       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
158   std::shared_ptr<GeomAPI_XYZ> anY = aNorm->xyz()->cross(aX->xyz());
159
160   gp_Pnt anOriginPnt(anOrigin->x(), anOrigin->y(), anOrigin->z());
161   gp_Vec aVec(anOriginPnt, thePoint);
162
163   if (!theView.IsNull()) {
164     V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
165     theView->Eye(XEye, YEye, ZEye);
166
167     theView->At(XAt, YAt, ZAt);
168     gp_Pnt EyePoint(XEye, YEye, ZEye);
169     gp_Pnt AtPoint(XAt, YAt, ZAt);
170
171     if (EyePoint.Distance(AtPoint) > gp::Resolution()) {
172       gp_Vec anEyeVec(EyePoint, AtPoint);
173       anEyeVec.Normalize();
174
175       std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
176          aData->attribute(SketchPlugin_Sketch::NORM_ID()));
177       gp_Vec aNormalVec(aNormal->x(), aNormal->y(), aNormal->z());
178
179       double aDen = anEyeVec * aNormalVec;
180       double aLVec = aDen != 0 ? aVec * aNormalVec / aDen : DBL_MAX;
181
182       gp_Vec aDeltaVec = anEyeVec * aLVec;
183       aVec = aVec - aDeltaVec;
184     }
185 else {
186   int qq = 0;
187 }
188   }
189   theX = aVec.X() * aX->x() + aVec.Y() * aX->y() + aVec.Z() * aX->z();
190   theY = aVec.X() * anY->x() + aVec.Y() * anY->y() + aVec.Z() * anY->z();
191 }
192
193 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::convertTo2D(FeaturePtr theSketch,
194                                                     const std::shared_ptr<GeomAPI_Pnt>& thePnt)
195 {
196   std::shared_ptr<GeomAPI_Pnt2d> aRes;
197   if (theSketch->getKind() != SketchPlugin_Sketch::ID())
198     return aRes;
199   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
200       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
201   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
202       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
203   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
204       theSketch->data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
205   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
206   return thePnt->to2D(aC->pnt(), aX->dir(), aY);
207 }
208
209
210 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::convertTo3D(const double theX, const double theY,
211                                                         FeaturePtr theSketch)
212 {
213   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
214
215   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
216       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
217   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
218       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
219   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
220       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
221   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
222
223   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d =
224     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
225
226   return aPnt2d->to3D(aC->pnt(), aX->dir(), aY);
227 }
228
229 std::shared_ptr<ModelAPI_Document> PartSet_Tools::document()
230 {
231   return ModelAPI_Session::get()->moduleDocument();
232 }
233
234 void PartSet_Tools::setFeatureValue(FeaturePtr theFeature, double theValue,
235                                     const std::string& theAttribute)
236 {
237   if (!theFeature)
238     return;
239   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
240   AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
241       aData->attribute(theAttribute));
242   if (anAttribute)
243     anAttribute->setValue(theValue);
244 }
245
246 double PartSet_Tools::featureValue(FeaturePtr theFeature, const std::string& theAttribute,
247                                    bool& isValid)
248 {
249   isValid = false;
250   double aValue = 0;
251   if (theFeature) {
252     std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
253     AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
254         aData->attribute(theAttribute));
255     if (anAttribute) {
256       aValue = anAttribute->value();
257       isValid = true;
258     }
259   }
260   return aValue;
261 }
262
263 FeaturePtr PartSet_Tools::feature(FeaturePtr theFeature, const std::string& theAttribute,
264                                   const std::string& theKind)
265 {
266   FeaturePtr aFeature;
267   if (!theFeature)
268     return aFeature;
269
270   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
271   std::shared_ptr<ModelAPI_AttributeRefAttr> anAttr = std::dynamic_pointer_cast<
272       ModelAPI_AttributeRefAttr>(aData->attribute(theAttribute));
273   if (anAttr) {
274     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->object());
275     if (!theKind.empty() && aFeature && aFeature->getKind() != theKind) {
276       aFeature = FeaturePtr();
277     }
278   }
279   return aFeature;
280 }
281
282 void PartSet_Tools::createConstraint(CompositeFeaturePtr theSketch,
283                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint1,
284                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint2)
285 {
286   FeaturePtr aFeature;
287   if (theSketch) {
288     aFeature = theSketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
289   } else {
290     std::shared_ptr<ModelAPI_Document> aDoc = document();
291     aFeature = aDoc->addFeature(SketchPlugin_ConstraintCoincidence::ID());
292   }
293
294   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
295
296   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
297       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
298   aRef1->setAttr(thePoint1);
299
300   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
301       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
302   aRef2->setAttr(thePoint2);
303
304   // we need to flush created signal in order to coincidence is processed by solver
305   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
306 }
307
308 std::shared_ptr<GeomAPI_Pln> PartSet_Tools::sketchPlane(CompositeFeaturePtr theSketch)
309 {
310   std::shared_ptr<GeomAPI_Pln> aPlane;
311
312   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
313       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
314   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
315       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
316
317   if (aNormal.get() && aNormal->isInitialized() &&
318       anOrigin.get() && anOrigin->isInitialized())
319     aPlane = std::shared_ptr<GeomAPI_Pln>(new GeomAPI_Pln(anOrigin->pnt(), aNormal->dir()));
320
321   return aPlane;
322 }
323
324 void PartSet_Tools::nullifySketchPlane(CompositeFeaturePtr theSketch)
325 {
326   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
327     theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
328   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
329     theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
330
331   aNormal->reset();
332   anOrigin->reset();
333 }
334
335 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::point3D(std::shared_ptr<GeomAPI_Pnt2d> thePoint2D,
336                                                       CompositeFeaturePtr theSketch)
337 {
338   std::shared_ptr<GeomAPI_Pnt> aPoint;
339   if (!theSketch || !thePoint2D)
340     return aPoint;
341
342   DataPtr aData = theSketch->data();
343   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
344       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
345   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
346       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
347   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
348       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
349   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
350
351   return thePoint2D->to3D(aC->pnt(), aX->dir(), aY);
352 }
353
354 ResultPtr PartSet_Tools::findFixedObjectByExternal(const TopoDS_Shape& theShape,
355                                                    const ObjectPtr& theObject,
356                                                    CompositeFeaturePtr theSketch)
357 {
358   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
359   if (!aResult.get())
360     return ResultPtr();
361
362   for (int i = 0, aNbSubs = theSketch->numberOfSubs(); i < aNbSubs; i++) {
363     FeaturePtr aFeature = theSketch->subFeature(i);
364     if (aFeature->getKind() != SketchPlugin_Projection::PROJECTED_FEATURE_ID())
365       continue;
366     if (aFeature->lastResult() == aResult)
367       return aResult;
368   }
369   return ResultPtr();
370 }
371
372 ResultPtr PartSet_Tools::createFixedObjectByExternal(
373                                    const std::shared_ptr<GeomAPI_Shape>& theShape,
374                                    const ObjectPtr& theObject,
375                                    CompositeFeaturePtr theSketch,
376                                    const bool theTemporary,
377                                    FeaturePtr& theCreatedFeature)
378 {
379   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
380   if (!aResult.get())
381     return ResultPtr();
382
383   FeaturePtr aProjectionFeature = theSketch->addFeature(SketchPlugin_Projection::ID());
384   theCreatedFeature = aProjectionFeature;
385   AttributeSelectionPtr anExternalAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(
386                  aProjectionFeature->attribute(SketchPlugin_Projection::EXTERNAL_FEATURE_ID()));
387   anExternalAttr->setValue(aResult, theShape);
388
389   AttributeBooleanPtr anIntoResult = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
390     (aProjectionFeature->data()->attribute(SketchPlugin_Projection::INCLUDE_INTO_RESULT()));
391   anIntoResult->setValue(SKETCH_PROJECTION_INCLUDE_INTO_RESULT);
392   aProjectionFeature->execute();
393
394   // if projection feature has not been created, exit
395   AttributeRefAttrPtr aRefAttr = aProjectionFeature->data()->refattr(
396     SketchPlugin_Projection::PROJECTED_FEATURE_ID());
397   if (!aRefAttr || !aRefAttr->isInitialized())
398   {
399     // remove external feature if the attribute is not filled
400     std::set<FeaturePtr> aFeatures;
401     aFeatures.insert(aProjectionFeature);
402     ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
403     return ResultPtr();
404   }
405
406   FeaturePtr aProjection = ModelAPI_Feature::feature(aRefAttr->object());
407   if (aProjection.get() && aProjection->lastResult().get())
408     return aProjection->lastResult();
409
410   return ResultPtr();
411 }
412
413 bool PartSet_Tools::isContainPresentation(const QList<ModuleBase_ViewerPrsPtr>& theSelected,
414                                           const ModuleBase_ViewerPrsPtr& thePrs)
415 {
416   foreach (ModuleBase_ViewerPrsPtr aPrs, theSelected) {
417     if (aPrs->object() == thePrs->object())
418       return true;
419   }
420   return false;
421 }
422
423 GeomShapePtr PartSet_Tools::findShapeBy2DPoint(const AttributePtr& theAttribute,
424                                                        ModuleBase_IWorkshop* theWorkshop)
425 {
426   GeomShapePtr aShape;
427   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
428   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
429
430   // 2. find visualized vertices of the attribute and if the attribute of the vertex is
431   // the same, return it
432   FeaturePtr anAttributeFeature = ModelAPI_Feature::feature(theAttribute->owner());
433   // 2.1 get visualized results of the feature
434   const std::list<ResultPtr>& aResList = anAttributeFeature->results();
435   std::list<ResultPtr>::const_iterator anIt = aResList.begin(), aLast = aResList.end();
436   for (; anIt != aLast; anIt++) {
437     AISObjectPtr aAISObj = aDisplayer->getAISObject(*anIt);
438     if (aAISObj.get() != NULL) {
439       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
440       // 2.2 find selected owners of a visualizedd object
441       SelectMgr_IndexedMapOfOwner aSelectedOwners;
442       aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
443       for (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
444         Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
445         if (!anOwner.IsNull()) {
446           Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
447           if (!aBRepOwner.IsNull() && aBRepOwner->HasShape()) {
448             const TopoDS_Shape& aBRepShape = aBRepOwner->Shape();
449             if (aBRepShape.ShapeType() == TopAbs_VERTEX) {
450               // 2.3 if the owner is vertex and an attribute of the vertex is equal to the initial
451               // attribute, returns the shape
452               PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(theWorkshop->module());
453               PartSet_SketcherMgr* aSketchMgr = aModule->sketchMgr();
454               std::pair<AttributePtr, int> aPntAttrIndex = PartSet_Tools::findAttributeBy2dPoint(
455                   anAttributeFeature, aBRepShape, aSketchMgr->activeSketch());
456               if (aPntAttrIndex.first.get() != NULL && aPntAttrIndex.first == theAttribute) {
457                 aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
458                 aShape->setImpl(new TopoDS_Shape(aBRepShape));
459                 break;
460               }
461             }
462           }
463         }
464       }
465     }
466   }
467   return aShape;
468 }
469
470 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPoint(
471                                                   std::shared_ptr<ModelAPI_Feature>& theFeature,
472                                                   const std::string& theAttribute)
473 {
474   std::shared_ptr<GeomDataAPI_Point2D> aPointAttr = ModelGeomAlgo_Point2D::getPointOfRefAttr(
475                                           theFeature.get(), theAttribute, SketchPlugin_Point::ID(),
476                                           SketchPlugin_Point::COORD_ID());
477   if (aPointAttr.get() != NULL)
478     return aPointAttr->pnt();
479   return std::shared_ptr<GeomAPI_Pnt2d>();
480 }
481
482 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPnt2d(QMouseEvent* theEvent,
483                                                 ModuleBase_IViewWindow* theWindow,
484                                                 const FeaturePtr& theSketch)
485 {
486   gp_Pnt aPnt = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
487   double aX, anY;
488   Handle(V3d_View) aView = theWindow->v3dView();
489   PartSet_Tools::convertTo2D(aPnt, theSketch, aView, aX, anY);
490
491   return std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(aX, anY));
492 }
493
494 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPnt2d(const Handle(V3d_View)& theView,
495                                                        const TopoDS_Shape& theShape,
496                                                        const FeaturePtr& theSketch)
497 {
498   GeomPnt2dPtr aPoint2D;
499   if (!theShape.IsNull() && theShape.ShapeType() == TopAbs_VERTEX) {
500     const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
501     if (!aVertex.IsNull()) {
502       // the case when the point is taken from the existing vertex
503       gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
504       double aX, aY;
505       PartSet_Tools::convertTo2D(aPoint, theSketch, theView, aX, aY);
506       aPoint2D.reset(new GeomAPI_Pnt2d(aX, aY));
507     }
508   }
509   return aPoint2D;
510 }
511
512 FeaturePtr findFirstCoincidenceByData(const DataPtr& theData,
513                                       std::shared_ptr<GeomAPI_Pnt2d> thePoint)
514 {
515   FeaturePtr aCoincident;
516
517   const std::set<AttributePtr>& aRefsList = theData->refsToMe();
518   std::set<AttributePtr>::const_iterator aIt;
519   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
520     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
521     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
522     if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
523       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
524         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
525       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
526         aCoincident = aConstrFeature;
527         break;
528       } else {
529         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
530                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
531         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
532           aCoincident = aConstrFeature;
533           break;
534         }
535       }
536     }
537   }
538   return aCoincident;
539 }
540
541 FeaturePtr PartSet_Tools::findFirstCoincidence(const FeaturePtr& theFeature,
542                                                std::shared_ptr<GeomAPI_Pnt2d> thePoint)
543 {
544   FeaturePtr aCoincident;
545   if (theFeature.get() == NULL)
546     return aCoincident;
547
548   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
549   std::set<AttributePtr>::const_iterator aIt;
550   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
551     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
552     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
553     if (aConstrFeature && aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
554       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
555         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
556       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
557         aCoincident = aConstrFeature;
558         break;
559       } else {
560         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
561                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
562         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
563           aCoincident = aConstrFeature;
564           break;
565         }
566       }
567     }
568   }
569   /// Find by result
570   if (!aCoincident.get()) {
571     std::list<ResultPtr> aResults = theFeature->results();
572     std::list<ResultPtr>::const_iterator aIt;
573     for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
574       ResultPtr aResult = *aIt;
575       aCoincident = findFirstCoincidenceByData(aResult->data(), thePoint);
576       if (aCoincident.get())
577         break;
578     }
579   }
580   return aCoincident;
581 }
582
583 void PartSet_Tools::findCoincidences(FeaturePtr theStartCoin, QList<FeaturePtr>& theList,
584                                      QList<FeaturePtr>& theCoincidencies,
585                                      std::string theAttr, QList<bool>& theIsAttributes)
586 {
587   std::shared_ptr<GeomAPI_Pnt2d> aOrig = getCoincedencePoint(theStartCoin);
588   if (aOrig.get() == NULL)
589     return;
590
591   AttributeRefAttrPtr aPnt = theStartCoin->refattr(theAttr);
592   if (!aPnt)
593     return;
594   ObjectPtr aObj = aPnt->object();
595   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
596   if (aFeature.get()) {
597     if (!theList.contains(aFeature)) {
598       theList.append(aFeature);
599       theCoincidencies.append(theStartCoin);
600       theIsAttributes.append(true); // point attribute on a feature
601       const std::set<AttributePtr>& aRefsList = aFeature->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   } else {
620     // Find by Results
621     ResultConstructionPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
622     if (aResult.get()) {
623       FeaturePtr aFeature = ModelAPI_Feature::feature(aPnt->object());
624       if (!theList.contains(aFeature))
625         theList.append(aFeature);
626       theCoincidencies.append(theStartCoin);
627       theIsAttributes.append(false); // point attribute on a feature
628
629       const std::set<AttributePtr>& aRefsList = aResult->data()->refsToMe();
630       std::set<AttributePtr>::const_iterator aIt;
631       for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
632         std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
633         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
634         if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
635           if (!theCoincidencies.contains(aConstrFeature)) {
636             std::shared_ptr<GeomAPI_Pnt2d> aPnt = getCoincedencePoint(aConstrFeature);
637             if (aPnt.get() && aOrig->isEqual(aPnt)) {
638               findCoincidences(aConstrFeature, theList, theCoincidencies,
639                 SketchPlugin_ConstraintCoincidence::ENTITY_A(), theIsAttributes);
640               findCoincidences(aConstrFeature, theList, theCoincidencies,
641                 SketchPlugin_ConstraintCoincidence::ENTITY_B(), theIsAttributes);
642             }
643           }
644         }
645       }
646     }
647   }
648 }
649
650 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getCoincedencePoint(FeaturePtr theStartCoin)
651 {
652   std::shared_ptr<GeomAPI_Pnt2d> aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(),
653                                                         SketchPlugin_Constraint::ENTITY_A());
654   if (aPnt.get() == NULL)
655     aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(), SketchPlugin_Constraint::ENTITY_B());
656   return aPnt;
657 }
658
659 class PointWrapper
660 {
661 public:
662   PointWrapper(AttributePtr theAttribute)
663     : myPoint(std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute)),
664       myArray(std::dynamic_pointer_cast<GeomDataAPI_Point2DArray>(theAttribute))
665   {}
666
667   int size() const { return myPoint.get() ? 1 : (myArray.get() ? myArray->size() : 0); }
668
669   GeomPointPtr point(int theIndex, FeaturePtr theSketch)
670   {
671     GeomPnt2dPtr aP2d;
672     if (myPoint.get())
673       aP2d = myPoint->pnt();
674     else if (myArray.get())
675       aP2d = myArray->pnt(theIndex);
676
677     GeomPointPtr aP3d;
678     if (aP2d.get())
679       aP3d = PartSet_Tools::convertTo3D(aP2d->x(), aP2d->y(), theSketch);
680     return aP3d;
681   }
682
683   bool isArray() const { return myArray.get(); }
684
685 private:
686   AttributePoint2DPtr myPoint;
687   AttributePoint2DArrayPtr myArray;
688 };
689
690 std::pair<AttributePtr, int> PartSet_Tools::findAttributeBy2dPoint(ObjectPtr theObj,
691                                                                    const TopoDS_Shape theShape,
692                                                                    FeaturePtr theSketch)
693 {
694
695   AttributePtr anAttribute;
696   int aPointIndex = -1;
697   FeaturePtr aFeature = ModelAPI_Feature::feature(theObj);
698   if (aFeature) {
699     if (theShape.ShapeType() == TopAbs_VERTEX) {
700       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
701       if (!aVertex.IsNull())  {
702         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
703         std::shared_ptr<GeomAPI_Pnt> aValue = std::shared_ptr<GeomAPI_Pnt>(
704             new GeomAPI_Pnt(aPoint.X(), aPoint.Y(), aPoint.Z()));
705
706         // find the given point in the feature attributes
707         std::list<AttributePtr> anAttiributes =
708           aFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
709         std::list<AttributePtr> anArrays =
710           aFeature->data()->attributes(GeomDataAPI_Point2DArray::typeId());
711         anAttiributes.insert(anAttiributes.end(), anArrays.begin(), anArrays.end());
712
713         std::list<AttributePtr>::const_iterator anIt = anAttiributes.begin(),
714                                                 aLast = anAttiributes.end();
715         double aMinDistance = 1.e-6; // searching for point with minimal distance and < 1.e-6
716         for (; anIt != aLast && !anAttribute; anIt++) {
717           PointWrapper aWrapper(*anIt);
718           for (int anIndex = 0, aSize = aWrapper.size(); anIndex < aSize; ++anIndex) {
719             std::shared_ptr<GeomAPI_Pnt> aPnt = aWrapper.point(anIndex, theSketch);
720             if (aPnt) {
721               double aDistance = aPnt->distance(aValue);
722               if (aDistance < aMinDistance) {
723                 anAttribute = *anIt;
724                 if (aWrapper.isArray())
725                   aPointIndex = anIndex;
726                 aMinDistance = aPnt->distance(aValue);
727               }
728             }
729           }
730         }
731       }
732     }
733   }
734   return std::pair<AttributePtr, int>(anAttribute, aPointIndex);
735 }
736
737 void PartSet_Tools::sendSubFeaturesEvent(const CompositeFeaturePtr& theComposite,
738                                          const Events_ID theEventId)
739 {
740   if (!theComposite.get())
741     return;
742
743   static Events_Loop* aLoop = Events_Loop::loop();
744   int aNumberOfSubs = theComposite->numberOfSubs();
745   for (int i = 0; i < aNumberOfSubs; i++) {
746     FeaturePtr aSubFeature = theComposite->subFeature(i);
747     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
748     aECreator->sendUpdated(aSubFeature, theEventId);
749   }
750   Events_Loop::loop()->flush(theEventId);
751 }
752
753 bool PartSet_Tools::isAuxiliarySketchEntity(const ObjectPtr& theObject)
754 {
755   bool isAuxiliaryFeature = false;
756
757   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
758   std::string anAuxiliaryAttribute = SketchPlugin_SketchEntity::AUXILIARY_ID();
759   AttributeBooleanPtr anAuxiliaryAttr = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(
760                                     anObjectFeature->data()->attribute(anAuxiliaryAttribute));
761   if (anAuxiliaryAttr.get())
762     isAuxiliaryFeature = anAuxiliaryAttr->value();
763
764
765   return isAuxiliaryFeature;
766 }
767
768 bool PartSet_Tools::isIncludeIntoSketchResult(const ObjectPtr& theObject)
769 {
770   // check the feature is neither Projection nor IntersectionPoint feature
771   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
772   if (aFeature->getKind() == SketchPlugin_Projection::ID() ||
773       aFeature->getKind() == SketchPlugin_IntersectionPoint::ID())
774     return false;
775
776   // go through the references to the feature to check
777   // if it was created by Projection or Intersection
778   const std::set<AttributePtr>& aRefs = theObject->data()->refsToMe();
779   for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
780        aRefIt != aRefs.end(); ++aRefIt) {
781     AttributePtr anAttr = *aRefIt;
782     std::string anIncludeToResultAttrName;
783     if (anAttr->id() == SketchPlugin_Projection::PROJECTED_FEATURE_ID())
784       anIncludeToResultAttrName = SketchPlugin_Projection::INCLUDE_INTO_RESULT();
785     else if (anAttr->id() == SketchPlugin_IntersectionPoint::INTERSECTION_POINTS_ID())
786       anIncludeToResultAttrName = SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT();
787
788     if (!anIncludeToResultAttrName.empty()) {
789       // check "include into result" flag
790       FeaturePtr aParent = ModelAPI_Feature::feature(anAttr->owner());
791       return aParent->boolean(anIncludeToResultAttrName)->value();
792     }
793   }
794   return true;
795 }
796
797
798 ResultPtr PartSet_Tools::createFixedByExternalCenter(
799     const ObjectPtr& theObject,
800     const std::shared_ptr<GeomAPI_Edge>& theEdge,
801     ModelAPI_AttributeSelection::CenterType theType,
802     const CompositeFeaturePtr& theSketch,
803     bool theTemporary,
804     FeaturePtr& theCreatedFeature)
805 {
806   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
807   if (!aResult.get())
808     return ResultPtr();
809
810   FeaturePtr aProjectionFeature = theSketch->addFeature(SketchPlugin_Projection::ID());
811   theCreatedFeature = aProjectionFeature;
812   AttributeSelectionPtr anExternalAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(
813                  aProjectionFeature->attribute(SketchPlugin_Projection::EXTERNAL_FEATURE_ID()));
814   anExternalAttr->setValueCenter(aResult, theEdge, theType, theTemporary);
815
816   AttributeBooleanPtr anIntoResult = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
817     (aProjectionFeature->data()->attribute(SketchPlugin_Projection::INCLUDE_INTO_RESULT()));
818   anIntoResult->setValue(SKETCH_PROJECTION_INCLUDE_INTO_RESULT);
819   aProjectionFeature->execute();
820
821   // if projection feature has not been created, exit
822   AttributeRefAttrPtr aRefAttr = aProjectionFeature->data()->refattr(
823     SketchPlugin_Projection::PROJECTED_FEATURE_ID());
824   if (!aRefAttr || !aRefAttr->isInitialized())
825     return ResultPtr();
826
827   FeaturePtr aProjection = ModelAPI_Feature::feature(aRefAttr->object());
828   if (aProjection.get() && aProjection->lastResult().get())
829     return aProjection->lastResult();
830
831   return ResultPtr();
832 }
833
834 void PartSet_Tools::getFirstAndLastIndexInFolder(const ObjectPtr& theFolder,
835   int& theFirst, int& theLast)
836 {
837   theFirst = -1;
838   theLast = -1;
839
840   DocumentPtr aDoc = theFolder->document();
841   FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theFolder);
842   if (!aFolder.get())
843     return;
844
845   AttributeReferencePtr aFirstFeatAttr =
846     aFolder->data()->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
847   if (!aFirstFeatAttr.get())
848     return;
849   FeaturePtr aFirstFeatureInFolder = ModelAPI_Feature::feature(aFirstFeatAttr->value());
850   if (!aFirstFeatureInFolder.get())
851     return;
852
853   FeaturePtr aLastFeatureInFolder = aFolder->lastVisibleFeature();
854   if (!aLastFeatureInFolder.get())
855     return;
856
857   theFirst = aDoc->index(aFirstFeatureInFolder);
858   theLast = aDoc->index(aLastFeatureInFolder);
859 }
860
861
862 void PartSet_Tools::getDefaultColor(ObjectPtr theObject, const bool isEmptyColorValid,
863   std::vector<int>& theColor)
864 {
865   theColor.clear();
866   // get default color from the preferences manager for the given result
867   if (theColor.empty()) {
868     std::string aSection, aName, aDefault;
869     theObject->colorConfigInfo(aSection, aName, aDefault);
870     if (!aSection.empty() && !aName.empty()) {
871       theColor = Config_PropManager::color(aSection, aName);
872     }
873   }
874   if (!isEmptyColorValid && theColor.empty()) {
875     // all AIS objects, where the color is not set, are in black.
876     // The color should be defined in XML or set in the attribute
877     theColor = Config_PropManager::color("Visualization", "object_default_color");
878     Events_InfoMessage("PartSet_Tools",
879       "A default color is not defined in the preferences for this result type").send();
880   }
881 }
882
883 double PartSet_Tools::getDefaultDeflection(const ObjectPtr& theObject)
884 {
885   double aDeflection = -1;
886   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
887   if (aResult.get()) {
888     bool isConstruction = false;
889
890     std::string aResultGroup = aResult->groupName();
891     if (aResultGroup == ModelAPI_ResultConstruction::group())
892       isConstruction = true;
893     else if (aResultGroup == ModelAPI_ResultBody::group()) {
894       GeomShapePtr aGeomShape = aResult->shape();
895       if (aGeomShape.get()) {
896         // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
897         // correction of deviation for them should not influence to the application performance
898         GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
899         isConstruction = !anExp.more();
900       }
901     }
902     if (isConstruction)
903       aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
904     else
905       aDeflection = Config_PropManager::real("Visualization", "body_deflection");
906   }
907   return aDeflection;
908 }
909
910
911 double PartSet_Tools::getDefaultTransparency()
912 {
913   return Config_PropManager::integer("Visualization", "shaper_default_transparency") / 100.;
914 }
915
916 QCursor PartSet_Tools::getOperationCursor()
917 {
918   int aId = Config_PropManager::integer(SKETCH_TAB_NAME, "operation_cursor");
919   switch (aId) {
920   case 0:
921     return QCursor(Qt::ArrowCursor);
922   case 1:
923     return QCursor(Qt::CrossCursor);
924   case 2:
925     return QCursor(Qt::PointingHandCursor);
926   }
927   return QCursor();
928 }