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