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