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