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