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