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