Salome HOME
Merge remote-tracking branch 'origin/Toolbars_Management'
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Fillet.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "SketchPlugin_Fillet.h"
22
23 #include "SketchPlugin_Arc.h"
24 #include "SketchPlugin_Line.h"
25 #include "SketchPlugin_Point.h"
26 #include "SketchPlugin_Sketch.h"
27 #include "SketchPlugin_ConstraintDistance.h"
28 #include "SketchPlugin_ConstraintEqual.h"
29 #include "SketchPlugin_ConstraintCoincidence.h"
30 #include "SketchPlugin_ConstraintLength.h"
31 #include "SketchPlugin_ConstraintMiddle.h"
32 #include "SketchPlugin_ConstraintTangent.h"
33 #include "SketchPlugin_ConstraintRadius.h"
34 #include "SketchPlugin_Tools.h"
35
36 #include <ModelAPI_AttributeDouble.h>
37 #include <ModelAPI_AttributeInteger.h>
38 #include <ModelAPI_AttributeRefAttr.h>
39 #include <ModelAPI_Data.h>
40 #include <ModelAPI_Events.h>
41 #include <ModelAPI_Session.h>
42 #include <ModelAPI_Tools.h>
43 #include <ModelAPI_Validator.h>
44
45 #include <GeomAlgoAPI_Circ2dBuilder.h>
46 #include <GeomAlgoAPI_EdgeBuilder.h>
47
48 #include <GeomAPI_Circ2d.h>
49 #include <GeomAPI_Dir2d.h>
50 #include <GeomAPI_Lin2d.h>
51 #include <GeomAPI_Pnt2d.h>
52 #include <GeomAPI_XY.h>
53
54 #include <GeomDataAPI_Point2D.h>
55
56 #include <Events_Loop.h>
57
58 #include <math.h>
59
60 const double tolerance = 1.e-7;
61 const double paramTolerance = 1.e-4;
62 const double PI = 3.141592653589793238463;
63
64 /// \brief Attract specified point on theNewArc to the attribute of theFeature
65 static void recalculateAttributes(FeaturePtr theNewArc, const std::string& theNewArcAttribute,
66   FeaturePtr theFeature, const std::string& theFeatureAttribute);
67
68
69 /// \brief Calculate radius of a fillet.
70 ///        It should not be greater than 1/3 of shortest edge length.
71 static double calculateFilletRadius(FeaturePtr theFilletFeatures[2]);
72
73 /// \brief Calculates center of fillet arc and coordinates of tangency points
74 static void calculateFilletCenter(FeaturePtr theFilletFeatures[2],
75                                   double theFilletRadius,
76                                   const std::shared_ptr<GeomAPI_Ax3>& theSketchPlane,
77                                   std::shared_ptr<GeomAPI_XY>& theCenter,
78                                   std::shared_ptr<GeomAPI_XY>& theTangentA,
79                                   std::shared_ptr<GeomAPI_XY>& theTangentB);
80
81 static std::set<FeaturePtr> findFeaturesToRemove(const FeaturePtr theFeature,
82                                                  const AttributePtr theAttribute);
83
84 SketchPlugin_Fillet::SketchPlugin_Fillet()
85 : myFilletCreated(false), myIsReversed(false)
86 {
87   myIsNotInversed[0] = myIsNotInversed[1] = true;
88 }
89
90 void SketchPlugin_Fillet::initAttributes()
91 {
92   data()->addAttribute(FILLET_POINT_ID(), ModelAPI_AttributeRefAttr::typeId());
93 }
94
95 void SketchPlugin_Fillet::execute()
96 {
97   // Wait all constraints being created, then send update events
98   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
99   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
100   if (isUpdateFlushed)
101     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
102
103   // set flag here to avoid building Fillet presentation if "Redisplay" event appears
104   myFilletCreated = true;
105
106   // create feature for fillet arc
107   FeaturePtr aFilletArc = createFilletArc();
108   if (!aFilletArc) {
109     setError("Error: unable to create a fillet arc.");
110     return;
111   }
112
113   // collect features referred to the edges participating in fillet
114   AttributePoint2DPtr aFilletPoints[2];
115   int aFeatInd[2];
116   int anAttrInd[2];
117   std::set<FeaturePtr> aFeaturesToBeRemoved;
118   for (int i = 0; i < 2; ++i) {
119     bool isFirstIndex = (i == 0);
120     aFeatInd[i] = myIsReversed == isFirstIndex ? 1 : 0;
121     anAttrInd[i] = (myIsReversed == isFirstIndex ? 2 : 0) + (myIsNotInversed[aFeatInd[i]] ? 0 : 1);
122     aFilletPoints[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
123         myBaseFeatures[aFeatInd[i]]->attribute(myFeatAttributes[anAttrInd[i]]));
124     std::set<FeaturePtr> aRemove =
125         findFeaturesToRemove(myBaseFeatures[aFeatInd[i]], aFilletPoints[i]);
126     aFeaturesToBeRemoved.insert(aRemove.begin(), aRemove.end());
127   }
128
129   // keep "distance" constraints and remove all other references
130   removeReferencesButKeepDistances(aFeaturesToBeRemoved, aFilletPoints);
131
132   // Update fillet edges.
133   recalculateAttributes(aFilletArc, SketchPlugin_Arc::START_ID(),
134                         myBaseFeatures[aFeatInd[0]], myFeatAttributes[anAttrInd[0]]);
135   recalculateAttributes(aFilletArc, SketchPlugin_Arc::END_ID(),
136                         myBaseFeatures[aFeatInd[1]], myFeatAttributes[anAttrInd[1]]);
137
138   FeaturePtr aConstraint;
139
140   // Create coincidence features.
141   aConstraint = SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
142                     SketchPlugin_ConstraintCoincidence::ID(),
143                     aFilletArc->attribute(SketchPlugin_Arc::START_ID()),
144                     myBaseFeatures[aFeatInd[0]]->attribute(myFeatAttributes[anAttrInd[0]]));
145   ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
146   aConstraint = SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
147                     SketchPlugin_ConstraintCoincidence::ID(),
148                     aFilletArc->attribute(SketchPlugin_Arc::END_ID()),
149                     myBaseFeatures[aFeatInd[1]]->attribute(myFeatAttributes[anAttrInd[1]]));
150   ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
151
152   // Create tangent features.
153   for (int i = 0; i < 2; i++) {
154     aConstraint = SketchPlugin_Tools::createConstraintObjectObject(sketch(),
155                       SketchPlugin_ConstraintTangent::ID(),
156                       aFilletArc->lastResult(),
157                       myBaseFeatures[i]->lastResult());
158     aConstraint->execute();
159     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
160   }
161
162   // Send events to update the sub-features by the solver.
163   if (isUpdateFlushed)
164     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
165 }
166
167 AISObjectPtr SketchPlugin_Fillet::getAISObject(AISObjectPtr thePrevious)
168 {
169   if(myFilletCreated) {
170     return AISObjectPtr();
171   }
172
173   SketchPlugin_Sketch* aSketch = sketch();
174   if(!aSketch) {
175     return AISObjectPtr();
176   }
177
178   if (!calculateFilletParameters())
179     return AISObjectPtr();
180
181   // Create arc for presentation.
182   std::shared_ptr<GeomAPI_Pnt> aCenterPnt(aSketch->to3D(myCenterXY->x(), myCenterXY->y()));
183   std::shared_ptr<GeomAPI_Pnt> aTangentPnt1(aSketch->to3D(myTangentXY1->x(),
184                                                           myTangentXY1->y()));
185   std::shared_ptr<GeomAPI_Pnt> aTangentPnt2(aSketch->to3D(myTangentXY2->x(),
186                                                           myTangentXY2->y()));
187   std::shared_ptr<GeomDataAPI_Dir> aNDir = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
188     aSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
189   std::shared_ptr<GeomAPI_Shape> anArcShape =
190       GeomAlgoAPI_EdgeBuilder::lineCircleArc(aCenterPnt, aTangentPnt1, aTangentPnt2, aNDir->dir());
191
192   AISObjectPtr anAISObject = thePrevious;
193   if(!anAISObject.get()) {
194     anAISObject = AISObjectPtr(new GeomAPI_AISObject);
195   }
196   anAISObject->createShape(anArcShape);
197   return anAISObject;
198 }
199
200 bool SketchPlugin_Fillet::calculateFilletParameters()
201 {
202   // Get fillet point.
203   AttributeRefAttrPtr aPointRefAttr = refattr(FILLET_POINT_ID());
204   if (!aPointRefAttr->isInitialized() || aPointRefAttr->isObject())
205     return false;
206   std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2D =
207     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aPointRefAttr->attr());
208   if (!aFilletPoint2D.get())
209     return false;
210
211   std::set<AttributePoint2DPtr> aCoincidentPoints =
212       SketchPlugin_Tools::findPointsCoincidentToPoint(aFilletPoint2D);
213   std::set<FeaturePtr> aFilletFeatures;
214   for (std::set<AttributePoint2DPtr>::iterator aCPIt = aCoincidentPoints.begin();
215        aCPIt != aCoincidentPoints.end(); ++aCPIt) {
216     std::shared_ptr<SketchPlugin_Feature> anOwner =
217         std::dynamic_pointer_cast<SketchPlugin_Feature>(
218         ModelAPI_Feature::feature((*aCPIt)->owner()));
219     if (anOwner && !anOwner->isExternal())
220       aFilletFeatures.insert(anOwner);
221   }
222   if (aFilletFeatures.size() != 2) {
223     setError("Error: Selected point does not have two suitable edges for fillet.");
224     return false;
225   }
226
227   std::set<FeaturePtr>::iterator aFIt = aFilletFeatures.begin();
228   myBaseFeatures[0] = *aFIt;
229   myBaseFeatures[1] = *(++aFIt);
230
231   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
232   double aRadius = calculateFilletRadius(myBaseFeatures);
233
234   // Calculate arc attributes.
235   static const int aNbFeatures = 2;
236   // First pair of points relate to first feature, second pair -  to second.
237   std::shared_ptr<GeomAPI_Pnt2d> aStartEndPnt[aNbFeatures * 2];
238   for (int i = 0; i < aNbFeatures; i++) {
239     std::string aStartAttr, aEndAttr;
240     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
241       aStartAttr = SketchPlugin_Line::START_ID();
242       aEndAttr = SketchPlugin_Line::END_ID();
243     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
244       aStartAttr = SketchPlugin_Arc::START_ID();
245       aEndAttr = SketchPlugin_Arc::END_ID();
246     } else { // Wrong argument.
247       setError("Error: One of the points has wrong coincide feature");
248       return false;
249     }
250     myFeatAttributes[2*i] = aStartAttr;
251     aStartEndPnt[2*i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
252       myBaseFeatures[i]->attribute(aStartAttr))->pnt();
253     myFeatAttributes[2*i+1] = aEndAttr;
254     aStartEndPnt[2*i+1] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
255       myBaseFeatures[i]->attribute(aEndAttr))->pnt();
256   }
257   for (int aFeatInd = 0; aFeatInd < aNbFeatures; aFeatInd++) {
258     for (int j = 0; j < 2; j++) // loop on start-end of each feature
259       if (aStartEndPnt[aFeatInd * aNbFeatures + j]->distance(aFilletPnt2d) < 1.e-10) {
260         myIsNotInversed[aFeatInd] = (j==0);
261         break;
262       }
263   }
264
265   std::shared_ptr<GeomAPI_Ax3> aSketchPlane = SketchPlugin_Sketch::plane(sketch());
266   calculateFilletCenter(myBaseFeatures, aRadius, aSketchPlane,
267                         myCenterXY, myTangentXY1, myTangentXY2);
268
269   // Tangent directions of the features in coincident point.
270   std::shared_ptr<GeomAPI_Dir2d> aTangentDir[aNbFeatures];
271   for (int i = 0; i < aNbFeatures; i++) {
272     std::shared_ptr<GeomAPI_XY> aDir;
273     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
274       aDir = aStartEndPnt[2*i+1]->xy()->decreased(aStartEndPnt[2*i]->xy());
275       if (!myIsNotInversed[i])
276         aDir = aDir->multiplied(-1.0);
277     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
278       std::shared_ptr<GeomAPI_Pnt2d> aCenterPoint =
279         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
280         myBaseFeatures[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
281       aDir = myIsNotInversed[i] ? aStartEndPnt[2*i]->xy() : aStartEndPnt[2*i+1]->xy();
282       aDir = aDir->decreased(aCenterPoint->xy());
283
284       double x = aDir->x();
285       double y = aDir->y();
286       aDir->setX(-y);
287       aDir->setY(x);
288       if (myIsNotInversed[i] ==
289           std::dynamic_pointer_cast<SketchPlugin_Arc>(myBaseFeatures[i])->isReversed())
290         aDir = aDir->multiplied(-1.0);
291     }
292     aTangentDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aDir));
293   }
294
295   // By default, the start point of fillet arc is connected to FeatureA,
296   // and the end point - to FeatureB. But when the angle between TangentDirA and
297   // TangentDirB greater 180 degree, the sequaence of features need to be reversed.
298   double cosBA = aTangentDir[0]->cross(aTangentDir[1]); // cos(B-A),
299   // where A and B - angles between corresponding tanget direction and the X axis
300   myIsReversed = cosBA > 0.0;
301
302   if(myIsReversed) {
303     std::shared_ptr<GeomAPI_XY> aTmp = myTangentXY1;
304     myTangentXY1 = myTangentXY2;
305     myTangentXY2 = aTmp;
306   }
307   return true;
308 }
309
310 FeaturePtr SketchPlugin_Fillet::createFilletArc()
311 {
312   // Calculate Fillet parameters if does not yet
313   if (!myBaseFeatures[0] || !myBaseFeatures[1])
314     calculateFilletParameters();
315
316   // fix for issue #2810 (sometimes, myCenterXY is NULL, fillet should report an error)
317   if (!myCenterXY)
318     return FeaturePtr();
319
320   // Create arc feature.
321   FeaturePtr aFilletArc = sketch()->addFeature(SketchPlugin_Arc::ID());
322
323   // Set arc attributes.
324   bool aWasBlocked = aFilletArc->data()->blockSendAttributeUpdated(true);
325   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
326       aFilletArc->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(myCenterXY->x(),
327                                                                       myCenterXY->y());
328   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint =
329       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
330           aFilletArc->attribute(SketchPlugin_Arc::START_ID()));
331   std::shared_ptr<GeomDataAPI_Point2D> aEndPoint =
332       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
333           aFilletArc->attribute(SketchPlugin_Arc::END_ID()));
334   if(aStartPoint->isInitialized() && aEndPoint->isInitialized()
335       && (aStartPoint->pnt()->xy()->distance(myTangentXY1) > tolerance
336       || aEndPoint->pnt()->xy()->distance(myTangentXY2) > tolerance)) {
337     std::dynamic_pointer_cast<SketchPlugin_Arc>(aFilletArc)->setReversed(false);
338   }
339   aStartPoint->setValue(myTangentXY1->x(), myTangentXY1->y());
340   aEndPoint->setValue(myTangentXY2->x(), myTangentXY2->y());
341   aFilletArc->data()->blockSendAttributeUpdated(aWasBlocked);
342   aFilletArc->execute();
343
344   return aFilletArc;
345 }
346
347 FeaturePtr SketchPlugin_Fillet::createFilletApex(const GeomPnt2dPtr& theCoordinates)
348 {
349   FeaturePtr anApex = sketch()->addFeature(SketchPlugin_Point::ID());
350   AttributePoint2DPtr aCoord = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
351       anApex->attribute(SketchPlugin_Point::COORD_ID()));
352   aCoord->setValue(theCoordinates);
353   anApex->boolean(SketchPlugin_Point::AUXILIARY_ID())->setValue(true);
354
355   // additional coincidence constraints
356   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
357   FeaturePtr aConstraint;
358   for (int i = 0; i < 2; i++) {
359     aConstraint = SketchPlugin_Tools::createConstraintAttrObject(sketch(),
360                       SketchPlugin_ConstraintCoincidence::ID(),
361                       aCoord,
362                       myBaseFeatures[i]->lastResult());
363     aConstraint->execute();
364     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
365   }
366
367   return anApex;
368 }
369
370 struct Length {
371   AttributePtr myPoints[2];
372   std::string myValueText;
373   double myValueDouble;
374   GeomPnt2dPtr myFlyoutPoint;
375   int myLocationType;
376 };
377
378 void SketchPlugin_Fillet::removeReferencesButKeepDistances(
379     std::set<FeaturePtr>& theFeaturesToRemove,
380     const AttributePoint2DPtr theFilletPoints[2])
381 {
382   FeaturePtr aFilletApex;
383   std::list<Length> aLengthToDistance;
384
385   std::set<FeaturePtr>::iterator aFeat = theFeaturesToRemove.begin();
386   while (aFeat != theFeaturesToRemove.end()) {
387     std::shared_ptr<SketchPlugin_ConstraintDistance> aDistance =
388         std::dynamic_pointer_cast<SketchPlugin_ConstraintDistance>(*aFeat);
389     if (aDistance) {
390       if (!aFilletApex)
391         aFilletApex = createFilletApex(theFilletPoints[0]->pnt());
392       // update attributes of distance constraints
393       bool isUpdated = false;
394       for (int attrInd = 0; attrInd < CONSTRAINT_ATTR_SIZE && !isUpdated; ++attrInd) {
395         AttributeRefAttrPtr aRefAttr =
396             aDistance->refattr(SketchPlugin_Constraint::ATTRIBUTE(attrInd));
397         if (aRefAttr && !aRefAttr->isObject() &&
398            (aRefAttr->attr() == theFilletPoints[0] || aRefAttr->attr() == theFilletPoints[1])) {
399           aRefAttr->setAttr(aFilletApex->attribute(SketchPlugin_Point::COORD_ID()));
400           isUpdated = true;
401         }
402       }
403       // avoid distance from removing if it is updated
404       std::set<FeaturePtr>::iterator aKeepIt = aFeat++;
405       if (isUpdated)
406         theFeaturesToRemove.erase(aKeepIt);
407
408     } else {
409       std::shared_ptr<SketchPlugin_ConstraintLength> aLength =
410           std::dynamic_pointer_cast<SketchPlugin_ConstraintLength>(*aFeat);
411       if (aLength) {
412         if (!aFilletApex)
413           aFilletApex = createFilletApex(theFilletPoints[0]->pnt());
414         // remove Length, but create new distance constraint
415         AttributeRefAttrPtr aRefAttr =
416           aLength->refattr(SketchPlugin_Constraint::ENTITY_A());
417         FeaturePtr aLine = ModelAPI_Feature::feature(aRefAttr->object());
418         if (aLine) {
419           aLengthToDistance.push_back(Length());
420           Length& aNewLength = aLengthToDistance.back();
421           // main attrbutes
422           for (int i = 0; i < 2; ++i) {
423             AttributePtr anAttr = aLine->attribute(
424                 i == 0 ? SketchPlugin_Line::START_ID() : SketchPlugin_Line::END_ID());
425             if (anAttr == theFilletPoints[0] || anAttr == theFilletPoints[1])
426               aNewLength.myPoints[i] = aFilletApex->attribute(SketchPlugin_Point::COORD_ID());
427             else
428               aNewLength.myPoints[i] = anAttr;
429           }
430           // value
431           AttributeDoublePtr aValue = aLength->real(SketchPlugin_Constraint::VALUE());
432           aNewLength.myValueDouble = aValue->value();
433           aNewLength.myValueText = aValue->text();
434           // auxiliary attributes
435           AttributePoint2DPtr aFlyoutAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
436               aLength->attribute(SketchPlugin_ConstraintLength::FLYOUT_VALUE_PNT()));
437           if (aFlyoutAttr && aFlyoutAttr->isInitialized())
438             aNewLength.myFlyoutPoint = SketchPlugin_Tools::flyoutPointCoordinates(aLength);
439           AttributeIntegerPtr aLocationAttr =
440               aLength->integer(SketchPlugin_ConstraintLength::LOCATION_TYPE_ID());
441           if (aLocationAttr && aLocationAttr->isInitialized())
442             aNewLength.myLocationType = aLocationAttr->value();
443           else
444             aNewLength.myLocationType = -1;
445         }
446       }
447
448       ++aFeat;
449     }
450   }
451
452   // remove references
453   ModelAPI_Tools::removeFeaturesAndReferences(theFeaturesToRemove);
454   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
455
456   // restore Length constraints as point-point distances
457   FeaturePtr aConstraint;
458   std::list<Length>::iterator anIt = aLengthToDistance.begin();
459   for (; anIt != aLengthToDistance.end(); ++anIt) {
460     aConstraint = SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
461         SketchPlugin_ConstraintDistance::ID(), anIt->myPoints[0], anIt->myPoints[1]);
462     // set value
463     AttributeDoublePtr aValue = aConstraint->real(SketchPlugin_Constraint::VALUE());
464     if (anIt->myValueText.empty())
465       aValue->setValue(anIt->myValueDouble);
466     else
467       aValue->setText(anIt->myValueText);
468     // set flyout point if exists
469     if (anIt->myFlyoutPoint) {
470       AttributePoint2DPtr aFlyoutAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
471           aConstraint->attribute(SketchPlugin_ConstraintDistance::FLYOUT_VALUE_PNT()));
472       aFlyoutAttr->setValue(anIt->myFlyoutPoint);
473     }
474     // set location type if initialized
475     if (anIt->myLocationType >= 0) {
476       AttributeIntegerPtr aLocationType =
477           aConstraint->integer(SketchPlugin_ConstraintDistance::LOCATION_TYPE_ID());
478       aLocationType->setValue(anIt->myLocationType);
479     }
480     aConstraint->execute();
481     ModelAPI_EventCreator::get()->sendUpdated(aConstraint,
482         Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
483   }
484 }
485
486 // =========   Auxiliary functions   =================
487 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
488                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
489 {
490   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
491       theNewArc->attribute(theNewArcAttribute))->pnt();
492   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
493       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
494 }
495
496 static std::shared_ptr<GeomAPI_Pnt2d> toPoint(const AttributePtr& theAttribute)
497 {
498   std::shared_ptr<GeomAPI_Pnt2d> aPoint;
499   AttributePoint2DPtr aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
500   if (aPointAttr)
501     aPoint = aPointAttr->pnt();
502   return aPoint;
503 }
504
505 static std::shared_ptr<GeomAPI_Lin2d> toLine(const FeaturePtr& theFeature)
506 {
507   std::shared_ptr<GeomAPI_Lin2d> aLine;
508   if (theFeature->getKind() == SketchPlugin_Line::ID()) {
509     std::shared_ptr<GeomAPI_Pnt2d> aStart =
510         toPoint( theFeature->attribute(SketchPlugin_Line::START_ID()) );
511     std::shared_ptr<GeomAPI_Pnt2d> aEnd =
512         toPoint( theFeature->attribute(SketchPlugin_Line::END_ID()) );
513     aLine = std::shared_ptr<GeomAPI_Lin2d>(new GeomAPI_Lin2d(aStart, aEnd));
514   }
515   return aLine;
516 }
517
518 static std::shared_ptr<GeomAPI_Circ2d> toCircle(const FeaturePtr& theFeature)
519 {
520   std::shared_ptr<GeomAPI_Circ2d> aCircle;
521   if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
522     std::shared_ptr<GeomAPI_Pnt2d> aCenter =
523         toPoint( theFeature->attribute(SketchPlugin_Arc::CENTER_ID()) );
524     std::shared_ptr<GeomAPI_Pnt2d> aStart =
525         toPoint( theFeature->attribute(SketchPlugin_Arc::START_ID()) );
526     aCircle = std::shared_ptr<GeomAPI_Circ2d>(new GeomAPI_Circ2d(aCenter, aStart));
527   }
528   return aCircle;
529 }
530
531
532 void calculateFilletCenter(FeaturePtr theFilletFeatures[2],
533                            double theFilletRadius,
534                            const std::shared_ptr<GeomAPI_Ax3>& theSketchPlane,
535                            std::shared_ptr<GeomAPI_XY>& theCenter,
536                            std::shared_ptr<GeomAPI_XY>& theTangentA,
537                            std::shared_ptr<GeomAPI_XY>& theTangentB)
538 {
539   GeomShapePtr aShapeA = theFilletFeatures[0]->lastResult()->shape();
540   GeomShapePtr aShapeB = theFilletFeatures[1]->lastResult()->shape();
541
542   GeomAlgoAPI_Circ2dBuilder aCircBuilder(theSketchPlane);
543   aCircBuilder.addTangentCurve(aShapeA);
544   aCircBuilder.addTangentCurve(aShapeB);
545   aCircBuilder.setRadius(theFilletRadius);
546
547   std::shared_ptr<GeomAPI_Circ2d> aFilletCircle = aCircBuilder.circle();
548   if (!aFilletCircle)
549     return;
550
551   theCenter = aFilletCircle->center()->xy();
552   // tangent points
553   std::shared_ptr<GeomAPI_Pnt2d> aTgPoints[2];
554   for (int i = 0; i < 2; ++i) {
555     std::shared_ptr<GeomAPI_Circ2d> aCircle = toCircle(theFilletFeatures[i]);
556     if (aCircle)
557       aTgPoints[i] = aCircle->project(aFilletCircle->center());
558     else {
559       std::shared_ptr<GeomAPI_Lin2d> aLine = toLine(theFilletFeatures[i]);
560       if (aLine)
561         aTgPoints[i] = aLine->project(aFilletCircle->center());
562     }
563   }
564   theTangentA = aTgPoints[0]->xy();
565   theTangentB = aTgPoints[1]->xy();
566 }
567
568 double calculateFilletRadius(FeaturePtr theFilletFeatures[2])
569 {
570   double aLengths[2] = { 0, 0 };
571   for (int i = 0; i < 2; ++i) {
572     GeomShapePtr aShape = theFilletFeatures[i]->lastResult()->shape();
573     std::shared_ptr<GeomAPI_Edge> anEdge = std::dynamic_pointer_cast<GeomAPI_Edge>(aShape);
574     if (anEdge)
575       aLengths[i] = anEdge->length();
576   }
577   return (aLengths[0] < aLengths[1] ? aLengths[0] : aLengths[1]) / 6.0;
578 }
579
580 std::set<FeaturePtr> findFeaturesToRemove(const FeaturePtr theFeature,
581                                           const AttributePtr theAttribute) {
582   std::set<FeaturePtr> aFeaturesToBeRemoved;
583   std::set<AttributePtr> aRefs = theFeature->data()->refsToMe();
584   std::list<ResultPtr> aResults = theFeature->results();
585   for(std::list<ResultPtr>::const_iterator aResultsIt = aResults.cbegin();
586       aResultsIt != aResults.cend();
587       ++aResultsIt) {
588     ResultPtr aResult = *aResultsIt;
589     std::set<AttributePtr> aResultRefs = aResult->data()->refsToMe();
590     aRefs.insert(aResultRefs.begin(), aResultRefs.end());
591   }
592   for(std::set<AttributePtr>::const_iterator anIt = aRefs.cbegin();
593     anIt != aRefs.cend();
594     ++anIt) {
595     std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
596     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
597     if(aFeature->getKind() == SketchPlugin_Fillet::ID()) {
598       continue;
599     }
600     if(aFeature->getKind() == SketchPlugin_ConstraintLength::ID()
601         || aFeature->getKind() == SketchPlugin_ConstraintEqual::ID()
602         || aFeature->getKind() == SketchPlugin_ConstraintMiddle::ID()) {
603       aFeaturesToBeRemoved.insert(aFeature);
604     } else {
605       std::list<AttributePtr> anAttrs =
606           aFeature->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
607       for(std::list<AttributePtr>::const_iterator aRefAttrsIt = anAttrs.cbegin();
608           aRefAttrsIt != anAttrs.cend();
609           ++aRefAttrsIt) {
610         AttributeRefAttrPtr anAttrRefAttr =
611           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*aRefAttrsIt);
612         if(anAttrRefAttr.get() && anAttrRefAttr->attr() == theAttribute) {
613           aFeaturesToBeRemoved.insert(aFeature);
614         }
615       }
616     }
617   }
618   return aFeaturesToBeRemoved;
619 }