]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_Group.cpp
Salome HOME
Update groups merging (issue #933)
[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_Builder.h>
10 #include <SketchSolver_Constraint.h>
11 #include <SketchSolver_ConstraintCoincidence.h>
12 #include <SketchSolver_Error.h>
13
14 #include <Events_Error.h>
15 #include <Events_Loop.h>
16 #include <GeomAPI_XY.h>
17 #include <GeomAPI_Dir2d.h>
18 #include <GeomAPI_Pnt2d.h>
19 #include <GeomDataAPI_Dir.h>
20 #include <GeomDataAPI_Point.h>
21 #include <GeomDataAPI_Point2D.h>
22 #include <ModelAPI_AttributeDouble.h>
23 #include <ModelAPI_AttributeString.h>
24 #include <ModelAPI_Document.h>
25 #include <ModelAPI_Events.h>
26 #include <ModelAPI_ResultConstruction.h>
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_Validator.h>
29
30 #include <SketchPlugin_Constraint.h>
31 #include <SketchPlugin_ConstraintAngle.h>
32 #include <SketchPlugin_ConstraintCoincidence.h>
33 #include <SketchPlugin_ConstraintDistance.h>
34 #include <SketchPlugin_ConstraintEqual.h>
35 #include <SketchPlugin_ConstraintHorizontal.h>
36 #include <SketchPlugin_ConstraintLength.h>
37 #include <SketchPlugin_ConstraintFillet.h>
38 #include <SketchPlugin_ConstraintMirror.h>
39 #include <SketchPlugin_ConstraintParallel.h>
40 #include <SketchPlugin_ConstraintPerpendicular.h>
41 #include <SketchPlugin_ConstraintRadius.h>
42 #include <SketchPlugin_ConstraintRigid.h>
43 #include <SketchPlugin_ConstraintTangent.h>
44 #include <SketchPlugin_ConstraintVertical.h>
45 #include <SketchPlugin_Feature.h>
46 #include <SketchPlugin_MultiRotation.h>
47 #include <SketchPlugin_MultiTranslation.h>
48 #include <SketchPlugin_Sketch.h>
49
50 #include <SketchPlugin_Arc.h>
51 #include <SketchPlugin_Circle.h>
52 #include <SketchPlugin_Line.h>
53 #include <SketchPlugin_Point.h>
54 #include <SketchPlugin_Sketch.h>
55
56 #include <math.h>
57 #include <assert.h>
58
59
60 /// \brief This class is used to give unique index to the groups
61 class GroupIndexer
62 {
63 public:
64   /// \brief Return vacant index
65   static Slvs_hGroup NEW_GROUP() { return ++myGroupIndex; }
66   /// \brief Removes the index
67   static void REMOVE_GROUP(const Slvs_hGroup& theIndex) {
68     if (myGroupIndex == theIndex)
69       myGroupIndex--;
70   }
71
72 private:
73   GroupIndexer() {};
74
75   static Slvs_hGroup myGroupIndex; ///< index of the group
76 };
77
78 Slvs_hGroup GroupIndexer::myGroupIndex = 0;
79
80
81 static void sendMessage(const char* theMessageName)
82 {
83   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
84       new Events_Message(Events_Loop::eventByName(theMessageName)));
85   Events_Loop::loop()->send(aMessage);
86 }
87
88
89
90 // ========================================================
91 // =========  SketchSolver_Group  ===============
92 // ========================================================
93
94 SketchSolver_Group::SketchSolver_Group(
95     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
96     : myID(GroupIndexer::NEW_GROUP()),
97       myPrevSolved(true)
98 {
99   // Initialize workplane
100   myWorkplaneID = SLVS_E_UNKNOWN;
101 #ifndef NDEBUG
102   assert(addWorkplane(theWorkplane));
103 #else
104   addWorkplane(theWorkplane);
105 #endif
106 }
107
108 SketchSolver_Group::~SketchSolver_Group()
109 {
110   myConstraints.clear();
111   GroupIndexer::REMOVE_GROUP(myID);
112 }
113
114 // ============================================================================
115 //  Function: isBaseWorkplane
116 //  Class:    SketchSolver_Group
117 //  Purpose:  verify the group is based on the given workplane
118 // ============================================================================
119 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
120 {
121   return theWorkplane == mySketch;
122 }
123
124 // ============================================================================
125 //  Function: isInteract
126 //  Class:    SketchSolver_Group
127 //  Purpose:  verify are there any entities in the group used by given constraint
128 // ============================================================================
129 bool SketchSolver_Group::isInteract(
130     std::shared_ptr<SketchPlugin_Feature> theFeature) const
131 {
132   // Empty group interacts with everything
133   if (isEmpty()) return true;
134   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
135   if (aConstraint)
136     return myFeatureStorage->isInteract(aConstraint);
137   return myFeatureStorage->isInteract(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
138 }
139
140 // ============================================================================
141 //  Function: getFeatureId
142 //  Class:    SketchSolver_Group
143 //  Purpose:  Find the identifier of the feature, if it already exists in the group
144 // ============================================================================
145 Slvs_hEntity SketchSolver_Group::getFeatureId(FeaturePtr theFeature) const
146 {
147   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
148   if (!myFeatureStorage)
149     return aResult;
150   std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(theFeature);
151   if (aConstraints.empty())
152     return aResult;
153   std::set<ConstraintPtr>::iterator aConstrIter = aConstraints.begin();
154   for (; aConstrIter != aConstraints.end(); aConstrIter++) {
155     ConstraintConstraintMap::const_iterator aCIter = myConstraints.find(*aConstrIter);
156     if (aCIter == myConstraints.end())
157       continue;
158     aResult = aCIter->second->getId(theFeature);
159     if (aResult != SLVS_E_UNKNOWN)
160       return aResult;
161   }
162   return SLVS_E_UNKNOWN;
163 }
164
165 // ============================================================================
166 //  Function: getAttributeId
167 //  Class:    SketchSolver_Group
168 //  Purpose:  Find the identifier of the attribute, if it already exists in the group
169 // ============================================================================
170 Slvs_hEntity SketchSolver_Group::getAttributeId(AttributePtr theAttribute) const
171 {
172   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
173   if (!myFeatureStorage)
174     return aResult;
175   std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(theAttribute);
176   if (aConstraints.empty())
177     return aResult;
178   std::set<ConstraintPtr>::iterator aConstrIter = aConstraints.begin();
179   for (; aConstrIter != aConstraints.end(); aConstrIter++) {
180     ConstraintConstraintMap::const_iterator aCIter = myConstraints.find(*aConstrIter);
181     if (aCIter == myConstraints.end())
182       continue;
183     aResult = aCIter->second->getId(theAttribute);
184     if (aResult != SLVS_E_UNKNOWN)
185       return aResult;
186   }
187   return SLVS_E_UNKNOWN;
188 }
189
190 // ============================================================================
191 //  Function: changeConstraint
192 //  Class:    SketchSolver_Group
193 //  Purpose:  create/update the constraint in the group
194 // ============================================================================
195 bool SketchSolver_Group::changeConstraint(
196     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
197 {
198   // There is no workplane yet, something wrong
199   if (myWorkplaneID == SLVS_E_UNKNOWN)
200     return false;
201
202   if (!theConstraint)
203     return false;
204
205   if (!checkFeatureValidity(theConstraint))
206     return false;
207
208   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
209   if (isNewConstraint) {
210     // Add constraint to the current group
211     SolverConstraintPtr aConstraint =
212         SketchSolver_Builder::getInstance()->createConstraint(theConstraint);
213     if (!aConstraint)
214       return false;
215     aConstraint->setGroup(this);
216     aConstraint->setStorage(myStorage);
217     if (!aConstraint->error().empty()) {
218       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
219         return false; // some attribute are not initialized yet, don't show message
220       Events_Error::send(aConstraint->error(), this);
221     }
222
223     // Additional verification of coincidence of several points
224     if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
225       ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
226       for (; aCIter != myConstraints.end(); aCIter++) {
227         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoincidence =
228           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aCIter->second);
229         if (!aCoincidence)
230           continue;
231         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoinc2 =
232           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aConstraint);
233         if (aCoincidence != aCoinc2 && aCoincidence->isCoincide(aCoinc2)) {
234           aCoinc2->attach(aCoincidence);
235           // update other coincidences
236           ConstraintConstraintMap::iterator anIt = aCIter;
237           for (++anIt; anIt != myConstraints.end(); ++anIt)
238             if (anIt->second == aCIter->second)
239               anIt->second = aCoinc2;
240           aCIter->second = aCoinc2;
241         }
242       }
243     }
244     myConstraints[theConstraint] = aConstraint;
245   }
246   else
247     myConstraints[theConstraint]->update();
248
249   // Fix base features for fillet
250   if (isNewConstraint && theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
251     std::list<AttributePtr> anAttrList =
252         theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
253     std::list<AttributePtr>::iterator anAttrIter = anAttrList.begin();
254     for (; anAttrIter != anAttrList.end(); anAttrIter++) {
255       AttributeRefAttrPtr aRefAttr =
256           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
257       if (!aRefAttr || !aRefAttr->isObject())
258         continue;
259       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
260       SolverConstraintPtr aConstraint =
261           SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
262       if (!aConstraint)
263         continue;
264       aConstraint->setGroup(this);
265       aConstraint->setStorage(myStorage);
266       setTemporary(aConstraint);
267     }
268   }
269   // Fix mirror line
270   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
271     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
272         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
273     if (aRefAttr && aRefAttr->isObject()) {
274       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
275       if (aFeature) {
276         SolverConstraintPtr aConstraint =
277             SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
278         if (aConstraint) {
279           aConstraint->setGroup(this);
280           aConstraint->setStorage(myStorage);
281           setTemporary(aConstraint);
282         }
283       }
284     }
285   }
286
287   if (!myFeatureStorage)
288     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
289   myFeatureStorage->changeConstraint(theConstraint);
290
291   return true;
292 }
293
294
295 void SketchSolver_Group::updateConstraints()
296 {
297   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
298
299   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
300   for (; anIt != myConstraints.end(); ++anIt) {
301     if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
302       continue;
303     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
304         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
305       aPostponed.insert(anIt->second);
306     else
307       anIt->second->update();
308   }
309
310   // Update postponed constraints
311   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
312   for (; aSCIter != aPostponed.end(); ++aSCIter)
313     (*aSCIter)->update();
314
315   myChangedConstraints.clear();
316 }
317
318 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
319 {
320   if (!checkFeatureValidity(theFeature))
321     return false;
322
323   std::set<ConstraintPtr> aConstraints =
324       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
325   if (aConstraints.empty())
326     return false;
327   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
328   for (; aCIter != aConstraints.end(); aCIter++) {
329     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
330     if (aSolConIter == myConstraints.end() || !aSolConIter->first->data() ||
331         !aSolConIter->first->data()->isValid())
332       continue;
333     myFeatureStorage->changeFeature(theFeature, aSolConIter->first);
334
335     aSolConIter->second->addFeature(theFeature);
336     myChangedConstraints.insert(aSolConIter->first);
337   }
338   return true;
339 }
340
341 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
342 {
343   // Firstly, create temporary rigid constraint
344   SolverConstraintPtr aConstraint =
345       SketchSolver_Builder::getInstance()->createMovementConstraint(theFeature);
346   if (!aConstraint)
347     return;
348   aConstraint->setGroup(this);
349   aConstraint->setStorage(myStorage);
350   if (aConstraint->error().empty())
351     setTemporary(aConstraint);
352   // Secondly, update the feature
353   updateFeature(theFeature);
354 }
355
356 // ============================================================================
357 //  Function: fixFeaturesList
358 //  Class:    SketchSolver_Group
359 //  Purpose:  Apply temporary rigid constraints for the list of features
360 // ============================================================================
361 void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
362 {
363   std::list<ObjectPtr> aList = theList->list();
364   std::list<ObjectPtr>::iterator anIt = aList.begin();
365   std::list<FeaturePtr> aFeatures;
366   // Sort features, at begining there are features used by Equal constraint
367   for (; anIt != aList.end(); anIt++) {
368     if (!(*anIt))
369       continue;
370     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
371     std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(aFeature);
372     std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
373     for (; aCIter != aConstraints.end(); aCIter++)
374       if ((*aCIter)->getKind() == SketchPlugin_ConstraintEqual::ID())
375         break;
376     if (aCIter != aConstraints.end())
377       aFeatures.push_front(aFeature);
378     else
379       aFeatures.push_back(aFeature);
380   }
381
382   std::list<FeaturePtr>::iterator aFeatIter = aFeatures.begin();
383   for (; aFeatIter != aFeatures.end(); aFeatIter++) {
384     SolverConstraintPtr aConstraint =
385         SketchSolver_Builder::getInstance()->createRigidConstraint(*aFeatIter);
386     if (!aConstraint)
387       continue;
388     aConstraint->setGroup(this);
389     aConstraint->setStorage(myStorage);
390     setTemporary(aConstraint);
391   }
392 }
393
394 // ============================================================================
395 //  Function: addWorkplane
396 //  Class:    SketchSolver_Group
397 //  Purpose:  create workplane for the group
398 // ============================================================================
399 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
400 {
401   if (myWorkplaneID != SLVS_E_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
402     return false;  // the workplane already exists or the function parameter is not Sketch
403
404   mySketch = theSketch;
405   updateWorkplane();
406   return true;
407 }
408
409 // ============================================================================
410 //  Function: updateWorkplane
411 //  Class:    SketchSolver_Group
412 //  Purpose:  update parameters of workplane
413 // ============================================================================
414 bool SketchSolver_Group::updateWorkplane()
415 {
416   if (!myStorage) // Create storage if not exists
417     myStorage = StoragePtr(new SketchSolver_Storage);
418   SketchSolver_Builder* aBuilder = SketchSolver_Builder::getInstance();
419
420   std::vector<Slvs_Entity> anEntities;
421   std::vector<Slvs_Param> aParams;
422   if (!aBuilder->createWorkplane(mySketch, anEntities, aParams))
423     return false;
424
425   if (myWorkplaneID == SLVS_E_UNKNOWN) {
426     myWorkplaneID = anEntities.back().h;
427     // Add new workplane elements
428     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
429     for (; aParIter != aParams.end(); aParIter++) {
430       aParIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
431       aParIter->group = myID;
432       aParIter->h = myStorage->addParameter(*aParIter);
433     }
434     std::vector<Slvs_Entity>::iterator anEntIter = anEntities.begin();
435     for (; anEntIter != anEntities.end(); anEntIter++) {
436       anEntIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
437       anEntIter->group = myID;
438       anEntIter->wrkpl = myWorkplaneID;
439       for (int i = 0; i < 4; i++)
440         if (anEntIter->param[i] != SLVS_E_UNKNOWN)
441           anEntIter->param[i] = aParams[anEntIter->param[i]-1].h;
442       for (int i = 0; i < 4; i++)
443         if (anEntIter->point[i] != SLVS_E_UNKNOWN)
444           anEntIter->point[i] = anEntities[anEntIter->point[i]-1].h;
445       anEntIter->h = myStorage->addEntity(*anEntIter);
446     }
447   } else {
448     // Update existent workplane
449     const Slvs_Entity& aWP = myStorage->getEntity(myWorkplaneID);
450     const Slvs_Entity& anOrigin = myStorage->getEntity(aWP.point[0]);
451     const Slvs_Entity& aNormal = myStorage->getEntity(aWP.normal);
452     // Get parameters and update them
453     Slvs_hParam aWPParams[7] = {
454         anOrigin.param[0], anOrigin.param[1], anOrigin.param[2],
455         aNormal.param[0], aNormal.param[1], aNormal.param[2], aNormal.param[3]
456       };
457     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
458     for (int i = 0; aParIter != aParams.end(); aParIter++, i++) {
459       Slvs_Param aParam = myStorage->getParameter(aWPParams[i]);
460       aParam.val = aParIter->val;
461       myStorage->updateParameter(aParam);
462     }
463   }
464   return myWorkplaneID > 0;
465 }
466
467 // ============================================================================
468 //  Function: resolveConstraints
469 //  Class:    SketchSolver_Group
470 //  Purpose:  solve the set of constraints for the current group
471 // ============================================================================
472 bool SketchSolver_Group::resolveConstraints()
473 {
474   if (!myChangedConstraints.empty())
475     updateConstraints();
476
477   bool aResolved = false;
478   if (myStorage->isNeedToResolve() && !isEmpty()) {
479     myConstrSolver.setGroupID(myID);
480     myStorage->initializeSolver(myConstrSolver);
481
482     int aResult = SLVS_RESULT_OKAY;
483     try {
484       if (myStorage->hasDuplicatedConstraint())
485         aResult = SLVS_RESULT_INCONSISTENT;
486       else {
487         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
488         // and try to find the case without overconstraint
489         bool isLastChance = false;
490         int aNbTemp = myStorage->numberTemporary();
491         while (true) {
492           aResult = myConstrSolver.solve();
493           if (aResult == SLVS_RESULT_OKAY || isLastChance)
494             break;
495           if (aNbTemp <= 0) {
496             // try to update parameters and resolve once again
497             ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
498             for (; aConstrIt != myConstraints.end(); ++aConstrIt)
499               aConstrIt->second->update();
500             isLastChance = true;
501           } else
502             aNbTemp = myStorage->deleteTemporaryConstraint();
503           myStorage->initializeSolver(myConstrSolver);
504         }
505       }
506     } catch (...) {
507 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
508       if (myPrevSolved) {
509         sendMessage(EVENT_SOLVER_FAILED);
510         myPrevSolved = false;
511       }
512       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
513       return false;
514     }
515     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
516       myFeatureStorage->blockEvents(true);
517       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
518       for (; aConstrIter != myConstraints.end(); aConstrIter++)
519         aConstrIter->second->refresh();
520       myFeatureStorage->blockEvents(false);
521       if (!myPrevSolved) {
522         sendMessage(EVENT_SOLVER_REPAIRED);
523         myPrevSolved = true;
524       }
525       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
526     } else if (!myConstraints.empty()) {
527 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
528       if (myPrevSolved) {
529         sendMessage(EVENT_SOLVER_FAILED);
530         myPrevSolved = false;
531       }
532       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
533     }
534
535     aResolved = true;
536   }
537   removeTemporaryConstraints();
538   myStorage->setNeedToResolve(false);
539   return aResolved;
540 }
541
542 // ============================================================================
543 //  Function: mergeGroups
544 //  Class:    SketchSolver_Group
545 //  Purpose:  append specified group to the current group
546 // ============================================================================
547 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
548 {
549   // If specified group is empty, no need to merge
550   if (theGroup.isEmpty())
551     return;
552   if (!myFeatureStorage)
553     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
554
555   std::set<ObjectPtr> aConstraints;
556   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
557   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
558     aConstraints.insert(aConstrIter->first);
559
560   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
561   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
562   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
563     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
564     if (!aConstr)
565       continue;
566     changeConstraint(aConstr);
567   }
568 }
569
570 // ============================================================================
571 //  Function: splitGroup
572 //  Class:    SketchSolver_Group
573 //  Purpose:  divide the group into several subgroups
574 // ============================================================================
575 void SketchSolver_Group::splitGroup(std::vector<SketchSolver_Group*>& theCuts)
576 {
577   // Obtain constraints, which should be separated
578   FeatureStoragePtr aNewFeatStorage(new SketchSolver_FeatureStorage);
579   std::vector<ConstraintPtr> anUnusedConstraints;
580   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
581   for ( ; aCIter != myConstraints.end(); aCIter++) {
582     std::list<ConstraintPtr> aBaseConstraints = aCIter->second->constraints();
583     std::list<ConstraintPtr>::iterator anIter = aBaseConstraints.begin();
584     for (; anIter != aBaseConstraints.end(); anIter++)
585       if (aNewFeatStorage->isInteract(*anIter)) {
586         aNewFeatStorage->changeConstraint(*anIter);
587       } else
588         anUnusedConstraints.push_back(*anIter);
589   }
590
591   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
592   std::vector<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
593   while (aUnuseIt != anUnusedConstraints.end()) {
594     if (aNewFeatStorage->isInteract(*aUnuseIt)) {
595       size_t aShift = aUnuseIt - anUnusedConstraints.begin();
596       anUnusedConstraints.erase(aUnuseIt);
597       aUnuseIt = anUnusedConstraints.begin() + aShift;
598       continue;
599     }
600     aUnuseIt++;
601   }
602
603   std::vector<SketchSolver_Group*>::iterator aCutsIter;
604   aUnuseIt = anUnusedConstraints.begin();
605   for ( ; aUnuseIt != anUnusedConstraints.end(); aUnuseIt++) {
606     // Remove unused constraints
607     removeConstraint(*aUnuseIt);
608     // Try to append constraint to already existent group
609     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); aCutsIter++)
610       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
611         (*aCutsIter)->changeConstraint(*aUnuseIt);
612         break;
613       }
614     if (aCutsIter == theCuts.end()) {
615       // Add new group
616       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
617       aGroup->changeConstraint(*aUnuseIt);
618       theCuts.push_back(aGroup);
619     }
620   }
621 }
622
623 // ============================================================================
624 //  Function: isConsistent
625 //  Class:    SketchSolver_Group
626 //  Purpose:  search removed entities and constraints
627 // ============================================================================
628 bool SketchSolver_Group::isConsistent()
629 {
630   if (!myFeatureStorage) // no one constraint is initialized yet
631     return true;
632
633   bool aResult = myFeatureStorage->isConsistent();
634   if (!aResult) {
635     // remove invalid entities
636     std::set<ConstraintPtr> anInvalidConstraints;
637     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
638     for (; aCIter != myConstraints.end(); ++aCIter) {
639       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
640         anInvalidConstraints.insert(aCIter->first);
641     }
642     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
643     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
644       removeConstraint(*aRemoveIt);
645   }
646   return aResult;
647 }
648
649 // ============================================================================
650 //  Function: removeTemporaryConstraints
651 //  Class:    SketchSolver_Group
652 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
653 //            resolving the set of constraints
654 // ============================================================================
655 void SketchSolver_Group::removeTemporaryConstraints()
656 {
657   myTempConstraints.clear();
658   while (myStorage->numberTemporary())
659     myStorage->deleteTemporaryConstraint();
660   // Clean lists of removed entities in the storage
661   std::set<Slvs_hParam> aRemPar;
662   std::set<Slvs_hEntity> aRemEnt;
663   std::set<Slvs_hConstraint> aRemCon;
664   myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
665   myStorage->setNeedToResolve(false);
666 }
667
668 // ============================================================================
669 //  Function: removeConstraint
670 //  Class:    SketchSolver_Group
671 //  Purpose:  remove constraint and all unused entities
672 // ============================================================================
673 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
674 {
675   bool isFullyRemoved = true;
676   myFeatureStorage->removeConstraint(theConstraint);
677   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
678   for (; aCIter != myConstraints.end(); aCIter++)
679     if (aCIter->second->hasConstraint(theConstraint)) {
680       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
681         isFullyRemoved = false;
682       break;
683     }
684   if (aCIter == myConstraints.end())
685     return;
686
687   if (isFullyRemoved)
688     myConstraints.erase(aCIter);
689   else if (aCIter != myConstraints.end() &&
690            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
691     // Update multicoincidence
692     std::list<ConstraintPtr> aMultiCoinc;
693     SolverConstraintPtr aCoincidence = aCIter->second;
694     while (aCIter != myConstraints.end()) {
695       if (aCIter->second != aCoincidence) {
696         ++aCIter;
697         continue;
698       }
699       if (aCIter->first != theConstraint)
700         aMultiCoinc.push_back(aCIter->first);
701       aCIter->second->remove(aCIter->first);
702       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
703       myConstraints.erase(aRemoveIt);
704     }
705
706     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
707     for (; anIt != aMultiCoinc.end(); ++anIt)
708       changeConstraint(*anIt);
709   }
710 }
711
712 // ============================================================================
713 //  Function: isComplexConstraint
714 //  Class:    SketchSolver_Group
715 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
716 // ============================================================================
717 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
718 {
719   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
720          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
721          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
722 }
723
724 // ============================================================================
725 //  Function: setTemporary
726 //  Class:    SketchSolver_Group
727 //  Purpose:  append given constraint to th group of temporary constraints
728 // ============================================================================
729 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
730 {
731   theConstraint->makeTemporary();
732   myTempConstraints.insert(theConstraint);
733 }
734
735
736 // ============================================================================
737 //  Function: checkFeatureValidity
738 //  Class:    SketchSolver_Group
739 //  Purpose:  verifies is the feature valid
740 // ============================================================================
741 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
742 {
743   if (!theFeature || !theFeature->data()->isValid())
744     return true;
745
746   SessionPtr aMgr = ModelAPI_Session::get();
747   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
748   return aFactory->validate(theFeature);
749 }
750
751
752
753
754
755 // ===========   Auxiliary functions   ========================================
756 static double featureToVal(FeaturePtr theFeature)
757 {
758   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
759     return 0.0; // sketch
760   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
761   if (!aConstraint)
762     return 1.0; // features (arc, circle, line, point)
763
764   const std::string& anID = aConstraint->getKind();
765   if (anID == SketchPlugin_ConstraintCoincidence::ID())
766     return 2.0;
767   if (anID == SketchPlugin_ConstraintDistance::ID() ||
768       anID == SketchPlugin_ConstraintLength::ID() ||
769       anID == SketchPlugin_ConstraintRadius::ID() ||
770       anID == SketchPlugin_ConstraintAngle::ID())
771     return 3.0;
772   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
773       anID == SketchPlugin_ConstraintVertical::ID() ||
774       anID == SketchPlugin_ConstraintParallel::ID() ||
775       anID == SketchPlugin_ConstraintPerpendicular::ID())
776     return 4.0;
777   if (anID == SketchPlugin_ConstraintEqual::ID())
778     return 5.0;
779   if (anID == SketchPlugin_ConstraintTangent::ID() ||
780       anID == SketchPlugin_ConstraintMirror::ID())
781     return 6.0;
782   if (anID == SketchPlugin_ConstraintRigid::ID())
783     return 7.0;
784   if (anID == SketchPlugin_MultiRotation::ID() ||
785       anID == SketchPlugin_MultiTranslation::ID())
786     return 8.0;
787
788   // all other constraints are placed between Equal and Tangent constraints
789   return 5.5;
790 }
791
792 static bool operator< (FeaturePtr theFeature1, FeaturePtr theFeature2)
793 {
794   return featureToVal(theFeature1) < featureToVal(theFeature2);
795 }
796
797 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
798 {
799   std::list<FeaturePtr> aResult;
800   std::list<FeaturePtr>::iterator aResIt;
801
802   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
803   for (; anObjIter != theObjects.end(); ++anObjIter) {
804     // Operate sketch itself and SketchPlugin features only.
805     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
806     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
807     if (!aFeature)
808       continue;
809     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
810         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
811     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
812         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
813       continue;
814
815     // Find the place where to insert a feature
816     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
817       if (aFeature < *aResIt)
818         break;
819     aResult.insert(aResIt, aFeature);
820   }
821
822   return aResult;
823 }
824