Salome HOME
3cb51724764bb3d49f163e25583e4cb04aa9a209
[modules/shaper.git] / src / SketchSolver / SketchSolver_ConstraintGroup.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SketchSolver_ConstraintGroup.cpp
4 // Created: 27 May 2014
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchSolver_ConstraintGroup.h"
8
9 #include <SketchSolver_Constraint.h>
10
11 #include <Events_Error.h>
12 #include <Events_Loop.h>
13 #include <GeomAPI_XY.h>
14 #include <GeomAPI_Pnt2d.h>
15 #include <GeomDataAPI_Dir.h>
16 #include <GeomDataAPI_Point.h>
17 #include <GeomDataAPI_Point2D.h>
18 #include <ModelAPI_AttributeDouble.h>
19 #include <ModelAPI_AttributeRefList.h>
20 #include <ModelAPI_Document.h>
21 #include <ModelAPI_Events.h>
22 #include <ModelAPI_ResultConstruction.h>
23
24 #include <SketchPlugin_Constraint.h>
25 #include <SketchPlugin_ConstraintLength.h>
26 #include <SketchPlugin_ConstraintCoincidence.h>
27 #include <SketchPlugin_ConstraintRigid.h>
28
29 #include <SketchPlugin_Arc.h>
30 #include <SketchPlugin_Circle.h>
31 #include <SketchPlugin_Line.h>
32 #include <SketchPlugin_Point.h>
33 #include <SketchPlugin_Sketch.h>
34
35 #include <math.h>
36 #include <assert.h>
37
38 /// Tolerance for value of parameters
39 const double tolerance = 1.e-10;
40
41 /**
42  * Collects all sketch solver error' codes
43  * as inline static functions
44  */
45  // TODO: Move this class into a separate file
46 class SketchSolver_Error
47 {
48  public:
49   /// The value parameter for the constraint
50   inline static const std::string& CONSTRAINTS()
51   {
52     static const std::string MY_ERROR_VALUE("Conflicting constraints");
53     return MY_ERROR_VALUE;
54   }
55 };
56
57 /// This value is used to give unique index to the groups
58 static Slvs_hGroup myGroupIndexer = 0;
59
60 /** \brief Search the entity/parameter with specified ID in the list of elements
61  *  \param[in] theEntityID unique ID of the element
62  *  \param[in] theEntities list of elements
63  *  \return position of the found element or -1 if the element is not found
64  */
65 template<typename T>
66 static int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities);
67
68 // ========================================================
69 // =========  SketchSolver_ConstraintGroup  ===============
70 // ========================================================
71
72 SketchSolver_ConstraintGroup::SketchSolver_ConstraintGroup(
73     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
74     : myID(++myGroupIndexer),
75       myParamMaxID(0),
76       myEntityMaxID(0),
77       myConstrMaxID(0),
78       myConstraintMap(),
79       myNeedToSolve(false),
80       myConstrSolver()
81 {
82   myParams.clear();
83   myEntities.clear();
84   myEntOfConstr.clear();
85   myConstraints.clear();
86
87   myTempConstraints.clear();
88   myTempPointWhereDragged.clear();
89   myTempPointWDrgdID = 0;
90
91   // Initialize workplane
92   myWorkplane.h = SLVS_E_UNKNOWN;
93 #ifndef NDEBUG
94   assert(addWorkplane(theWorkplane));
95 #else
96   addWorkplane(theWorkplane);
97 #endif
98 }
99
100 SketchSolver_ConstraintGroup::~SketchSolver_ConstraintGroup()
101 {
102   myParams.clear();
103   myEntities.clear();
104   myEntOfConstr.clear();
105   myConstraints.clear();
106   myConstraintMap.clear();
107   myTempConstraints.clear();
108   myTempPointWhereDragged.clear();
109
110   // If the group with maximal identifier is deleted, decrease the indexer
111   if (myID == myGroupIndexer)
112     myGroupIndexer--;
113 }
114
115 // ============================================================================
116 //  Function: isBaseWorkplane
117 //  Class:    SketchSolver_ConstraintGroup
118 //  Purpose:  verify the group is based on the given workplane
119 // ============================================================================
120 bool SketchSolver_ConstraintGroup::isBaseWorkplane(
121     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane) const
122 {
123   return theWorkplane == mySketch;
124 }
125
126 // ============================================================================
127 //  Function: isInteract
128 //  Class:    SketchSolver_ConstraintGroup
129 //  Purpose:  verify are there any entities in the group used by given constraint
130 // ============================================================================
131 bool SketchSolver_ConstraintGroup::isInteract(
132     std::shared_ptr<SketchPlugin_Feature> theFeature) const
133 {
134   // Check the group is empty
135   if (isEmpty())
136     return true;
137
138   // Check if the feature is already in the group
139   if (myEntityFeatMap.find(theFeature) != myEntityFeatMap.end())
140     return true;
141   std::shared_ptr<SketchPlugin_Constraint> aConstr =
142       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
143   if (aConstr && myConstraintMap.find(aConstr) != myConstraintMap.end())
144     return true;
145
146   // Go through the attributes and verify if some of them already in the group
147   std::list<std::shared_ptr<ModelAPI_Attribute>> 
148       anAttrList = theFeature->data()->attributes(std::string());
149   std::list<std::shared_ptr<ModelAPI_Attribute>>::const_iterator
150       anAttrIter = anAttrList.begin();
151   for ( ; anAttrIter != anAttrList.end(); anAttrIter++) {
152     std::shared_ptr<ModelAPI_AttributeRefAttr> aCAttrRef =
153         std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
154     if (!aCAttrRef || !aCAttrRef->isObject()) {
155       std::shared_ptr<ModelAPI_Attribute> anAttr = 
156           aCAttrRef ? aCAttrRef->attr() : *anAttrIter;
157       if (myEntityAttrMap.find(anAttr) != myEntityAttrMap.end())
158         return true;
159     } else {
160       ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(
161           aCAttrRef->object());
162       if (!aRC)
163         continue;
164       std::shared_ptr<ModelAPI_Document> aDoc = aRC->document();
165       FeaturePtr aFeature = aDoc->feature(aRC);
166       if (myEntityFeatMap.find(aFeature) != myEntityFeatMap.end())
167         return true;
168       // search attributes of a feature to be parameters of constraint
169       std::list<std::shared_ptr<ModelAPI_Attribute> > aFeatAttrList =
170           aFeature->data()->attributes(std::string());
171       std::list<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aFAIter = aFeatAttrList
172           .begin();
173       for (; aFAIter != aFeatAttrList.end(); aFAIter++)
174         if (myEntityAttrMap.find(*aFAIter) != myEntityAttrMap.end())
175           return true;
176     }
177   }
178
179   // Entities did not found
180   return false;
181 }
182
183 // ============================================================================
184 //  Function: checkConstraintConsistence
185 //  Class:    SketchSolver_ConstraintGroup
186 //  Purpose:  verifies and changes parameters of the constraint
187 // ============================================================================
188 void SketchSolver_ConstraintGroup::checkConstraintConsistence(Slvs_Constraint& theConstraint)
189 {
190   if (theConstraint.type == SLVS_C_PT_LINE_DISTANCE) {
191     // Get constraint parameters and check the sign of constraint value
192
193     // point coordinates
194     int aPtPos = Search(theConstraint.ptA, myEntities);
195     int aPtParamPos = Search(myEntities[aPtPos].param[0], myParams);
196     std::shared_ptr<GeomAPI_XY> aPoint(
197         new GeomAPI_XY(myParams[aPtParamPos].val, myParams[aPtParamPos + 1].val));
198
199     // line coordinates
200     int aLnPos = Search(theConstraint.entityA, myEntities);
201     aPtPos = Search(myEntities[aLnPos].point[0], myEntities);
202     aPtParamPos = Search(myEntities[aPtPos].param[0], myParams);
203     std::shared_ptr<GeomAPI_XY> aStart(
204         new GeomAPI_XY(-myParams[aPtParamPos].val, -myParams[aPtParamPos + 1].val));
205     aPtPos = Search(myEntities[aLnPos].point[1], myEntities);
206     aPtParamPos = Search(myEntities[aPtPos].param[0], myParams);
207     std::shared_ptr<GeomAPI_XY> aEnd(
208         new GeomAPI_XY(myParams[aPtParamPos].val, myParams[aPtParamPos + 1].val));
209
210     aEnd = aEnd->added(aStart);
211     aPoint = aPoint->added(aStart);
212     if (aPoint->cross(aEnd) * theConstraint.valA < 0.0)
213       theConstraint.valA *= -1.0;
214   }
215 }
216
217 // ============================================================================
218 //  Function: changeConstraint
219 //  Class:    SketchSolver_ConstraintGroup
220 //  Purpose:  create/update the constraint in the group
221 // ============================================================================
222 bool SketchSolver_ConstraintGroup::changeConstraint(
223     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
224 {
225   // There is no workplane yet, something wrong
226   if (myWorkplane.h == SLVS_E_UNKNOWN)
227     return false;
228
229   if (theConstraint && theConstraint->getKind() == SketchPlugin_ConstraintRigid::ID())
230     return changeRigidConstraint(theConstraint);
231
232   // Search this constraint in the current group to update it
233   ConstraintMap::const_iterator aConstrMapIter = myConstraintMap.find(theConstraint);
234   std::vector<Slvs_Constraint>::iterator aConstrIter;
235   if (aConstrMapIter != myConstraintMap.end()) {
236     int aConstrPos = Search(aConstrMapIter->second.front(), myConstraints);
237     aConstrIter = myConstraints.begin() + aConstrPos;
238   }
239
240   // Get constraint type and verify the constraint parameters are correct
241   SketchSolver_Constraint aConstraint(theConstraint);
242   int aConstrType = aConstraint.getType();
243   if (aConstrType == SLVS_C_UNKNOWN
244       || (aConstrMapIter != myConstraintMap.end() && aConstrIter->type != aConstrType))
245     return false;
246   const std::vector<std::string>& aConstraintAttributes = aConstraint.getAttributes();
247
248   // Create constraint parameters
249   double aDistance = 0.0;  // scalar value of the constraint
250   AttributeDoublePtr aDistAttr = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
251       theConstraint->data()->attribute(SketchPlugin_Constraint::VALUE()));
252   if (aDistAttr) {
253     aDistance = aDistAttr->value();
254     // Issue #196: checking the positivity of the distance constraint
255     if (aDistance < tolerance &&
256        (aConstrType == SLVS_C_PT_PT_DISTANCE || aConstrType == SLVS_C_PT_LINE_DISTANCE))
257       return false;
258     // SketchPlugin circle defined by its radius, but SolveSpace uses constraint for diameter
259     if (aConstrType == SLVS_C_DIAMETER)
260       aDistance *= 2.0;
261     if (aConstrMapIter != myConstraintMap.end()
262         && fabs(aConstrIter->valA - aDistance) > tolerance) {
263       myNeedToSolve = true;
264       aConstrIter->valA = aDistance;
265     }
266   }
267
268   size_t aNbTmpConstraints = myTempConstraints.size();
269   Slvs_hEntity aConstrEnt[CONSTRAINT_ATTR_SIZE];  // parameters of the constraint
270   for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++) {
271     aConstrEnt[indAttr] = SLVS_E_UNKNOWN;
272     std::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr = std::dynamic_pointer_cast<
273         ModelAPI_AttributeRefAttr>(
274         theConstraint->data()->attribute(aConstraintAttributes[indAttr]));
275     if (!aConstrAttr)
276       continue;
277
278     // Convert the object of the attribute to the feature
279     FeaturePtr aFeature;
280     if (aConstrAttr->isObject() && aConstrAttr->object()) {
281       ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(
282           aConstrAttr->object());
283       if (!aRC)
284         continue;
285       std::shared_ptr<ModelAPI_Document> aDoc = aRC->document();
286       aFeature = aDoc->feature(aRC);
287     }
288
289     // For the length constraint the start and end points of the line should be added to the entities list instead of line
290     if (aConstrType == SLVS_C_PT_PT_DISTANCE
291         && theConstraint->getKind().compare(SketchPlugin_ConstraintLength::ID()) == 0) {
292       Slvs_hEntity aLineEnt = changeEntityFeature(aFeature);
293       int aEntPos = Search(aLineEnt, myEntities);
294       aConstrEnt[indAttr++] = myEntities[aEntPos].point[0];
295       aConstrEnt[indAttr++] = myEntities[aEntPos].point[1];
296       while (indAttr < CONSTRAINT_ATTR_SIZE)
297         aConstrEnt[indAttr++] = 0;
298       break;  // there should be no other entities
299     } else if (aConstrAttr->isObject())
300       aConstrEnt[indAttr] = changeEntityFeature(aFeature);
301     else
302       aConstrEnt[indAttr] = changeEntity(aConstrAttr->attr());
303   }
304
305   if (aConstrMapIter == myConstraintMap.end()) { // Add new constraint
306     // Several points may be coincident, it is not necessary to store all constraints between them.
307     // Try to find sequence of coincident points which connects the points of new constraint
308     if (aConstrType == SLVS_C_POINTS_COINCIDENT) {
309       if (aConstrEnt[0] == aConstrEnt[1])  // no need to add self coincidence
310         return false;
311       if (!addCoincidentPoints(aConstrEnt[0], aConstrEnt[1])) {
312         myExtraCoincidence.insert(theConstraint);  // the constraint is stored for further purposes
313         return false;
314       }
315       if (aNbTmpConstraints < myTempConstraints.size()) {
316         // There was added temporary constraint. Check that there is no coincident points which already rigid.
317
318         // Get list of already fixed points
319         std::set<Slvs_hEntity> anAlreadyFixed;
320         std::vector<Slvs_Constraint>::const_iterator aCIter = myConstraints.begin();
321         for (; aCIter != myConstraints.end(); aCIter++)
322           if (aCIter->type == SLVS_C_WHERE_DRAGGED) {
323             std::list<Slvs_hConstraint>::const_iterator aTmpIt = myTempConstraints.begin();
324             for (; aTmpIt != myTempConstraints.end(); aTmpIt++)
325               if (*aTmpIt == aCIter->h)
326                 break;
327             if (aTmpIt == myTempConstraints.end())
328               anAlreadyFixed.insert(aCIter->ptA);
329           }
330
331         std::set<Slvs_hConstraint> aTmpConstrToDelete;
332         std::list<Slvs_hConstraint>::reverse_iterator aTmpIter = myTempConstraints.rbegin();
333         size_t aCurSize = myTempConstraints.size();
334         for (; aCurSize > aNbTmpConstraints && aTmpIter != myTempConstraints.rend();
335             aTmpIter++, aCurSize--) {
336           int aConstrPos = Search(*aTmpIter, myConstraints);
337           std::vector<std::set<Slvs_hEntity> >::const_iterator
338             aCoincIter = myCoincidentPoints.begin();
339           for (; aCoincIter != myCoincidentPoints.end(); aCoincIter++)
340             if (aCoincIter->find(myConstraints[aConstrPos].ptA) != aCoincIter->end()) {
341               std::set<Slvs_hEntity>::const_iterator anIt;
342               for (anIt = aCoincIter->begin(); anIt != aCoincIter->end(); anIt++)
343                 if (anAlreadyFixed.find(*anIt) != anAlreadyFixed.end()) {
344                   aTmpConstrToDelete.insert(*aTmpIter);
345                   break;
346                 }
347               break;
348             }
349         }
350         if (!aTmpConstrToDelete.empty())
351           removeTemporaryConstraints(aTmpConstrToDelete);
352       }
353     }
354
355     // Create SolveSpace constraint structure
356     Slvs_Constraint aConstraint = Slvs_MakeConstraint(++myConstrMaxID, myID, aConstrType,
357                                                       myWorkplane.h, aDistance, aConstrEnt[0],
358                                                       aConstrEnt[1], aConstrEnt[2], aConstrEnt[3]);
359     myConstraints.push_back(aConstraint);
360     myConstraintMap[theConstraint] = std::vector<Slvs_hEntity>(1, aConstraint.h);
361     int aConstrPos = Search(aConstraint.h, myConstraints);
362     aConstrIter = myConstraints.begin() + aConstrPos;
363     myNeedToSolve = true;
364   } else { // Attributes of constraint may be changed => update constraint
365     Slvs_hEntity* aCurrentAttr[] = {&aConstrIter->ptA, &aConstrIter->ptB,
366                                    &aConstrIter->entityA, &aConstrIter->entityB,
367                                    &aConstrIter->entityC, &aConstrIter->entityD};
368     for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++) {
369       if (*(aCurrentAttr[indAttr]) != aConstrEnt[indAttr])
370       {
371         *(aCurrentAttr[indAttr]) = aConstrEnt[indAttr];
372         myNeedToSolve = true;
373       }
374     }
375   }
376
377   // Update flags of entities to be used by constraints
378   for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++)
379     if (aConstrEnt[indAttr] != 0) {
380       int aPos = Search(aConstrEnt[indAttr], myEntities);
381       myEntOfConstr[aPos] = true;
382       // Sub-entities should be used implcitly
383       Slvs_hEntity* aEntPtr = myEntities[aPos].point;
384       while (*aEntPtr != 0) {
385         aPos = Search(*aEntPtr, myEntities);
386         myEntOfConstr[aPos] = true;
387         aEntPtr++;
388       }
389     }
390
391   checkConstraintConsistence(*aConstrIter);
392   return true;
393 }
394
395 // ============================================================================
396 //  Function: changeRigidConstraint
397 //  Class:    SketchSolver_ConstraintGroup
398 //  Purpose:  create/update the "Rigid" constraint in the group
399 // ============================================================================
400 bool SketchSolver_ConstraintGroup::changeRigidConstraint(
401     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
402 {
403   // Search this constraint in the current group to update it
404   ConstraintMap::const_iterator aConstrMapIter = myConstraintMap.find(theConstraint);
405   std::vector<Slvs_Constraint>::iterator aConstrIter;
406   if (aConstrMapIter != myConstraintMap.end()) {
407     int aConstrPos = Search(aConstrMapIter->second.front(), myConstraints);
408     aConstrIter = myConstraints.begin() + aConstrPos;
409   }
410
411   // Get constraint type and verify the constraint parameters are correct
412   SketchSolver_Constraint aConstraint(theConstraint);
413   int aConstrType = aConstraint.getType();
414   if (aConstrType == SLVS_C_UNKNOWN
415       || (aConstrMapIter != myConstraintMap.end() && aConstrIter->type != aConstrType))
416     return false;
417   const std::vector<std::string>& aConstraintAttributes = aConstraint.getAttributes();
418
419   Slvs_hEntity aConstrEnt = SLVS_E_UNKNOWN;
420   std::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr = std::dynamic_pointer_cast<
421       ModelAPI_AttributeRefAttr>(
422       theConstraint->data()->attribute(aConstraintAttributes[0]));
423   if (!aConstrAttr)
424     return false;
425
426   // Convert the object of the attribute to the feature
427   FeaturePtr aFeature;
428   if (aConstrAttr->isObject() && aConstrAttr->object()) {
429     ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(
430         aConstrAttr->object());
431     if (!aRC)
432       return false;
433     std::shared_ptr<ModelAPI_Document> aDoc = aRC->document();
434     aFeature = aDoc->feature(aRC);
435   }
436
437   aConstrEnt = aConstrAttr->isObject() ? changeEntityFeature(aFeature) : changeEntity(aConstrAttr->attr());
438
439   if (aConstrMapIter == myConstraintMap.end()) { // Add new constraint
440     // Check the fixed entity is not a point.
441     std::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr = std::dynamic_pointer_cast<
442         ModelAPI_AttributeRefAttr>(theConstraint->data()->attribute(aConstraintAttributes[0]));
443     std::shared_ptr<GeomDataAPI_Point> aPoint =
444         std::dynamic_pointer_cast<GeomDataAPI_Point>(aConstrAttr->attr());
445     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
446         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aConstrAttr->attr());
447     if (aPoint || aPoint2D) {
448       // Create SolveSpace constraint structure
449       Slvs_Constraint aConstraint = Slvs_MakeConstraint(
450           ++myConstrMaxID, myID, aConstrType, myWorkplane.h, 0.0,
451           aConstrEnt, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
452       myConstraints.push_back(aConstraint);
453       myConstraintMap[theConstraint] = std::vector<Slvs_hEntity>(1, aConstraint.h);
454       int aConstrPos = Search(aConstraint.h, myConstraints);
455       aConstrIter = myConstraints.begin() + aConstrPos;
456       myNeedToSolve = true;
457     } else {
458       myConstraintMap[theConstraint] = std::vector<Slvs_hEntity>();
459
460       // To avoid SolveSpace problems:
461       // * if the circle is rigid, we will fix its center and radius;
462       // * if the arc is rigid, we will fix its start and end points and radius.
463       double aRadius = 0.0;
464       bool isArc = false;
465       bool isCircle = false;
466       if (aFeature) {
467         if (aFeature->getKind() == SketchPlugin_Arc::ID()) {
468           std::shared_ptr<GeomDataAPI_Point2D> aCenter =
469               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
470               aFeature->data()->attribute(SketchPlugin_Arc::CENTER_ID()));
471           std::shared_ptr<GeomDataAPI_Point2D> aStart =
472               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
473               aFeature->data()->attribute(SketchPlugin_Arc::START_ID()));
474           aRadius = aStart->pnt()->distance(aCenter->pnt());
475           isArc = true;
476         } else if (aFeature->getKind() == SketchPlugin_Circle::ID()) {
477           aRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
478               aFeature->data()->attribute(SketchPlugin_Circle::RADIUS_ID()))->value();
479           isCircle = true;
480         }
481       }
482
483       // Get list of already fixed points
484       std::set<Slvs_hEntity> anAlreadyFixed;
485       std::vector<Slvs_Constraint>::const_iterator aCIter = myConstraints.begin();
486       for (; aCIter != myConstraints.end(); aCIter++)
487         if (aCIter->type == SLVS_C_WHERE_DRAGGED)
488           anAlreadyFixed.insert(aCIter->ptA);
489
490       // Create constraints to fix the parameters of the entity
491       int aEntPos = Search(aConstrEnt, myEntities);
492       Slvs_hEntity* aPointsPtr = myEntities[aEntPos].point;
493       if (isArc) aPointsPtr++; // avoid to fix center of arc
494       while (*aPointsPtr != 0) {
495         // Avoid to create additional "Rigid" constraints for coincident points
496         bool isCoincAlreadyFixed = false;
497         if (!anAlreadyFixed.empty()) {
498           if (anAlreadyFixed.find(*aPointsPtr) != anAlreadyFixed.end())
499             isCoincAlreadyFixed = true;
500
501           std::vector<std::set<Slvs_hEntity> >::const_iterator aCoincIter =
502               myCoincidentPoints.begin();
503           for (; !isCoincAlreadyFixed && aCoincIter != myCoincidentPoints.end(); aCoincIter++) {
504             if (aCoincIter->find(*aPointsPtr) == aCoincIter->end())
505               continue;
506             std::set<Slvs_hEntity>::const_iterator anIter = anAlreadyFixed.begin();
507             for (; !isCoincAlreadyFixed && anIter != anAlreadyFixed.end(); anIter++)
508               if (aCoincIter->find(*anIter) != aCoincIter->end())
509                 isCoincAlreadyFixed = true;
510           }
511         }
512
513         if (!isCoincAlreadyFixed) {
514           Slvs_Constraint aConstraint = Slvs_MakeConstraint(
515               ++myConstrMaxID, myID, aConstrType, myWorkplane.h, 0.0,
516               *aPointsPtr, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
517           myConstraints.push_back(aConstraint);
518           myConstraintMap[theConstraint].push_back(aConstraint.h);
519         }
520         aPointsPtr++;
521       }
522
523       if (isArc || isCircle) { // add radius constraint
524         Slvs_Constraint aConstraint = Slvs_MakeConstraint(
525             ++myConstrMaxID, myID, SLVS_C_DIAMETER, myWorkplane.h, 2.0 * aRadius,
526             SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, aConstrEnt, SLVS_E_UNKNOWN);
527         myConstraints.push_back(aConstraint);
528         myConstraintMap[theConstraint].push_back(aConstraint.h);
529       }
530
531       // The object is already rigid, so there is no constraints added
532       if (myConstraintMap[theConstraint].empty()) {
533         myConstraintMap.erase(theConstraint);
534         myNeedToSolve = false;
535       }
536       else
537         myNeedToSolve = true;
538     }
539   }
540   return true;
541 }
542
543 // ============================================================================
544 //  Function: changeEntity
545 //  Class:    SketchSolver_ConstraintGroup
546 //  Purpose:  create/update the element affected by any constraint
547 // ============================================================================
548 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
549     std::shared_ptr<ModelAPI_Attribute> theEntity)
550 {
551   // If the entity is already in the group, try to find it
552   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aEntIter =
553       myEntityAttrMap.find(theEntity);
554   int aEntPos;
555   std::vector<Slvs_Param>::const_iterator aParamIter;  // looks at first parameter of already existent entity or at the end of vector otherwise
556   if (aEntIter == myEntityAttrMap.end())  // no such entity => should be created
557     aParamIter = myParams.end();
558   else {  // the entity already exists
559     aEntPos = Search(aEntIter->second, myEntities);
560     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
561     aParamIter = myParams.begin() + aParamPos;
562   }
563   const bool isEntExists = (aEntIter != myEntityAttrMap.end());  // defines that the entity already exists
564   const bool isNeedToSolve = myNeedToSolve;
565   myNeedToSolve = false;
566
567   if (isEntExists) {
568     // Verify that the entity is not used by "Rigid" constraint.
569     // If it is used, the object should not move.
570     std::vector<std::set<Slvs_hEntity> >::iterator aCoincIter = myCoincidentPoints.begin();
571     for (; aCoincIter != myCoincidentPoints.end(); aCoincIter++)
572       if (aCoincIter->find(aEntIter->second) != aCoincIter->end())
573         break;
574     std::set<Slvs_hEntity> aCoincident;
575     if (aCoincIter != myCoincidentPoints.end()) {
576       aCoincident = *aCoincIter;
577       aCoincident.erase(aEntIter->second);
578
579       std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
580       for (; aConstrIter != myConstraints.end(); aConstrIter++)
581         if (aConstrIter->type == SLVS_C_WHERE_DRAGGED &&
582             aCoincident.find(aConstrIter->ptA) != aCoincident.end()) {
583           myNeedToSolve = true;
584           return aEntIter->second;
585         }
586     }
587   }
588
589   // Look over supported types of entities
590   Slvs_Entity aNewEntity;
591   aNewEntity.h = SLVS_E_UNKNOWN;
592
593   // Point in 3D
594   std::shared_ptr<GeomDataAPI_Point> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point>(
595       theEntity);
596   if (aPoint) {
597     Slvs_hParam aX = changeParameter(aPoint->x(), aParamIter);
598     Slvs_hParam aY = changeParameter(aPoint->y(), aParamIter);
599     Slvs_hParam aZ = changeParameter(aPoint->z(), aParamIter);
600     if (!isEntExists) // New entity
601       aNewEntity = Slvs_MakePoint3d(++myEntityMaxID, myID, aX, aY, aZ);
602   } else {
603     // All entities except 3D points are created on workplane. So, if there is no workplane yet, then error
604     if (myWorkplane.h == SLVS_E_UNKNOWN)
605       return SLVS_E_UNKNOWN;
606
607     // Point in 2D
608     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
609         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
610     if (aPoint2D) {
611       Slvs_hParam aU = changeParameter(aPoint2D->x(), aParamIter);
612       Slvs_hParam aV = changeParameter(aPoint2D->y(), aParamIter);
613       if (!isEntExists) // New entity
614         aNewEntity = Slvs_MakePoint2d(++myEntityMaxID, myID, myWorkplane.h, aU, aV);
615     } else {
616       // Scalar value (used for the distance entities)
617       AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theEntity);
618       if (aScalar) {
619         Slvs_hParam aValue = changeParameter(aScalar->value(), aParamIter);
620         if (!isEntExists) // New entity
621           aNewEntity = Slvs_MakeDistance(++myEntityMaxID, myID, myWorkplane.h, aValue);
622       }
623     }
624   }
625   /// \todo Other types of entities
626
627   Slvs_hEntity aResult = SLVS_E_UNKNOWN; // Unsupported or wrong entity type
628
629   if (isEntExists) {
630     myNeedToSolve = myNeedToSolve || isNeedToSolve;
631     aResult = aEntIter->second;
632   } else if (aNewEntity.h != SLVS_E_UNKNOWN) {
633     myEntities.push_back(aNewEntity);
634     myEntOfConstr.push_back(false);
635     myEntityAttrMap[theEntity] = aNewEntity.h;
636     aResult = aNewEntity.h;
637   }
638
639   // If the attribute was changed by the user, we need to fix it before solving
640   if (myNeedToSolve && theEntity->isImmutable())
641     addTemporaryConstraintWhereDragged(theEntity, false);
642
643   return aResult;
644 }
645
646 // ============================================================================
647 //  Function: changeEntity
648 //  Class:    SketchSolver_ConstraintGroup
649 //  Purpose:  create/update the element defined by the feature affected by any constraint
650 // ============================================================================
651 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntityFeature(FeaturePtr theEntity)
652 {
653   if (!theEntity->data()->isValid())
654     return SLVS_E_UNKNOWN;
655   // If the entity is already in the group, try to find it
656   std::map<FeaturePtr, Slvs_hEntity>::const_iterator aEntIter = myEntityFeatMap.find(theEntity);
657   // defines that the entity already exists
658   const bool isEntExists = (myEntityFeatMap.find(theEntity) != myEntityFeatMap.end());
659   
660   Slvs_Entity aNewEntity;
661   aNewEntity.h = SLVS_E_UNKNOWN;
662
663   // SketchPlugin features
664   std::shared_ptr<SketchPlugin_Feature> aFeature = std::dynamic_pointer_cast<
665       SketchPlugin_Feature>(theEntity);
666   if (aFeature) {  // Verify the feature by its kind
667     const std::string& aFeatureKind = aFeature->getKind();
668     AttributePtr anAttribute;
669
670     // Line
671     if (aFeatureKind.compare(SketchPlugin_Line::ID()) == 0) {
672       anAttribute = aFeature->data()->attribute(SketchPlugin_Line::START_ID());
673       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
674       Slvs_hEntity aStart = changeEntity(anAttribute);
675
676       anAttribute = aFeature->data()->attribute(SketchPlugin_Line::END_ID());
677       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
678       Slvs_hEntity aEnd = changeEntity(anAttribute);
679
680       if (!isEntExists) // New entity
681         aNewEntity = Slvs_MakeLineSegment(++myEntityMaxID, myID, myWorkplane.h, aStart, aEnd);
682     }
683     // Circle
684     else if (aFeatureKind.compare(SketchPlugin_Circle::ID()) == 0) {
685       anAttribute = aFeature->data()->attribute(SketchPlugin_Circle::CENTER_ID());
686       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
687       Slvs_hEntity aCenter = changeEntity(anAttribute);
688
689       anAttribute = aFeature->data()->attribute(SketchPlugin_Circle::RADIUS_ID());
690       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
691       Slvs_hEntity aRadius = changeEntity(anAttribute);
692
693       if (!isEntExists) // New entity
694         aNewEntity = Slvs_MakeCircle(++myEntityMaxID, myID, myWorkplane.h, aCenter,
695                                      myWorkplane.normal, aRadius);
696     }
697     // Arc
698     else if (aFeatureKind.compare(SketchPlugin_Arc::ID()) == 0) {
699       anAttribute = aFeature->data()->attribute(SketchPlugin_Arc::CENTER_ID());
700       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
701       Slvs_hEntity aCenter = changeEntity(anAttribute);
702
703       anAttribute = aFeature->data()->attribute(SketchPlugin_Arc::START_ID());
704       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
705       Slvs_hEntity aStart = changeEntity(anAttribute);
706
707       anAttribute = aFeature->data()->attribute(SketchPlugin_Arc::END_ID());
708       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
709       Slvs_hEntity aEnd = changeEntity(anAttribute);
710
711       if (!isEntExists)
712         aNewEntity = Slvs_MakeArcOfCircle(++myEntityMaxID, myID, myWorkplane.h,
713                                           myWorkplane.normal, aCenter, aStart, aEnd);
714     }
715     // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
716     else if (aFeatureKind.compare(SketchPlugin_Point::ID()) == 0) {
717       anAttribute = aFeature->data()->attribute(SketchPlugin_Point::COORD_ID());
718       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
719       Slvs_hEntity aPoint = changeEntity(anAttribute);
720
721       if (isEntExists)
722         return aEntIter->second;
723
724       // Both the sketch point and its attribute (coordinates) link to the same SolveSpace point identifier
725       myEntityFeatMap[theEntity] = aPoint;
726       myNeedToSolve = true;
727       return aPoint;
728     }
729   }
730   /// \todo Other types of features
731
732   if (isEntExists)
733     return aEntIter->second;
734
735   if (aNewEntity.h != SLVS_E_UNKNOWN) {
736     myEntities.push_back(aNewEntity);
737     myEntOfConstr.push_back(false);
738     myEntityFeatMap[theEntity] = aNewEntity.h;
739     myNeedToSolve = true;
740     return aNewEntity.h;
741   }
742
743   // Unsupported or wrong entity type
744   return SLVS_E_UNKNOWN;
745 }
746
747 // ============================================================================
748 //  Function: changeNormal
749 //  Class:    SketchSolver_ConstraintGroup
750 //  Purpose:  create/update the normal of workplane
751 // ============================================================================
752 Slvs_hEntity SketchSolver_ConstraintGroup::changeNormal(
753     std::shared_ptr<ModelAPI_Attribute> theDirX, std::shared_ptr<ModelAPI_Attribute> theDirY,
754     std::shared_ptr<ModelAPI_Attribute> theNorm)
755 {
756   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
757   std::shared_ptr<GeomDataAPI_Dir> aDirY = std::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirY);
758   if (!aDirX || !aDirY || (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance)
759       || (fabs(aDirY->x()) + fabs(aDirY->y()) + fabs(aDirY->z()) < tolerance))
760     return SLVS_E_UNKNOWN;
761
762   // quaternion parameters of normal vector
763   double qw, qx, qy, qz;
764   Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(), aDirY->x(), aDirY->y(), aDirY->z(), &qw,
765                       &qx, &qy, &qz);
766   double aNormCoord[4] = { qw, qx, qy, qz };
767
768   // Try to find existent normal
769   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aEntIter =
770       myEntityAttrMap.find(theNorm);
771   std::vector<Slvs_Param>::const_iterator aParamIter;  // looks to the first parameter of already existent entity or to the end of vector otherwise
772   if (aEntIter == myEntityAttrMap.end())  // no such entity => should be created
773     aParamIter = myParams.end();
774   else {  // the entity already exists, update it
775     int aEntPos = Search(aEntIter->second, myEntities);
776     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
777     aParamIter = myParams.begin() + aParamPos;
778   }
779
780   // Change parameters of the normal
781   Slvs_hParam aNormParams[4];
782   for (int i = 0; i < 4; i++)
783     aNormParams[i] = changeParameter(aNormCoord[i], aParamIter);
784
785   if (aEntIter != myEntityAttrMap.end())  // the entity already exists
786     return aEntIter->second;
787
788   // Create a normal
789   Slvs_Entity aNormal = Slvs_MakeNormal3d(++myEntityMaxID, myID, aNormParams[0], aNormParams[1],
790                                           aNormParams[2], aNormParams[3]);
791   myEntities.push_back(aNormal);
792   myEntOfConstr.push_back(false);
793   myEntityAttrMap[theNorm] = aNormal.h;
794   return aNormal.h;
795 }
796
797 // ============================================================================
798 //  Function: addWorkplane
799 //  Class:    SketchSolver_ConstraintGroup
800 //  Purpose:  create workplane for the group
801 // ============================================================================
802 bool SketchSolver_ConstraintGroup::addWorkplane(std::shared_ptr<ModelAPI_CompositeFeature> theSketch)
803 {
804   if (myWorkplane.h || theSketch->getKind().compare(SketchPlugin_Sketch::ID()) != 0)
805     return false;  // the workplane already exists or the function parameter is not Sketch
806
807   mySketch = theSketch;
808   updateWorkplane();
809   return true;
810 }
811
812 // ============================================================================
813 //  Function: updateWorkplane
814 //  Class:    SketchSolver_ConstraintGroup
815 //  Purpose:  update parameters of workplane
816 // ============================================================================
817 bool SketchSolver_ConstraintGroup::updateWorkplane()
818 {
819   if (!mySketch->data())
820     return false; // case sketch is deleted
821   // Get parameters of workplane
822   std::shared_ptr<ModelAPI_Attribute> aDirX = mySketch->data()->attribute(
823       SketchPlugin_Sketch::DIRX_ID());
824   std::shared_ptr<ModelAPI_Attribute> aDirY = mySketch->data()->attribute(
825       SketchPlugin_Sketch::DIRY_ID());
826   std::shared_ptr<ModelAPI_Attribute> aNorm = mySketch->data()->attribute(
827       SketchPlugin_Sketch::NORM_ID());
828   std::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(
829       SketchPlugin_Sketch::ORIGIN_ID());
830   // Transform them into SolveSpace format
831   Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
832   if (!aNormalWP)
833     return false;
834   Slvs_hEntity anOriginWP = changeEntity(anOrigin);
835   if (!anOriginWP)
836     return false;
837
838   if (!myWorkplane.h) {
839     // Create workplane
840     myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
841     // Workplane should be added to the list of entities
842     myEntities.push_back(myWorkplane);
843     myEntOfConstr.push_back(false);
844   }
845   return true;
846 }
847
848 // ============================================================================
849 //  Function: changeParameter
850 //  Class:    SketchSolver_ConstraintGroup
851 //  Purpose:  create/update value of parameter
852 // ============================================================================
853 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
854     const double& theParam, std::vector<Slvs_Param>::const_iterator& thePrmIter)
855 {
856   if (thePrmIter != myParams.end()) {  // Parameter should be updated
857     int aParamPos = thePrmIter - myParams.begin();
858     if (fabs(thePrmIter->val - theParam) > tolerance) {
859       myNeedToSolve = true;  // parameter is changed, need to resolve constraints
860       myParams[aParamPos].val = theParam;
861     }
862     thePrmIter++;
863     return myParams[aParamPos].h;
864   }
865
866   // Newly created parameter
867   Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
868   myParams.push_back(aParam);
869   myNeedToSolve = true;
870   // The list of parameters is changed, move iterator to the end of the list to avoid problems
871   thePrmIter = myParams.end();
872   return aParam.h;
873 }
874
875 // ============================================================================
876 //  Function: resolveConstraints
877 //  Class:    SketchSolver_ConstraintGroup
878 //  Purpose:  solve the set of constraints for the current group
879 // ============================================================================
880 bool SketchSolver_ConstraintGroup::resolveConstraints()
881 {
882   if (!myNeedToSolve)
883     return false;
884
885   myConstrSolver.setGroupID(myID);
886   myConstrSolver.setParameters(myParams);
887   myConstrSolver.setEntities(myEntities);
888   myConstrSolver.setConstraints(myConstraints);
889   myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
890
891   int aResult = myConstrSolver.solve();
892   if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
893                                       // Obtain result into the same list of parameters
894     if (!myConstrSolver.getResult(myParams))
895       return true;
896
897     // We should go through the attributes map, because only attributes have valued parameters
898     std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntIter =
899         myEntityAttrMap.begin();
900     for (; anEntIter != myEntityAttrMap.end(); anEntIter++) {
901       if (anEntIter->first->owner().get() && anEntIter->first->owner()->data().get())
902         anEntIter->first->owner()->data()->blockSendAttributeUpdated(true);
903       if (updateAttribute(anEntIter->first, anEntIter->second))
904         updateRelatedConstraints(anEntIter->first);
905     }
906     // unblock all features then
907     for (anEntIter = myEntityAttrMap.begin(); anEntIter != myEntityAttrMap.end(); anEntIter++) {
908       if (anEntIter->first->owner().get() && anEntIter->first->owner()->data().get())
909         anEntIter->first->owner()->data()->blockSendAttributeUpdated(false);
910     }
911   } else if (!myConstraints.empty())
912     Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
913
914   removeTemporaryConstraints();
915   myNeedToSolve = false;
916   return true;
917 }
918
919 // ============================================================================
920 //  Function: mergeGroups
921 //  Class:    SketchSolver_ConstraintGroup
922 //  Purpose:  append specified group to the current group
923 // ============================================================================
924 void SketchSolver_ConstraintGroup::mergeGroups(const SketchSolver_ConstraintGroup& theGroup)
925 {
926   // If specified group is empty, no need to merge
927   if (theGroup.myConstraintMap.empty())
928     return;
929
930   // Map between old and new indexes of SolveSpace constraints
931   std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
932
933   // Add all constraints from theGroup to the current group
934   ConstraintMap::const_iterator aConstrIter = theGroup.myConstraintMap.begin();
935   for (; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
936     if (changeConstraint(aConstrIter->first))
937       aConstrMap[aConstrIter->second.back()] = myConstrMaxID;  // the constraint was added => store its ID
938
939   // Add temporary constraints from theGroup
940   std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
941   for (; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++) {
942     std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(
943         *aTempConstrIter);
944     if (aFind != aConstrMap.end())
945       myTempConstraints.push_back(aFind->second);
946   }
947
948   if (myTempPointWhereDragged.empty())
949     myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
950   else if (!theGroup.myTempPointWhereDragged.empty()) {  // Need to create additional transient constraint
951     std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aFeatureIter =
952         theGroup.myEntityAttrMap.begin();
953     for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
954       if (aFeatureIter->second == myTempPointWDrgdID) {
955         addTemporaryConstraintWhereDragged(aFeatureIter->first);
956         break;
957       }
958   }
959
960   myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
961 }
962
963 // ============================================================================
964 //  Function: splitGroup
965 //  Class:    SketchSolver_ConstraintGroup
966 //  Purpose:  divide the group into several subgroups
967 // ============================================================================
968 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
969 {
970   // Divide constraints and entities into several groups
971   std::vector<std::set<Slvs_hEntity> > aGroupsEntities;
972   std::vector<std::set<Slvs_hConstraint> > aGroupsConstr;
973   int aMaxNbEntities = 0;  // index of the group with maximal nuber of elements (this group will be left in the current)
974   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
975   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
976     Slvs_hEntity aConstrEnt[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA,
977         aConstrIter->entityB };
978     std::vector<int> anIndexes;
979     // Go through the groupped entities and find even one of entities of current constraint
980     std::vector<std::set<Slvs_hEntity> >::iterator aGrEntIter;
981     for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++) {
982       bool isFound = false;
983       for (int i = 0; i < 4 && !isFound; i++)
984         if (aConstrEnt[i] != 0) {
985           isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
986           // Also we need to check sub-entities
987           int aEntPos = Search(aConstrEnt[i], myEntities);
988           if (aEntPos != myEntities.size()) { // MPV: to fix the crash on close
989             Slvs_hEntity* aSub = myEntities[aEntPos].point;
990             for (int j = 0; *aSub != 0 && j < 4 && !isFound; aSub++, j++)
991               isFound = (aGrEntIter->find(*aSub) != aGrEntIter->end());
992           }
993         }
994       if (isFound)
995         anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
996     }
997     // Add new group if no one is found
998     if (anIndexes.empty()) {
999       std::set<Slvs_hEntity> aNewGrEnt;
1000       for (int i = 0; i < 4; i++)
1001         if (aConstrEnt[i] != 0) {
1002           aNewGrEnt.insert(aConstrEnt[i]);
1003           int aEntPos = Search(aConstrEnt[i], myEntities);
1004           if (aEntPos != myEntities.size()) { // MPV: to fix the crash on close
1005             Slvs_hEntity* aSub = myEntities[aEntPos].point;
1006             for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
1007               aNewGrEnt.insert(*aSub);
1008           }
1009         }
1010       std::set<Slvs_hConstraint> aNewGrConstr;
1011       aNewGrConstr.insert(aConstrIter->h);
1012
1013       aGroupsEntities.push_back(aNewGrEnt);
1014       aGroupsConstr.push_back(aNewGrConstr);
1015       if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
1016         aMaxNbEntities = aGroupsEntities.size() - 1;
1017     } else {  // Add entities indexes into the found group
1018       aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
1019       for (int i = 0; i < 4; i++)
1020         if (aConstrEnt[i] != 0) {
1021           aGrEntIter->insert(aConstrEnt[i]);
1022           int aEntPos = Search(aConstrEnt[i], myEntities);
1023           if (aEntPos != myEntities.size()) { // MPV: to fix the crash on close
1024             Slvs_hEntity* aSub = myEntities[aEntPos].point;
1025             for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
1026               aGrEntIter->insert(*aSub);
1027           }
1028         }
1029       aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
1030       if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
1031         aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
1032       if (anIndexes.size() > 1) {  // There are found several connected groups, merge them
1033         std::vector<std::set<Slvs_hEntity> >::iterator aFirstGroup = aGroupsEntities.begin()
1034             + anIndexes.front();
1035         std::vector<std::set<Slvs_hConstraint> >::iterator aFirstConstr = aGroupsConstr.begin()
1036             + anIndexes.front();
1037         std::vector<int>::iterator anInd = anIndexes.begin();
1038         for (++anInd; anInd != anIndexes.end(); anInd++) {
1039           aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
1040           aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
1041         }
1042         if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
1043           aMaxNbEntities = anIndexes.front();
1044         // Remove merged groups
1045         for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--) {
1046           aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
1047           aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
1048         }
1049       }
1050     }
1051   }
1052
1053   if (aGroupsEntities.size() <= 1)
1054     return;
1055
1056   // Remove the group with maximum elements as it will be left in the current group
1057   aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
1058   aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
1059
1060   // Add new groups of constraints and divide current group
1061   std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
1062   for (int i = aGroupsEntities.size(); i > 0; i--) {
1063     SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
1064     aNewGroups.push_back(aG);
1065   }
1066   ConstraintMap::const_iterator aConstrMapIter = myConstraintMap.begin();
1067   int aConstrMapPos = 0;  // position of iterator in the map (used to restore iterator after removing constraint)
1068   while (aConstrMapIter != myConstraintMap.end()) {
1069     std::vector<std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
1070     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
1071     for (; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
1072       if (aGIter->find(aConstrMapIter->second.front()) != aGIter->end()) {
1073         (*aGroup)->changeConstraint(aConstrMapIter->first);
1074         removeConstraint(aConstrMapIter->first);
1075         // restore iterator
1076         aConstrMapIter = myConstraintMap.begin();
1077         for (int i = 0; i < aConstrMapPos; i++)
1078           aConstrMapIter++;
1079         break;
1080       }
1081     if (aGIter == aGroupsConstr.end()) {
1082       aConstrMapIter++;
1083       aConstrMapPos++;
1084     }
1085   }
1086
1087   theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
1088 }
1089
1090 // ============================================================================
1091 //  Function: updateGroup
1092 //  Class:    SketchSolver_ConstraintGroup
1093 //  Purpose:  search removed entities and constraints
1094 // ============================================================================
1095 bool SketchSolver_ConstraintGroup::updateGroup()
1096 {
1097   ConstraintMap::reverse_iterator aConstrIter = myConstraintMap.rbegin();
1098   bool isAllValid = true;
1099   bool isCCRemoved = false;  // indicates that at least one of coincidence constraints was removed
1100   int aConstrIndex = 0;
1101   while (/*isAllValid && */aConstrIter != myConstraintMap.rend()) {
1102     if (!aConstrIter->first->data() || !aConstrIter->first->data()->isValid()) {
1103       if (aConstrIter->first->getKind().compare(SketchPlugin_ConstraintCoincidence::ID()) == 0)
1104         isCCRemoved = true;
1105       removeConstraint(aConstrIter->first);
1106       isAllValid = false;
1107       // Get back the correct position of iterator after the "remove" operation
1108       aConstrIter = myConstraintMap.rbegin();
1109       for (int i = 0; i < aConstrIndex && aConstrIter != myConstraintMap.rend(); i++)
1110         aConstrIter++;
1111     } else {
1112       aConstrIter++;
1113       aConstrIndex++;
1114     }
1115   }
1116
1117   // Check if some entities are invalid too
1118   std::set<Slvs_hEntity> anEntToRemove;
1119   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1120       anAttrIter = myEntityAttrMap.begin();
1121   while (anAttrIter != myEntityAttrMap.end()) {
1122     if (!anAttrIter->first->owner() || !anAttrIter->first->owner()->data() ||
1123         !anAttrIter->first->owner()->data()->isValid()) {
1124       anEntToRemove.insert(anAttrIter->second);
1125       std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1126           aRemovedIter = anAttrIter;
1127       anAttrIter++;
1128       myEntityAttrMap.erase(aRemovedIter);
1129     } else
1130       anAttrIter++;
1131   }
1132   std::map<FeaturePtr, Slvs_hEntity>::iterator aFeatIter = myEntityFeatMap.begin();
1133   while (aFeatIter != myEntityFeatMap.end()) {
1134     if (!aFeatIter->first || !aFeatIter->first->data() ||
1135         !aFeatIter->first->data()->isValid()) {
1136       anEntToRemove.insert(aFeatIter->second);
1137       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = aFeatIter;
1138       aFeatIter++;
1139       myEntityFeatMap.erase(aRemovedIter);
1140     } else
1141       aFeatIter++;
1142   }
1143   removeEntitiesById(anEntToRemove);
1144
1145   // Probably, need to update coincidence constraints
1146   if (isCCRemoved && !myExtraCoincidence.empty()) {
1147     // Make a copy, because the new list of unused constrtaints will be generated
1148     std::set<std::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
1149     myExtraCoincidence.clear();
1150
1151     std::set<std::shared_ptr<SketchPlugin_Constraint> >::iterator aCIter = anExtraCopy.begin();
1152     for (; aCIter != anExtraCopy.end(); aCIter++)
1153       if ((*aCIter)->data() && (*aCIter)->data()->isValid())
1154         changeConstraint(*aCIter);
1155   }
1156
1157   return !isAllValid;
1158 }
1159
1160 // ============================================================================
1161 //  Function: updateAttribute
1162 //  Class:    SketchSolver_ConstraintGroup
1163 //  Purpose:  update features of sketch after resolving constraints
1164 // ============================================================================
1165 bool SketchSolver_ConstraintGroup::updateAttribute(
1166     std::shared_ptr<ModelAPI_Attribute> theAttribute, const Slvs_hEntity& theEntityID)
1167 {
1168   // Search the position of the first parameter of the entity
1169   int anEntPos = Search(theEntityID, myEntities);
1170   int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
1171
1172   // Look over supported types of entities
1173
1174   // Point in 3D
1175   std::shared_ptr<GeomDataAPI_Point> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point>(
1176       theAttribute);
1177   if (aPoint) {
1178     if (fabs(aPoint->x() - myParams[aFirstParamPos].val) > tolerance
1179         || fabs(aPoint->y() - myParams[aFirstParamPos + 1].val) > tolerance
1180         || fabs(aPoint->z() - myParams[aFirstParamPos + 2].val) > tolerance) {
1181       aPoint->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val,
1182                        myParams[aFirstParamPos + 2].val);
1183       return true;
1184     }
1185     return false;
1186   }
1187
1188   // Point in 2D
1189   std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
1190       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
1191   if (aPoint2D) {
1192     if (fabs(aPoint2D->x() - myParams[aFirstParamPos].val) > tolerance
1193         || fabs(aPoint2D->y() - myParams[aFirstParamPos + 1].val) > tolerance) {
1194       aPoint2D->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val);
1195       return true;
1196     }
1197     return false;
1198   }
1199
1200   // Scalar value
1201   AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
1202   if (aScalar) {
1203     if (fabs(aScalar->value() - myParams[aFirstParamPos].val) > tolerance) {
1204       aScalar->setValue(myParams[aFirstParamPos].val);
1205       return true;
1206     }
1207     return false;
1208   }
1209
1210   /// \todo Support other types of entities
1211   return false;
1212 }
1213
1214 // ============================================================================
1215 //  Function: updateEntityIfPossible
1216 //  Class:    SketchSolver_ConstraintGroup
1217 //  Purpose:  search the entity in this group and update it
1218 // ============================================================================
1219 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
1220     std::shared_ptr<ModelAPI_Attribute> theEntity)
1221 {
1222   if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end()) {
1223     // If the attribute is a point and it is changed (the group needs to rebuild),
1224     // probably user has dragged this point into this position,
1225     // so it is necessary to add constraint which will guarantee the point will not change
1226
1227     // Store myNeedToSolve flag to verify the entity is really changed
1228     bool aNeedToSolveCopy = myNeedToSolve;
1229     myNeedToSolve = false;
1230
1231     changeEntity(theEntity);
1232
1233     if (myNeedToSolve)  // the entity is changed
1234     {
1235       // Verify the entity is a point and add temporary constraint of permanency
1236       std::shared_ptr<GeomDataAPI_Point> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point>(
1237           theEntity);
1238       std::shared_ptr<GeomDataAPI_Point2D> aPoint2D = std::dynamic_pointer_cast<
1239           GeomDataAPI_Point2D>(theEntity);
1240       if (aPoint || aPoint2D)
1241         addTemporaryConstraintWhereDragged(theEntity);
1242     }
1243
1244     // Restore flag of changes
1245     myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
1246
1247     if (myNeedToSolve)
1248       updateRelatedConstraints(theEntity);
1249   }
1250 }
1251
1252 // ============================================================================
1253 //  Function: addTemporaryConstraintWhereDragged
1254 //  Class:    SketchSolver_ConstraintGroup
1255 //  Purpose:  add transient constraint SLVS_C_WHERE_DRAGGED for the entity, 
1256 //            which was moved by user
1257 // ============================================================================
1258 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
1259     std::shared_ptr<ModelAPI_Attribute> theEntity,
1260     bool theAllowToFit)
1261 {
1262   // Find identifier of the entity
1263   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator anEntIter =
1264       myEntityAttrMap.find(theEntity);
1265   if (anEntIter == myEntityAttrMap.end())
1266     return;
1267
1268   // Get identifiers of all dragged points
1269   std::set<Slvs_hEntity> aDraggedPntID;
1270   aDraggedPntID.insert(myTempPointWDrgdID);
1271   std::list<Slvs_hConstraint>::const_iterator aTmpCoIter = myTempConstraints.begin();
1272   for (; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++) {
1273     unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
1274     if (aConstrPos < myConstraints.size())
1275       aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
1276   }
1277   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1278   for (; aConstrIter != myConstraints.end(); aConstrIter++)
1279     if (aConstrIter->type == SLVS_C_WHERE_DRAGGED)
1280       aDraggedPntID.insert(aConstrIter->ptA);
1281   // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
1282   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1283   for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++) {
1284     if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
1285       continue;  // the entity was not found in current set
1286
1287     // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
1288     std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
1289     for (; aDrgIter != aDraggedPntID.end(); aDrgIter++)
1290       if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
1291         return;  // the SLVS_C_WHERE_DRAGGED constraint already exists
1292   }
1293   if (aDraggedPntID.find(anEntIter->second) != aDraggedPntID.end())
1294     return;
1295
1296   // If this is a first dragged point, its parameters should be placed 
1297   // into Slvs_System::dragged field to avoid system inconsistense
1298   if (myTempPointWhereDragged.empty() && theAllowToFit) {
1299     int anEntPos = Search(anEntIter->second, myEntities);
1300     Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
1301     for (int i = 0; i < 4; i++, aDraggedParam++)
1302       if (*aDraggedParam != 0)
1303         myTempPointWhereDragged.push_back(*aDraggedParam);
1304     myTempPointWDrgdID = myEntities[anEntPos].h;
1305     return;
1306   }
1307
1308   // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
1309   Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
1310                                                   myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
1311   myConstraints.push_back(aWDConstr);
1312   myTempConstraints.push_back(aWDConstr.h);
1313 }
1314
1315 // ============================================================================
1316 //  Function: removeTemporaryConstraints
1317 //  Class:    SketchSolver_ConstraintGroup
1318 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
1319 //            resolving the set of constraints
1320 // ============================================================================
1321 void SketchSolver_ConstraintGroup::removeTemporaryConstraints(
1322     const std::set<Slvs_hConstraint>& theRemoved)
1323 {
1324   std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
1325   for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend();
1326       aTmpConstrIter++) {
1327     if (!theRemoved.empty() && theRemoved.find(*aTmpConstrIter) == theRemoved.end())
1328       continue;
1329     unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
1330     if (aConstrPos >= myConstraints.size())
1331       continue;
1332     myConstraints.erase(myConstraints.begin() + aConstrPos);
1333
1334     // If the removing constraint has higher index, decrease the indexer
1335     if (*aTmpConstrIter == myConstrMaxID)
1336       myConstrMaxID--;
1337   }
1338   myTempConstraints.clear();
1339
1340   // Clear basic dragged point
1341   myTempPointWhereDragged.clear();
1342   myTempPointWDrgdID = SLVS_E_UNKNOWN;
1343 }
1344
1345 // ============================================================================
1346 //  Function: removeConstraint
1347 //  Class:    SketchSolver_ConstraintGroup
1348 //  Purpose:  remove constraint and all unused entities
1349 // ============================================================================
1350 void SketchSolver_ConstraintGroup::removeConstraint(
1351     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
1352 {
1353   ConstraintMap::iterator anIterToRemove = myConstraintMap.find(theConstraint);
1354   if (anIterToRemove == myConstraintMap.end())
1355     return;
1356
1357   std::vector<Slvs_hConstraint> aCnstrToRemove = anIterToRemove->second;
1358   // Remove constraint from the map
1359   myConstraintMap.erase(anIterToRemove);
1360
1361   std::set<Slvs_hEntity> anEntToRemove;
1362   
1363   // Find unused entities
1364   std::vector<Slvs_hConstraint>::iterator aCnstrToRemoveIter = aCnstrToRemove.begin();
1365   for (; aCnstrToRemoveIter != aCnstrToRemove.end(); aCnstrToRemoveIter++) {
1366     int aConstrPos = Search(*aCnstrToRemoveIter, myConstraints);
1367     Slvs_hEntity aCnstEnt[] = { myConstraints[aConstrPos].ptA, myConstraints[aConstrPos].ptB,
1368         myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB };
1369     for (int i = 0; i < 4; i++)
1370       if (aCnstEnt[i] != 0)
1371         anEntToRemove.insert(aCnstEnt[i]);
1372     myConstraints.erase(myConstraints.begin() + aConstrPos);
1373     if (*aCnstrToRemoveIter == myConstrMaxID)
1374       myConstrMaxID--;
1375   }
1376
1377   // Find all entities which are based on these unused
1378   std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
1379   for ( ; anEntIter != myEntities.end(); anEntIter++)
1380     if (anEntIter->type == SLVS_E_LINE_SEGMENT || anEntIter->type == SLVS_E_CIRCLE ||
1381         anEntIter->type == SLVS_E_ARC_OF_CIRCLE) {
1382       for (int i = 0; i < 4; i++)
1383         if (anEntToRemove.find(anEntIter->point[i]) != anEntToRemove.end()) {
1384           anEntToRemove.insert(anEntIter->h);
1385           for (int j = 0; j < 4; j++)
1386             if (anEntIter->param[j] != 0)
1387               anEntToRemove.insert(anEntIter->point[j]);
1388           break;
1389         }
1390     }
1391
1392   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1393   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
1394     Slvs_hEntity aEnts[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA, aConstrIter
1395         ->entityB };
1396     for (int i = 0; i < 4; i++)
1397       if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
1398         anEntToRemove.erase(aEnts[i]);
1399   }
1400
1401   if (anEntToRemove.empty())
1402     return;
1403
1404   // Remove unused entities
1405   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntAttrIter =
1406       myEntityAttrMap.begin();
1407   while (anEntAttrIter != myEntityAttrMap.end()) {
1408     if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end()) {
1409       std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator aRemovedIter =
1410           anEntAttrIter;
1411       anEntAttrIter++;
1412       myEntityAttrMap.erase(aRemovedIter);
1413     } else
1414       anEntAttrIter++;
1415   }
1416   std::map<FeaturePtr, Slvs_hEntity>::iterator anEntFeatIter = myEntityFeatMap.begin();
1417   while (anEntFeatIter != myEntityFeatMap.end()) {
1418     if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end()) {
1419       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = anEntFeatIter;
1420       anEntFeatIter++;
1421       myEntityFeatMap.erase(aRemovedIter);
1422     } else
1423       anEntFeatIter++;
1424   }
1425
1426   removeEntitiesById(anEntToRemove);
1427
1428   if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1429     myCoincidentPoints.clear();
1430 }
1431
1432 // ============================================================================
1433 //  Function: removeEntitiesById
1434 //  Class:    SketchSolver_ConstraintGroup
1435 //  Purpose:  Removes specified entities and their parameters
1436 // ============================================================================
1437 void SketchSolver_ConstraintGroup::removeEntitiesById(const std::set<Slvs_hEntity>& theEntities)
1438 {
1439   std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = theEntities.rbegin();
1440   for (; aRemIter != theEntities.rend(); aRemIter++) {
1441     unsigned int anEntPos = Search(*aRemIter, myEntities);
1442     if (anEntPos >= myEntities.size())
1443       continue;
1444     if (myEntities[anEntPos].param[0] != 0) {
1445       unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1446       if (aParamPos >= myParams.size())
1447         continue;
1448       int aNbParams = 0;
1449       while (myEntities[anEntPos].param[aNbParams] != 0)
1450         aNbParams++;
1451       if (myEntities[anEntPos].param[aNbParams - 1] == myParamMaxID)
1452         myParamMaxID -= aNbParams;
1453       myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1454       if (*aRemIter == myEntityMaxID)
1455         myEntityMaxID--;
1456     }
1457     myEntities.erase(myEntities.begin() + anEntPos);
1458     myEntOfConstr.erase(myEntOfConstr.begin() + anEntPos);
1459
1460     // Remove entity's ID from the lists of conincident points
1461     std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1462     for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1463       aCoPtIter->erase(*aRemIter);
1464   }
1465 }
1466
1467 // ============================================================================
1468 //  Function: addCoincidentPoints
1469 //  Class:    SketchSolver_ConstraintGroup
1470 //  Purpose:  add coincident point the appropriate list of such points
1471 // ============================================================================
1472 bool SketchSolver_ConstraintGroup::addCoincidentPoints(const Slvs_hEntity& thePoint1,
1473                                                        const Slvs_hEntity& thePoint2)
1474 {
1475   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1476   std::vector<std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1477   while (aCoPtIter != myCoincidentPoints.end()) {
1478     bool isFound[2] = {  // indicate which point ID was already in coincidence constraint
1479         aCoPtIter->find(thePoint1) != aCoPtIter->end(), aCoPtIter->find(thePoint2)
1480             != aCoPtIter->end(), };
1481     if (isFound[0] && isFound[1])  // points are already connected by coincidence constraints => no need additional one
1482       return false;
1483     if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1])) {
1484       if (aFirstFound != myCoincidentPoints.end()) {  // there are two groups of coincident points connected by created constraint => merge them
1485         int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1486         int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1487         aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1488         myCoincidentPoints.erase(aCoPtIter);
1489         aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1490         aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1491         continue;
1492       } else {
1493         aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1494         aFirstFound = aCoPtIter;
1495       }
1496     }
1497     aCoPtIter++;
1498   }
1499   // No points were found, need to create new set
1500   if (aFirstFound == myCoincidentPoints.end()) {
1501     std::set<Slvs_hEntity> aNewSet;
1502     aNewSet.insert(thePoint1);
1503     aNewSet.insert(thePoint2);
1504     myCoincidentPoints.push_back(aNewSet);
1505   }
1506
1507   return true;
1508 }
1509
1510 // ============================================================================
1511 //  Function: updateRelatedConstraints
1512 //  Class:    SketchSolver_ConstraintGroup
1513 //  Purpose:  emit the signal to update constraints
1514 // ============================================================================
1515 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1516     std::shared_ptr<ModelAPI_Attribute> theEntity) const
1517 {
1518   ConstraintMap::const_iterator aConstrIter = myConstraintMap.begin();
1519   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1520     std::list<std::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1521         ->attributes(std::string());
1522
1523     std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1524     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1525       bool isUpd = (*anAttrIter == theEntity);
1526       std::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = std::dynamic_pointer_cast<
1527           ModelAPI_AttributeRefAttr>(*anAttrIter);
1528       if (aRefAttr && !aRefAttr->isObject() && aRefAttr->attr() == theEntity)
1529         isUpd = true;
1530
1531       if (isUpd) {
1532         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1533         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1534         break;
1535       }
1536     }
1537   }
1538 }
1539
1540 void SketchSolver_ConstraintGroup::updateRelatedConstraintsFeature(
1541     std::shared_ptr<ModelAPI_Feature> theFeature) const
1542 {
1543   ConstraintMap::const_iterator aConstrIter = myConstraintMap.begin();
1544   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1545     std::list<std::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1546         ->attributes(std::string());
1547
1548     std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1549     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1550       std::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = std::dynamic_pointer_cast<
1551           ModelAPI_AttributeRefAttr>(*anAttrIter);
1552       if (aRefAttr && aRefAttr->isObject() && aRefAttr->object() == theFeature) {
1553         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1554         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1555         break;
1556       }
1557     }
1558   }
1559 }
1560
1561 // ========================================================
1562 // =========      Auxiliary functions       ===============
1563 // ========================================================
1564
1565 template<typename T>
1566 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1567 {
1568   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1569   int aVecSize = theEntities.size();
1570   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1571     aResIndex--;
1572   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1573     aResIndex++;
1574   if (aResIndex == -1)
1575     aResIndex = aVecSize;
1576   return aResIndex;
1577 }