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