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