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