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