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