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