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