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