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