]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_Group.cpp
Salome HOME
67b9d31ddee87f6c679f365c4a3f118192b391b3
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SketchSolver_Group.cpp
4 // Created: 27 May 2014
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchSolver_Group.h"
8
9 #include <SketchSolver_Builder.h>
10 #include <SketchSolver_Constraint.h>
11 #include <SketchSolver_ConstraintCoincidence.h>
12 #include <SketchSolver_ConstraintMulti.h>
13 #include <SketchSolver_Error.h>
14
15 #include <Events_Error.h>
16 #include <Events_Loop.h>
17 #include <GeomAPI_XY.h>
18 #include <GeomAPI_Dir2d.h>
19 #include <GeomAPI_Pnt2d.h>
20 #include <GeomDataAPI_Dir.h>
21 #include <GeomDataAPI_Point.h>
22 #include <GeomDataAPI_Point2D.h>
23 #include <ModelAPI_AttributeDouble.h>
24 #include <ModelAPI_AttributeString.h>
25 #include <ModelAPI_Document.h>
26 #include <ModelAPI_Events.h>
27 #include <ModelAPI_ResultConstruction.h>
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_Validator.h>
30
31 #include <SketchPlugin_Constraint.h>
32 #include <SketchPlugin_ConstraintAngle.h>
33 #include <SketchPlugin_ConstraintCoincidence.h>
34 #include <SketchPlugin_ConstraintDistance.h>
35 #include <SketchPlugin_ConstraintEqual.h>
36 #include <SketchPlugin_ConstraintHorizontal.h>
37 #include <SketchPlugin_ConstraintLength.h>
38 #include <SketchPlugin_ConstraintFillet.h>
39 #include <SketchPlugin_ConstraintMirror.h>
40 #include <SketchPlugin_ConstraintParallel.h>
41 #include <SketchPlugin_ConstraintPerpendicular.h>
42 #include <SketchPlugin_ConstraintRadius.h>
43 #include <SketchPlugin_ConstraintRigid.h>
44 #include <SketchPlugin_ConstraintTangent.h>
45 #include <SketchPlugin_ConstraintVertical.h>
46 #include <SketchPlugin_Feature.h>
47 #include <SketchPlugin_MultiRotation.h>
48 #include <SketchPlugin_MultiTranslation.h>
49 #include <SketchPlugin_Sketch.h>
50
51 #include <SketchPlugin_Arc.h>
52 #include <SketchPlugin_Circle.h>
53 #include <SketchPlugin_Line.h>
54 #include <SketchPlugin_Point.h>
55 #include <SketchPlugin_Sketch.h>
56
57 #include <math.h>
58 #include <assert.h>
59
60
61 /// \brief This class is used to give unique index to the groups
62 class GroupIndexer
63 {
64 public:
65   /// \brief Return vacant index
66   static Slvs_hGroup NEW_GROUP() { return ++myGroupIndex; }
67   /// \brief Removes the index
68   static void REMOVE_GROUP(const Slvs_hGroup& theIndex) {
69     if (myGroupIndex == theIndex)
70       myGroupIndex--;
71   }
72
73 private:
74   GroupIndexer() {};
75
76   static Slvs_hGroup myGroupIndex; ///< index of the group
77 };
78
79 Slvs_hGroup GroupIndexer::myGroupIndex = SLVS_G_OUTOFGROUP;
80
81
82 static void sendMessage(const char* theMessageName)
83 {
84   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
85       new Events_Message(Events_Loop::eventByName(theMessageName)));
86   Events_Loop::loop()->send(aMessage);
87 }
88
89
90
91 // ========================================================
92 // =========  SketchSolver_Group  ===============
93 // ========================================================
94
95 SketchSolver_Group::SketchSolver_Group(
96     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
97     : myID(GroupIndexer::NEW_GROUP()),
98       myPrevSolved(true)
99 {
100   // Initialize workplane
101   myWorkplaneID = SLVS_E_UNKNOWN;
102 #ifndef NDEBUG
103   assert(addWorkplane(theWorkplane));
104 #else
105   addWorkplane(theWorkplane);
106 #endif
107 }
108
109 SketchSolver_Group::~SketchSolver_Group()
110 {
111   myConstraints.clear();
112   GroupIndexer::REMOVE_GROUP(myID);
113 }
114
115 // ============================================================================
116 //  Function: isBaseWorkplane
117 //  Class:    SketchSolver_Group
118 //  Purpose:  verify the group is based on the given workplane
119 // ============================================================================
120 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
121 {
122   return theWorkplane == mySketch;
123 }
124
125 // ============================================================================
126 //  Function: isInteract
127 //  Class:    SketchSolver_Group
128 //  Purpose:  verify are there any entities in the group used by given constraint
129 // ============================================================================
130 bool SketchSolver_Group::isInteract(
131     std::shared_ptr<SketchPlugin_Feature> theFeature) const
132 {
133   // Empty group interacts with everything
134   if (isEmpty()) return true;
135   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
136   if (aConstraint)
137     return myFeatureStorage->isInteract(aConstraint);
138   return myFeatureStorage->isInteract(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
139 }
140
141 // ============================================================================
142 //  Function: getFeatureId
143 //  Class:    SketchSolver_Group
144 //  Purpose:  Find the identifier of the feature, if it already exists in the group
145 // ============================================================================
146 Slvs_hEntity SketchSolver_Group::getFeatureId(FeaturePtr theFeature) const
147 {
148   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
149   if (!myFeatureStorage)
150     return aResult;
151   // Obtain regular constraints interacting with the feature and find its ID
152   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
153   for (; aCIter != myConstraints.end(); ++aCIter) {
154     aResult = aCIter->second->getId(theFeature);
155     if (aResult != SLVS_E_UNKNOWN)
156       return aResult;
157   }
158   // The feature is not found, check it in the temporary constraints
159   std::set<SolverConstraintPtr>::iterator aTmpCIter = myTempConstraints.begin();
160   for (; aTmpCIter != myTempConstraints.end() && aResult == SLVS_E_UNKNOWN; ++aTmpCIter)
161     aResult = (*aTmpCIter)->getId(theFeature);
162   return aResult;
163 }
164
165 // ============================================================================
166 //  Function: getAttributeId
167 //  Class:    SketchSolver_Group
168 //  Purpose:  Find the identifier of the attribute, if it already exists in the group
169 // ============================================================================
170 Slvs_hEntity SketchSolver_Group::getAttributeId(AttributePtr theAttribute) const
171 {
172   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
173   if (!myFeatureStorage)
174     return aResult;
175   // Obtain regular constraints interacting with the attribute and find its ID
176   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
177   for (; aCIter != myConstraints.end(); ++aCIter) {
178     aResult = aCIter->second->getId(theAttribute);
179     if (aResult != SLVS_E_UNKNOWN)
180       return aResult;
181   }
182   // The attribute is not found, check it in the temporary constraints
183   std::set<SolverConstraintPtr>::const_iterator aTmpCIter = myTempConstraints.begin();
184   for (; aTmpCIter != myTempConstraints.end() && aResult == SLVS_E_UNKNOWN; ++aTmpCIter)
185     aResult = (*aTmpCIter)->getId(theAttribute);
186   // Last chance to find attribute in parametric constraints
187   std::map<AttributePtr, SolverConstraintPtr>::const_iterator aParIter =
188       myParametricConstraints.find(theAttribute);
189   if (aParIter != myParametricConstraints.end())
190     aResult = aParIter->second->getId(theAttribute);
191   return aResult;
192 }
193
194 // ============================================================================
195 //  Function: changeConstraint
196 //  Class:    SketchSolver_Group
197 //  Purpose:  create/update the constraint in the group
198 // ============================================================================
199 bool SketchSolver_Group::changeConstraint(
200     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
201 {
202   // There is no workplane yet, something wrong
203   if (myWorkplaneID == SLVS_E_UNKNOWN)
204     return false;
205
206   if (!theConstraint || !theConstraint->data())
207     return false;
208
209   if (!checkFeatureValidity(theConstraint))
210     return false;
211
212   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
213   if (isNewConstraint) {
214     // Add constraint to the current group
215     SolverConstraintPtr aConstraint =
216         SketchSolver_Builder::getInstance()->createConstraint(theConstraint);
217     if (!aConstraint)
218       return false;
219     aConstraint->setGroup(this);
220     aConstraint->setStorage(myStorage);
221     if (!aConstraint->error().empty()) {
222       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
223         return false; // some attribute are not initialized yet, don't show message
224       Events_Error::send(aConstraint->error(), this);
225     }
226
227     // Additional verification of coincidence of several points
228     if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
229       bool hasMultiCoincidence = false;
230       ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
231       for (; aCIter != myConstraints.end(); ++aCIter) {
232         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoincidence =
233           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aCIter->second);
234         if (!aCoincidence)
235           continue;
236         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoinc2 =
237           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aConstraint);
238         if (aCoincidence != aCoinc2 && aCoincidence->isCoincide(aCoinc2)) {
239           aCoinc2->attach(aCoincidence);
240           // update other coincidences
241           ConstraintConstraintMap::iterator anIt = aCIter;
242           for (++anIt; anIt != myConstraints.end(); ++anIt)
243             if (anIt->second == aCIter->second)
244               anIt->second = aCoinc2;
245           aCIter->second = aCoinc2;
246           hasMultiCoincidence = true;
247         }
248       }
249
250       if (hasMultiCoincidence)
251         notifyMultiConstraints();
252     }
253     myConstraints[theConstraint] = aConstraint;
254   }
255   else
256     myConstraints[theConstraint]->update();
257
258   // Fix base features for fillet
259   if (isNewConstraint && theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
260     std::list<AttributePtr> anAttrList =
261         theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
262     std::list<AttributePtr>::iterator anAttrIter = anAttrList.begin();
263     for (; anAttrIter != anAttrList.end(); anAttrIter++) {
264       AttributeRefAttrPtr aRefAttr =
265           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
266       if (!aRefAttr || !aRefAttr->isObject())
267         continue;
268       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
269       SolverConstraintPtr aConstraint =
270           SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
271       if (!aConstraint)
272         continue;
273       aConstraint->setGroup(this);
274       aConstraint->setStorage(myStorage);
275       setTemporary(aConstraint);
276     }
277   }
278   // Fix mirror line
279   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
280     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
281         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
282     if (aRefAttr && aRefAttr->isObject()) {
283       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
284       if (aFeature) {
285         SolverConstraintPtr aConstraint =
286             SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
287         if (aConstraint) {
288           aConstraint->setGroup(this);
289           aConstraint->setStorage(myStorage);
290           setTemporary(aConstraint);
291         }
292       }
293     }
294   }
295
296   if (!myFeatureStorage)
297     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
298   myFeatureStorage->changeConstraint(theConstraint);
299
300   // Check the attributes of constraint are given by parametric expression
301   std::list<AttributePtr> anAttributes =
302       theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
303   std::list<AttributePtr>::iterator anAttrIt = anAttributes.begin();
304   for (; anAttrIt != anAttributes.end(); ++anAttrIt) {
305     AttributeRefAttrPtr aRefAttr =
306         std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIt);
307     if (!aRefAttr || aRefAttr->isObject())
308       continue;
309     std::shared_ptr<GeomDataAPI_Point2D> aPoint =
310         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aRefAttr->attr());
311     if (!aPoint || (aPoint->textX().empty() && aPoint->textY().empty()))
312       continue;
313
314     std::map<AttributePtr, SolverConstraintPtr>::iterator aFound =
315         myParametricConstraints.find(aRefAttr->attr());
316     if (aFound == myParametricConstraints.end()) {
317       SolverConstraintPtr aConstraint =
318           SketchSolver_Builder::getInstance()->createParametricConstraint(aRefAttr->attr());
319       if (!aConstraint)
320         continue;
321       aConstraint->setGroup(this);
322       aConstraint->setStorage(myStorage);
323       myParametricConstraints[aRefAttr->attr()] = aConstraint;
324     } else
325       aFound->second->update();
326   }
327
328   return true;
329 }
330
331
332 void SketchSolver_Group::updateConstraints()
333 {
334   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
335
336   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
337   for (; anIt != myConstraints.end(); ++anIt) {
338     if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
339       continue;
340     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
341         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
342       aPostponed.insert(anIt->second);
343     else
344       anIt->second->update();
345   }
346
347   // Update postponed constraints
348   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
349   for (; aSCIter != aPostponed.end(); ++aSCIter)
350     (*aSCIter)->update();
351
352   myChangedConstraints.clear();
353 }
354
355 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
356 {
357   if (!checkFeatureValidity(theFeature))
358     return false;
359
360   std::set<ConstraintPtr> aConstraints =
361       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
362   if (aConstraints.empty())
363     return false;
364   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
365   for (; aCIter != aConstraints.end(); aCIter++) {
366     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
367     if (aSolConIter == myConstraints.end() || !aSolConIter->first->data() ||
368         !aSolConIter->first->data()->isValid())
369       continue;
370     myFeatureStorage->changeFeature(theFeature, aSolConIter->first);
371
372     aSolConIter->second->addFeature(theFeature);
373     myChangedConstraints.insert(aSolConIter->first);
374   }
375
376   // Search attributes of the feature in the set of parametric constraints and update them
377   std::list<AttributePtr> anAttrList =
378       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
379   std::list<AttributePtr>::iterator anAttrIt = anAttrList.begin();
380   for (; anAttrIt != anAttrList.end(); ++anAttrIt) {
381     std::map<AttributePtr, SolverConstraintPtr>::iterator aFound =
382         myParametricConstraints.find(*anAttrIt);
383     if (aFound != myParametricConstraints.end())
384       aFound->second->update();
385     else {
386       std::shared_ptr<GeomDataAPI_Point2D> aPoint =
387           std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anAttrIt);
388       if (aPoint && (!aPoint->textX().empty() || !aPoint->textY().empty())) {
389         // Create new parametric constraint
390         SolverConstraintPtr aConstraint =
391             SketchSolver_Builder::getInstance()->createParametricConstraint(*anAttrIt);
392         if (!aConstraint)
393           continue;
394         aConstraint->setGroup(this);
395         aConstraint->setStorage(myStorage);
396         myParametricConstraints[*anAttrIt] = aConstraint;
397       }
398     }
399   }
400   return true;
401 }
402
403 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
404 {
405   // Firstly, create temporary rigid constraint
406   SolverConstraintPtr aConstraint =
407       SketchSolver_Builder::getInstance()->createMovementConstraint(theFeature);
408   if (!aConstraint)
409     return;
410   aConstraint->setGroup(this);
411   aConstraint->setStorage(myStorage);
412   if (aConstraint->error().empty())
413     setTemporary(aConstraint);
414   // Secondly, update the feature
415   updateFeature(theFeature);
416 }
417
418 // ============================================================================
419 //  Function: fixFeaturesList
420 //  Class:    SketchSolver_Group
421 //  Purpose:  Apply temporary rigid constraints for the list of features
422 // ============================================================================
423 void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
424 {
425   std::list<ObjectPtr> aList = theList->list();
426   std::list<ObjectPtr>::iterator anIt = aList.begin();
427   std::list<FeaturePtr> aFeatures;
428   // Sort features, at begining there are features used by Equal constraint
429   for (; anIt != aList.end(); anIt++) {
430     if (!(*anIt))
431       continue;
432     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
433     std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(aFeature);
434     std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
435     for (; aCIter != aConstraints.end(); aCIter++)
436       if ((*aCIter)->getKind() == SketchPlugin_ConstraintEqual::ID())
437         break;
438     if (aCIter != aConstraints.end())
439       aFeatures.push_front(aFeature);
440     else
441       aFeatures.push_back(aFeature);
442   }
443
444   std::list<FeaturePtr>::iterator aFeatIter = aFeatures.begin();
445   for (; aFeatIter != aFeatures.end(); aFeatIter++) {
446     SolverConstraintPtr aConstraint =
447         SketchSolver_Builder::getInstance()->createRigidConstraint(*aFeatIter);
448     if (!aConstraint)
449       continue;
450     aConstraint->setGroup(this);
451     aConstraint->setStorage(myStorage);
452     setTemporary(aConstraint);
453   }
454 }
455
456 // ============================================================================
457 //  Function: addWorkplane
458 //  Class:    SketchSolver_Group
459 //  Purpose:  create workplane for the group
460 // ============================================================================
461 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
462 {
463   if (myWorkplaneID != SLVS_E_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
464     return false;  // the workplane already exists or the function parameter is not Sketch
465
466   mySketch = theSketch;
467   updateWorkplane();
468   return true;
469 }
470
471 // ============================================================================
472 //  Function: updateWorkplane
473 //  Class:    SketchSolver_Group
474 //  Purpose:  update parameters of workplane
475 // ============================================================================
476 bool SketchSolver_Group::updateWorkplane()
477 {
478   if (!myStorage) // Create storage if not exists
479     myStorage = StoragePtr(new SketchSolver_Storage);
480   SketchSolver_Builder* aBuilder = SketchSolver_Builder::getInstance();
481
482   std::vector<Slvs_Entity> anEntities;
483   std::vector<Slvs_Param> aParams;
484   if (!aBuilder->createWorkplane(mySketch, anEntities, aParams))
485     return false;
486
487   if (myWorkplaneID == SLVS_E_UNKNOWN) {
488     myWorkplaneID = anEntities.back().h;
489     // Add new workplane elements
490     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
491     for (; aParIter != aParams.end(); aParIter++) {
492       aParIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
493       aParIter->group = SLVS_G_OUTOFGROUP;
494       aParIter->h = myStorage->addParameter(*aParIter);
495     }
496     std::vector<Slvs_Entity>::iterator anEntIter = anEntities.begin();
497     for (; anEntIter != anEntities.end(); anEntIter++) {
498       anEntIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
499       anEntIter->group = SLVS_G_OUTOFGROUP;
500       anEntIter->wrkpl = myWorkplaneID;
501       for (int i = 0; i < 4; i++)
502         if (anEntIter->param[i] != SLVS_E_UNKNOWN)
503           anEntIter->param[i] = aParams[anEntIter->param[i]-1].h;
504       for (int i = 0; i < 4; i++)
505         if (anEntIter->point[i] != SLVS_E_UNKNOWN)
506           anEntIter->point[i] = anEntities[anEntIter->point[i]-1].h;
507       anEntIter->h = myStorage->addEntity(*anEntIter);
508     }
509   } else {
510     // Update existent workplane
511     const Slvs_Entity& aWP = myStorage->getEntity(myWorkplaneID);
512     const Slvs_Entity& anOrigin = myStorage->getEntity(aWP.point[0]);
513     const Slvs_Entity& aNormal = myStorage->getEntity(aWP.normal);
514     // Get parameters and update them
515     Slvs_hParam aWPParams[7] = {
516         anOrigin.param[0], anOrigin.param[1], anOrigin.param[2],
517         aNormal.param[0], aNormal.param[1], aNormal.param[2], aNormal.param[3]
518       };
519     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
520     for (int i = 0; aParIter != aParams.end(); aParIter++, i++) {
521       Slvs_Param aParam = myStorage->getParameter(aWPParams[i]);
522       aParam.val = aParIter->val;
523       myStorage->updateParameter(aParam);
524     }
525   }
526   return myWorkplaneID > 0;
527 }
528
529 // ============================================================================
530 //  Function: resolveConstraints
531 //  Class:    SketchSolver_Group
532 //  Purpose:  solve the set of constraints for the current group
533 // ============================================================================
534 bool SketchSolver_Group::resolveConstraints()
535 {
536   if (!myChangedConstraints.empty())
537     updateConstraints();
538
539   bool aResolved = false;
540   if (myStorage->isNeedToResolve() && !isEmpty()) {
541     myConstrSolver.setGroupID(myID);
542     myConstrSolver.calculateFailedConstraints(false);
543     myStorage->initializeSolver(myConstrSolver);
544
545     int aResult = SLVS_RESULT_OKAY;
546     try {
547       if (myStorage->hasDuplicatedConstraint())
548         aResult = SLVS_RESULT_INCONSISTENT;
549       else {
550         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
551         // and try to find the case without overconstraint
552         bool isLastChance = false;
553         int aNbTemp = myStorage->numberTemporary();
554         while (true) {
555           aResult = myConstrSolver.solve();
556           if (aResult == SLVS_RESULT_OKAY || isLastChance)
557             break;
558           if (aNbTemp <= 0) {
559             // try to update parameters and resolve once again
560             ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
561             for (; aConstrIt != myConstraints.end(); ++aConstrIt)
562               aConstrIt->second->update();
563             isLastChance = true;
564           } else
565             aNbTemp = myStorage->deleteTemporaryConstraint();
566           myConstrSolver.calculateFailedConstraints(true); // something failed => need to find it
567           myStorage->initializeSolver(myConstrSolver);
568         }
569       }
570     } catch (...) {
571 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
572       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
573       if (myPrevSolved) {
574         // the error message should be changed before sending the message
575         sendMessage(EVENT_SOLVER_FAILED);
576         myPrevSolved = false;
577       }
578       return false;
579     }
580     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
581       myFeatureStorage->blockEvents(true);
582       // First refresh parametric constraints to satisfy parameters
583       std::map<AttributePtr, SolverConstraintPtr>::iterator aParIter = myParametricConstraints.begin();
584       for (; aParIter != myParametricConstraints.end(); ++aParIter)
585         aParIter->second->refresh();
586       // Update all other constraints
587       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
588       for (; aConstrIter != myConstraints.end(); ++aConstrIter)
589         aConstrIter->second->refresh();
590       myFeatureStorage->blockEvents(false);
591       if (!myPrevSolved) {
592         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
593         // the error message should be changed before sending the message
594         sendMessage(EVENT_SOLVER_REPAIRED);
595         myPrevSolved = true;
596       }
597     } else if (!myConstraints.empty()) {
598 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
599       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
600       if (myPrevSolved) {
601         // the error message should be changed before sending the message
602         sendMessage(EVENT_SOLVER_FAILED);
603         myPrevSolved = false;
604       }
605     }
606
607     aResolved = true;
608   }
609   removeTemporaryConstraints();
610   myStorage->setNeedToResolve(false);
611   return aResolved;
612 }
613
614 // ============================================================================
615 //  Function: mergeGroups
616 //  Class:    SketchSolver_Group
617 //  Purpose:  append specified group to the current group
618 // ============================================================================
619 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
620 {
621   // If specified group is empty, no need to merge
622   if (theGroup.isEmpty())
623     return;
624   if (!myFeatureStorage)
625     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
626
627   std::set<ObjectPtr> aConstraints;
628   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
629   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
630     aConstraints.insert(aConstrIter->first);
631
632   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
633   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
634   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
635     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
636     if (!aConstr)
637       continue;
638     changeConstraint(aConstr);
639   }
640 }
641
642 // ============================================================================
643 //  Function: splitGroup
644 //  Class:    SketchSolver_Group
645 //  Purpose:  divide the group into several subgroups
646 // ============================================================================
647 void SketchSolver_Group::splitGroup(std::vector<SketchSolver_Group*>& theCuts)
648 {
649   // Obtain constraints, which should be separated
650   FeatureStoragePtr aNewFeatStorage(new SketchSolver_FeatureStorage);
651   std::vector<ConstraintPtr> anUnusedConstraints;
652   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
653   for ( ; aCIter != myConstraints.end(); aCIter++) {
654     std::list<ConstraintPtr> aBaseConstraints = aCIter->second->constraints();
655     std::list<ConstraintPtr>::iterator anIter = aBaseConstraints.begin();
656     for (; anIter != aBaseConstraints.end(); anIter++)
657       if (aNewFeatStorage->isInteract(*anIter)) {
658         aNewFeatStorage->changeConstraint(*anIter);
659       } else
660         anUnusedConstraints.push_back(*anIter);
661   }
662
663   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
664   std::vector<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
665   while (aUnuseIt != anUnusedConstraints.end()) {
666     if (aNewFeatStorage->isInteract(*aUnuseIt)) {
667       aNewFeatStorage->changeConstraint(*aUnuseIt);
668       anUnusedConstraints.erase(aUnuseIt);
669       aUnuseIt = anUnusedConstraints.begin();
670       continue;
671     }
672     aUnuseIt++;
673   }
674
675   std::vector<SketchSolver_Group*>::iterator aCutsIter;
676   aUnuseIt = anUnusedConstraints.begin();
677   for ( ; aUnuseIt != anUnusedConstraints.end(); aUnuseIt++) {
678     // Remove unused constraints
679     removeConstraint(*aUnuseIt);
680     // Try to append constraint to already existent group
681     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); aCutsIter++)
682       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
683         (*aCutsIter)->changeConstraint(*aUnuseIt);
684         break;
685       }
686     if (aCutsIter == theCuts.end()) {
687       // Add new group
688       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
689       aGroup->changeConstraint(*aUnuseIt);
690       theCuts.push_back(aGroup);
691     }
692   }
693
694   // Update feature storage
695   myFeatureStorage = aNewFeatStorage;
696 }
697
698 // ============================================================================
699 //  Function: isConsistent
700 //  Class:    SketchSolver_Group
701 //  Purpose:  search removed entities and constraints
702 // ============================================================================
703 bool SketchSolver_Group::isConsistent()
704 {
705   if (!myFeatureStorage) // no one constraint is initialized yet
706     return true;
707
708   bool aResult = myFeatureStorage->isConsistent();
709   if (!aResult) {
710     // remove invalid entities
711     std::set<ConstraintPtr> anInvalidConstraints;
712     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
713     for (; aCIter != myConstraints.end(); ++aCIter) {
714       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
715         anInvalidConstraints.insert(aCIter->first);
716     }
717     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
718     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
719       removeConstraint(*aRemoveIt);
720   }
721   return aResult;
722 }
723
724 // ============================================================================
725 //  Function: removeTemporaryConstraints
726 //  Class:    SketchSolver_Group
727 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
728 //            resolving the set of constraints
729 // ============================================================================
730 void SketchSolver_Group::removeTemporaryConstraints()
731 {
732   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
733   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
734     (*aTmpIt)->remove();
735   myTempConstraints.clear();
736
737   while (myStorage->numberTemporary())
738     myStorage->deleteTemporaryConstraint();
739   // Clean lists of removed entities in the storage
740   std::set<Slvs_hParam> aRemPar;
741   std::set<Slvs_hEntity> aRemEnt;
742   std::set<Slvs_hConstraint> aRemCon;
743   myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
744   myStorage->setNeedToResolve(false);
745 }
746
747 // ============================================================================
748 //  Function: removeConstraint
749 //  Class:    SketchSolver_Group
750 //  Purpose:  remove constraint and all unused entities
751 // ============================================================================
752 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
753 {
754   bool isFullyRemoved = true;
755   myFeatureStorage->removeConstraint(theConstraint);
756   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
757   for (; aCIter != myConstraints.end(); aCIter++)
758     if (aCIter->second->hasConstraint(theConstraint)) {
759       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
760         isFullyRemoved = false;
761       break;
762     }
763   if (aCIter == myConstraints.end())
764     return;
765
766   // Remove entities not used by constraints
767   myStorage->removeUnusedEntities();
768
769   if (isFullyRemoved)
770     myConstraints.erase(aCIter);
771   else if (aCIter != myConstraints.end() &&
772            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
773     // Update multicoincidence
774     std::list<ConstraintPtr> aMultiCoinc;
775     SolverConstraintPtr aCoincidence = aCIter->second;
776     while (aCIter != myConstraints.end()) {
777       if (aCIter->second != aCoincidence) {
778         ++aCIter;
779         continue;
780       }
781       if (aCIter->first != theConstraint)
782         aMultiCoinc.push_back(aCIter->first);
783       aCIter->second->remove(aCIter->first);
784       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
785       myConstraints.erase(aRemoveIt);
786     }
787
788     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
789     for (; anIt != aMultiCoinc.end(); ++anIt)
790       changeConstraint(*anIt);
791
792     notifyMultiConstraints();
793   }
794 }
795
796 // ============================================================================
797 //  Function: isComplexConstraint
798 //  Class:    SketchSolver_Group
799 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
800 // ============================================================================
801 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
802 {
803   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
804          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
805          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
806 }
807
808 // ============================================================================
809 //  Function: setTemporary
810 //  Class:    SketchSolver_Group
811 //  Purpose:  append given constraint to th group of temporary constraints
812 // ============================================================================
813 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
814 {
815   theConstraint->makeTemporary();
816   myTempConstraints.insert(theConstraint);
817 }
818
819
820 // ============================================================================
821 //  Function: checkFeatureValidity
822 //  Class:    SketchSolver_Group
823 //  Purpose:  verifies is the feature valid
824 // ============================================================================
825 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
826 {
827   if (!theFeature || !theFeature->data()->isValid())
828     return true;
829
830   SessionPtr aMgr = ModelAPI_Session::get();
831   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
832   return aFactory->validate(theFeature);
833 }
834
835 // ============================================================================
836 //  Function: notifyMultiConstraints
837 //  Class:    SketchSolver_Group
838 //  Purpose:  Update Multi-Translation/-Rotation constraints due to multi coincidence appears/disappears
839 // ============================================================================
840 void SketchSolver_Group::notifyMultiConstraints()
841 {
842   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
843   for (; aCIter != myConstraints.end(); ++aCIter) {
844     if (aCIter->first->getKind() == SketchPlugin_MultiRotation::ID() ||
845         aCIter->first->getKind() == SketchPlugin_MultiTranslation::ID()) {
846       std::shared_ptr<SketchSolver_ConstraintMulti> aMulti = 
847           std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIter->second);
848       aMulti->checkCoincidence();
849     }
850   }
851 }
852
853
854
855
856 // ===========   Auxiliary functions   ========================================
857 static double featureToVal(FeaturePtr theFeature)
858 {
859   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
860     return 0.0; // sketch
861   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
862   if (!aConstraint)
863     return 1.0; // features (arc, circle, line, point)
864
865   const std::string& anID = aConstraint->getKind();
866   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
867     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
868         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
869     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
870         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
871     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
872       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
873     return 2.5;
874   }
875   if (anID == SketchPlugin_ConstraintDistance::ID() ||
876       anID == SketchPlugin_ConstraintLength::ID() ||
877       anID == SketchPlugin_ConstraintRadius::ID())
878     return 3.0;
879   if (anID == SketchPlugin_ConstraintAngle::ID())
880     return 3.5;
881   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
882       anID == SketchPlugin_ConstraintVertical::ID() ||
883       anID == SketchPlugin_ConstraintParallel::ID() ||
884       anID == SketchPlugin_ConstraintPerpendicular::ID())
885     return 4.0;
886   if (anID == SketchPlugin_ConstraintEqual::ID())
887     return 5.0;
888   if (anID == SketchPlugin_ConstraintTangent::ID() ||
889       anID == SketchPlugin_ConstraintMirror::ID())
890     return 6.0;
891   if (anID == SketchPlugin_ConstraintRigid::ID())
892     return 7.0;
893   if (anID == SketchPlugin_MultiRotation::ID() ||
894       anID == SketchPlugin_MultiTranslation::ID())
895     return 8.0;
896
897   // all other constraints are placed between Equal and Tangent constraints
898   return 5.5;
899 }
900
901 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
902 {
903   return featureToVal(theFeature1) < featureToVal(theFeature2);
904 }
905
906 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
907 {
908   std::list<FeaturePtr> aResult;
909   std::list<FeaturePtr>::iterator aResIt;
910
911   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
912   for (; anObjIter != theObjects.end(); ++anObjIter) {
913     // Operate sketch itself and SketchPlugin features only.
914     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
915     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
916     if (!aFeature)
917       continue;
918     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
919         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
920     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
921         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
922       continue;
923
924     // Find the place where to insert a feature
925     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
926       if (isLess(aFeature, *aResIt))
927         break;
928     aResult.insert(aResIt, aFeature);
929   }
930
931   return aResult;
932 }
933