Salome HOME
Minor updates in SketchSolver plugin
[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_Constraint.h>
10 #include <SketchSolver_ConstraintCoincidence.h>
11 #include <SketchSolver_ConstraintMulti.h>
12 #include <SketchSolver_Error.h>
13 #include <SketchSolver_Manager.h>
14
15 #include <Events_Error.h>
16 #include <Events_Loop.h>
17 #include <ModelAPI_AttributeString.h>
18 #include <ModelAPI_Events.h>
19 #include <ModelAPI_Session.h>
20 #include <ModelAPI_Validator.h>
21
22 #include <SketchPlugin_ConstraintAngle.h>
23 #include <SketchPlugin_ConstraintCoincidence.h>
24 #include <SketchPlugin_ConstraintDistance.h>
25 #include <SketchPlugin_ConstraintEqual.h>
26 #include <SketchPlugin_ConstraintHorizontal.h>
27 #include <SketchPlugin_ConstraintLength.h>
28 #include <SketchPlugin_ConstraintFillet.h>
29 #include <SketchPlugin_ConstraintMirror.h>
30 #include <SketchPlugin_ConstraintParallel.h>
31 #include <SketchPlugin_ConstraintPerpendicular.h>
32 #include <SketchPlugin_ConstraintRadius.h>
33 #include <SketchPlugin_ConstraintRigid.h>
34 #include <SketchPlugin_ConstraintTangent.h>
35 #include <SketchPlugin_ConstraintVertical.h>
36 #include <SketchPlugin_MultiRotation.h>
37 #include <SketchPlugin_MultiTranslation.h>
38
39 #include <math.h>
40 #include <assert.h>
41
42
43 /// \brief This class is used to give unique index to the groups
44 class GroupIndexer
45 {
46 public:
47   /// \brief Return vacant index
48   static GroupID NEW_GROUP() { return ++myGroupIndex; }
49   /// \brief Removes the index
50   static void REMOVE_GROUP(const GroupID& theIndex) {
51     if (myGroupIndex == theIndex)
52       myGroupIndex--;
53   }
54
55 private:
56   GroupIndexer() {};
57
58   static GroupID myGroupIndex; ///< index of the group
59 };
60
61 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
62
63
64 static void sendMessage(const char* theMessageName)
65 {
66   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
67       new Events_Message(Events_Loop::eventByName(theMessageName)));
68   Events_Loop::loop()->send(aMessage);
69 }
70
71
72
73 // ========================================================
74 // =========  SketchSolver_Group  ===============
75 // ========================================================
76
77 SketchSolver_Group::SketchSolver_Group(
78     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
79     : myID(GroupIndexer::NEW_GROUP()),
80       myPrevSolved(true)
81 {
82   // Initialize workplane
83   myWorkplaneID = EID_UNKNOWN;
84   addWorkplane(theWorkplane);
85 }
86
87 SketchSolver_Group::~SketchSolver_Group()
88 {
89   myConstraints.clear();
90   GroupIndexer::REMOVE_GROUP(myID);
91 }
92
93 // ============================================================================
94 //  Function: isBaseWorkplane
95 //  Class:    SketchSolver_Group
96 //  Purpose:  verify the group is based on the given workplane
97 // ============================================================================
98 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
99 {
100   return theWorkplane == mySketch;
101 }
102
103 // ============================================================================
104 //  Function: isInteract
105 //  Class:    SketchSolver_Group
106 //  Purpose:  verify are there any entities in the group used by given constraint
107 // ============================================================================
108 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
109 {
110   // Empty group interacts with everything
111   if (isEmpty())
112     return true;
113   // Check interaction with the storage
114   return myStorage->isInteract(theFeature);
115 }
116
117 // ============================================================================
118 //  Function: changeConstraint
119 //  Class:    SketchSolver_Group
120 //  Purpose:  create/update the constraint in the group
121 // ============================================================================
122 bool SketchSolver_Group::changeConstraint(
123     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
124 {
125   // There is no workplane yet, something wrong
126   if (myWorkplaneID == EID_UNKNOWN)
127     return false;
128
129   if (!theConstraint || !theConstraint->data())
130     return false;
131
132   if (!checkFeatureValidity(theConstraint))
133     return false;
134
135   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
136   myStorage->blockEvents(true);
137
138   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
139   if (isNewConstraint) {
140     // Add constraint to the current group
141     SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
142     if (!aConstraint)
143       return false;
144     aConstraint->process(myStorage, getId(), getWorkplaneId());
145     if (!aConstraint->error().empty()) {
146       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
147         return false; // some attribute are not initialized yet, don't show message
148       Events_Error::send(aConstraint->error(), this);
149     }
150     myConstraints[theConstraint] = aConstraint;
151   }
152   else
153     myConstraints[theConstraint]->update();
154
155   // Fix mirror line
156   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
157     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
158         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
159     if (aRefAttr && aRefAttr->isObject()) {
160       std::shared_ptr<SketchPlugin_Feature> aFeature =
161           std::dynamic_pointer_cast<SketchPlugin_Feature>(
162           ModelAPI_Feature::feature(aRefAttr->object()));
163       if (aFeature) {
164         SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
165         if (aConstraint) {
166           aConstraint->process(myStorage, getId(), getWorkplaneId());
167           setTemporary(aConstraint);
168         }
169       }
170     }
171   }
172   return true;
173 }
174
175
176 void SketchSolver_Group::updateConstraints()
177 {
178   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
179
180   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
181   for (; anIt != myConstraints.end(); ++anIt) {
182     if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
183       continue;
184     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
185         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
186       aPostponed.insert(anIt->second);
187     else
188       anIt->second->update();
189   }
190
191   // Update postponed constraints
192   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
193   for (; aSCIter != aPostponed.end(); ++aSCIter)
194     (*aSCIter)->update();
195
196   myChangedConstraints.clear();
197 }
198
199 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
200 {
201   ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
202   for (; aCIt != theConstraints.end(); ++aCIt) {
203     if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
204          aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
205         && aCIt->second->isUsed(theFeature))
206       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
207   }
208 }
209
210 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
211 {
212   if (!checkFeatureValidity(theFeature))
213     return false;
214
215   myStorage->blockEvents(true);
216   myStorage->refresh(true);
217   bool isUpdated = myStorage->update(theFeature);
218
219   updateMultiConstraints(myConstraints, theFeature);
220   return isUpdated;
221 }
222
223 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
224 {
225   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
226
227   // Firstly, revert changes in the fixed entities
228   myStorage->blockEvents(true);
229   myStorage->refresh(true);
230
231   // Then, create temporary Fixed constraint
232   SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
233   if (!aConstraint)
234     return;
235   aConstraint->process(myStorage, getId(), getWorkplaneId());
236   if (aConstraint->error().empty())
237     setTemporary(aConstraint);
238
239   // Secondly, search attributes of the feature in the list of the Multi constraints and update them
240   updateMultiConstraints(myConstraints, theFeature);
241 }
242
243 // ============================================================================
244 //  Function: addWorkplane
245 //  Class:    SketchSolver_Group
246 //  Purpose:  create workplane for the group
247 // ============================================================================
248 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
249 {
250   if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
251     return false;  // the workplane already exists or the function parameter is not Sketch
252
253   mySketch = theSketch;
254   if (!updateWorkplane()) {
255     mySketch = CompositeFeaturePtr();
256     return false;
257   }
258   return true;
259 }
260
261 // ============================================================================
262 //  Function: updateWorkplane
263 //  Class:    SketchSolver_Group
264 //  Purpose:  update parameters of workplane
265 // ============================================================================
266 bool SketchSolver_Group::updateWorkplane()
267 {
268   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
269   if (!myStorage) // Create storage if not exists
270     myStorage = aBuilder->createStorage(getId());
271
272   // sketch should be unchanged, set it out of current group
273   bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
274   if (isUpdated) {
275     EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
276     myWorkplaneID = anEntity->id();
277   }
278   return isUpdated;
279 }
280
281 // ============================================================================
282 //  Function: resolveConstraints
283 //  Class:    SketchSolver_Group
284 //  Purpose:  solve the set of constraints for the current group
285 // ============================================================================
286 bool SketchSolver_Group::resolveConstraints()
287 {
288   if (!myChangedConstraints.empty())
289     updateConstraints();
290
291   bool aResolved = false;
292   bool isGroupEmpty = isEmpty();
293   if (myStorage->isNeedToResolve() && !isGroupEmpty) {
294     if (!mySketchSolver)
295       mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
296
297     mySketchSolver->setGroup(myID);
298     mySketchSolver->calculateFailedConstraints(false);
299     myStorage->initializeSolver(mySketchSolver);
300
301     SketchSolver_SolveStatus aResult = STATUS_OK;
302     try {
303       if (myStorage->hasDuplicatedConstraint())
304         aResult = STATUS_INCONSISTENT;
305       else {
306         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
307         // and try to find the case without overconstraint
308         bool isLastChance = false;
309         while (true) {
310           aResult = mySketchSolver->solve();
311           if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
312             break;
313           // try to update parameters and resolve once again
314           ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
315           for (; aConstrIt != myConstraints.end(); ++aConstrIt)
316             aConstrIt->second->update();
317           isLastChance = true;
318
319           removeTemporaryConstraints();
320           mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
321           myStorage->initializeSolver(mySketchSolver);
322         }
323       }
324     } catch (...) {
325 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
326       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
327       if (myPrevSolved) {
328         // the error message should be changed before sending the message
329         sendMessage(EVENT_SOLVER_FAILED);
330         myPrevSolved = false;
331       }
332       return false;
333     }
334     if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) {  // solution succeeded, store results into correspondent attributes
335       myStorage->refresh();
336       if (!myPrevSolved) {
337         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
338         // the error message should be changed before sending the message
339         sendMessage(EVENT_SOLVER_REPAIRED);
340         myPrevSolved = true;
341       }
342     } else if (!myConstraints.empty()) {
343 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
344       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
345       if (myPrevSolved) {
346         // the error message should be changed before sending the message
347         sendMessage(EVENT_SOLVER_FAILED);
348         myPrevSolved = false;
349       }
350     }
351
352     aResolved = true;
353   } else if (!isGroupEmpty) {
354     // Check there are constraints Fixed. If they exist, update parameters by stored values
355     ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
356     for (; aCIt != myConstraints.end(); ++aCIt)
357       if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
358         aResolved = true;
359         break;
360       }
361     if (aCIt != myConstraints.end())
362       myStorage->refresh();
363   }
364   removeTemporaryConstraints();
365   myStorage->blockEvents(false);
366   myStorage->setNeedToResolve(false);
367   return aResolved;
368 }
369
370 // ============================================================================
371 //  Function: mergeGroups
372 //  Class:    SketchSolver_Group
373 //  Purpose:  append specified group to the current group
374 // ============================================================================
375 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
376 {
377   // If specified group is empty, no need to merge
378   if (theGroup.isEmpty())
379     return;
380
381   std::set<ObjectPtr> aConstraints;
382   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
383   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
384     aConstraints.insert(aConstrIter->first);
385
386   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
387   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
388   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
389     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
390     if (!aConstr)
391       continue;
392     changeConstraint(aConstr);
393   }
394 }
395
396 // ============================================================================
397 //  Function: splitGroup
398 //  Class:    SketchSolver_Group
399 //  Purpose:  divide the group into several subgroups
400 // ============================================================================
401 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
402 {
403   // New storage will be used in trimmed way to store the list of constraint interacted together.
404   StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
405   std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
406
407   // Obtain constraints, which should be separated
408   std::list<ConstraintPtr> anUnusedConstraints;
409   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
410   for ( ; aCIter != myConstraints.end(); aCIter++) {
411     if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
412       aNewStorage->addConstraint(aCIter->first, aDummyVec);
413     else
414       anUnusedConstraints.push_back(aCIter->first);
415   }
416
417   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
418   std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
419   while (aUnuseIt != anUnusedConstraints.end()) {
420     if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
421       aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
422       anUnusedConstraints.erase(aUnuseIt);
423       aUnuseIt = anUnusedConstraints.begin();
424       continue;
425     }
426     aUnuseIt++;
427   }
428
429   std::list<SketchSolver_Group*>::iterator aCutsIter;
430   aUnuseIt = anUnusedConstraints.begin();
431   for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
432     // Remove unused constraints
433     removeConstraint(*aUnuseIt);
434     // Try to append constraint to already existent group
435     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
436       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
437         (*aCutsIter)->changeConstraint(*aUnuseIt);
438         break;
439       }
440     if (aCutsIter == theCuts.end()) {
441       // Add new group
442       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
443       aGroup->changeConstraint(*aUnuseIt);
444       theCuts.push_back(aGroup);
445     } else {
446       // Find other groups interacting with constraint
447       std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
448       for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
449         if ((*aCutsIter)->isInteract(*aUnuseIt)) {
450           (*aBaseGroupIt)->mergeGroups(**aCutsIter);
451           std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
452           theCuts.erase(aRemoveIt);
453         }
454     }
455   }
456 }
457
458 // ============================================================================
459 //  Function: isConsistent
460 //  Class:    SketchSolver_Group
461 //  Purpose:  search removed entities and constraints
462 // ============================================================================
463 bool SketchSolver_Group::isConsistent()
464 {
465   if (isEmpty()) // no one constraint is initialized yet
466     return true;
467
468   // Check the features and constraint is the storage are valid
469   bool aResult = myStorage->isConsistent();
470   if (aResult) {
471     // additional check of consistency of the Fixed constraint,
472     // because they are not added to the storage
473     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
474     for (; aCIter != myConstraints.end(); ++aCIter)
475       if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
476          (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
477         aResult = false;
478         break;
479       }
480   }
481   if (!aResult) {
482     // remove invalid constraints
483     std::set<ConstraintPtr> anInvalidConstraints;
484     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
485     for (; aCIter != myConstraints.end(); ++aCIter) {
486       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
487         anInvalidConstraints.insert(aCIter->first);
488     }
489     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
490     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
491       removeConstraint(*aRemoveIt);
492     // remove invalid features
493     myStorage->removeInvalidEntities();
494   }
495   return aResult;
496 }
497
498 // ============================================================================
499 //  Function: removeTemporaryConstraints
500 //  Class:    SketchSolver_Group
501 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
502 //            resolving the set of constraints
503 // ============================================================================
504 void SketchSolver_Group::removeTemporaryConstraints()
505 {
506   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
507   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
508     (*aTmpIt)->remove();
509
510   if (!myTempConstraints.empty())
511     myStorage->verifyFixed();
512   myStorage->setNeedToResolve(false);
513   myTempConstraints.clear();
514 }
515
516 // ============================================================================
517 //  Function: removeConstraint
518 //  Class:    SketchSolver_Group
519 //  Purpose:  remove constraint and all unused entities
520 // ============================================================================
521 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
522 {
523   bool isFullyRemoved = true;
524   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
525   for (; aCIter != myConstraints.end(); aCIter++)
526     if (aCIter->first == theConstraint) {
527       if (!aCIter->second->remove()) // the constraint is not fully removed
528         isFullyRemoved = false;
529       break;
530     }
531   if (aCIter == myConstraints.end())
532     return;
533
534   if (isFullyRemoved)
535     myConstraints.erase(aCIter);
536   else if (aCIter != myConstraints.end() &&
537            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
538     // Update multicoincidence
539     std::list<ConstraintPtr> aMultiCoinc;
540     SolverConstraintPtr aCoincidence = aCIter->second;
541     while (aCIter != myConstraints.end()) {
542       if (aCIter->second != aCoincidence) {
543         ++aCIter;
544         continue;
545       }
546       if (aCIter->first != theConstraint)
547         aMultiCoinc.push_back(aCIter->first);
548       aCIter->second->remove();
549       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
550       myConstraints.erase(aRemoveIt);
551     }
552
553     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
554     for (; anIt != aMultiCoinc.end(); ++anIt)
555       changeConstraint(*anIt);
556   }
557 }
558
559 // ============================================================================
560 //  Function: isComplexConstraint
561 //  Class:    SketchSolver_Group
562 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
563 // ============================================================================
564 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
565 {
566   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
567          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
568          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
569 }
570
571 // ============================================================================
572 //  Function: setTemporary
573 //  Class:    SketchSolver_Group
574 //  Purpose:  append given constraint to the group of temporary constraints
575 // ============================================================================
576 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
577 {
578   myTempConstraints.insert(theConstraint);
579 }
580
581
582 // ============================================================================
583 //  Function: checkFeatureValidity
584 //  Class:    SketchSolver_Group
585 //  Purpose:  verifies is the feature valid
586 // ============================================================================
587 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
588 {
589   if (!theFeature || !theFeature->data()->isValid())
590     return true;
591
592   SessionPtr aMgr = ModelAPI_Session::get();
593   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
594   return aFactory->validate(theFeature);
595 }
596
597
598
599
600 // ===========   Auxiliary functions   ========================================
601 static double featureToVal(FeaturePtr theFeature)
602 {
603   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
604     return 0.0; // sketch
605   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
606   if (!aConstraint)
607     return 1.0; // features (arc, circle, line, point)
608
609   const std::string& anID = aConstraint->getKind();
610   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
611     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
612         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
613     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
614         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
615     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
616       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
617     return 2.5;
618   }
619   if (anID == SketchPlugin_ConstraintDistance::ID() ||
620       anID == SketchPlugin_ConstraintLength::ID() ||
621       anID == SketchPlugin_ConstraintRadius::ID())
622     return 3.0;
623   if (anID == SketchPlugin_ConstraintAngle::ID())
624     return 3.5;
625   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
626       anID == SketchPlugin_ConstraintVertical::ID() ||
627       anID == SketchPlugin_ConstraintParallel::ID() ||
628       anID == SketchPlugin_ConstraintPerpendicular::ID())
629     return 4.0;
630   if (anID == SketchPlugin_ConstraintEqual::ID())
631     return 5.0;
632   if (anID == SketchPlugin_ConstraintTangent::ID() ||
633       anID == SketchPlugin_ConstraintMirror::ID())
634     return 6.0;
635   if (anID == SketchPlugin_ConstraintRigid::ID())
636     return 7.0;
637   if (anID == SketchPlugin_MultiRotation::ID() ||
638       anID == SketchPlugin_MultiTranslation::ID())
639     return 8.0;
640
641   // all other constraints are placed between Equal and Tangent constraints
642   return 5.5;
643 }
644
645 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
646 {
647   return featureToVal(theFeature1) < featureToVal(theFeature2);
648 }
649
650 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
651 {
652   std::list<FeaturePtr> aResult;
653   std::list<FeaturePtr>::iterator aResIt;
654
655   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
656   for (; anObjIter != theObjects.end(); ++anObjIter) {
657     // Operate sketch itself and SketchPlugin features only.
658     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
659     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
660     if (!aFeature)
661       continue;
662     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
663         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
664     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
665         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
666       continue;
667
668     // Find the place where to insert a feature
669     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
670       if (isLess(aFeature, *aResIt))
671         break;
672     aResult.insert(aResIt, aFeature);
673   }
674
675   return aResult;
676 }
677