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