Salome HOME
Copyright update 2022
[modules/shaper.git] / src / PartSet / PartSet_Tools.cpp
1 // Copyright (C) 2014-2022  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 XAt, YAt, ZAt;
119   theView->At(XAt, YAt, ZAt);
120   gp_Pnt AtPoint(XAt, YAt, ZAt);
121
122   double aX, aY, aZ;
123   theView->Proj(aX, aY, aZ);
124   gp_Dir EyeDir(aX, aY, aZ);
125   EyeDir.Reverse();
126
127   gp_Pln PlaneOfTheView = gp_Pln(AtPoint, EyeDir);
128   Standard_Real X, Y, Z;
129   theView->Convert(thePoint.x(), thePoint.y(), X, Y, Z);
130   gp_Pnt ConvertedPoint(X, Y, Z);
131
132   gp_Pnt2d ConvertedPointOnPlane = ProjLib::Project(PlaneOfTheView, ConvertedPoint);
133   return ElSLib::Value(ConvertedPointOnPlane.X(), ConvertedPointOnPlane.Y(),
134                                      PlaneOfTheView);
135 }
136
137 void PartSet_Tools::convertTo2D(const gp_Pnt& thePoint, FeaturePtr theSketch,
138 Handle(V3d_View) theView,
139                                 double& theX, double& theY)
140 {
141   if (!theSketch)
142     return;
143
144   AttributeDoublePtr anAttr;
145   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
146
147   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
148       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
149
150   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
151       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
152   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
153       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
154   std::shared_ptr<GeomAPI_XYZ> anY = aNorm->xyz()->cross(aX->xyz());
155
156   gp_Pnt anOriginPnt(anOrigin->x(), anOrigin->y(), anOrigin->z());
157   gp_Vec aVec(anOriginPnt, thePoint);
158
159   if (!theView.IsNull()) {
160     V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
161     theView->Eye(XEye, YEye, ZEye);
162
163     theView->At(XAt, YAt, ZAt);
164     gp_Pnt EyePoint(XEye, YEye, ZEye);
165     gp_Pnt AtPoint(XAt, YAt, ZAt);
166
167     if (EyePoint.Distance(AtPoint) > gp::Resolution()) {
168       gp_Vec anEyeVec(EyePoint, AtPoint);
169       anEyeVec.Normalize();
170
171       std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
172          aData->attribute(SketchPlugin_Sketch::NORM_ID()));
173       gp_Vec aNormalVec(aNormal->x(), aNormal->y(), aNormal->z());
174
175       double aDen = anEyeVec * aNormalVec;
176       double aLVec = aDen != 0 ? aVec * aNormalVec / aDen : DBL_MAX;
177
178       gp_Vec aDeltaVec = anEyeVec * aLVec;
179       aVec = aVec - aDeltaVec;
180     }
181   }
182   theX = aVec.X() * aX->x() + aVec.Y() * aX->y() + aVec.Z() * aX->z();
183   theY = aVec.X() * anY->x() + aVec.Y() * anY->y() + aVec.Z() * anY->z();
184 }
185
186 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::convertTo2D(FeaturePtr theSketch,
187                                                     const std::shared_ptr<GeomAPI_Pnt>& thePnt)
188 {
189   std::shared_ptr<GeomAPI_Pnt2d> aRes;
190   if (theSketch->getKind() != SketchPlugin_Sketch::ID())
191     return aRes;
192   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
193       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
194   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
195       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
196   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
197       theSketch->data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
198   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
199   return thePnt->to2D(aC->pnt(), aX->dir(), aY);
200 }
201
202
203 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::convertTo3D(const double theX, const double theY,
204                                                         FeaturePtr theSketch)
205 {
206   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
207
208   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
209       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
210   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
211       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
212   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
213       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
214   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
215
216   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d =
217     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
218
219   return aPnt2d->to3D(aC->pnt(), aX->dir(), aY);
220 }
221
222 std::shared_ptr<ModelAPI_Document> PartSet_Tools::document()
223 {
224   return ModelAPI_Session::get()->moduleDocument();
225 }
226
227 void PartSet_Tools::setFeatureValue(FeaturePtr theFeature, double theValue,
228                                     const std::string& theAttribute)
229 {
230   if (!theFeature)
231     return;
232   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
233   AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
234       aData->attribute(theAttribute));
235   if (anAttribute)
236     anAttribute->setValue(theValue);
237 }
238
239 double PartSet_Tools::featureValue(FeaturePtr theFeature, const std::string& theAttribute,
240                                    bool& isValid)
241 {
242   isValid = false;
243   double aValue = 0;
244   if (theFeature) {
245     std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
246     AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
247         aData->attribute(theAttribute));
248     if (anAttribute) {
249       aValue = anAttribute->value();
250       isValid = true;
251     }
252   }
253   return aValue;
254 }
255
256 FeaturePtr PartSet_Tools::feature(FeaturePtr theFeature, const std::string& theAttribute,
257                                   const std::string& theKind)
258 {
259   FeaturePtr aFeature;
260   if (!theFeature)
261     return aFeature;
262
263   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
264   std::shared_ptr<ModelAPI_AttributeRefAttr> anAttr = std::dynamic_pointer_cast<
265       ModelAPI_AttributeRefAttr>(aData->attribute(theAttribute));
266   if (anAttr) {
267     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->object());
268     if (!theKind.empty() && aFeature && aFeature->getKind() != theKind) {
269       aFeature = FeaturePtr();
270     }
271   }
272   return aFeature;
273 }
274
275 void PartSet_Tools::createConstraint(CompositeFeaturePtr theSketch,
276                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint1,
277                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint2)
278 {
279   FeaturePtr aFeature;
280   if (theSketch) {
281     aFeature = theSketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
282   } else {
283     std::shared_ptr<ModelAPI_Document> aDoc = document();
284     aFeature = aDoc->addFeature(SketchPlugin_ConstraintCoincidence::ID());
285   }
286
287   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
288
289   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
290       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
291   aRef1->setAttr(thePoint1);
292
293   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
294       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
295   aRef2->setAttr(thePoint2);
296
297   // we need to flush created signal in order to coincidence is processed by solver
298   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
299 }
300
301 std::shared_ptr<GeomAPI_Pln> PartSet_Tools::sketchPlane(CompositeFeaturePtr theSketch)
302 {
303   std::shared_ptr<GeomAPI_Pln> aPlane;
304
305   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
306       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
307   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
308       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
309
310   if (aNormal.get() && aNormal->isInitialized() &&
311       anOrigin.get() && anOrigin->isInitialized())
312     aPlane = std::shared_ptr<GeomAPI_Pln>(new GeomAPI_Pln(anOrigin->pnt(), aNormal->dir()));
313
314   return aPlane;
315 }
316
317 void PartSet_Tools::nullifySketchPlane(CompositeFeaturePtr theSketch)
318 {
319   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
320     theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
321   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
322     theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
323
324   aNormal->reset();
325   anOrigin->reset();
326 }
327
328 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::point3D(std::shared_ptr<GeomAPI_Pnt2d> thePoint2D,
329                                                       CompositeFeaturePtr theSketch)
330 {
331   std::shared_ptr<GeomAPI_Pnt> aPoint;
332   if (!theSketch || !thePoint2D)
333     return aPoint;
334
335   DataPtr aData = theSketch->data();
336   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
337       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
338   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
339       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
340   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
341       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
342   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
343
344   return thePoint2D->to3D(aC->pnt(), aX->dir(), aY);
345 }
346
347 ResultPtr PartSet_Tools::findFixedObjectByExternal(const TopoDS_Shape& theShape,
348                                                    const ObjectPtr& theObject,
349                                                    CompositeFeaturePtr theSketch)
350 {
351   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
352   if (!aResult.get())
353     return ResultPtr();
354
355   for (int i = 0, aNbSubs = theSketch->numberOfSubs(); i < aNbSubs; i++) {
356     FeaturePtr aFeature = theSketch->subFeature(i);
357     if (aFeature->getKind() != SketchPlugin_Projection::PROJECTED_FEATURE_ID())
358       continue;
359     if (aFeature->lastResult() == aResult)
360       return aResult;
361   }
362   return ResultPtr();
363 }
364
365 ResultPtr PartSet_Tools::createFixedObjectByExternal(
366                                    const std::shared_ptr<GeomAPI_Shape>& theShape,
367                                    const ObjectPtr& theObject,
368                                    CompositeFeaturePtr theSketch,
369                                    const bool theTemporary,
370                                    FeaturePtr& theCreatedFeature)
371 {
372   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
373   if (!aResult.get())
374     return ResultPtr();
375
376   FeaturePtr aProjectionFeature = theSketch->addFeature(SketchPlugin_Projection::ID());
377   theCreatedFeature = aProjectionFeature;
378   AttributeSelectionPtr anExternalAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(
379                  aProjectionFeature->attribute(SketchPlugin_Projection::EXTERNAL_FEATURE_ID()));
380   anExternalAttr->setValue(aResult, theShape);
381
382   AttributeBooleanPtr anIntoResult = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
383     (aProjectionFeature->data()->attribute(SketchPlugin_Projection::INCLUDE_INTO_RESULT()));
384   anIntoResult->setValue(SKETCH_PROJECTION_INCLUDE_INTO_RESULT);
385   aProjectionFeature->execute();
386
387   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
388   bool isValid = aValidators->validate(aProjectionFeature);
389
390   // if projection feature has not been created, exit
391   AttributeRefAttrPtr aRefAttr = aProjectionFeature->data()->refattr(
392     SketchPlugin_Projection::PROJECTED_FEATURE_ID());
393   if (!isValid || !aRefAttr || !aRefAttr->isInitialized())
394   {
395     // remove external feature if the attribute is not filled
396     std::set<FeaturePtr> aFeatures;
397     aFeatures.insert(aProjectionFeature);
398     ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
399     return ResultPtr();
400   }
401
402   FeaturePtr aProjection = ModelAPI_Feature::feature(aRefAttr->object());
403   if (aProjection.get() && aProjection->lastResult().get())
404     return aProjection->lastResult();
405
406   return ResultPtr();
407 }
408
409 bool PartSet_Tools::isContainPresentation(const QList<ModuleBase_ViewerPrsPtr>& theSelected,
410                                           const ModuleBase_ViewerPrsPtr& thePrs)
411 {
412   foreach (ModuleBase_ViewerPrsPtr aPrs, theSelected) {
413     if (aPrs->object() == thePrs->object())
414       return true;
415   }
416   return false;
417 }
418
419 GeomShapePtr PartSet_Tools::findShapeBy2DPoint(const AttributePtr& theAttribute,
420                                                        ModuleBase_IWorkshop* theWorkshop)
421 {
422   GeomShapePtr aShape;
423   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
424   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
425
426   // 2. find visualized vertices of the attribute and if the attribute of the vertex is
427   // the same, return it
428   FeaturePtr anAttributeFeature = ModelAPI_Feature::feature(theAttribute->owner());
429   // 2.1 get visualized results of the feature
430   const std::list<ResultPtr>& aResList = anAttributeFeature->results();
431   std::list<ResultPtr>::const_iterator anIt = aResList.begin(), aLast = aResList.end();
432   for (; anIt != aLast; anIt++) {
433     AISObjectPtr aAISObj = aDisplayer->getAISObject(*anIt);
434     if (aAISObj.get() != NULL) {
435       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
436       // 2.2 find selected owners of a visualizedd object
437       SelectMgr_IndexedMapOfOwner aSelectedOwners;
438       aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
439       for (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
440         Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
441         if (!anOwner.IsNull()) {
442           Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
443           if (!aBRepOwner.IsNull() && aBRepOwner->HasShape()) {
444             const TopoDS_Shape& aBRepShape = aBRepOwner->Shape();
445             if (aBRepShape.ShapeType() == TopAbs_VERTEX) {
446               // 2.3 if the owner is vertex and an attribute of the vertex is equal to the initial
447               // attribute, returns the shape
448               PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(theWorkshop->module());
449               PartSet_SketcherMgr* aSketchMgr = aModule->sketchMgr();
450               std::pair<AttributePtr, int> aPntAttrIndex = PartSet_Tools::findAttributeBy2dPoint(
451                   anAttributeFeature, aBRepShape, aSketchMgr->activeSketch());
452               if (aPntAttrIndex.first.get() != NULL && aPntAttrIndex.first == theAttribute) {
453                 aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
454                 aShape->setImpl(new TopoDS_Shape(aBRepShape));
455                 break;
456               }
457             }
458           }
459         }
460       }
461     }
462   }
463   return aShape;
464 }
465
466 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPoint(
467                                                   std::shared_ptr<ModelAPI_Feature>& theFeature,
468                                                   const std::string& theAttribute)
469 {
470   std::shared_ptr<GeomDataAPI_Point2D> aPointAttr = ModelGeomAlgo_Point2D::getPointOfRefAttr(
471                                           theFeature.get(), theAttribute, SketchPlugin_Point::ID(),
472                                           SketchPlugin_Point::COORD_ID());
473   if (aPointAttr.get() != NULL)
474     return aPointAttr->pnt();
475   return std::shared_ptr<GeomAPI_Pnt2d>();
476 }
477
478 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPnt2d(QMouseEvent* theEvent,
479                                                 ModuleBase_IViewWindow* theWindow,
480                                                 const FeaturePtr& theSketch)
481 {
482   gp_Pnt aPnt = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
483   double aX, anY;
484   Handle(V3d_View) aView = theWindow->v3dView();
485   PartSet_Tools::convertTo2D(aPnt, theSketch, aView, aX, anY);
486
487   return std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(aX, anY));
488 }
489
490 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPnt2d(const Handle(V3d_View)& theView,
491                                                        const TopoDS_Shape& theShape,
492                                                        const FeaturePtr& theSketch)
493 {
494   GeomPnt2dPtr aPoint2D;
495   if (!theShape.IsNull() && theShape.ShapeType() == TopAbs_VERTEX) {
496     const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
497     if (!aVertex.IsNull()) {
498       // the case when the point is taken from the existing vertex
499       gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
500       double aX, aY;
501       PartSet_Tools::convertTo2D(aPoint, theSketch, theView, aX, aY);
502       aPoint2D.reset(new GeomAPI_Pnt2d(aX, aY));
503     }
504   }
505   return aPoint2D;
506 }
507
508 FeaturePtr findFirstCoincidenceByData(const DataPtr& theData,
509                                       std::shared_ptr<GeomAPI_Pnt2d> thePoint)
510 {
511   FeaturePtr aCoincident;
512
513   const std::set<AttributePtr>& aRefsList = theData->refsToMe();
514   std::set<AttributePtr>::const_iterator aIt;
515   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
516     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
517     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
518     if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
519       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
520         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
521       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
522         aCoincident = aConstrFeature;
523         break;
524       } else {
525         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
526                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
527         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
528           aCoincident = aConstrFeature;
529           break;
530         }
531       }
532     }
533   }
534   return aCoincident;
535 }
536
537 FeaturePtr PartSet_Tools::findFirstCoincidence(const FeaturePtr& theFeature,
538                                                std::shared_ptr<GeomAPI_Pnt2d> thePoint)
539 {
540   FeaturePtr aCoincident;
541   if (theFeature.get() == NULL)
542     return aCoincident;
543
544   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
545   std::set<AttributePtr>::const_iterator aIt;
546   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
547     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
548     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
549     if (aConstrFeature && aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
550       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
551         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
552       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
553         aCoincident = aConstrFeature;
554         break;
555       } else {
556         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
557                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
558         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
559           aCoincident = aConstrFeature;
560           break;
561         }
562       }
563     }
564   }
565   /// Find by result
566   if (!aCoincident.get()) {
567     std::list<ResultPtr> aResults = theFeature->results();
568     std::list<ResultPtr>::const_iterator aResIt;
569     for (aResIt = aResults.cbegin(); aResIt != aResults.cend(); ++aResIt) {
570       ResultPtr aResult = *aResIt;
571       aCoincident = findFirstCoincidenceByData(aResult->data(), thePoint);
572       if (aCoincident.get())
573         break;
574     }
575   }
576   return aCoincident;
577 }
578
579 void PartSet_Tools::findCoincidences(FeaturePtr theStartCoin, QList<FeaturePtr>& theList,
580                                      QList<FeaturePtr>& theCoincidencies,
581                                      std::string theAttr, QList<bool>& theIsAttributes)
582 {
583   std::shared_ptr<GeomAPI_Pnt2d> aOrig = getCoincedencePoint(theStartCoin);
584   if (aOrig.get() == NULL)
585     return;
586
587   AttributeRefAttrPtr aPnt = theStartCoin->refattr(theAttr);
588   if (!aPnt)
589     return;
590   ObjectPtr aObj = aPnt->object();
591   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
592   if (aFeature.get()) {
593     if (!theList.contains(aFeature)) {
594       theList.append(aFeature);
595       theCoincidencies.append(theStartCoin);
596       theIsAttributes.append(true); // point attribute on a feature
597       const std::set<AttributePtr>& aRefsList = aFeature->data()->refsToMe();
598       std::set<AttributePtr>::const_iterator aIt;
599       for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
600         std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
601         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
602         if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
603           if (!theCoincidencies.contains(aConstrFeature)) {
604             std::shared_ptr<GeomAPI_Pnt2d> aCoincPnt = getCoincedencePoint(aConstrFeature);
605             if (aCoincPnt.get() && aOrig->isEqual(aCoincPnt)) {
606               findCoincidences(aConstrFeature, theList, theCoincidencies,
607                 SketchPlugin_ConstraintCoincidence::ENTITY_A(), theIsAttributes);
608               findCoincidences(aConstrFeature, theList, theCoincidencies,
609                 SketchPlugin_ConstraintCoincidence::ENTITY_B(), theIsAttributes);
610             }
611           }
612         }
613       }
614     }
615   } else {
616     // Find by Results
617     ResultConstructionPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
618     if (aResult.get()) {
619       FeaturePtr aFeat = ModelAPI_Feature::feature(aPnt->object());
620       if (!theList.contains(aFeat))
621         theList.append(aFeat);
622       theCoincidencies.append(theStartCoin);
623       theIsAttributes.append(false); // point attribute on a feature
624
625       const std::set<AttributePtr>& aRefsList = aResult->data()->refsToMe();
626       std::set<AttributePtr>::const_iterator aIt;
627       for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
628         std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
629         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
630         if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
631           if (!theCoincidencies.contains(aConstrFeature)) {
632             std::shared_ptr<GeomAPI_Pnt2d> aCoincPnt = getCoincedencePoint(aConstrFeature);
633             if (aCoincPnt.get() && aOrig->isEqual(aCoincPnt)) {
634               findCoincidences(aConstrFeature, theList, theCoincidencies,
635                 SketchPlugin_ConstraintCoincidence::ENTITY_A(), theIsAttributes);
636               findCoincidences(aConstrFeature, theList, theCoincidencies,
637                 SketchPlugin_ConstraintCoincidence::ENTITY_B(), theIsAttributes);
638             }
639           }
640         }
641       }
642     }
643   }
644 }
645
646 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getCoincedencePoint(FeaturePtr theStartCoin)
647 {
648   std::shared_ptr<GeomAPI_Pnt2d> aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(),
649                                                         SketchPlugin_Constraint::ENTITY_A());
650   if (aPnt.get() == NULL)
651     aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(), SketchPlugin_Constraint::ENTITY_B());
652   return aPnt;
653 }
654
655 class PointWrapper
656 {
657 public:
658   PointWrapper(AttributePtr theAttribute)
659     : myPoint(std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute)),
660       myArray(std::dynamic_pointer_cast<GeomDataAPI_Point2DArray>(theAttribute))
661   {}
662
663   int size() const { return myPoint.get() ? 1 : (myArray.get() ? myArray->size() : 0); }
664
665   GeomPointPtr point(int theIndex, FeaturePtr theSketch)
666   {
667     GeomPnt2dPtr aP2d;
668     if (myPoint.get())
669       aP2d = myPoint->pnt();
670     else if (myArray.get())
671       aP2d = myArray->pnt(theIndex);
672
673     GeomPointPtr aP3d;
674     if (aP2d.get())
675       aP3d = PartSet_Tools::convertTo3D(aP2d->x(), aP2d->y(), theSketch);
676     return aP3d;
677   }
678
679   bool isArray() const { return myArray.get(); }
680
681 private:
682   AttributePoint2DPtr myPoint;
683   AttributePoint2DArrayPtr myArray;
684 };
685
686 std::pair<AttributePtr, int> PartSet_Tools::findAttributeBy2dPoint(ObjectPtr theObj,
687                                                                    const TopoDS_Shape theShape,
688                                                                    FeaturePtr theSketch)
689 {
690
691   AttributePtr anAttribute;
692   int aPointIndex = -1;
693   FeaturePtr aFeature = ModelAPI_Feature::feature(theObj);
694   if (aFeature) {
695     if (theShape.ShapeType() == TopAbs_VERTEX) {
696       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
697       if (!aVertex.IsNull())  {
698         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
699         std::shared_ptr<GeomAPI_Pnt> aValue = std::shared_ptr<GeomAPI_Pnt>(
700             new GeomAPI_Pnt(aPoint.X(), aPoint.Y(), aPoint.Z()));
701
702         // find the given point in the feature attributes
703         std::list<AttributePtr> anAttiributes =
704           aFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
705         std::list<AttributePtr> anArrays =
706           aFeature->data()->attributes(GeomDataAPI_Point2DArray::typeId());
707         anAttiributes.insert(anAttiributes.end(), anArrays.begin(), anArrays.end());
708
709         std::list<AttributePtr>::const_iterator anIt = anAttiributes.begin(),
710                                                 aLast = anAttiributes.end();
711         double aMinDistance = 1.e-6; // searching for point with minimal distance and < 1.e-6
712         for (; anIt != aLast && !anAttribute; anIt++) {
713           PointWrapper aWrapper(*anIt);
714           for (int anIndex = 0, aSize = aWrapper.size(); anIndex < aSize; ++anIndex) {
715             std::shared_ptr<GeomAPI_Pnt> aPnt = aWrapper.point(anIndex, theSketch);
716             if (aPnt) {
717               double aDistance = aPnt->distance(aValue);
718               if (aDistance < aMinDistance) {
719                 anAttribute = *anIt;
720                 if (aWrapper.isArray())
721                   aPointIndex = anIndex;
722                 aMinDistance = aPnt->distance(aValue);
723               }
724             }
725           }
726         }
727       }
728     }
729   }
730   return std::pair<AttributePtr, int>(anAttribute, aPointIndex);
731 }
732
733 void PartSet_Tools::sendSubFeaturesEvent(const CompositeFeaturePtr& theComposite,
734                                          const Events_ID theEventId)
735 {
736   if (!theComposite.get())
737     return;
738
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   std::string aSection, aName, aDefault;
863   theObject->colorConfigInfo(aSection, aName, aDefault);
864   if (!aSection.empty() && !aName.empty()) {
865     theColor = Config_PropManager::color(aSection, aName);
866   }
867   if (!isEmptyColorValid && theColor.empty()) {
868     // all AIS objects, where the color is not set, are in black.
869     // The color should be defined in XML or set in the attribute
870     theColor = Config_PropManager::color("Visualization", "object_default_color");
871     Events_InfoMessage("PartSet_Tools",
872       "A default color is not defined in the preferences for this result type").send();
873   }
874 }
875
876 double PartSet_Tools::getDefaultDeflection(const ObjectPtr& theObject)
877 {
878   double aDeflection = -1;
879   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
880   if (aResult.get()) {
881     bool isConstruction = false;
882
883     std::string aResultGroup = aResult->groupName();
884     if (aResultGroup == ModelAPI_ResultConstruction::group())
885       isConstruction = true;
886     else if (aResultGroup == ModelAPI_ResultBody::group()) {
887       GeomShapePtr aGeomShape = aResult->shape();
888       if (aGeomShape.get()) {
889         // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
890         // correction of deviation for them should not influence to the application performance
891         GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
892         isConstruction = !anExp.more();
893       }
894     }
895     if (isConstruction)
896       aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
897     else
898       aDeflection = Config_PropManager::real("Visualization", "body_deflection");
899   }
900   return aDeflection;
901 }
902
903
904 double PartSet_Tools::getDefaultTransparency()
905 {
906   return Config_PropManager::integer("Visualization", "shaper_default_transparency") / 100.;
907 }
908
909 QCursor PartSet_Tools::getOperationCursor()
910 {
911   int aId = Config_PropManager::integer(SKETCH_TAB_NAME, "operation_cursor");
912   switch (aId) {
913   case 0:
914     return QCursor(Qt::ArrowCursor);
915   case 1:
916     return QCursor(Qt::CrossCursor);
917   case 2:
918     return QCursor(Qt::PointingHandCursor);
919   }
920   return QCursor();
921 }