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