Salome HOME
8b4026ef22993dced39bece02f4d4af1522359d6
[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)
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   return true;
302 }
303
304
305 void SketchSolver_Group::updateConstraints()
306 {
307   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
308
309   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
310   for (; anIt != myConstraints.end(); ++anIt) {
311     if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
312       continue;
313     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
314         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
315       aPostponed.insert(anIt->second);
316     else
317       anIt->second->update();
318   }
319
320   // Update postponed constraints
321   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
322   for (; aSCIter != aPostponed.end(); ++aSCIter)
323     (*aSCIter)->update();
324
325   myChangedConstraints.clear();
326 }
327
328 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
329 {
330   if (!checkFeatureValidity(theFeature))
331     return false;
332
333   std::set<ConstraintPtr> aConstraints =
334       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
335   if (aConstraints.empty())
336     return false;
337   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
338   for (; aCIter != aConstraints.end(); aCIter++) {
339     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
340     if (aSolConIter == myConstraints.end() || !aSolConIter->first->data() ||
341         !aSolConIter->first->data()->isValid())
342       continue;
343     myFeatureStorage->changeFeature(theFeature, aSolConIter->first);
344
345     aSolConIter->second->addFeature(theFeature);
346     myChangedConstraints.insert(aSolConIter->first);
347   }
348   return true;
349 }
350
351 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
352 {
353   // Firstly, create temporary rigid constraint
354   SolverConstraintPtr aConstraint =
355       SketchSolver_Builder::getInstance()->createMovementConstraint(theFeature);
356   if (!aConstraint)
357     return;
358   aConstraint->setGroup(this);
359   aConstraint->setStorage(myStorage);
360   if (aConstraint->error().empty())
361     setTemporary(aConstraint);
362   // Secondly, update the feature
363   updateFeature(theFeature);
364 }
365
366 // ============================================================================
367 //  Function: fixFeaturesList
368 //  Class:    SketchSolver_Group
369 //  Purpose:  Apply temporary rigid constraints for the list of features
370 // ============================================================================
371 void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
372 {
373   std::list<ObjectPtr> aList = theList->list();
374   std::list<ObjectPtr>::iterator anIt = aList.begin();
375   std::list<FeaturePtr> aFeatures;
376   // Sort features, at begining there are features used by Equal constraint
377   for (; anIt != aList.end(); anIt++) {
378     if (!(*anIt))
379       continue;
380     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
381     std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(aFeature);
382     std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
383     for (; aCIter != aConstraints.end(); aCIter++)
384       if ((*aCIter)->getKind() == SketchPlugin_ConstraintEqual::ID())
385         break;
386     if (aCIter != aConstraints.end())
387       aFeatures.push_front(aFeature);
388     else
389       aFeatures.push_back(aFeature);
390   }
391
392   std::list<FeaturePtr>::iterator aFeatIter = aFeatures.begin();
393   for (; aFeatIter != aFeatures.end(); aFeatIter++) {
394     SolverConstraintPtr aConstraint =
395         SketchSolver_Builder::getInstance()->createRigidConstraint(*aFeatIter);
396     if (!aConstraint)
397       continue;
398     aConstraint->setGroup(this);
399     aConstraint->setStorage(myStorage);
400     setTemporary(aConstraint);
401   }
402 }
403
404 // ============================================================================
405 //  Function: addWorkplane
406 //  Class:    SketchSolver_Group
407 //  Purpose:  create workplane for the group
408 // ============================================================================
409 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
410 {
411   if (myWorkplaneID != SLVS_E_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
412     return false;  // the workplane already exists or the function parameter is not Sketch
413
414   mySketch = theSketch;
415   updateWorkplane();
416   return true;
417 }
418
419 // ============================================================================
420 //  Function: updateWorkplane
421 //  Class:    SketchSolver_Group
422 //  Purpose:  update parameters of workplane
423 // ============================================================================
424 bool SketchSolver_Group::updateWorkplane()
425 {
426   if (!myStorage) // Create storage if not exists
427     myStorage = StoragePtr(new SketchSolver_Storage);
428   SketchSolver_Builder* aBuilder = SketchSolver_Builder::getInstance();
429
430   std::vector<Slvs_Entity> anEntities;
431   std::vector<Slvs_Param> aParams;
432   if (!aBuilder->createWorkplane(mySketch, anEntities, aParams))
433     return false;
434
435   if (myWorkplaneID == SLVS_E_UNKNOWN) {
436     myWorkplaneID = anEntities.back().h;
437     // Add new workplane elements
438     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
439     for (; aParIter != aParams.end(); aParIter++) {
440       aParIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
441       aParIter->group = myID;
442       aParIter->h = myStorage->addParameter(*aParIter);
443     }
444     std::vector<Slvs_Entity>::iterator anEntIter = anEntities.begin();
445     for (; anEntIter != anEntities.end(); anEntIter++) {
446       anEntIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
447       anEntIter->group = myID;
448       anEntIter->wrkpl = myWorkplaneID;
449       for (int i = 0; i < 4; i++)
450         if (anEntIter->param[i] != SLVS_E_UNKNOWN)
451           anEntIter->param[i] = aParams[anEntIter->param[i]-1].h;
452       for (int i = 0; i < 4; i++)
453         if (anEntIter->point[i] != SLVS_E_UNKNOWN)
454           anEntIter->point[i] = anEntities[anEntIter->point[i]-1].h;
455       anEntIter->h = myStorage->addEntity(*anEntIter);
456     }
457   } else {
458     // Update existent workplane
459     const Slvs_Entity& aWP = myStorage->getEntity(myWorkplaneID);
460     const Slvs_Entity& anOrigin = myStorage->getEntity(aWP.point[0]);
461     const Slvs_Entity& aNormal = myStorage->getEntity(aWP.normal);
462     // Get parameters and update them
463     Slvs_hParam aWPParams[7] = {
464         anOrigin.param[0], anOrigin.param[1], anOrigin.param[2],
465         aNormal.param[0], aNormal.param[1], aNormal.param[2], aNormal.param[3]
466       };
467     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
468     for (int i = 0; aParIter != aParams.end(); aParIter++, i++) {
469       Slvs_Param aParam = myStorage->getParameter(aWPParams[i]);
470       aParam.val = aParIter->val;
471       myStorage->updateParameter(aParam);
472     }
473   }
474   return myWorkplaneID > 0;
475 }
476
477 // ============================================================================
478 //  Function: resolveConstraints
479 //  Class:    SketchSolver_Group
480 //  Purpose:  solve the set of constraints for the current group
481 // ============================================================================
482 bool SketchSolver_Group::resolveConstraints()
483 {
484   if (!myChangedConstraints.empty())
485     updateConstraints();
486
487   bool aResolved = false;
488   if (myStorage->isNeedToResolve() && !isEmpty()) {
489     myConstrSolver.setGroupID(myID);
490     myStorage->initializeSolver(myConstrSolver);
491
492     int aResult = SLVS_RESULT_OKAY;
493     try {
494       if (myStorage->hasDuplicatedConstraint())
495         aResult = SLVS_RESULT_INCONSISTENT;
496       else {
497         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
498         // and try to find the case without overconstraint
499         bool isLastChance = false;
500         int aNbTemp = myStorage->numberTemporary();
501         while (true) {
502           aResult = myConstrSolver.solve();
503           if (aResult == SLVS_RESULT_OKAY || isLastChance)
504             break;
505           if (aNbTemp <= 0) {
506             // try to update parameters and resolve once again
507             ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
508             for (; aConstrIt != myConstraints.end(); ++aConstrIt)
509               aConstrIt->second->update();
510             isLastChance = true;
511           } else
512             aNbTemp = myStorage->deleteTemporaryConstraint();
513           myStorage->initializeSolver(myConstrSolver);
514         }
515       }
516     } catch (...) {
517 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
518       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
519       if (myPrevSolved) {
520         // the error message should be changed before sending the message
521         sendMessage(EVENT_SOLVER_FAILED);
522         myPrevSolved = false;
523       }
524       return false;
525     }
526     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
527       myFeatureStorage->blockEvents(true);
528       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
529       for (; aConstrIter != myConstraints.end(); aConstrIter++)
530         aConstrIter->second->refresh();
531       myFeatureStorage->blockEvents(false);
532       if (!myPrevSolved) {
533         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
534         // the error message should be changed before sending the message
535         sendMessage(EVENT_SOLVER_REPAIRED);
536         myPrevSolved = true;
537       }
538     } else if (!myConstraints.empty()) {
539 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
540       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
541       if (myPrevSolved) {
542         // the error message should be changed before sending the message
543         sendMessage(EVENT_SOLVER_FAILED);
544         myPrevSolved = false;
545       }
546     }
547
548     aResolved = true;
549   }
550   removeTemporaryConstraints();
551   myStorage->setNeedToResolve(false);
552   return aResolved;
553 }
554
555 // ============================================================================
556 //  Function: mergeGroups
557 //  Class:    SketchSolver_Group
558 //  Purpose:  append specified group to the current group
559 // ============================================================================
560 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
561 {
562   // If specified group is empty, no need to merge
563   if (theGroup.isEmpty())
564     return;
565   if (!myFeatureStorage)
566     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
567
568   std::set<ObjectPtr> aConstraints;
569   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
570   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
571     aConstraints.insert(aConstrIter->first);
572
573   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
574   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
575   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
576     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
577     if (!aConstr)
578       continue;
579     changeConstraint(aConstr);
580   }
581 }
582
583 // ============================================================================
584 //  Function: splitGroup
585 //  Class:    SketchSolver_Group
586 //  Purpose:  divide the group into several subgroups
587 // ============================================================================
588 void SketchSolver_Group::splitGroup(std::vector<SketchSolver_Group*>& theCuts)
589 {
590   // Obtain constraints, which should be separated
591   FeatureStoragePtr aNewFeatStorage(new SketchSolver_FeatureStorage);
592   std::vector<ConstraintPtr> anUnusedConstraints;
593   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
594   for ( ; aCIter != myConstraints.end(); aCIter++) {
595     std::list<ConstraintPtr> aBaseConstraints = aCIter->second->constraints();
596     std::list<ConstraintPtr>::iterator anIter = aBaseConstraints.begin();
597     for (; anIter != aBaseConstraints.end(); anIter++)
598       if (aNewFeatStorage->isInteract(*anIter)) {
599         aNewFeatStorage->changeConstraint(*anIter);
600       } else
601         anUnusedConstraints.push_back(*anIter);
602   }
603
604   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
605   std::vector<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
606   while (aUnuseIt != anUnusedConstraints.end()) {
607     if (aNewFeatStorage->isInteract(*aUnuseIt)) {
608       size_t aShift = aUnuseIt - anUnusedConstraints.begin();
609       anUnusedConstraints.erase(aUnuseIt);
610       aUnuseIt = anUnusedConstraints.begin() + aShift;
611       continue;
612     }
613     aUnuseIt++;
614   }
615
616   std::vector<SketchSolver_Group*>::iterator aCutsIter;
617   aUnuseIt = anUnusedConstraints.begin();
618   for ( ; aUnuseIt != anUnusedConstraints.end(); aUnuseIt++) {
619     // Remove unused constraints
620     removeConstraint(*aUnuseIt);
621     // Try to append constraint to already existent group
622     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); aCutsIter++)
623       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
624         (*aCutsIter)->changeConstraint(*aUnuseIt);
625         break;
626       }
627     if (aCutsIter == theCuts.end()) {
628       // Add new group
629       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
630       aGroup->changeConstraint(*aUnuseIt);
631       theCuts.push_back(aGroup);
632     }
633   }
634 }
635
636 // ============================================================================
637 //  Function: isConsistent
638 //  Class:    SketchSolver_Group
639 //  Purpose:  search removed entities and constraints
640 // ============================================================================
641 bool SketchSolver_Group::isConsistent()
642 {
643   if (!myFeatureStorage) // no one constraint is initialized yet
644     return true;
645
646   bool aResult = myFeatureStorage->isConsistent();
647   if (!aResult) {
648     // remove invalid entities
649     std::set<ConstraintPtr> anInvalidConstraints;
650     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
651     for (; aCIter != myConstraints.end(); ++aCIter) {
652       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
653         anInvalidConstraints.insert(aCIter->first);
654     }
655     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
656     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
657       removeConstraint(*aRemoveIt);
658   }
659   return aResult;
660 }
661
662 // ============================================================================
663 //  Function: removeTemporaryConstraints
664 //  Class:    SketchSolver_Group
665 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
666 //            resolving the set of constraints
667 // ============================================================================
668 void SketchSolver_Group::removeTemporaryConstraints()
669 {
670   myTempConstraints.clear();
671   while (myStorage->numberTemporary())
672     myStorage->deleteTemporaryConstraint();
673   // Clean lists of removed entities in the storage
674   std::set<Slvs_hParam> aRemPar;
675   std::set<Slvs_hEntity> aRemEnt;
676   std::set<Slvs_hConstraint> aRemCon;
677   myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
678   myStorage->setNeedToResolve(false);
679 }
680
681 // ============================================================================
682 //  Function: removeConstraint
683 //  Class:    SketchSolver_Group
684 //  Purpose:  remove constraint and all unused entities
685 // ============================================================================
686 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
687 {
688   bool isFullyRemoved = true;
689   myFeatureStorage->removeConstraint(theConstraint);
690   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
691   for (; aCIter != myConstraints.end(); aCIter++)
692     if (aCIter->second->hasConstraint(theConstraint)) {
693       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
694         isFullyRemoved = false;
695       break;
696     }
697   if (aCIter == myConstraints.end())
698     return;
699
700   if (isFullyRemoved)
701     myConstraints.erase(aCIter);
702   else if (aCIter != myConstraints.end() &&
703            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
704     // Update multicoincidence
705     std::list<ConstraintPtr> aMultiCoinc;
706     SolverConstraintPtr aCoincidence = aCIter->second;
707     while (aCIter != myConstraints.end()) {
708       if (aCIter->second != aCoincidence) {
709         ++aCIter;
710         continue;
711       }
712       if (aCIter->first != theConstraint)
713         aMultiCoinc.push_back(aCIter->first);
714       aCIter->second->remove(aCIter->first);
715       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
716       myConstraints.erase(aRemoveIt);
717     }
718
719     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
720     for (; anIt != aMultiCoinc.end(); ++anIt)
721       changeConstraint(*anIt);
722   }
723 }
724
725 // ============================================================================
726 //  Function: isComplexConstraint
727 //  Class:    SketchSolver_Group
728 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
729 // ============================================================================
730 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
731 {
732   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
733          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
734          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
735 }
736
737 // ============================================================================
738 //  Function: setTemporary
739 //  Class:    SketchSolver_Group
740 //  Purpose:  append given constraint to th group of temporary constraints
741 // ============================================================================
742 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
743 {
744   theConstraint->makeTemporary();
745   myTempConstraints.insert(theConstraint);
746 }
747
748
749 // ============================================================================
750 //  Function: checkFeatureValidity
751 //  Class:    SketchSolver_Group
752 //  Purpose:  verifies is the feature valid
753 // ============================================================================
754 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
755 {
756   if (!theFeature || !theFeature->data()->isValid())
757     return true;
758
759   SessionPtr aMgr = ModelAPI_Session::get();
760   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
761   return aFactory->validate(theFeature);
762 }
763
764
765
766
767
768 // ===========   Auxiliary functions   ========================================
769 static double featureToVal(FeaturePtr theFeature)
770 {
771   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
772     return 0.0; // sketch
773   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
774   if (!aConstraint)
775     return 1.0; // features (arc, circle, line, point)
776
777   const std::string& anID = aConstraint->getKind();
778   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
779     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
780         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
781     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
782         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
783     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
784       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
785     return 2.5;
786   }
787   if (anID == SketchPlugin_ConstraintDistance::ID() ||
788       anID == SketchPlugin_ConstraintLength::ID() ||
789       anID == SketchPlugin_ConstraintRadius::ID())
790     return 3.0;
791   if (anID == SketchPlugin_ConstraintAngle::ID())
792     return 3.5;
793   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
794       anID == SketchPlugin_ConstraintVertical::ID() ||
795       anID == SketchPlugin_ConstraintParallel::ID() ||
796       anID == SketchPlugin_ConstraintPerpendicular::ID())
797     return 4.0;
798   if (anID == SketchPlugin_ConstraintEqual::ID())
799     return 5.0;
800   if (anID == SketchPlugin_ConstraintTangent::ID() ||
801       anID == SketchPlugin_ConstraintMirror::ID())
802     return 6.0;
803   if (anID == SketchPlugin_ConstraintRigid::ID())
804     return 7.0;
805   if (anID == SketchPlugin_MultiRotation::ID() ||
806       anID == SketchPlugin_MultiTranslation::ID())
807     return 8.0;
808
809   // all other constraints are placed between Equal and Tangent constraints
810   return 5.5;
811 }
812
813 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
814 {
815   return featureToVal(theFeature1) < featureToVal(theFeature2);
816 }
817
818 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
819 {
820   std::list<FeaturePtr> aResult;
821   std::list<FeaturePtr>::iterator aResIt;
822
823   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
824   for (; anObjIter != theObjects.end(); ++anObjIter) {
825     // Operate sketch itself and SketchPlugin features only.
826     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
827     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
828     if (!aFeature)
829       continue;
830     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
831         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
832     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
833         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
834       continue;
835
836     // Find the place where to insert a feature
837     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
838       if (isLess(aFeature, *aResIt))
839         break;
840     aResult.insert(aResIt, aFeature);
841   }
842
843   return aResult;
844 }
845