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