Salome HOME
Merge branch 'Dev_1.5.0' of salome:modules/shaper into Dev_1.5.0
[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_Dir2d.h>
10 #include <GeomAPI_Pnt2d.h>
11 #include <GeomAPI_XY.h>
12 #include <GeomDataAPI_Point2D.h>
13 #include <ModelAPI_AttributeDouble.h>
14 #include <ModelAPI_AttributeRefAttr.h>
15 #include <ModelAPI_AttributeRefList.h>
16 #include <ModelAPI_Data.h>
17 #include <ModelAPI_Events.h>
18 #include <ModelAPI_ResultConstruction.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_Sketch.h>
25 #include <SketchPlugin_ConstraintCoincidence.h>
26 #include <SketchPlugin_ConstraintTangent.h>
27 #include <SketchPlugin_ConstraintRadius.h>
28 #include <SketchPlugin_Tools.h>
29
30 #include <SketcherPrs_Factory.h>
31 #include <SketcherPrs_Tools.h>
32
33 #include <Config_PropManager.h>
34 #include <Events_Loop.h>
35
36 #define _USE_MATH_DEFINES
37 #include <math.h>
38
39 static const std::string PREVIOUS_VALUE("FilletPreviousRadius");
40
41 /// \brief Attract specified point on theNewArc to the attribute of theFeature
42 static void recalculateAttributes(FeaturePtr theNewArc, const std::string& theNewArcAttribute,
43   FeaturePtr theFeature, const std::string& theFeatureAttribute);
44
45 /// \brief Calculates center of fillet arc and coordinates of tangency points
46 static void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
47                                   double theRadius, bool theNotInversed[2],
48                                   std::shared_ptr<GeomAPI_XY>& theCenter,
49                                   std::shared_ptr<GeomAPI_XY>& theTangentA,
50                                   std::shared_ptr<GeomAPI_XY>& theTangentB);
51
52 SketchPlugin_ConstraintFillet::SketchPlugin_ConstraintFillet()
53 {
54 }
55
56 void SketchPlugin_ConstraintFillet::initAttributes()
57 {
58   data()->addAttribute(SketchPlugin_Constraint::VALUE(), ModelAPI_AttributeDouble::typeId());
59   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefAttr::typeId());
60   data()->addAttribute(SketchPlugin_Constraint::ENTITY_B(), ModelAPI_AttributeRefList::typeId());
61   // This attribute used to store base edges
62   data()->addAttribute(SketchPlugin_Constraint::ENTITY_C(), ModelAPI_AttributeRefList::typeId());
63   data()->addAttribute(PREVIOUS_VALUE, ModelAPI_AttributeDouble::typeId());
64   // initialize attribute not applicable for user
65   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_B());
66   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_C());
67   data()->attribute(PREVIOUS_VALUE)->setInitialized();
68   std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(data()->attribute(PREVIOUS_VALUE))->setValue(0.0);
69 }
70
71 void SketchPlugin_ConstraintFillet::execute()
72 {
73   // the viewer update should be blocked in order to avoid the temporaty fillet sub-features visualization
74   // before they are processed by the solver
75   //std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
76   //    new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)));
77   //Events_Loop::loop()->send(aMsg);
78
79   std::shared_ptr<ModelAPI_Data> aData = data();
80   ResultConstructionPtr aRC;
81   // Check the base objects are initialized
82   double aFilletRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
83       aData->attribute(SketchPlugin_Constraint::VALUE()))->value();
84   AttributeRefAttrPtr aBaseA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
85       aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
86   if (!aBaseA->isInitialized() || aBaseA->isObject()) {
87     setError("Bad vertex selected");
88     return;
89   }
90
91   // Check the fillet shapes is not initialized yet
92   AttributeRefListPtr aRefListOfFillet = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
93       aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
94   bool needNewObjects = aRefListOfFillet->size() == 0;
95
96   AttributeRefListPtr aRefListOfBaseLines = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
97       aData->attribute(SketchPlugin_Constraint::ENTITY_C()));
98
99   // Obtain base features
100   FeaturePtr anOldFeatureA, anOldFeatureB;
101   std::list<ObjectPtr> aNewFeatList = aRefListOfBaseLines->list();
102   std::list<ObjectPtr>::iterator aFeatIt = aNewFeatList.begin();
103   anOldFeatureA = ModelAPI_Feature::feature(*aFeatIt++);
104   anOldFeatureB = ModelAPI_Feature::feature(*aFeatIt);
105
106
107   if(!anOldFeatureA.get() || !anOldFeatureB.get()) {
108     setError("One of the edges is empty");
109     return;
110   }
111
112   FeaturePtr aNewFeatureA, aNewFeatureB, aNewArc;
113   if (needNewObjects) {
114     // Create list of objects composing a fillet
115     // copy aFeatureA
116     aNewFeatureA = SketchPlugin_Sketch::addUniqueNamedCopiedFeature(anOldFeatureA, sketch());
117     // copy aFeatureB
118     aNewFeatureB = SketchPlugin_Sketch::addUniqueNamedCopiedFeature(anOldFeatureB, sketch());
119     // create filleting arc (it will be attached to the list later)
120     aNewArc = sketch()->addFeature(SketchPlugin_Arc::ID());
121   } else {
122     // Obtain features from the list
123     std::list<ObjectPtr> aNewFeatList = aRefListOfFillet->list();
124     std::list<ObjectPtr>::iterator aFeatIt = aNewFeatList.begin();
125     aNewFeatureA = ModelAPI_Feature::feature(*aFeatIt++);
126     aNewFeatureB = ModelAPI_Feature::feature(*aFeatIt++);
127     aNewArc = ModelAPI_Feature::feature(*aFeatIt);
128   }
129
130   // Calculate arc attributes
131   static const int aNbFeatures = 2;
132   FeaturePtr aFeature[aNbFeatures] = {anOldFeatureA, anOldFeatureB};
133   FeaturePtr aNewFeature[aNbFeatures] = {aNewFeatureA, aNewFeatureB};
134   std::shared_ptr<GeomAPI_Dir2d> aTangentDir[aNbFeatures]; // tangent directions of the features in coincident point
135   bool isStart[aNbFeatures]; // indicates which point the features share
136   std::shared_ptr<GeomAPI_Pnt2d> aStartEndPnt[aNbFeatures * 2]; // first pair of points relate to first feature, second pair -  to second
137   std::string aFeatAttributes[aNbFeatures * 2]; // attributes of features
138   for (int i = 0; i < aNbFeatures; i++) {
139     std::string aStartAttr, aEndAttr;
140     if (aNewFeature[i]->getKind() == SketchPlugin_Line::ID()) {
141       aStartAttr = SketchPlugin_Line::START_ID();
142       aEndAttr = SketchPlugin_Line::END_ID();
143     } else if (aNewFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
144       aStartAttr = SketchPlugin_Arc::START_ID();
145       aEndAttr = SketchPlugin_Arc::END_ID();
146     } else { // wrong argument
147       aRefListOfFillet->remove(aNewFeatureA);
148       aRefListOfFillet->remove(aNewFeatureB);
149       aRefListOfFillet->remove(aNewArc);
150       aRefListOfBaseLines->clear();
151       return;
152     }
153     aFeatAttributes[2*i] = aStartAttr;
154     aStartEndPnt[2*i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
155         aFeature[i]->attribute(aStartAttr))->pnt();
156     aFeatAttributes[2*i+1] = aEndAttr;
157     aStartEndPnt[2*i+1] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
158         aFeature[i]->attribute(aEndAttr))->pnt();
159   }
160   for (int i = 0; i < aNbFeatures; i++) {
161     int j = aNbFeatures;
162     for (; j < 2 * aNbFeatures; j++)
163       if (aStartEndPnt[i]->distance(aStartEndPnt[j]) < 1.e-10) {
164         isStart[0] = i==0;
165         isStart[1] = j==aNbFeatures;
166         break;
167       }
168     if (j < 2 * aNbFeatures)
169       break;
170   }
171   // tangent directions of the features
172   for (int i = 0; i < aNbFeatures; i++) {
173     std::shared_ptr<GeomAPI_XY> aDir;
174     if (aNewFeature[i]->getKind() == SketchPlugin_Line::ID()) {
175       aDir = aStartEndPnt[2*i+1]->xy()->decreased(aStartEndPnt[2*i]->xy());
176       if (!isStart[i])
177         aDir = aDir->multiplied(-1.0);
178     } else if (aNewFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
179       std::shared_ptr<GeomAPI_Pnt2d> aCenterPoint =
180           std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
181           aNewFeature[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
182       aDir = isStart[i] ? aStartEndPnt[2*i]->xy() : aStartEndPnt[2*i+1]->xy();
183       aDir = aDir->decreased(aCenterPoint->xy());
184
185       double x = aDir->x();
186       double y = aDir->y();
187       aDir->setX(-y);
188       aDir->setY(x);
189       if (!isStart[i])
190         aDir = aDir->multiplied(-1.0);
191     }
192     aTangentDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aDir));
193   }
194
195   // Wait all constraints being created, then send update events
196   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
197   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
198   if (isUpdateFlushed)
199     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
200
201   // By default, the start point of fillet arc is connected to FeatureA,
202   // and the end point - to FeatureB. But when the angle between TangentDirA and
203   // TangentDirB greater 180 degree, the sequaence of features need to be reversed.
204   double cosBA = aTangentDir[0]->cross(aTangentDir[1]); // cos(B-A), where A and B - angles between corresponding tanget direction and the X axis
205   bool isReversed = cosBA > 0.0;
206
207   // Calculate fillet arc parameters
208   std::shared_ptr<GeomAPI_XY> aCenter, aTangentPntA, aTangentPntB;
209   calculateFilletCenter(anOldFeatureA, anOldFeatureB, aFilletRadius, isStart, aCenter, aTangentPntA, aTangentPntB);
210   // update features
211   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
212       aNewFeatureA->attribute(aFeatAttributes[isStart[0] ? 0 : 1]))->setValue(
213       aTangentPntA->x(), aTangentPntA->y());
214   aNewFeatureA->execute();
215   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
216       aNewFeatureB->attribute(aFeatAttributes[2 + (isStart[1] ? 0 : 1)]))->setValue(
217       aTangentPntB->x(), aTangentPntB->y());
218   aNewFeatureB->execute();
219   // update fillet arc: make the arc correct for sure, so, it is not needed to process the "attribute updated"
220   // by arc; moreover, it may cause cyclicity in hte mechanism of updater
221   aNewArc->data()->blockSendAttributeUpdated(true);
222   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
223       aNewArc->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(
224       aCenter->x(), aCenter->y());
225   if (isReversed) {
226     std::shared_ptr<GeomAPI_XY> aTmp = aTangentPntA;
227     aTangentPntA = aTangentPntB;
228     aTangentPntB = aTmp;
229   }
230   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
231       aNewArc->attribute(SketchPlugin_Arc::START_ID()))->setValue(aTangentPntA->x(), aTangentPntA->y());
232   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
233       aNewArc->attribute(SketchPlugin_Arc::END_ID()))->setValue(aTangentPntB->x(), aTangentPntB->y());
234   aNewArc->data()->blockSendAttributeUpdated(false);
235   aNewArc->execute();
236
237   if (needNewObjects) {
238     // attach new arc to the list
239     aRefListOfFillet->append(aNewFeatureA->lastResult());
240     aRefListOfFillet->append(aNewFeatureB->lastResult());
241     aRefListOfFillet->append(aNewArc->lastResult());
242
243     // attach base lines to the list
244     aRefListOfBaseLines->append(anOldFeatureA);
245     aRefListOfBaseLines->append(anOldFeatureB);
246
247     myProducedFeatures.push_back(aNewFeatureA);
248     myProducedFeatures.push_back(aNewFeatureB);
249     myProducedFeatures.push_back(aNewArc);
250
251     // Create list of additional constraints:
252     // 1. Coincidence of boundary points of features (copied lines/arcs) and fillet arc
253     // 1.1. coincidence
254     FeaturePtr aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
255     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
256         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
257     aRefAttr->setAttr(aNewArc->attribute(SketchPlugin_Arc::START_ID()));
258     aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
259         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
260     int aFeatInd = isReversed ? 1 : 0;
261     int anAttrInd = (isReversed ? 2 : 0) + (isStart[isReversed ? 1 : 0] ? 0 : 1);
262     aRefAttr->setAttr(aNewFeature[aFeatInd]->attribute(aFeatAttributes[anAttrInd]));
263     recalculateAttributes(aNewArc, SketchPlugin_Arc::START_ID(), aNewFeature[aFeatInd], aFeatAttributes[anAttrInd]);
264     aConstraint->execute();
265     myProducedFeatures.push_back(aConstraint);
266     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
267     // 1.2. coincidence
268     aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
269     aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
270         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
271     aRefAttr->setAttr(aNewArc->attribute(SketchPlugin_Arc::END_ID()));
272     aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
273         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
274     aFeatInd = isReversed ? 0 : 1;
275     anAttrInd = (isReversed ? 0 : 2) + (isStart[isReversed ? 0 : 1] ? 0 : 1);
276     aRefAttr->setAttr(aNewFeature[aFeatInd]->attribute(aFeatAttributes[anAttrInd]));
277     recalculateAttributes(aNewArc, SketchPlugin_Arc::END_ID(), aNewFeature[aFeatInd], aFeatAttributes[anAttrInd]);
278     aConstraint->execute();
279     myProducedFeatures.push_back(aConstraint);
280     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
281     // 2. Fillet arc radius
282     //aConstraint = sketch()->addFeature(SketchPlugin_ConstraintRadius::ID());
283     //aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
284     //    aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
285     //aRefAttr->setObject(aNewArc->lastResult());
286     //std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
287     //    aConstraint->attribute(SketchPlugin_Constraint::VALUE()))->setValue(aFilletRadius);
288     //std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
289     //    aConstraint->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT()))->setValue(
290     //    isStart[0] ? aStartEndPnt[0] : aStartEndPnt[1]);
291     //aConstraint->execute();
292     //myProducedFeatures.push_back(aConstraint);
293     //ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
294     // 3. Tangency of fillet arc and features
295     for (int i = 0; i < aNbFeatures; i++) {
296       aConstraint = sketch()->addFeature(SketchPlugin_ConstraintTangent::ID());
297       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
298           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
299       aRefAttr->setObject(aNewArc->lastResult());
300       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
301           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
302       bool isArc = aNewFeature[i]->getKind() == SketchPlugin_Arc::ID();
303       aRefAttr->setObject(isArc ? aNewFeature[i]->lastResult() : aNewFeature[i]->firstResult());
304       aConstraint->execute();
305       myProducedFeatures.push_back(aConstraint);
306       ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
307     }
308     // 4. Coincidence of free boundaries of base and copied features
309     for (int i = 0; i < aNbFeatures; i++) {
310       anAttrInd = 2*i + (isStart[i] ? 1 : 0);
311       aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
312       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
313           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
314       aRefAttr->setAttr(aFeature[i]->attribute(aFeatAttributes[anAttrInd]));
315       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
316           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
317       aRefAttr->setAttr(aNewFeature[i]->attribute(aFeatAttributes[anAttrInd]));
318       myProducedFeatures.push_back(aConstraint);
319     }
320     // 5. Tangent points should be placed on the base features
321     for (int i = 0; i < aNbFeatures; i++) {
322       anAttrInd = 2*i + (isStart[i] ? 0 : 1);
323       aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
324       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
325           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
326       aRefAttr->setAttr(aNewFeature[i]->attribute(aFeatAttributes[anAttrInd]));
327       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
328           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
329       aRefAttr->setObject(aFeature[i]->lastResult());
330       myProducedFeatures.push_back(aConstraint);
331     }
332     // make base features auxiliary
333     anOldFeatureA->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(true);
334     anOldFeatureB->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(true);
335     myBaseObjects.clear();
336     myBaseObjects.push_back(anOldFeatureA);
337     myBaseObjects.push_back(anOldFeatureB);
338     // exchange the naming IDs of newly created and old line that become auxiliary
339     sketch()->exchangeIDs(anOldFeatureA, aNewFeatureA);
340     sketch()->exchangeIDs(anOldFeatureB, aNewFeatureB);
341   } else {
342     // Update radius value
343     int aNbSubs = sketch()->numberOfSubs();
344     FeaturePtr aSubFeature;
345     for (int aSub = 0; aSub < aNbSubs; aSub++) {
346       aSubFeature = sketch()->subFeature(aSub);
347       if (aSubFeature->getKind() != SketchPlugin_ConstraintRadius::ID())
348         continue;
349       AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
350           aSubFeature->attribute(SketchPlugin_Constraint::ENTITY_A()));
351       if (!aRefAttr || !aRefAttr->isObject())
352         continue;
353       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
354       if (aFeature == aNewArc) {
355         AttributeDoublePtr aRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
356           aSubFeature->attribute(SketchPlugin_Constraint::VALUE()));
357         aRadius->setValue(aFilletRadius);
358         break;
359       }
360     }
361   }
362
363   // send events to update the sub-features by the solver
364   if (isUpdateFlushed)
365     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
366
367   // the viewer update should be unblocked in order after the fillet features
368   // are processed by the solver
369   //aMsg = std::shared_ptr<Events_Message>(
370   //              new Events_Message(Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)));
371   //Events_Loop::loop()->send(aMsg);
372 }
373
374 void SketchPlugin_ConstraintFillet::attributeChanged(const std::string& theID)
375 {
376   if (theID == SketchPlugin_Constraint::ENTITY_A()) {
377     // clear the list of fillet entities
378     AttributeRefListPtr aRefListOfFillet = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
379         data()->attribute(SketchPlugin_Constraint::ENTITY_B()));
380     aRefListOfFillet->clear();
381
382     // clear the list of base features
383     AttributeRefListPtr aRefListOfBaseLines = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
384         data()->attribute(SketchPlugin_Constraint::ENTITY_C()));
385       aRefListOfBaseLines->clear();
386
387     // remove all produced objects and constraints
388     DocumentPtr aDoc = sketch()->document();
389     std::list<FeaturePtr>::iterator aCIt = myProducedFeatures.begin();
390     for (; aCIt != myProducedFeatures.end(); ++aCIt)
391       aDoc->removeFeature(*aCIt);
392     myProducedFeatures.clear();
393
394     // clear auxiliary flag on initial objects
395     for (aCIt = myBaseObjects.begin(); aCIt != myBaseObjects.end(); ++aCIt)
396       (*aCIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(false);
397     myBaseObjects.clear();
398
399     AttributeRefAttrPtr aBaseA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
400         data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
401     if(!aBaseA->isInitialized() || aBaseA->isObject()) {
402       return;
403     }
404
405     AttributePtr anAttrBase = aBaseA->attr();
406     const std::set<AttributePtr>& aRefsList = anAttrBase->owner()->data()->refsToMe();
407     std::set<AttributePtr>::const_iterator aIt;
408     FeaturePtr aCoincident;
409     for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
410       std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
411       FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
412       if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
413         AttributeRefAttrPtr anAttrRefA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
414           aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_A()));
415         AttributeRefAttrPtr anAttrRefB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
416           aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_B()));
417         if(anAttrRefA.get() && !anAttrRefA->isObject()) {
418           AttributePtr anAttrA = anAttrRefA->attr();
419           if(anAttrBase == anAttrA) {
420             aCoincident = aConstrFeature;
421             break;
422           }
423         }
424         if(anAttrRefA.get() && !anAttrRefB->isObject()) {
425           AttributePtr anAttrB = anAttrRefB->attr();
426           if(anAttrBase == anAttrB) {
427             aCoincident = aConstrFeature;
428             break;
429           }
430         }
431       }
432     }
433
434     if(!aCoincident.get()) {
435       setError("No coincident edges at selected vertex");
436       return;
437     }
438
439     std::set<FeaturePtr> aCoinsideLines;
440     SketchPlugin_Tools::findCoincidences(aCoincident,
441                                          SketchPlugin_ConstraintCoincidence::ENTITY_A(),
442                                          aCoinsideLines);
443     SketchPlugin_Tools::findCoincidences(aCoincident,
444                                          SketchPlugin_ConstraintCoincidence::ENTITY_B(),
445                                          aCoinsideLines);
446
447     // Remove auxilary lines
448     if(aCoinsideLines.size() > 2) {
449       std::set<FeaturePtr> aNewLines;
450       for(std::set<FeaturePtr>::iterator anIt = aCoinsideLines.begin(); anIt != aCoinsideLines.end(); ++anIt) {
451         if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
452           aNewLines.insert(*anIt);
453         }
454       }
455       aCoinsideLines = aNewLines;
456     }
457
458
459     if(aCoinsideLines.size() != 2) {
460       setError("At selected vertex should be two coincident lines");
461       return;
462     }
463
464     FeaturePtr anOldFeatureA, anOldFeatureB;
465     std::set<FeaturePtr>::iterator aLinesIt = aCoinsideLines.begin();
466     anOldFeatureA = *aLinesIt++;
467     anOldFeatureB = *aLinesIt;
468     aRefListOfBaseLines->append(anOldFeatureA);
469     aRefListOfBaseLines->append(anOldFeatureB);
470
471
472     // Set default value equal to 1/3 of the smallest line sharing the point.
473     static const int aNbFeatures = 2;
474     FeaturePtr aFeature[aNbFeatures] = {anOldFeatureA, anOldFeatureB};
475     double aLength = 0;
476
477     double aLengths[aNbFeatures];
478     for (int i = 0; i < aNbFeatures; i++) {
479       std::shared_ptr<GeomAPI_Pnt2d> aStartPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aFeature[i]->attribute(
480         aFeature[i]->getKind() == SketchPlugin_Line::ID() ? SketchPlugin_Line::START_ID() : SketchPlugin_Arc::START_ID()))->pnt();
481       std::shared_ptr<GeomAPI_Pnt2d> anEndPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aFeature[i]->attribute(
482         aFeature[i]->getKind() == SketchPlugin_Line::ID() ? SketchPlugin_Line::END_ID() : SketchPlugin_Arc::END_ID()))->pnt();
483       if(aFeature[i]->getKind() == SketchPlugin_Line::ID()) {
484         aLengths[i] = aStartPnt->distance(anEndPnt);
485       } else {
486         std::shared_ptr<GeomAPI_Pnt2d> anArcCenter = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aFeature[i]->attribute(
487           SketchPlugin_Arc::CENTER_ID()))->pnt();
488         std::shared_ptr<GeomAPI_Dir2d> aStartDir(new GeomAPI_Dir2d(aStartPnt->xy()->decreased(anArcCenter->xy())));
489         std::shared_ptr<GeomAPI_Dir2d> anEndDir(new GeomAPI_Dir2d(anEndPnt->xy()->decreased(anArcCenter->xy())));
490         double aRadius = aStartPnt->distance(anArcCenter);
491         double anAngle = aStartDir->angle(anEndDir);
492         aLengths[i] = aRadius * abs(anAngle);
493       }
494     }
495     aLength = aLengths[0];
496     for(int i = 1; i < aNbFeatures; i++) {
497       if(aLengths[i] < aLength) aLength = aLengths[i];
498     }
499     std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(data()->attribute(SketchPlugin_Constraint::VALUE()))->setValue(aLength / 3.0);
500   }
501 }
502
503 AISObjectPtr SketchPlugin_ConstraintFillet::getAISObject(AISObjectPtr thePrevious)
504 {
505   if (!sketch())
506     return thePrevious;
507
508   AISObjectPtr anAIS = thePrevious;
509   /// TODO: Equal constraint presentation should be put here
510   return anAIS;
511 }
512
513 bool SketchPlugin_ConstraintFillet::isMacro() const
514 {
515   return true;
516 }
517
518
519 // =========   Auxiliary functions   =================
520 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
521                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
522 {
523   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
524       theNewArc->attribute(theNewArcAttribute))->pnt();
525   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
526       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
527 }
528
529 /// \brief Find intersections of lines shifted along normal direction
530 void possibleFilletCenterLineLine(
531     std::shared_ptr<GeomAPI_XY> thePointA, std::shared_ptr<GeomAPI_Dir2d> theDirA,
532     std::shared_ptr<GeomAPI_XY> thePointB, std::shared_ptr<GeomAPI_Dir2d> theDirB,
533     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
534 {
535   std::shared_ptr<GeomAPI_Dir2d> aDirAT(new GeomAPI_Dir2d(-theDirA->y(), theDirA->x()));
536   std::shared_ptr<GeomAPI_Dir2d> aDirBT(new GeomAPI_Dir2d(-theDirB->y(), theDirB->x()));
537   std::shared_ptr<GeomAPI_XY> aPntA, aPntB;
538   double aDet = theDirA->cross(theDirB);
539   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
540     aPntA = thePointA->added(aDirAT->xy()->multiplied(aStepA * theRadius));
541     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
542       aPntB = thePointB->added(aDirBT->xy()->multiplied(aStepB * theRadius));
543       double aVX = aDirAT->xy()->dot(aPntA);
544       double aVY = aDirBT->xy()->dot(aPntB);
545       std::shared_ptr<GeomAPI_XY> aPoint(new GeomAPI_XY(
546           (theDirB->x() * aVX - theDirA->x() * aVY) / aDet,
547           (theDirB->y() * aVX - theDirA->y() * aVY) / aDet));
548       theCenters.push_back(aPoint);
549     }
550   }
551 }
552
553 /// \brief Find intersections of line shifted along normal direction in both sides
554 ///        and a circle with extended radius
555 void possibleFilletCenterLineArc(
556     std::shared_ptr<GeomAPI_XY> theStartLine, std::shared_ptr<GeomAPI_Dir2d> theDirLine,
557     std::shared_ptr<GeomAPI_XY> theCenterArc, double theRadiusArc,
558     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
559 {
560   std::shared_ptr<GeomAPI_Dir2d> aDirT(new GeomAPI_Dir2d(-theDirLine->y(), theDirLine->x()));
561   std::shared_ptr<GeomAPI_XY> aPnt;
562   double aDirNorm2 = theDirLine->dot(theDirLine);
563   double aRad = 0.0;
564   double aDirX = theDirLine->x();
565   double aDirX2 = theDirLine->x() * theDirLine->x();
566   double aDirY2 = theDirLine->y() * theDirLine->y();
567   double aDirXY = theDirLine->x() * theDirLine->y();
568   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
569     aPnt = theStartLine->added(aDirT->xy()->multiplied(aStepA * theRadius));
570     double aCoeff = aDirT->xy()->dot(aPnt->decreased(theCenterArc));
571     double aCoeff2 = aCoeff * aCoeff;
572     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
573       aRad = theRadiusArc + aStepB * theRadius;
574       double aD = aRad * aRad * aDirNorm2 - aCoeff2;
575       if (aD < 0.0)
576         continue;
577       double aDs = sqrt(aD);
578       double x1 = theCenterArc->x() + (aCoeff * aDirT->x() - aDirT->y() * aDs) / aDirNorm2;
579       double x2 = theCenterArc->x() + (aCoeff * aDirT->x() + aDirT->y() * aDs) / aDirNorm2;
580       double y1 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
581           aDirXY * (aPnt->x() - theCenterArc->x()) - theDirLine->y() * aDs) / aDirNorm2;
582       double y2 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
583           aDirXY * (aPnt->x() - theCenterArc->x()) + theDirLine->y() * aDs) / aDirNorm2;
584
585       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
586       theCenters.push_back(aPoint1);
587       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
588       theCenters.push_back(aPoint2);
589     }
590   }
591 }
592
593 /// \brief Find intersections of two circles with extended radii
594 void possibleFilletCenterArcArc(
595     std::shared_ptr<GeomAPI_XY> theCenterA, double theRadiusA,
596     std::shared_ptr<GeomAPI_XY> theCenterB, double theRadiusB,
597     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
598 {
599   std::shared_ptr<GeomAPI_XY> aCenterDir = theCenterB->decreased(theCenterA);
600   double aCenterDist2 = aCenterDir->dot(aCenterDir);
601   double aCenterDist = sqrt(aCenterDist2);
602
603   double aRadA, aRadB;
604   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
605     aRadA = theRadiusA + aStepA * theRadius;
606     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
607       aRadB = theRadiusB + aStepB * theRadius;
608       if (aRadA + aRadB < aCenterDist || fabs(aRadA - aRadB) > aCenterDist)
609         continue; // there is no intersections
610
611       double aMedDist = (aRadA * aRadA - aRadB * aRadB + aCenterDist2) / (2.0 * aCenterDist);
612       double aHeight = sqrt(aRadA * aRadA - aMedDist * aMedDist);
613
614       double x1 = theCenterA->x() + (aMedDist * aCenterDir->x() + aCenterDir->y() * aHeight) / aCenterDist;
615       double y1 = theCenterA->y() + (aMedDist * aCenterDir->y() - aCenterDir->x() * aHeight) / aCenterDist;
616
617       double x2 = theCenterA->x() + (aMedDist * aCenterDir->x() - aCenterDir->y() * aHeight) / aCenterDist;
618       double y2 = theCenterA->y() + (aMedDist * aCenterDir->y() + aCenterDir->x() * aHeight) / aCenterDist;
619
620       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
621       theCenters.push_back(aPoint1);
622       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
623       theCenters.push_back(aPoint2);
624     }
625   }
626 }
627
628 void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
629                            double theRadius, bool theNotInversed[2],
630                            std::shared_ptr<GeomAPI_XY>& theCenter,
631                            std::shared_ptr<GeomAPI_XY>& theTangentA,
632                            std::shared_ptr<GeomAPI_XY>& theTangentB)
633 {
634   static const int aNbFeatures = 2;
635   FeaturePtr aFeature[aNbFeatures] = {theFeatureA, theFeatureB};
636   std::shared_ptr<GeomAPI_XY> aStart[aNbFeatures], aEnd[aNbFeatures], aCenter[aNbFeatures];
637   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, aEndPoint;
638
639   for (int i = 0; i < aNbFeatures; i++) {
640     if (aFeature[i]->getKind() == SketchPlugin_Line::ID()) {
641       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
642           aFeature[i]->attribute(SketchPlugin_Line::START_ID()));
643       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
644           aFeature[i]->attribute(SketchPlugin_Line::END_ID()));
645     } else if (aFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
646       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
647           aFeature[i]->attribute(SketchPlugin_Arc::START_ID()));
648       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
649           aFeature[i]->attribute(SketchPlugin_Arc::END_ID()));
650       aCenter[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
651           aFeature[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt()->xy();
652     } else
653       return;
654     aStart[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
655         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()) :
656         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()));
657     aEnd[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
658         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()) :
659         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()));
660   }
661
662   if (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
663       theFeatureB->getKind() == SketchPlugin_Line::ID()) {
664     std::shared_ptr<GeomAPI_Dir2d> aDir[2];
665     std::shared_ptr<GeomAPI_Dir2d> aDirT[2];
666     for (int i = 0; i < aNbFeatures; i++) {
667       aDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aEnd[i]->decreased(aStart[i])));
668       aDirT[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(-aDir[i]->y(), aDir[i]->x()));
669     }
670
671     // get and filter possible centers
672     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
673     possibleFilletCenterLineLine(aStart[0], aDir[0], aStart[1], aDir[1], theRadius, aSuspectCenters);
674     double aDot = 0.0;
675     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
676     for (; anIt != aSuspectCenters.end(); anIt++) {
677       aDot = aDirT[0]->xy()->dot(aStart[0]->decreased(*anIt));
678       theTangentA = (*anIt)->added(aDirT[0]->xy()->multiplied(aDot));
679       if (theTangentA->decreased(aStart[0])->dot(aDir[0]->xy()) < 0.0)
680         continue; // incorrect position
681       aDot = aDirT[1]->xy()->dot(aStart[1]->decreased(*anIt));
682       theTangentB = (*anIt)->added(aDirT[1]->xy()->multiplied(aDot));
683       if (theTangentB->decreased(aStart[1])->dot(aDir[1]->xy()) < 0.0)
684         continue; // incorrect position
685       // the center is found, stop searching
686       theCenter = *anIt;
687       return;
688     }
689   } else if ((theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
690       theFeatureB->getKind() == SketchPlugin_Line::ID()) || 
691       (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
692       theFeatureB->getKind() == SketchPlugin_Arc::ID())) {
693     int aLineInd = theFeatureA->getKind() == SketchPlugin_Line::ID() ? 0 : 1;
694     double anArcRadius = aStart[1-aLineInd]->distance(aCenter[1-aLineInd]);
695     std::shared_ptr<GeomAPI_Dir2d> aDirLine = std::shared_ptr<GeomAPI_Dir2d>(
696         new GeomAPI_Dir2d(aEnd[aLineInd]->decreased(aStart[aLineInd])));
697     std::shared_ptr<GeomAPI_Dir2d> aDirT = std::shared_ptr<GeomAPI_Dir2d>(
698         new GeomAPI_Dir2d(-aDirLine->y(), aDirLine->x()));
699
700     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir = std::shared_ptr<GeomAPI_Dir2d>(
701         new GeomAPI_Dir2d(aStart[1-aLineInd]->decreased(aCenter[1-aLineInd])));
702     std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
703         new GeomAPI_Dir2d(aEnd[1-aLineInd]->decreased(aCenter[1-aLineInd])));
704     double anArcAngle = aEndArcDir->angle(aStartArcDir);
705
706     // get and filter possible centers
707     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
708     possibleFilletCenterLineArc(aStart[aLineInd], aDirLine, aCenter[1-aLineInd], anArcRadius, theRadius, aSuspectCenters);
709     double aDot = 0.0;
710     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
711     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
712     for (; anIt != aSuspectCenters.end(); anIt++) {
713       aDot = aDirT->xy()->dot(aStart[aLineInd]->decreased(*anIt));
714       aLineTgPoint = (*anIt)->added(aDirT->xy()->multiplied(aDot));
715       if (aLineTgPoint->decreased(aStart[aLineInd])->dot(aDirLine->xy()) < 0.0)
716         continue; // incorrect position
717       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
718           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1-aLineInd])));
719       double aCurAngle = aCurDir->angle(aStartArcDir);
720       if (anArcAngle < 0.0) aCurAngle *= -1.0;
721       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle))
722         continue; // incorrect position
723       // the center is found, stop searching
724       theCenter = *anIt;
725       anArcTgPoint = aCenter[1-aLineInd]->added(aCurDir->xy()->multiplied(anArcRadius));
726       if (theFeatureA->getKind() == SketchPlugin_Line::ID()) {
727         theTangentA = aLineTgPoint;
728         theTangentB = anArcTgPoint;
729       } else {
730         theTangentA = anArcTgPoint;
731         theTangentB = aLineTgPoint;
732       }
733       return;
734     }
735   } else if (theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
736       theFeatureB->getKind() == SketchPlugin_Arc::ID()) {
737     double anArcRadius[aNbFeatures];
738     double anArcAngle[aNbFeatures];
739     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir[aNbFeatures];
740     for (int i = 0; i < aNbFeatures; i++) {
741       anArcRadius[i] = aStart[i]->distance(aCenter[i]);
742       aStartArcDir[i] = std::shared_ptr<GeomAPI_Dir2d>(
743           new GeomAPI_Dir2d(aStart[i]->decreased(aCenter[i])));
744       std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
745           new GeomAPI_Dir2d(aEnd[i]->decreased(aCenter[i])));
746       anArcAngle[i] = aEndArcDir->angle(aStartArcDir[i]);
747     }
748
749     // get and filter possible centers
750     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
751     possibleFilletCenterArcArc(aCenter[0], anArcRadius[0], aCenter[1], anArcRadius[1], theRadius, aSuspectCenters);
752     double aDot = 0.0;
753     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
754     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
755     for (; anIt != aSuspectCenters.end(); anIt++) {
756       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
757           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[0])));
758       double aCurAngle = aCurDir->angle(aStartArcDir[0]);
759       if (anArcAngle[0] < 0.0) aCurAngle *= -1.0;
760       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[0]))
761         continue; // incorrect position
762       theTangentA = aCenter[0]->added(aCurDir->xy()->multiplied(anArcRadius[0]));
763
764       aCurDir = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1])));
765       aCurAngle = aCurDir->angle(aStartArcDir[1]);
766       if (anArcAngle[1] < 0.0) aCurAngle *= -1.0;
767       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[1]))
768         continue; // incorrect position
769       theTangentB = aCenter[1]->added(aCurDir->xy()->multiplied(anArcRadius[1]));
770
771       // the center is found, stop searching
772       theCenter = *anIt;
773       return;
774     }
775   }
776 }