]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchPlugin/SketchPlugin_ConstraintFillet.cpp
Salome HOME
Issue #1860: fix end lines with spaces
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_ConstraintFillet.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 // File:    SketchPlugin_ConstraintFillet.cpp
4 // Created: 19 Mar 2015
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchPlugin_ConstraintFillet.h"
8
9 #include <GeomAPI_Circ2d.h>
10 #include <GeomAPI_Dir2d.h>
11 #include <GeomAPI_Lin2d.h>
12 #include <GeomAPI_Pnt2d.h>
13 #include <GeomAPI_XY.h>
14 #include <GeomDataAPI_Point2D.h>
15 #include <ModelAPI_AttributeDouble.h>
16 #include <ModelAPI_AttributeRefAttrList.h>
17 #include <ModelAPI_Data.h>
18 #include <ModelAPI_Events.h>
19 #include <ModelAPI_Session.h>
20 #include <ModelAPI_Validator.h>
21
22 #include <SketchPlugin_Arc.h>
23 #include <SketchPlugin_Line.h>
24 #include <SketchPlugin_Point.h>
25 #include <SketchPlugin_Sketch.h>
26 #include <SketchPlugin_ConstraintCoincidence.h>
27 #include <SketchPlugin_ConstraintTangent.h>
28 #include <SketchPlugin_ConstraintRadius.h>
29 #include <SketchPlugin_Tools.h>
30
31 #include <Events_Loop.h>
32
33 #include <math.h>
34
35 const double tolerance = 1.e-7;
36 const double paramTolerance = 1.e-4;
37
38 /// \brief Attract specified point on theNewArc to the attribute of theFeature
39 static void recalculateAttributes(FeaturePtr theNewArc, const std::string& theNewArcAttribute,
40   FeaturePtr theFeature, const std::string& theFeatureAttribute);
41
42 /// \brief Calculates center of fillet arc and coordinates of tangency points
43 static void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
44                                   double theRadius, bool theNotInversed[2],
45                                   std::shared_ptr<GeomAPI_XY>& theCenter,
46                                   std::shared_ptr<GeomAPI_XY>& theTangentA,
47                                   std::shared_ptr<GeomAPI_XY>& theTangentB);
48
49 /// Get point on 1/3 length of edge from fillet point
50 static void getPointOnEdge(const FeaturePtr theFeature,
51                            const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
52                            std::shared_ptr<GeomAPI_Pnt2d>& thePoint);
53
54 /// Get distance from point to feature
55 static double getProjectionDistance(const FeaturePtr theFeature,
56                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint);
57
58 /// Get coincide edges for fillet
59 static std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence);
60
61 SketchPlugin_ConstraintFillet::SketchPlugin_ConstraintFillet()
62 : myListOfPointsChangedInCode(false),
63   myRadiusChangedByUser(false),
64   myRadiusChangedInCode(false),
65   myRadiusInitialized(false)
66 {
67 }
68
69 void SketchPlugin_ConstraintFillet::initAttributes()
70 {
71   data()->addAttribute(SketchPlugin_Constraint::VALUE(), ModelAPI_AttributeDouble::typeId());
72   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(),
73                        ModelAPI_AttributeRefAttrList::typeId());
74 }
75
76 void SketchPlugin_ConstraintFillet::execute()
77 {
78   std::shared_ptr<ModelAPI_Data> aData = data();
79
80   // Check the base objects are initialized.
81   AttributeRefAttrListPtr aPointsRefList = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(
82     aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
83   if(!aPointsRefList->isInitialized()) {
84     setError("Error: List of points is not initialized.");
85     return;
86   }
87
88   // Get fillet radius.
89   double aFilletRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
90     aData->attribute(SketchPlugin_Constraint::VALUE()))->value();
91
92   // Wait all constraints being created, then send update events
93   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
94   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
95   if (isUpdateFlushed)
96     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
97
98   for(std::set<AttributePtr>::iterator aPointsIter = myNewPoints.begin();
99       aPointsIter != myNewPoints.end();
100       ++aPointsIter) {
101     AttributePtr aPointAttr = *aPointsIter;
102     std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2d =
103       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aPointAttr);
104     if(!aFilletPoint2d.get()) {
105       setError("Error: One of the selected points is empty.");
106       return;
107     }
108     std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2d->pnt();
109
110     // Obtain base lines for fillet.
111     bool anIsNeedNewObjects = true;
112     FilletFeatures aFilletFeatures;
113     std::map<AttributePtr, FilletFeatures>::iterator aPrevPointsIter =
114       myPointFeaturesMap.find(aPointAttr);
115     if(aPrevPointsIter != myPointFeaturesMap.end()) {
116       anIsNeedNewObjects = false;
117       aFilletFeatures = aPrevPointsIter->second;
118     }
119     FeaturePtr aBaseEdgeA, aBaseEdgeB;
120     if(!anIsNeedNewObjects) {
121       aBaseEdgeA = aFilletFeatures.baseEdgesState.front().first;
122       aBaseEdgeB = aFilletFeatures.baseEdgesState.back().first;
123     } else {
124       // Obtain constraint coincidence for the fillet point.
125       FeaturePtr aConstraintCoincidence;
126       const std::set<AttributePtr>& aRefsList = aFilletPoint2d->owner()->data()->refsToMe();
127       for(std::set<AttributePtr>::const_iterator
128           anIt = aRefsList.cbegin(); anIt != aRefsList.cend(); ++anIt) {
129         std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
130         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
131         if(aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
132           AttributeRefAttrPtr anAttrRefA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
133             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_A()));
134           AttributeRefAttrPtr anAttrRefB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
135             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_B()));
136           if(anAttrRefA.get() && !anAttrRefA->isObject()) {
137             AttributePtr anAttrA = anAttrRefA->attr();
138             if(aFilletPoint2d == anAttrA) {
139               aConstraintCoincidence = aConstrFeature;
140               break;
141             }
142           }
143           if(anAttrRefB.get() && !anAttrRefB->isObject()) {
144             AttributePtr anAttrB = anAttrRefB->attr();
145             if(aFilletPoint2d == anAttrB) {
146               aConstraintCoincidence = aConstrFeature;
147               break;
148             }
149           }
150         }
151       }
152
153       if(!aConstraintCoincidence.get()) {
154         setError("Error: No coincident edges at one of the selected points.");
155         return;
156       }
157
158       // Get coincide edges.
159       std::set<FeaturePtr> aCoincides = getCoincides(aConstraintCoincidence);
160       if(aCoincides.size() != 2) {
161         setError("Error: One of the selected points does not have two suitable edges for fillet.");
162         return;
163       }
164
165       std::set<FeaturePtr>::iterator aLinesIt = aCoincides.begin();
166       aBaseEdgeA = *aLinesIt++;
167       aBaseEdgeB = *aLinesIt;
168
169       std::pair<FeaturePtr, bool> aBasePairA =
170         std::make_pair(aBaseEdgeA,
171                        aBaseEdgeA->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value());
172       std::pair<FeaturePtr, bool> aBasePairB =
173         std::make_pair(aBaseEdgeB,
174                        aBaseEdgeB->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value());
175       aFilletFeatures.baseEdgesState.push_back(aBasePairA);
176       aFilletFeatures.baseEdgesState.push_back(aBasePairB);
177     }
178
179     if(!aBaseEdgeA.get() || !aBaseEdgeB.get()) {
180       setError("Error: One of the base edges is empty.");
181       return;
182     }
183
184     // Create new edges and arc if needed.
185     FeaturePtr aResultEdgeA, aResultEdgeB, aResultArc;
186     if(!anIsNeedNewObjects) {
187       // Obtain features from the list.
188       std::list<FeaturePtr>::iterator aResultEdgesIt = aFilletFeatures.resultEdges.begin();
189       aResultEdgeA = *aResultEdgesIt++;
190       aResultEdgeB = *aResultEdgesIt++;
191       aResultArc = *aResultEdgesIt;
192     } else {
193       // Copy edges and create arc.
194       aResultEdgeA = SketchPlugin_Sketch::addUniqueNamedCopiedFeature(aBaseEdgeA, sketch());
195       aResultEdgeA->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(false);
196       aResultEdgeB = SketchPlugin_Sketch::addUniqueNamedCopiedFeature(aBaseEdgeB, sketch());
197       aResultEdgeB->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(false);
198       aResultArc = sketch()->addFeature(SketchPlugin_Arc::ID());
199
200       aFilletFeatures.resultEdges.push_back(aResultEdgeA);
201       aFilletFeatures.resultEdges.push_back(aResultEdgeB);
202       aFilletFeatures.resultEdges.push_back(aResultArc);
203     }
204
205     // Calculate arc attributes
206     static const int aNbFeatures = 2;
207     FeaturePtr aBaseFeatures[aNbFeatures] = {aBaseEdgeA, aBaseEdgeB};
208     FeaturePtr aResultFeatures[aNbFeatures] = {aResultEdgeA, aResultEdgeB};
209     // tangent directions of the features in coincident point
210     std::shared_ptr<GeomAPI_Dir2d> aTangentDir[aNbFeatures];
211     bool isStart[aNbFeatures]; // indicates which point the features share
212     // first pair of points relate to first feature, second pair -  to second
213     std::shared_ptr<GeomAPI_Pnt2d> aStartEndPnt[aNbFeatures * 2];
214     std::string aFeatAttributes[aNbFeatures * 2]; // attributes of features
215     for (int i = 0; i < aNbFeatures; i++) {
216       std::string aStartAttr, aEndAttr;
217       if (aResultFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
218         aStartAttr = SketchPlugin_Line::START_ID();
219         aEndAttr = SketchPlugin_Line::END_ID();
220       } else if (aResultFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
221         aStartAttr = SketchPlugin_Arc::START_ID();
222         aEndAttr = SketchPlugin_Arc::END_ID();
223       } else { // wrong argument
224         setError("Error: One of the points has wrong coincide feature");
225         return;
226       }
227       aFeatAttributes[2*i] = aStartAttr;
228       aStartEndPnt[2*i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
229         aBaseFeatures[i]->attribute(aStartAttr))->pnt();
230       aFeatAttributes[2*i+1] = aEndAttr;
231       aStartEndPnt[2*i+1] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
232         aBaseFeatures[i]->attribute(aEndAttr))->pnt();
233     }
234     for (int aFeatInd = 0; aFeatInd < aNbFeatures; aFeatInd++) {
235       for (int j = 0; j < 2; j++) // loop on start-end of each feature
236         if (aStartEndPnt[aFeatInd * aNbFeatures + j]->distance(aFilletPnt2d) < 1.e-10) {
237           isStart[aFeatInd] = (j==0);
238           break;
239         }
240     }
241     // tangent directions of the features
242     for (int i = 0; i < aNbFeatures; i++) {
243       std::shared_ptr<GeomAPI_XY> aDir;
244       if (aResultFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
245         aDir = aStartEndPnt[2*i+1]->xy()->decreased(aStartEndPnt[2*i]->xy());
246         if (!isStart[i])
247           aDir = aDir->multiplied(-1.0);
248       } else if (aResultFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
249         std::shared_ptr<GeomAPI_Pnt2d> aCenterPoint =
250           std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
251           aResultFeatures[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
252         aDir = isStart[i] ? aStartEndPnt[2*i]->xy() : aStartEndPnt[2*i+1]->xy();
253         aDir = aDir->decreased(aCenterPoint->xy());
254
255         double x = aDir->x();
256         double y = aDir->y();
257         aDir->setX(-y);
258         aDir->setY(x);
259         if (isStart[i] ==
260             std::dynamic_pointer_cast<SketchPlugin_Arc>(aBaseFeatures[i])->isReversed())
261           aDir = aDir->multiplied(-1.0);
262       }
263       aTangentDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aDir));
264     }
265
266     // By default, the start point of fillet arc is connected to FeatureA,
267     // and the end point - to FeatureB. But when the angle between TangentDirA and
268     // TangentDirB greater 180 degree, the sequaence of features need to be reversed.
269     double cosBA = aTangentDir[0]->cross(aTangentDir[1]); // cos(B-A),
270     // where A and B - angles between corresponding tanget direction and the X axis
271     bool isReversed = cosBA > 0.0;
272
273     // Calculate fillet arc parameters
274     std::shared_ptr<GeomAPI_XY> aCenter, aTangentPntA, aTangentPntB;
275     calculateFilletCenter(aBaseEdgeA, aBaseEdgeB, aFilletRadius,
276                           isStart, aCenter, aTangentPntA, aTangentPntB);
277     if(!aCenter.get() || !aTangentPntA.get() || !aTangentPntB.get()) {
278       setError("Can not create fillet with the specified parameters.");
279       return;
280     }
281     // update features
282     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
283       aResultEdgeA->attribute(aFeatAttributes[isStart[0] ? 0 : 1]))->
284       setValue(aTangentPntA->x(), aTangentPntA->y());
285     aResultEdgeA->execute();
286     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
287       aResultEdgeB->attribute(aFeatAttributes[2 + (isStart[1] ? 0 : 1)]))->
288       setValue(aTangentPntB->x(), aTangentPntB->y());
289     aResultEdgeB->execute();
290     // update fillet arc: make the arc correct for sure, so, it is not needed to
291     // process the "attribute updated"
292     // by arc; moreover, it may cause cyclicity in hte mechanism of updater
293     aResultArc->data()->blockSendAttributeUpdated(true);
294     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
295       aResultArc->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(aCenter->x(), aCenter->y());
296     if(isReversed) {
297       std::shared_ptr<GeomAPI_XY> aTmp = aTangentPntA;
298       aTangentPntA = aTangentPntB;
299       aTangentPntB = aTmp;
300     }
301     std::shared_ptr<GeomDataAPI_Point2D> aStartPoint =
302       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
303       aResultArc->attribute(SketchPlugin_Arc::START_ID()));
304     std::shared_ptr<GeomDataAPI_Point2D> aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
305       aResultArc->attribute(SketchPlugin_Arc::END_ID()));
306     if(aStartPoint->isInitialized() && aEndPoint->isInitialized() &&
307       (aStartPoint->pnt()->xy()->distance(aTangentPntA) > tolerance ||
308        aEndPoint->pnt()->xy()->distance(aTangentPntB) > tolerance)) {
309       std::dynamic_pointer_cast<SketchPlugin_Arc>(aResultArc)->setReversed(false);
310     }
311     aStartPoint->setValue(aTangentPntA->x(), aTangentPntA->y());
312     aEndPoint->setValue(aTangentPntB->x(), aTangentPntB->y());
313     aResultArc->data()->blockSendAttributeUpdated(false);
314     aResultArc->execute();
315
316     if(anIsNeedNewObjects) {
317       // Create list of additional constraints:
318       // 1. Coincidence of boundary points of features (copied lines/arcs) and fillet arc
319       // 1.1. coincidence
320       FeaturePtr aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
321       AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
322           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
323       aRefAttr->setAttr(aResultArc->attribute(SketchPlugin_Arc::START_ID()));
324       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
325           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
326       int aFeatInd = isReversed ? 1 : 0;
327       int anAttrInd = (isReversed ? 2 : 0) + (isStart[isReversed ? 1 : 0] ? 0 : 1);
328       aRefAttr->setAttr(aResultFeatures[aFeatInd]->attribute(aFeatAttributes[anAttrInd]));
329       recalculateAttributes(aResultArc, SketchPlugin_Arc::START_ID(),
330                             aResultFeatures[aFeatInd], aFeatAttributes[anAttrInd]);
331       aConstraint->execute();
332       aFilletFeatures.resultConstraints.push_back(aConstraint);
333       ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
334       // 1.2. coincidence
335       aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
336       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
337           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
338       aRefAttr->setAttr(aResultArc->attribute(SketchPlugin_Arc::END_ID()));
339       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
340           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
341       aFeatInd = isReversed ? 0 : 1;
342       anAttrInd = (isReversed ? 0 : 2) + (isStart[isReversed ? 0 : 1] ? 0 : 1);
343       aRefAttr->setAttr(aResultFeatures[aFeatInd]->attribute(aFeatAttributes[anAttrInd]));
344       recalculateAttributes(aResultArc, SketchPlugin_Arc::END_ID(),
345                             aResultFeatures[aFeatInd], aFeatAttributes[anAttrInd]);
346       aConstraint->execute();
347       aFilletFeatures.resultConstraints.push_back(aConstraint);
348       ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
349       // 2. Fillet arc radius
350       //aConstraint = sketch()->addFeature(SketchPlugin_ConstraintRadius::ID());
351       //aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
352       //    aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
353       //aRefAttr->setObject(aNewArc->lastResult());
354       //std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
355       //    aConstraint->attribute(SketchPlugin_Constraint::VALUE()))->setValue(aFilletRadius);
356       //std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
357       //    aConstraint->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT()))->setValue(
358       //    isStart[0] ? aStartEndPnt[0] : aStartEndPnt[1]);
359       //aConstraint->execute();
360       //myProducedFeatures.push_back(aConstraint);
361       //ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
362       // 3. Tangency of fillet arc and features
363       for (int i = 0; i < aNbFeatures; i++) {
364         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintTangent::ID());
365         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
366             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
367         aRefAttr->setObject(aResultArc->lastResult());
368         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
369             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
370         bool isArc = aResultFeatures[i]->getKind() == SketchPlugin_Arc::ID();
371         aRefAttr->setObject(isArc ? aResultFeatures[i]->lastResult() :
372                                     aResultFeatures[i]->firstResult());
373         aConstraint->execute();
374         aFilletFeatures.resultConstraints.push_back(aConstraint);
375         ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
376       }
377       // 4. Coincidence of free boundaries of base and copied features
378       for (int i = 0; i < aNbFeatures; i++) {
379         anAttrInd = 2*i + (isStart[i] ? 1 : 0);
380         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
381         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
382             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
383         aRefAttr->setAttr(aBaseFeatures[i]->attribute(aFeatAttributes[anAttrInd]));
384         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
385             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
386         aRefAttr->setAttr(aResultFeatures[i]->attribute(aFeatAttributes[anAttrInd]));
387         aFilletFeatures.resultConstraints.push_back(aConstraint);
388       }
389       // 4.1. Additional tangency constraints when the fillet is based on arcs.
390       //      It is used to verify the created arc will be placed on a source.
391       for (int i = 0; i < aNbFeatures; ++i) {
392         if (aResultFeatures[i]->getKind() != SketchPlugin_Arc::ID())
393           continue;
394         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintTangent::ID());
395         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
396             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
397         aRefAttr->setObject(aBaseFeatures[i]->lastResult());
398         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
399             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
400         aRefAttr->setObject(aResultFeatures[i]->lastResult());
401         aConstraint->execute();
402         aFilletFeatures.resultConstraints.push_back(aConstraint);
403         ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
404       }
405       // 5. Tangent points should be placed on the base features
406       for (int i = 0; i < aNbFeatures; i++) {
407         anAttrInd = 2*i + (isStart[i] ? 0 : 1);
408         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
409         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
410             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
411         aRefAttr->setAttr(aResultFeatures[i]->attribute(aFeatAttributes[anAttrInd]));
412         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
413             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
414         aRefAttr->setObject(aBaseFeatures[i]->lastResult());
415         aFilletFeatures.resultConstraints.push_back(aConstraint);
416       }
417       // make base features auxiliary
418       aBaseEdgeA->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(true);
419       aBaseEdgeB->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(true);
420
421       // exchange the naming IDs of newly created and old line that become auxiliary
422       sketch()->exchangeIDs(aBaseEdgeA, aResultEdgeA);
423       sketch()->exchangeIDs(aBaseEdgeB, aResultEdgeB);
424
425       // store point and features in the map.
426       myPointFeaturesMap[aPointAttr] = aFilletFeatures;
427     } else {
428       // Update radius value
429       int aNbSubs = sketch()->numberOfSubs();
430       FeaturePtr aSubFeature;
431       for (int aSub = 0; aSub < aNbSubs; aSub++) {
432         aSubFeature = sketch()->subFeature(aSub);
433         if (aSubFeature->getKind() != SketchPlugin_ConstraintRadius::ID())
434           continue;
435         AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
436             aSubFeature->attribute(SketchPlugin_Constraint::ENTITY_A()));
437         if (!aRefAttr || !aRefAttr->isObject())
438           continue;
439         FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
440         if (aFeature == aResultArc) {
441           AttributeDoublePtr aRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
442             aSubFeature->attribute(SketchPlugin_Constraint::VALUE()));
443           aRadius->setValue(aFilletRadius);
444           break;
445         }
446       }
447     }
448   }
449
450   // Send events to update the sub-features by the solver.
451   if(isUpdateFlushed) {
452     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
453   }
454 }
455
456 void SketchPlugin_ConstraintFillet::attributeChanged(const std::string& theID)
457 {
458   if(theID == SketchPlugin_Constraint::ENTITY_A()) {
459     if(myListOfPointsChangedInCode) {
460       return;
461     }
462
463     // Clear results.
464     clearResults();
465
466     // Clear list of new points.
467     myNewPoints.clear();
468
469     // Get list of points for fillets and current radius.
470     AttributeRefAttrListPtr aRefListOfFilletPoints =
471       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(
472       data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
473     AttributeDoublePtr aRadiusAttribute = real(VALUE());
474     int aListSize = aRefListOfFilletPoints->size();
475     if(aListSize == 0 && !myRadiusChangedByUser) {
476       // If list is empty reset radius to zero (if it was not changed by user).
477       myRadiusChangedInCode = true;
478       aRadiusAttribute->setValue(0);
479       myRadiusChangedInCode = false;
480       return;
481     }
482
483     // Iterate over points to get base lines an calculate radius for fillets.
484     double aMinimumRadius = 0;
485     std::list<std::pair<ObjectPtr, AttributePtr>>
486       aSelectedPointsList = aRefListOfFilletPoints->list();
487     std::list<std::pair<ObjectPtr, AttributePtr>>::iterator anIter = aSelectedPointsList.begin();
488     std::set<AttributePtr> aPointsToSkeep;
489     for(int anIndex = 0; anIndex < aListSize; anIndex++, anIter++) {
490       AttributePtr aFilletPointAttr = (*anIter).second;
491       std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2D =
492         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aFilletPointAttr);
493       if(!aFilletPoint2D.get()) {
494         myNewPoints.clear();
495         setError("Error: One of the selected points is invalid.");
496         return;
497       }
498
499       // If point or coincident point is already in list remove it from attribute.
500       if(aPointsToSkeep.find(aFilletPointAttr) != aPointsToSkeep.end()) {
501         myListOfPointsChangedInCode = true;
502         aRefListOfFilletPoints->remove(aFilletPointAttr);
503         myListOfPointsChangedInCode = false;
504         continue;
505       }
506
507       // Obtain constraint coincidence for the fillet point.
508       FeaturePtr aConstraintCoincidence;
509       const std::set<AttributePtr>& aRefsList = aFilletPointAttr->owner()->data()->refsToMe();
510       for(std::set<AttributePtr>::const_iterator
511           anIt = aRefsList.cbegin(); anIt != aRefsList.cend(); ++anIt) {
512         std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
513         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
514         if(aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
515           AttributeRefAttrPtr anAttrRefA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
516             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_A()));
517           AttributeRefAttrPtr anAttrRefB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
518             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_B()));
519           if(anAttrRefA.get()) {
520             AttributePtr anAttrA = anAttrRefA->attr();
521             if(aFilletPointAttr == anAttrA) {
522               aConstraintCoincidence = aConstrFeature;
523               break;
524             }
525           }
526           if(anAttrRefB.get()) {
527             AttributePtr anAttrB = anAttrRefB->attr();
528             if(aFilletPointAttr == anAttrB) {
529               aConstraintCoincidence = aConstrFeature;
530               break;
531             }
532           }
533         }
534       }
535
536       if(!aConstraintCoincidence.get()) {
537         myNewPoints.clear();
538         setError("Error: No coincident edges at one of the selected points.");
539         return;
540       }
541
542       // Get coincides from constraint.
543       std::set<FeaturePtr> aCoincides;
544
545
546       SketchPlugin_Tools::findCoincidences(aConstraintCoincidence,
547                                            SketchPlugin_ConstraintCoincidence::ENTITY_A(),
548                                            aCoincides);
549       SketchPlugin_Tools::findCoincidences(aConstraintCoincidence,
550                                            SketchPlugin_ConstraintCoincidence::ENTITY_B(),
551                                            aCoincides);
552
553       // Remove points from set of coincides.
554       // Also get all attributes which is equal to this point to exclude it.
555       std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
556       std::set<FeaturePtr> aNewSetOfCoincides;
557       for(std::set<FeaturePtr>::iterator
558           anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
559         std::string aFeatureKind = (*anIt)->getKind();
560         if(aFeatureKind == SketchPlugin_Point::ID()) {
561           AttributePtr anAttr = (*anIt)->attribute(SketchPlugin_Point::COORD_ID());
562           std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
563             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
564           if(aPoint2D.get() && aFilletPnt2d->isEqual(aPoint2D->pnt())) {
565             aPointsToSkeep.insert(anAttr);
566           }
567         } else if(aFeatureKind == SketchPlugin_Line::ID()) {
568           AttributePtr anAttrStart = (*anIt)->attribute(SketchPlugin_Line::START_ID());
569           std::shared_ptr<GeomDataAPI_Point2D> aPointStart2D =
570             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrStart);
571           if(aPointStart2D.get() && aFilletPnt2d->isEqual(aPointStart2D->pnt())) {
572             aPointsToSkeep.insert(anAttrStart);
573           }
574           AttributePtr anAttrEnd = (*anIt)->attribute(SketchPlugin_Line::END_ID());
575           std::shared_ptr<GeomDataAPI_Point2D> aPointEnd2D =
576             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrEnd);
577           if(aPointEnd2D.get() && aFilletPnt2d->isEqual(aPointEnd2D->pnt())) {
578             aPointsToSkeep.insert(anAttrEnd);
579           }
580           aNewSetOfCoincides.insert(*anIt);
581         } else if(aFeatureKind == SketchPlugin_Arc::ID() ) {
582           AttributePtr anAttrCenter = (*anIt)->attribute(SketchPlugin_Arc::CENTER_ID());
583           std::shared_ptr<GeomDataAPI_Point2D> aPointCenter2D =
584             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrCenter);
585           if(aPointCenter2D.get() && aFilletPnt2d->isEqual(aPointCenter2D->pnt())) {
586             aPointsToSkeep.insert(anAttrCenter);
587             continue;
588           }
589           AttributePtr anAttrStart = (*anIt)->attribute(SketchPlugin_Arc::START_ID());
590           std::shared_ptr<GeomDataAPI_Point2D> aPointStart2D =
591             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrStart);
592           if(aPointStart2D.get() && aFilletPnt2d->isEqual(aPointStart2D->pnt())) {
593             aPointsToSkeep.insert(anAttrStart);
594           }
595           AttributePtr anAttrEnd = (*anIt)->attribute(SketchPlugin_Arc::END_ID());
596           std::shared_ptr<GeomDataAPI_Point2D> aPointEnd2D =
597             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrEnd);
598           if(aPointEnd2D.get() && aFilletPnt2d->isEqual(aPointEnd2D->pnt())) {
599             aPointsToSkeep.insert(anAttrEnd);
600           }
601           aNewSetOfCoincides.insert(*anIt);
602         }
603       }
604       aCoincides = aNewSetOfCoincides;
605
606       // If we still have more than two coincides remove auxilary entities from set of coincides.
607       if(aCoincides.size() > 2) {
608         aNewSetOfCoincides.clear();
609         for(std::set<FeaturePtr>::iterator
610             anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
611           if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
612             aNewSetOfCoincides.insert(*anIt);
613           }
614         }
615         aCoincides = aNewSetOfCoincides;
616       }
617
618       if(aCoincides.size() != 2) {
619         myNewPoints.clear();
620         setError("Error: One of the selected points does not have two suitable edges for fillet.");
621         return;
622       }
623
624       // Store base point for fillet.
625       aPointsToSkeep.insert(aFilletPointAttr);
626       myNewPoints.insert(aFilletPointAttr);
627
628       // Get base lines for fillet.
629       FeaturePtr anOldFeatureA, anOldFeatureB;
630       std::set<FeaturePtr>::iterator aLinesIt = aCoincides.begin();
631       anOldFeatureA = *aLinesIt++;
632       anOldFeatureB = *aLinesIt;
633
634       // Getting radius value if it was not changed by user.
635       if(!myRadiusChangedByUser) {
636         // Getting points located at 1/3 of edge length from fillet point.
637         std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
638         std::shared_ptr<GeomAPI_Pnt2d> aPntA, aPntB;
639         getPointOnEdge(anOldFeatureA, aFilletPnt2d, aPntA);
640         getPointOnEdge(anOldFeatureB, aFilletPnt2d, aPntB);
641
642         /// Getting distances.
643         double aDistanceA = getProjectionDistance(anOldFeatureB, aPntA);
644         double aDistanceB = getProjectionDistance(anOldFeatureA, aPntB);
645         double aRadius = aDistanceA < aDistanceB ? aDistanceA / 2.0 : aDistanceB / 2.0;
646         aMinimumRadius = aMinimumRadius == 0 ? aRadius :
647           aRadius < aMinimumRadius ? aRadius : aMinimumRadius;
648       }
649     }
650
651     // Set new default radius if it was not changed by user.
652     if(!myRadiusChangedByUser) {
653       myRadiusChangedInCode = true;
654       aRadiusAttribute->setValue(aMinimumRadius);
655       myRadiusChangedInCode = false;
656     }
657
658   } else if(theID == SketchPlugin_Constraint::VALUE()) {
659     if(myRadiusInitialized && !myRadiusChangedInCode) {
660       myRadiusChangedByUser = true;
661     }
662     if(!myRadiusInitialized) {
663       myRadiusInitialized = true;
664     }
665   }
666 }
667
668 AISObjectPtr SketchPlugin_ConstraintFillet::getAISObject(AISObjectPtr thePrevious)
669 {
670   if (!sketch())
671     return thePrevious;
672
673   AISObjectPtr anAIS = thePrevious;
674   /// TODO: Equal constraint presentation should be put here
675   return anAIS;
676 }
677
678 bool SketchPlugin_ConstraintFillet::isMacro() const
679 {
680   return true;
681 }
682
683 void SketchPlugin_ConstraintFillet::clearResults()
684 {
685   // Clear auxiliary flag on initial objects.
686   for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
687       aPointsIter != myPointFeaturesMap.end();) {
688     const FilletFeatures& aFilletFeatures = aPointsIter->second;
689     std::list<std::pair<FeaturePtr, bool>>::const_iterator aFeatureIt;
690     for(aFeatureIt = aFilletFeatures.baseEdgesState.cbegin();
691         aFeatureIt != aFilletFeatures.baseEdgesState.cend();
692         ++aFeatureIt) {
693       aFeatureIt->first->boolean(
694         SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(aFeatureIt->second);
695     }
696     ++aPointsIter;
697   }
698
699   // And remove all produced features.
700   DocumentPtr aDoc = sketch()->document();
701   for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
702       aPointsIter != myPointFeaturesMap.end();) {
703     // Remove all produced constraints.
704     const FilletFeatures& aFilletFeatures = aPointsIter->second;
705     std::list<FeaturePtr>::const_iterator aFeatureIt;
706     for(aFeatureIt = aFilletFeatures.resultConstraints.cbegin();
707         aFeatureIt != aFilletFeatures.resultConstraints.cend();
708         ++aFeatureIt) {
709       aDoc->removeFeature(*aFeatureIt);
710     }
711
712     // Remove all result edges.
713     for(aFeatureIt = aFilletFeatures.resultEdges.cbegin();
714         aFeatureIt != aFilletFeatures.resultEdges.cend();
715         ++aFeatureIt) {
716       aDoc->removeFeature(*aFeatureIt);
717     }
718
719     // Remove point from map.
720     myPointFeaturesMap.erase(aPointsIter++);
721   }
722 };
723
724
725 // =========   Auxiliary functions   =================
726 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
727                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
728 {
729   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
730       theNewArc->attribute(theNewArcAttribute))->pnt();
731   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
732       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
733 }
734
735 /// \brief Find intersections of lines shifted along normal direction
736 void possibleFilletCenterLineLine(
737     std::shared_ptr<GeomAPI_XY> thePointA, std::shared_ptr<GeomAPI_Dir2d> theDirA,
738     std::shared_ptr<GeomAPI_XY> thePointB, std::shared_ptr<GeomAPI_Dir2d> theDirB,
739     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
740 {
741   std::shared_ptr<GeomAPI_Dir2d> aDirAT(new GeomAPI_Dir2d(-theDirA->y(), theDirA->x()));
742   std::shared_ptr<GeomAPI_Dir2d> aDirBT(new GeomAPI_Dir2d(-theDirB->y(), theDirB->x()));
743   std::shared_ptr<GeomAPI_XY> aPntA, aPntB;
744   double aDet = theDirA->cross(theDirB);
745   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
746     aPntA = thePointA->added(aDirAT->xy()->multiplied(aStepA * theRadius));
747     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
748       aPntB = thePointB->added(aDirBT->xy()->multiplied(aStepB * theRadius));
749       double aVX = aDirAT->xy()->dot(aPntA);
750       double aVY = aDirBT->xy()->dot(aPntB);
751       std::shared_ptr<GeomAPI_XY> aPoint(new GeomAPI_XY(
752           (theDirB->x() * aVX - theDirA->x() * aVY) / aDet,
753           (theDirB->y() * aVX - theDirA->y() * aVY) / aDet));
754       theCenters.push_back(aPoint);
755     }
756   }
757 }
758
759 /// \brief Find intersections of line shifted along normal direction in both sides
760 ///        and a circle with extended radius
761 void possibleFilletCenterLineArc(
762     std::shared_ptr<GeomAPI_XY> theStartLine, std::shared_ptr<GeomAPI_Dir2d> theDirLine,
763     std::shared_ptr<GeomAPI_XY> theCenterArc, double theRadiusArc,
764     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
765 {
766   std::shared_ptr<GeomAPI_Dir2d> aDirT(new GeomAPI_Dir2d(-theDirLine->y(), theDirLine->x()));
767   std::shared_ptr<GeomAPI_XY> aPnt;
768   double aDirNorm2 = theDirLine->dot(theDirLine);
769   double aRad = 0.0;
770   double aDirX = theDirLine->x();
771   double aDirX2 = theDirLine->x() * theDirLine->x();
772   double aDirY2 = theDirLine->y() * theDirLine->y();
773   double aDirXY = theDirLine->x() * theDirLine->y();
774   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
775     aPnt = theStartLine->added(aDirT->xy()->multiplied(aStepA * theRadius));
776     double aCoeff = aDirT->xy()->dot(aPnt->decreased(theCenterArc));
777     double aCoeff2 = aCoeff * aCoeff;
778     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
779       aRad = theRadiusArc + aStepB * theRadius;
780       double aD = aRad * aRad * aDirNorm2 - aCoeff2;
781       if (aD < 0.0)
782         continue;
783       double aDs = sqrt(aD);
784       double x1 = theCenterArc->x() + (aCoeff * aDirT->x() - aDirT->y() * aDs) / aDirNorm2;
785       double x2 = theCenterArc->x() + (aCoeff * aDirT->x() + aDirT->y() * aDs) / aDirNorm2;
786       double y1 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
787           aDirXY * (aPnt->x() - theCenterArc->x()) - theDirLine->y() * aDs) / aDirNorm2;
788       double y2 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
789           aDirXY * (aPnt->x() - theCenterArc->x()) + theDirLine->y() * aDs) / aDirNorm2;
790
791       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
792       theCenters.push_back(aPoint1);
793       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
794       theCenters.push_back(aPoint2);
795     }
796   }
797 }
798
799 /// \brief Find intersections of two circles with extended radii
800 void possibleFilletCenterArcArc(
801     std::shared_ptr<GeomAPI_XY> theCenterA, double theRadiusA,
802     std::shared_ptr<GeomAPI_XY> theCenterB, double theRadiusB,
803     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
804 {
805   std::shared_ptr<GeomAPI_XY> aCenterDir = theCenterB->decreased(theCenterA);
806   double aCenterDist2 = aCenterDir->dot(aCenterDir);
807   double aCenterDist = sqrt(aCenterDist2);
808
809   double aRadA, aRadB;
810   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
811     aRadA = theRadiusA + aStepA * theRadius;
812     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
813       aRadB = theRadiusB + aStepB * theRadius;
814       if (aRadA + aRadB < aCenterDist || fabs(aRadA - aRadB) > aCenterDist)
815         continue; // there is no intersections
816
817       double aMedDist = (aRadA * aRadA - aRadB * aRadB + aCenterDist2) / (2.0 * aCenterDist);
818       double aHeight = sqrt(aRadA * aRadA - aMedDist * aMedDist);
819
820       double x1 = theCenterA->x() +
821         (aMedDist * aCenterDir->x() + aCenterDir->y() * aHeight) / aCenterDist;
822       double y1 = theCenterA->y() +
823         (aMedDist * aCenterDir->y() - aCenterDir->x() * aHeight) / aCenterDist;
824
825       double x2 = theCenterA->x() +
826         (aMedDist * aCenterDir->x() - aCenterDir->y() * aHeight) / aCenterDist;
827       double y2 = theCenterA->y() +
828         (aMedDist * aCenterDir->y() + aCenterDir->x() * aHeight) / aCenterDist;
829
830       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
831       theCenters.push_back(aPoint1);
832       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
833       theCenters.push_back(aPoint2);
834     }
835   }
836 }
837
838 void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
839                            double theRadius, bool theNotInversed[2],
840                            std::shared_ptr<GeomAPI_XY>& theCenter,
841                            std::shared_ptr<GeomAPI_XY>& theTangentA,
842                            std::shared_ptr<GeomAPI_XY>& theTangentB)
843 {
844   static const int aNbFeatures = 2;
845   FeaturePtr aFeature[aNbFeatures] = {theFeatureA, theFeatureB};
846   std::shared_ptr<GeomAPI_XY> aStart[aNbFeatures], aEnd[aNbFeatures], aCenter[aNbFeatures];
847   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, aEndPoint;
848
849   for (int i = 0; i < aNbFeatures; i++) {
850     if (aFeature[i]->getKind() == SketchPlugin_Line::ID()) {
851       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
852           aFeature[i]->attribute(SketchPlugin_Line::START_ID()));
853       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
854           aFeature[i]->attribute(SketchPlugin_Line::END_ID()));
855     } else if (aFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
856       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
857           aFeature[i]->attribute(SketchPlugin_Arc::START_ID()));
858       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
859           aFeature[i]->attribute(SketchPlugin_Arc::END_ID()));
860       aCenter[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
861           aFeature[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt()->xy();
862     } else
863       return;
864     aStart[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
865         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()) :
866         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()));
867     aEnd[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
868         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()) :
869         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()));
870   }
871
872   if (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
873       theFeatureB->getKind() == SketchPlugin_Line::ID()) {
874     std::shared_ptr<GeomAPI_Dir2d> aDir[2];
875     std::shared_ptr<GeomAPI_Dir2d> aDirT[2];
876     for (int i = 0; i < aNbFeatures; i++) {
877       aDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aEnd[i]->decreased(aStart[i])));
878       aDirT[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(-aDir[i]->y(), aDir[i]->x()));
879     }
880
881     // get and filter possible centers
882     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
883     possibleFilletCenterLineLine(aStart[0], aDir[0], aStart[1], aDir[1],
884                                  theRadius, aSuspectCenters);
885     double aDot = 0.0;
886     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
887     for (; anIt != aSuspectCenters.end(); anIt++) {
888       aDot = aDirT[0]->xy()->dot(aStart[0]->decreased(*anIt));
889       theTangentA = (*anIt)->added(aDirT[0]->xy()->multiplied(aDot));
890       if (theTangentA->decreased(aStart[0])->dot(aDir[0]->xy()) < 0.0)
891         continue; // incorrect position
892       aDot = aDirT[1]->xy()->dot(aStart[1]->decreased(*anIt));
893       theTangentB = (*anIt)->added(aDirT[1]->xy()->multiplied(aDot));
894       if (theTangentB->decreased(aStart[1])->dot(aDir[1]->xy()) < 0.0)
895         continue; // incorrect position
896       // the center is found, stop searching
897       theCenter = *anIt;
898       return;
899     }
900   } else if ((theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
901       theFeatureB->getKind() == SketchPlugin_Line::ID()) ||
902       (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
903       theFeatureB->getKind() == SketchPlugin_Arc::ID())) {
904     int aLineInd = theFeatureA->getKind() == SketchPlugin_Line::ID() ? 0 : 1;
905     double anArcRadius = aStart[1-aLineInd]->distance(aCenter[1-aLineInd]);
906     std::shared_ptr<GeomAPI_Dir2d> aDirLine = std::shared_ptr<GeomAPI_Dir2d>(
907         new GeomAPI_Dir2d(aEnd[aLineInd]->decreased(aStart[aLineInd])));
908     std::shared_ptr<GeomAPI_Dir2d> aDirT = std::shared_ptr<GeomAPI_Dir2d>(
909         new GeomAPI_Dir2d(-aDirLine->y(), aDirLine->x()));
910
911     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir = std::shared_ptr<GeomAPI_Dir2d>(
912         new GeomAPI_Dir2d(aStart[1-aLineInd]->decreased(aCenter[1-aLineInd])));
913     std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
914         new GeomAPI_Dir2d(aEnd[1-aLineInd]->decreased(aCenter[1-aLineInd])));
915     double anArcAngle = aEndArcDir->angle(aStartArcDir);
916
917     // get possible centers and filter them
918     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
919     possibleFilletCenterLineArc(aStart[aLineInd], aDirLine, aCenter[1-aLineInd],
920                                 anArcRadius, theRadius, aSuspectCenters);
921     double aDot = 0.0;
922     // the line is forward into the arc
923     double innerArc = aCenter[1-aLineInd]->decreased(aStart[aLineInd])->dot(aDirLine->xy());
924     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
925     // The possible centers are ranged by their positions.
926     // If the point is not satisfy one of criteria, the weight is decreased with penalty.
927     int aBestWeight = 0;
928     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
929     for (; anIt != aSuspectCenters.end(); anIt++) {
930       int aWeight = 2;
931       aDot = aDirT->xy()->dot(aStart[aLineInd]->decreased(*anIt));
932       aLineTgPoint = (*anIt)->added(aDirT->xy()->multiplied(aDot));
933       // Check the point is placed on the correct arc (penalty if false)
934       if (aCenter[1-aLineInd]->distance(*anIt) * innerArc > anArcRadius * innerArc)
935         aWeight -= 1;
936       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
937           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1-aLineInd])));
938       double aCurAngle = aCurDir->angle(aStartArcDir);
939       if (anArcAngle < 0.0) aCurAngle *= -1.0;
940       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle))
941         continue;
942       if (aWeight > aBestWeight)
943         aBestWeight = aWeight;
944       else if (aWeight < aBestWeight ||
945                aStart[aLineInd]->distance(*anIt) >
946                aStart[aLineInd]->distance(theCenter)) // <-- take closer point
947         continue;
948       // the center is found, stop searching
949       theCenter = *anIt;
950       anArcTgPoint = aCenter[1-aLineInd]->added(aCurDir->xy()->multiplied(anArcRadius));
951       if (theFeatureA->getKind() == SketchPlugin_Line::ID()) {
952         theTangentA = aLineTgPoint;
953         theTangentB = anArcTgPoint;
954       } else {
955         theTangentA = anArcTgPoint;
956         theTangentB = aLineTgPoint;
957       }
958       //return;
959     }
960   } else if (theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
961       theFeatureB->getKind() == SketchPlugin_Arc::ID()) {
962     double anArcRadius[aNbFeatures];
963     double anArcAngle[aNbFeatures];
964     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir[aNbFeatures];
965     for (int i = 0; i < aNbFeatures; i++) {
966       anArcRadius[i] = aStart[i]->distance(aCenter[i]);
967       aStartArcDir[i] = std::shared_ptr<GeomAPI_Dir2d>(
968           new GeomAPI_Dir2d(aStart[i]->decreased(aCenter[i])));
969       std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
970           new GeomAPI_Dir2d(aEnd[i]->decreased(aCenter[i])));
971       anArcAngle[i] = aEndArcDir->angle(aStartArcDir[i]);
972     }
973
974     // get and filter possible centers
975     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
976     possibleFilletCenterArcArc(aCenter[0], anArcRadius[0], aCenter[1],
977                                anArcRadius[1], theRadius, aSuspectCenters);
978     double aDot = 0.0;
979     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
980     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
981     for (; anIt != aSuspectCenters.end(); anIt++) {
982       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
983           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[0])));
984       double aCurAngle = aCurDir->angle(aStartArcDir[0]);
985       if (anArcAngle[0] < 0.0) aCurAngle *= -1.0;
986       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[0]))
987         continue; // incorrect position
988       theTangentA = aCenter[0]->added(aCurDir->xy()->multiplied(anArcRadius[0]));
989
990       aCurDir = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1])));
991       aCurAngle = aCurDir->angle(aStartArcDir[1]);
992       if (anArcAngle[1] < 0.0) aCurAngle *= -1.0;
993       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[1]))
994         continue; // incorrect position
995       theTangentB = aCenter[1]->added(aCurDir->xy()->multiplied(anArcRadius[1]));
996
997       // the center is found, stop searching
998       theCenter = *anIt;
999       return;
1000     }
1001   }
1002 }
1003
1004 void getPointOnEdge(const FeaturePtr theFeature,
1005                     const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
1006                     std::shared_ptr<GeomAPI_Pnt2d>& thePoint) {
1007   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
1008     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1009       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
1010     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1011       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
1012     if(aPntStart->distance(theFilletPoint) > 1.e-7) {
1013       aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1014         theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
1015       aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1016         theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
1017     }
1018     thePoint.reset(
1019       new GeomAPI_Pnt2d(aPntStart->xy()->added(
1020       aPntEnd->xy()->decreased( aPntStart->xy() )->multiplied(1.0 / 3.0) ) ) );
1021   } else {
1022     std::shared_ptr<GeomAPI_Pnt2d> aPntTemp;
1023     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1024       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
1025     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1026       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
1027     if(theFeature->attribute(SketchPlugin_Arc::INVERSED_ID())) {
1028       aPntTemp = aPntStart;
1029       aPntStart = aPntEnd;
1030       aPntEnd = aPntTemp;
1031     }
1032     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1033       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
1034     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
1035     double aStartParameter(0), anEndParameter(0);
1036     aCirc->parameter(aPntStart, paramTolerance, aStartParameter);
1037     aCirc->parameter(aPntEnd, paramTolerance, anEndParameter);
1038     if(aPntStart->distance(theFilletPoint) > tolerance) {
1039       double aTmpParameter = aStartParameter;
1040       aStartParameter = anEndParameter;
1041       anEndParameter = aTmpParameter;
1042     }
1043     double aPntParameter = aStartParameter + (anEndParameter - aStartParameter) / 3.0;
1044     aCirc->D0(aPntParameter, thePoint);
1045   }
1046 }
1047
1048 double getProjectionDistance(const FeaturePtr theFeature,
1049                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint)
1050 {
1051   std::shared_ptr<GeomAPI_Pnt2d> aProjectPnt;
1052   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
1053     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1054       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
1055     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1056       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
1057     std::shared_ptr<GeomAPI_Lin2d> aLin(new GeomAPI_Lin2d(aPntStart, aPntEnd));
1058     aProjectPnt = aLin->project(thePoint);
1059   } else {
1060     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1061       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
1062     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1063       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
1064     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1065       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
1066     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
1067     aProjectPnt = aCirc->project(thePoint);
1068   }
1069   if(aProjectPnt.get()) {
1070     return aProjectPnt->distance(thePoint);
1071   }
1072   return -1;
1073 }
1074
1075 std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence)
1076 {
1077   std::set<FeaturePtr> aCoincides;
1078
1079   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt =
1080     SketchPlugin_Tools::getCoincidencePoint(theConstraintCoincidence);
1081
1082   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
1083                                        SketchPlugin_ConstraintCoincidence::ENTITY_A(),
1084                                        aCoincides);
1085   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
1086                                        SketchPlugin_ConstraintCoincidence::ENTITY_B(),
1087                                        aCoincides);
1088
1089   // Remove points from set of coincides.
1090   std::set<FeaturePtr> aNewSetOfCoincides;
1091   for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
1092     if((*anIt)->getKind() == SketchPlugin_Line::ID()) {
1093       aNewSetOfCoincides.insert(*anIt);
1094     } else if((*anIt)->getKind() == SketchPlugin_Arc::ID()) {
1095       AttributePtr anAttrCenter = (*anIt)->attribute(SketchPlugin_Arc::CENTER_ID());
1096       std::shared_ptr<GeomDataAPI_Point2D> aPointCenter2D =
1097         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrCenter);
1098       if(aPointCenter2D.get() && aFilletPnt->isEqual(aPointCenter2D->pnt())) {
1099         continue;
1100       }
1101       aNewSetOfCoincides.insert(*anIt);
1102     }
1103   }
1104   aCoincides = aNewSetOfCoincides;
1105
1106   // If we still have more than two coincides remove auxilary entities from set of coincides.
1107   if(aCoincides.size() > 2) {
1108     aNewSetOfCoincides.clear();
1109     for(std::set<FeaturePtr>::iterator
1110         anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
1111       if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
1112         aNewSetOfCoincides.insert(*anIt);
1113       }
1114     }
1115     aCoincides = aNewSetOfCoincides;
1116   }
1117
1118   return aCoincides;
1119 }