Salome HOME
Correct processing arcs in SketchSolver with SolveSpace (issue #1144)
[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 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
200 {
201   if (!checkFeatureValidity(theFeature))
202     return false;
203
204   myStorage->blockEvents(true);
205   myStorage->refresh(true);
206   return myStorage->update(theFeature);
207 }
208
209 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
210 {
211   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
212
213   // Firstly, revert changes in the fixed entities
214   myStorage->blockEvents(true);
215   myStorage->refresh(true);
216
217   // Secondly, search attributes of the feature in the list of the Multi constraints and update them
218   ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
219   for (; aCIt != myConstraints.end(); ++aCIt) {
220     if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
221          aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
222         && aCIt->second->isUsed(theFeature))
223       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
224   }
225
226   // Then, create temporary rigid constraint
227   SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
228   if (!aConstraint)
229     return;
230   aConstraint->process(myStorage, getId(), getWorkplaneId());
231   if (aConstraint->error().empty())
232     setTemporary(aConstraint);
233 }
234
235 // ============================================================================
236 //  Function: addWorkplane
237 //  Class:    SketchSolver_Group
238 //  Purpose:  create workplane for the group
239 // ============================================================================
240 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
241 {
242   if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
243     return false;  // the workplane already exists or the function parameter is not Sketch
244
245   mySketch = theSketch;
246   if (!updateWorkplane()) {
247     mySketch = CompositeFeaturePtr();
248     return false;
249   }
250   return true;
251 }
252
253 // ============================================================================
254 //  Function: updateWorkplane
255 //  Class:    SketchSolver_Group
256 //  Purpose:  update parameters of workplane
257 // ============================================================================
258 bool SketchSolver_Group::updateWorkplane()
259 {
260   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
261   if (!myStorage) // Create storage if not exists
262     myStorage = aBuilder->createStorage(getId());
263
264   // sketch should be unchanged, set it out of current group
265   bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
266   if (isUpdated) {
267     EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
268     myWorkplaneID = anEntity->id();
269   }
270   return isUpdated;
271 }
272
273 // ============================================================================
274 //  Function: resolveConstraints
275 //  Class:    SketchSolver_Group
276 //  Purpose:  solve the set of constraints for the current group
277 // ============================================================================
278 bool SketchSolver_Group::resolveConstraints()
279 {
280   if (!myChangedConstraints.empty())
281     updateConstraints();
282
283   bool aResolved = false;
284   bool isGroupEmpty = isEmpty();
285   if (myStorage->isNeedToResolve() && !isGroupEmpty) {
286     if (!mySketchSolver)
287       mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
288
289     mySketchSolver->setGroup(myID);
290     mySketchSolver->calculateFailedConstraints(false);
291     myStorage->initializeSolver(mySketchSolver);
292
293     SketchSolver_SolveStatus aResult = STATUS_OK;
294     try {
295       if (myStorage->hasDuplicatedConstraint())
296         aResult = STATUS_INCONSISTENT;
297       else {
298         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
299         // and try to find the case without overconstraint
300         bool isLastChance = false;
301         while (true) {
302           aResult = mySketchSolver->solve();
303           if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
304             break;
305           // try to update parameters and resolve once again
306           ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
307           for (; aConstrIt != myConstraints.end(); ++aConstrIt)
308             aConstrIt->second->update();
309           isLastChance = true;
310
311           removeTemporaryConstraints();
312           mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
313           myStorage->initializeSolver(mySketchSolver);
314         }
315       }
316     } catch (...) {
317 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
318       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
319       if (myPrevSolved) {
320         // the error message should be changed before sending the message
321         sendMessage(EVENT_SOLVER_FAILED);
322         myPrevSolved = false;
323       }
324       return false;
325     }
326     if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) {  // solution succeeded, store results into correspondent attributes
327       myStorage->refresh();
328       if (!myPrevSolved) {
329         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
330         // the error message should be changed before sending the message
331         sendMessage(EVENT_SOLVER_REPAIRED);
332         myPrevSolved = true;
333       }
334     } else if (!myConstraints.empty()) {
335 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
336       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
337       if (myPrevSolved) {
338         // the error message should be changed before sending the message
339         sendMessage(EVENT_SOLVER_FAILED);
340         myPrevSolved = false;
341       }
342     }
343
344     aResolved = true;
345   } else if (!isGroupEmpty) {
346     // Check there are constraints Fixed. If they exist, update parameters by stored values
347     ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
348     for (; aCIt != myConstraints.end(); ++aCIt)
349       if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
350         aResolved = true;
351         break;
352       }
353     if (aCIt != myConstraints.end())
354       myStorage->refresh();
355   }
356   removeTemporaryConstraints();
357   myStorage->blockEvents(false);
358   myStorage->setNeedToResolve(false);
359   return aResolved;
360 }
361
362 // ============================================================================
363 //  Function: mergeGroups
364 //  Class:    SketchSolver_Group
365 //  Purpose:  append specified group to the current group
366 // ============================================================================
367 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
368 {
369   // If specified group is empty, no need to merge
370   if (theGroup.isEmpty())
371     return;
372
373   std::set<ObjectPtr> aConstraints;
374   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
375   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
376     aConstraints.insert(aConstrIter->first);
377
378   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
379   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
380   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
381     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
382     if (!aConstr)
383       continue;
384     changeConstraint(aConstr);
385   }
386 }
387
388 // ============================================================================
389 //  Function: splitGroup
390 //  Class:    SketchSolver_Group
391 //  Purpose:  divide the group into several subgroups
392 // ============================================================================
393 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
394 {
395   // New storage will be used in trimmed way to store the list of constraint interacted together.
396   StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
397   std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
398
399   // Obtain constraints, which should be separated
400   std::list<ConstraintPtr> anUnusedConstraints;
401   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
402   for ( ; aCIter != myConstraints.end(); aCIter++) {
403     if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
404       aNewStorage->addConstraint(aCIter->first, aDummyVec);
405     else
406       anUnusedConstraints.push_back(aCIter->first);
407   }
408
409   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
410   std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
411   while (aUnuseIt != anUnusedConstraints.end()) {
412     if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
413       aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
414       anUnusedConstraints.erase(aUnuseIt);
415       aUnuseIt = anUnusedConstraints.begin();
416       continue;
417     }
418     aUnuseIt++;
419   }
420
421   std::list<SketchSolver_Group*>::iterator aCutsIter;
422   aUnuseIt = anUnusedConstraints.begin();
423   for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
424     // Remove unused constraints
425     removeConstraint(*aUnuseIt);
426     // Try to append constraint to already existent group
427     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
428       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
429         (*aCutsIter)->changeConstraint(*aUnuseIt);
430         break;
431       }
432     if (aCutsIter == theCuts.end()) {
433       // Add new group
434       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
435       aGroup->changeConstraint(*aUnuseIt);
436       theCuts.push_back(aGroup);
437     } else {
438       // Find other groups interacting with constraint
439       std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
440       for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
441         if ((*aCutsIter)->isInteract(*aUnuseIt)) {
442           (*aBaseGroupIt)->mergeGroups(**aCutsIter);
443           std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
444           theCuts.erase(aRemoveIt);
445         }
446     }
447   }
448 }
449
450 // ============================================================================
451 //  Function: isConsistent
452 //  Class:    SketchSolver_Group
453 //  Purpose:  search removed entities and constraints
454 // ============================================================================
455 bool SketchSolver_Group::isConsistent()
456 {
457   if (isEmpty()) // no one constraint is initialized yet
458     return true;
459
460   // Check the features and constraint is the storage are valid
461   bool aResult = myStorage->isConsistent();
462   if (aResult) {
463     // additional check of consistency of the Fixed constraint,
464     // because they are not added to the storage
465     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
466     for (; aCIter != myConstraints.end(); ++aCIter)
467       if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
468          (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
469         aResult = false;
470         break;
471       }
472   }
473   if (!aResult) {
474     // remove invalid constraints
475     std::set<ConstraintPtr> anInvalidConstraints;
476     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
477     for (; aCIter != myConstraints.end(); ++aCIter) {
478       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
479         anInvalidConstraints.insert(aCIter->first);
480     }
481     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
482     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
483       removeConstraint(*aRemoveIt);
484     // remove invalid features
485     myStorage->removeInvalidEntities();
486   }
487   return aResult;
488 }
489
490 // ============================================================================
491 //  Function: removeTemporaryConstraints
492 //  Class:    SketchSolver_Group
493 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
494 //            resolving the set of constraints
495 // ============================================================================
496 void SketchSolver_Group::removeTemporaryConstraints()
497 {
498   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
499   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
500     (*aTmpIt)->remove();
501
502   if (!myTempConstraints.empty())
503     myStorage->verifyFixed();
504   myStorage->setNeedToResolve(false);
505   myTempConstraints.clear();
506 }
507
508 // ============================================================================
509 //  Function: removeConstraint
510 //  Class:    SketchSolver_Group
511 //  Purpose:  remove constraint and all unused entities
512 // ============================================================================
513 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
514 {
515   bool isFullyRemoved = true;
516   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
517   for (; aCIter != myConstraints.end(); aCIter++)
518     if (aCIter->first == theConstraint) {
519       if (!aCIter->second->remove()) // the constraint is not fully removed
520         isFullyRemoved = false;
521       break;
522     }
523   if (aCIter == myConstraints.end())
524     return;
525
526   if (isFullyRemoved)
527     myConstraints.erase(aCIter);
528   else if (aCIter != myConstraints.end() &&
529            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
530     // Update multicoincidence
531     std::list<ConstraintPtr> aMultiCoinc;
532     SolverConstraintPtr aCoincidence = aCIter->second;
533     while (aCIter != myConstraints.end()) {
534       if (aCIter->second != aCoincidence) {
535         ++aCIter;
536         continue;
537       }
538       if (aCIter->first != theConstraint)
539         aMultiCoinc.push_back(aCIter->first);
540       aCIter->second->remove();
541       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
542       myConstraints.erase(aRemoveIt);
543     }
544
545     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
546     for (; anIt != aMultiCoinc.end(); ++anIt)
547       changeConstraint(*anIt);
548   }
549 }
550
551 // ============================================================================
552 //  Function: isComplexConstraint
553 //  Class:    SketchSolver_Group
554 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
555 // ============================================================================
556 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
557 {
558   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
559          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
560          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
561 }
562
563 // ============================================================================
564 //  Function: setTemporary
565 //  Class:    SketchSolver_Group
566 //  Purpose:  append given constraint to the group of temporary constraints
567 // ============================================================================
568 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
569 {
570   myTempConstraints.insert(theConstraint);
571 }
572
573
574 // ============================================================================
575 //  Function: checkFeatureValidity
576 //  Class:    SketchSolver_Group
577 //  Purpose:  verifies is the feature valid
578 // ============================================================================
579 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
580 {
581   if (!theFeature || !theFeature->data()->isValid())
582     return true;
583
584   SessionPtr aMgr = ModelAPI_Session::get();
585   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
586   return aFactory->validate(theFeature);
587 }
588
589
590
591
592 // ===========   Auxiliary functions   ========================================
593 static double featureToVal(FeaturePtr theFeature)
594 {
595   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
596     return 0.0; // sketch
597   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
598   if (!aConstraint)
599     return 1.0; // features (arc, circle, line, point)
600
601   const std::string& anID = aConstraint->getKind();
602   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
603     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
604         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
605     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
606         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
607     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
608       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
609     return 2.5;
610   }
611   if (anID == SketchPlugin_ConstraintDistance::ID() ||
612       anID == SketchPlugin_ConstraintLength::ID() ||
613       anID == SketchPlugin_ConstraintRadius::ID())
614     return 3.0;
615   if (anID == SketchPlugin_ConstraintAngle::ID())
616     return 3.5;
617   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
618       anID == SketchPlugin_ConstraintVertical::ID() ||
619       anID == SketchPlugin_ConstraintParallel::ID() ||
620       anID == SketchPlugin_ConstraintPerpendicular::ID())
621     return 4.0;
622   if (anID == SketchPlugin_ConstraintEqual::ID())
623     return 5.0;
624   if (anID == SketchPlugin_ConstraintTangent::ID() ||
625       anID == SketchPlugin_ConstraintMirror::ID())
626     return 6.0;
627   if (anID == SketchPlugin_ConstraintRigid::ID())
628     return 7.0;
629   if (anID == SketchPlugin_MultiRotation::ID() ||
630       anID == SketchPlugin_MultiTranslation::ID())
631     return 8.0;
632
633   // all other constraints are placed between Equal and Tangent constraints
634   return 5.5;
635 }
636
637 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
638 {
639   return featureToVal(theFeature1) < featureToVal(theFeature2);
640 }
641
642 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
643 {
644   std::list<FeaturePtr> aResult;
645   std::list<FeaturePtr>::iterator aResIt;
646
647   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
648   for (; anObjIter != theObjects.end(); ++anObjIter) {
649     // Operate sketch itself and SketchPlugin features only.
650     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
651     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
652     if (!aFeature)
653       continue;
654     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
655         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
656     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
657         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
658       continue;
659
660     // Find the place where to insert a feature
661     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
662       if (isLess(aFeature, *aResIt))
663         break;
664     aResult.insert(aResIt, aFeature);
665   }
666
667   return aResult;
668 }
669