Salome HOME
a7bffde09597e83ccf5f2528bc5dc4c0c5e41028
[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     std::list<AttributePtr> anAttributes = aFeature->data()->attributes(std::string());
443     std::list<AttributePtr>::iterator anAttrIter = anAttributes.begin();
444     for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
445       if (!(*anAttrIter)->isInitialized()) // the entity is not fully initialized, don't add it into solver
446         return SLVS_E_UNKNOWN;
447
448     // Line
449     if (aFeatureKind.compare(SketchPlugin_Line::ID()) == 0) {
450       Slvs_hEntity aStart = changeEntity(
451           aFeature->data()->attribute(SketchPlugin_Line::START_ID()));
452       Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(SketchPlugin_Line::END_ID()));
453
454       if (!isEntExists) // New entity
455         aNewEntity = Slvs_MakeLineSegment(++myEntityMaxID, myID, myWorkplane.h, aStart, aEnd);
456     }
457     // Circle
458     else if (aFeatureKind.compare(SketchPlugin_Circle::ID()) == 0) {
459       Slvs_hEntity aCenter = changeEntity(
460           aFeature->data()->attribute(SketchPlugin_Circle::CENTER_ID()));
461       Slvs_hEntity aRadius = changeEntity(
462           aFeature->data()->attribute(SketchPlugin_Circle::RADIUS_ID()));
463
464       if (!isEntExists) // New entity
465         aNewEntity = Slvs_MakeCircle(++myEntityMaxID, myID, myWorkplane.h, aCenter,
466                                      myWorkplane.normal, aRadius);
467     }
468     // Arc
469     else if (aFeatureKind.compare(SketchPlugin_Arc::ID()) == 0) {
470       Slvs_hEntity aCenter = changeEntity(
471           aFeature->data()->attribute(SketchPlugin_Arc::CENTER_ID()));
472       Slvs_hEntity aStart = changeEntity(aFeature->data()->attribute(SketchPlugin_Arc::START_ID()));
473       Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(SketchPlugin_Arc::END_ID()));
474
475       if (!isEntExists)
476         aNewEntity = Slvs_MakeArcOfCircle(++myEntityMaxID, myID, myWorkplane.h,
477                                           myWorkplane.normal, aCenter, aStart, aEnd);
478     }
479     // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
480     else if (aFeatureKind.compare(SketchPlugin_Point::ID()) == 0) {
481       Slvs_hEntity aPoint = changeEntity(
482           aFeature->data()->attribute(SketchPlugin_Point::COORD_ID()));
483
484       if (isEntExists)
485         return aEntIter->second;
486
487       // Both the sketch point and its attribute (coordinates) link to the same SolveSpace point identifier
488       myEntityFeatMap[theEntity] = aPoint;
489       myNeedToSolve = true;
490       return aPoint;
491     }
492   }
493   /// \todo Other types of features
494
495   if (isEntExists)
496     return aEntIter->second;
497
498   if (aNewEntity.h != SLVS_E_UNKNOWN) {
499     myEntities.push_back(aNewEntity);
500     myEntOfConstr.push_back(false);
501     myEntityFeatMap[theEntity] = aNewEntity.h;
502     myNeedToSolve = true;
503     return aNewEntity.h;
504   }
505
506
507   // Unsupported or wrong entity type
508   return SLVS_E_UNKNOWN;
509 }
510
511 // ============================================================================
512 //  Function: changeNormal
513 //  Class:    SketchSolver_ConstraintGroup
514 //  Purpose:  create/update the normal of workplane
515 // ============================================================================
516 Slvs_hEntity SketchSolver_ConstraintGroup::changeNormal(
517     boost::shared_ptr<ModelAPI_Attribute> theDirX, boost::shared_ptr<ModelAPI_Attribute> theDirY,
518     boost::shared_ptr<ModelAPI_Attribute> theNorm)
519 {
520   boost::shared_ptr<GeomDataAPI_Dir> aDirX = boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
521   boost::shared_ptr<GeomDataAPI_Dir> aDirY = boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirY);
522   if (!aDirX || !aDirY || (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance)
523       || (fabs(aDirY->x()) + fabs(aDirY->y()) + fabs(aDirY->z()) < tolerance))
524     return SLVS_E_UNKNOWN;
525
526   // quaternion parameters of normal vector
527   double qw, qx, qy, qz;
528   Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(), aDirY->x(), aDirY->y(), aDirY->z(), &qw,
529                       &qx, &qy, &qz);
530   double aNormCoord[4] = { qw, qx, qy, qz };
531
532   // Try to find existent normal
533   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aEntIter =
534       myEntityAttrMap.find(theNorm);
535   std::vector<Slvs_Param>::const_iterator aParamIter;  // looks to the first parameter of already existent entity or to the end of vector otherwise
536   if (aEntIter == myEntityAttrMap.end())  // no such entity => should be created
537     aParamIter = myParams.end();
538   else {  // the entity already exists, update it
539     int aEntPos = Search(aEntIter->second, myEntities);
540     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
541     aParamIter = myParams.begin() + aParamPos;
542   }
543
544   // Change parameters of the normal
545   Slvs_hParam aNormParams[4];
546   for (int i = 0; i < 4; i++)
547     aNormParams[i] = changeParameter(aNormCoord[i], aParamIter);
548
549   if (aEntIter != myEntityAttrMap.end())  // the entity already exists
550     return aEntIter->second;
551
552   // Create a normal
553   Slvs_Entity aNormal = Slvs_MakeNormal3d(++myEntityMaxID, myID, aNormParams[0], aNormParams[1],
554                                           aNormParams[2], aNormParams[3]);
555   myEntities.push_back(aNormal);
556   myEntOfConstr.push_back(false);
557   myEntityAttrMap[theNorm] = aNormal.h;
558   return aNormal.h;
559 }
560
561 // ============================================================================
562 //  Function: addWorkplane
563 //  Class:    SketchSolver_ConstraintGroup
564 //  Purpose:  create workplane for the group
565 // ============================================================================
566 bool SketchSolver_ConstraintGroup::addWorkplane(boost::shared_ptr<SketchPlugin_Feature> theSketch)
567 {
568   if (myWorkplane.h || theSketch->getKind().compare(SketchPlugin_Sketch::ID()) != 0)
569     return false;  // the workplane already exists or the function parameter is not Sketch
570
571   mySketch = theSketch;
572   updateWorkplane();
573   return true;
574 }
575
576 // ============================================================================
577 //  Function: updateWorkplane
578 //  Class:    SketchSolver_ConstraintGroup
579 //  Purpose:  update parameters of workplane
580 // ============================================================================
581 bool SketchSolver_ConstraintGroup::updateWorkplane()
582 {
583   // Get parameters of workplane
584   boost::shared_ptr<ModelAPI_Attribute> aDirX = mySketch->data()->attribute(
585       SketchPlugin_Sketch::DIRX_ID());
586   boost::shared_ptr<ModelAPI_Attribute> aDirY = mySketch->data()->attribute(
587       SketchPlugin_Sketch::DIRY_ID());
588   boost::shared_ptr<ModelAPI_Attribute> aNorm = mySketch->data()->attribute(
589       SketchPlugin_Sketch::NORM_ID());
590   boost::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(
591       SketchPlugin_Sketch::ORIGIN_ID());
592   // Transform them into SolveSpace format
593   Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
594   if (!aNormalWP)
595     return false;
596   Slvs_hEntity anOriginWP = changeEntity(anOrigin);
597   if (!anOriginWP)
598     return false;
599
600   if (!myWorkplane.h) {
601     // Create workplane
602     myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
603     // Workplane should be added to the list of entities
604     myEntities.push_back(myWorkplane);
605     myEntOfConstr.push_back(false);
606   }
607   return true;
608 }
609
610 // ============================================================================
611 //  Function: changeParameter
612 //  Class:    SketchSolver_ConstraintGroup
613 //  Purpose:  create/update value of parameter
614 // ============================================================================
615 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
616     const double& theParam, std::vector<Slvs_Param>::const_iterator& thePrmIter)
617 {
618   if (thePrmIter != myParams.end()) {  // Parameter should be updated
619     int aParamPos = thePrmIter - myParams.begin();
620     if (fabs(thePrmIter->val - theParam) > tolerance) {
621       myNeedToSolve = true;  // parameter is changed, need to resolve constraints
622       myParams[aParamPos].val = theParam;
623     }
624     thePrmIter++;
625     return myParams[aParamPos].h;
626   }
627
628   // Newly created parameter
629   Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
630   myParams.push_back(aParam);
631   myNeedToSolve = true;
632   // The list of parameters is changed, move iterator to the end of the list to avoid problems
633   thePrmIter = myParams.end();
634   return aParam.h;
635 }
636
637 // ============================================================================
638 //  Function: resolveConstraints
639 //  Class:    SketchSolver_ConstraintGroup
640 //  Purpose:  solve the set of constraints for the current group
641 // ============================================================================
642 bool SketchSolver_ConstraintGroup::resolveConstraints()
643 {
644   if (!myNeedToSolve)
645     return false;
646
647   myConstrSolver.setGroupID(myID);
648   myConstrSolver.setParameters(myParams);
649   myConstrSolver.setEntities(myEntities);
650   myConstrSolver.setConstraints(myConstraints);
651   myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
652
653   int aResult = myConstrSolver.solve();
654   if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
655                                       // Obtain result into the same list of parameters
656     if (!myConstrSolver.getResult(myParams))
657       return true;
658
659     // We should go through the attributes map, because only attributes have valued parameters
660     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntIter =
661         myEntityAttrMap.begin();
662     for (; anEntIter != myEntityAttrMap.end(); anEntIter++)
663       if (updateAttribute(anEntIter->first, anEntIter->second))
664         updateRelatedConstraints(anEntIter->first);
665   } else if (!myConstraints.empty())
666     Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
667
668   removeTemporaryConstraints();
669   myNeedToSolve = false;
670   return true;
671 }
672
673 // ============================================================================
674 //  Function: mergeGroups
675 //  Class:    SketchSolver_ConstraintGroup
676 //  Purpose:  append specified group to the current group
677 // ============================================================================
678 void SketchSolver_ConstraintGroup::mergeGroups(const SketchSolver_ConstraintGroup& theGroup)
679 {
680   // If specified group is empty, no need to merge
681   if (theGroup.myConstraintMap.empty())
682     return;
683
684   // Map between old and new indexes of SolveSpace constraints
685   std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
686
687   // Add all constraints from theGroup to the current group
688   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrIter =
689       theGroup.myConstraintMap.begin();
690   for (; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
691     if (changeConstraint(aConstrIter->first))
692       aConstrMap[aConstrIter->second] = myConstrMaxID;  // the constraint was added => store its ID
693
694   // Add temporary constraints from theGroup
695   std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
696   for (; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++) {
697     std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(
698         *aTempConstrIter);
699     if (aFind != aConstrMap.end())
700       myTempConstraints.push_back(aFind->second);
701   }
702
703   if (myTempPointWhereDragged.empty())
704     myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
705   else if (!theGroup.myTempPointWhereDragged.empty()) {  // Need to create additional transient constraint
706     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aFeatureIter =
707         theGroup.myEntityAttrMap.begin();
708     for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
709       if (aFeatureIter->second == myTempPointWDrgdID) {
710         addTemporaryConstraintWhereDragged(aFeatureIter->first);
711         break;
712       }
713   }
714
715   myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
716 }
717
718 // ============================================================================
719 //  Function: splitGroup
720 //  Class:    SketchSolver_ConstraintGroup
721 //  Purpose:  divide the group into several subgroups
722 // ============================================================================
723 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
724 {
725   // Divide constraints and entities into several groups
726   std::vector<std::set<Slvs_hEntity> > aGroupsEntities;
727   std::vector<std::set<Slvs_hConstraint> > aGroupsConstr;
728   int aMaxNbEntities = 0;  // index of the group with maximal nuber of elements (this group will be left in the current)
729   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
730   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
731     Slvs_hEntity aConstrEnt[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA,
732         aConstrIter->entityB };
733     std::vector<int> anIndexes;
734     // Go through the groupped entities and find even one of entities of current constraint
735     std::vector<std::set<Slvs_hEntity> >::iterator aGrEntIter;
736     for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++) {
737       bool isFound = false;
738       for (int i = 0; i < 4 && !isFound; i++)
739         if (aConstrEnt[i] != 0) {
740           isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
741           // Also we need to check sub-entities
742           int aEntPos = Search(aConstrEnt[i], myEntities);
743           Slvs_hEntity* aSub = myEntities[aEntPos].point;
744           for (int j = 0; *aSub != 0 && j < 4 && !isFound; aSub++, j++)
745             isFound = (aGrEntIter->find(*aSub) != aGrEntIter->end());
746         }
747       if (isFound)
748         anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
749     }
750     // Add new group if no one is found
751     if (anIndexes.empty()) {
752       std::set<Slvs_hEntity> aNewGrEnt;
753       for (int i = 0; i < 4; i++)
754         if (aConstrEnt[i] != 0) {
755           aNewGrEnt.insert(aConstrEnt[i]);
756           int aEntPos = Search(aConstrEnt[i], myEntities);
757           Slvs_hEntity* aSub = myEntities[aEntPos].point;
758           for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
759             aNewGrEnt.insert(*aSub);
760         }
761       std::set<Slvs_hConstraint> aNewGrConstr;
762       aNewGrConstr.insert(aConstrIter->h);
763
764       aGroupsEntities.push_back(aNewGrEnt);
765       aGroupsConstr.push_back(aNewGrConstr);
766       if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
767         aMaxNbEntities = aGroupsEntities.size() - 1;
768     } else {  // Add entities indexes into the found group
769       aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
770       for (int i = 0; i < 4; i++)
771         if (aConstrEnt[i] != 0) {
772           aGrEntIter->insert(aConstrEnt[i]);
773           int aEntPos = Search(aConstrEnt[i], myEntities);
774           Slvs_hEntity* aSub = myEntities[aEntPos].point;
775           for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
776             aGrEntIter->insert(*aSub);
777         }
778       aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
779       if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
780         aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
781       if (anIndexes.size() > 1) {  // There are found several connected groups, merge them
782         std::vector<std::set<Slvs_hEntity> >::iterator aFirstGroup = aGroupsEntities.begin()
783             + anIndexes.front();
784         std::vector<std::set<Slvs_hConstraint> >::iterator aFirstConstr = aGroupsConstr.begin()
785             + anIndexes.front();
786         std::vector<int>::iterator anInd = anIndexes.begin();
787         for (++anInd; anInd != anIndexes.end(); anInd++) {
788           aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
789           aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
790         }
791         if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
792           aMaxNbEntities = anIndexes.front();
793         // Remove merged groups
794         for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--) {
795           aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
796           aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
797         }
798       }
799     }
800   }
801
802   if (aGroupsEntities.size() <= 1)
803     return;
804
805   // Remove the group with maximum elements as it will be left in the current group
806   aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
807   aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
808
809   // Add new groups of constraints and divide current group
810   std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
811   for (int i = aGroupsEntities.size(); i > 0; i--) {
812     SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
813     aNewGroups.push_back(aG);
814   }
815   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrMapIter =
816       myConstraintMap.begin();
817   int aConstrMapPos = 0;  // position of iterator in the map (used to restore iterator after removing constraint)
818   while (aConstrMapIter != myConstraintMap.end()) {
819     std::vector<std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
820     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
821     for (; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
822       if (aGIter->find(aConstrMapIter->second) != aGIter->end()) {
823         (*aGroup)->changeConstraint(aConstrMapIter->first);
824         removeConstraint(aConstrMapIter->first);
825         // restore iterator
826         aConstrMapIter = myConstraintMap.begin();
827         for (int i = 0; i < aConstrMapPos; i++)
828           aConstrMapIter++;
829         break;
830       }
831     if (aGIter == aGroupsConstr.end()) {
832       aConstrMapIter++;
833       aConstrMapPos++;
834     }
835   }
836
837   theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
838 }
839
840 // ============================================================================
841 //  Function: updateGroup
842 //  Class:    SketchSolver_ConstraintGroup
843 //  Purpose:  search removed entities and constraints
844 // ============================================================================
845 bool SketchSolver_ConstraintGroup::updateGroup()
846 {
847   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator aConstrIter =
848       myConstraintMap.rbegin();
849   bool isAllValid = true;
850   bool isCCRemoved = false;  // indicates that at least one of coincidence constraints was removed
851   int aConstrIndex = 0;
852   while (/*isAllValid && */aConstrIter != myConstraintMap.rend()) {
853     if (!aConstrIter->first->data() || !aConstrIter->first->data()->isValid()) {
854       if (aConstrIter->first->getKind().compare(SketchPlugin_ConstraintCoincidence::ID()) == 0)
855         isCCRemoved = true;
856       removeConstraint(aConstrIter->first);
857       isAllValid = false;
858       // Get back the correct position of iterator after the "remove" operation
859       aConstrIter = myConstraintMap.rbegin();
860       for (int i = 0; i < aConstrIndex && aConstrIter != myConstraintMap.rend(); i++)
861         aConstrIter++;
862     } else {
863       aConstrIter++;
864       aConstrIndex++;
865     }
866   }
867
868   // Check if some entities are invalid too
869   std::set<Slvs_hEntity> anEntToRemove;
870   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
871       anAttrIter = myEntityAttrMap.begin();
872   while (anAttrIter != myEntityAttrMap.end()) {
873     if (!anAttrIter->first->owner() || !anAttrIter->first->owner()->data() ||
874         !anAttrIter->first->owner()->data()->isValid()) {
875       anEntToRemove.insert(anAttrIter->second);
876       std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
877           aRemovedIter = anAttrIter;
878       anAttrIter++;
879       myEntityAttrMap.erase(aRemovedIter);
880     } else
881       anAttrIter++;
882   }
883   std::map<FeaturePtr, Slvs_hEntity>::iterator aFeatIter = myEntityFeatMap.begin();
884   while (aFeatIter != myEntityFeatMap.end()) {
885     if (!aFeatIter->first || !aFeatIter->first->data() ||
886         !aFeatIter->first->data()->isValid()) {
887       anEntToRemove.insert(aFeatIter->second);
888       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = aFeatIter;
889       aFeatIter++;
890       myEntityFeatMap.erase(aRemovedIter);
891     } else
892       aFeatIter++;
893   }
894   removeEntitiesById(anEntToRemove);
895
896   // Probably, need to update coincidence constraints
897   if (isCCRemoved && !myExtraCoincidence.empty()) {
898     // Make a copy, because the new list of unused constrtaints will be generated
899     std::set<boost::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
900     myExtraCoincidence.clear();
901
902     std::set<boost::shared_ptr<SketchPlugin_Constraint> >::iterator aCIter = anExtraCopy.begin();
903     for (; aCIter != anExtraCopy.end(); aCIter++)
904       if ((*aCIter)->data() && (*aCIter)->data()->isValid())
905         changeConstraint(*aCIter);
906   }
907
908   return !isAllValid;
909 }
910
911 // ============================================================================
912 //  Function: updateAttribute
913 //  Class:    SketchSolver_ConstraintGroup
914 //  Purpose:  update features of sketch after resolving constraints
915 // ============================================================================
916 bool SketchSolver_ConstraintGroup::updateAttribute(
917     boost::shared_ptr<ModelAPI_Attribute> theAttribute, const Slvs_hEntity& theEntityID)
918 {
919   // Search the position of the first parameter of the entity
920   int anEntPos = Search(theEntityID, myEntities);
921   int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
922
923   // Look over supported types of entities
924
925   // Point in 3D
926   boost::shared_ptr<GeomDataAPI_Point> aPoint = boost::dynamic_pointer_cast<GeomDataAPI_Point>(
927       theAttribute);
928   if (aPoint) {
929     if (fabs(aPoint->x() - myParams[aFirstParamPos].val) > tolerance
930         || fabs(aPoint->y() - myParams[aFirstParamPos + 1].val) > tolerance
931         || fabs(aPoint->z() - myParams[aFirstParamPos + 2].val) > tolerance) {
932       aPoint->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val,
933                        myParams[aFirstParamPos + 2].val);
934       return true;
935     }
936     return false;
937   }
938
939   // Point in 2D
940   boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
941       boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
942   if (aPoint2D) {
943     if (fabs(aPoint2D->x() - myParams[aFirstParamPos].val) > tolerance
944         || fabs(aPoint2D->y() - myParams[aFirstParamPos + 1].val) > tolerance) {
945       aPoint2D->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val);
946       return true;
947     }
948     return false;
949   }
950
951   // Scalar value
952   AttributeDoublePtr aScalar = boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
953   if (aScalar) {
954     if (fabs(aScalar->value() - myParams[aFirstParamPos].val) > tolerance) {
955       aScalar->setValue(myParams[aFirstParamPos].val);
956       return true;
957     }
958     return false;
959   }
960
961   /// \todo Support other types of entities
962   return false;
963 }
964
965 // ============================================================================
966 //  Function: updateEntityIfPossible
967 //  Class:    SketchSolver_ConstraintGroup
968 //  Purpose:  search the entity in this group and update it
969 // ============================================================================
970 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
971     boost::shared_ptr<ModelAPI_Attribute> theEntity)
972 {
973   if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end()) {
974     // If the attribute is a point and it is changed (the group needs to rebuild),
975     // probably user has dragged this point into this position,
976     // so it is necessary to add constraint which will guarantee the point will not change
977
978     // Store myNeedToSolve flag to verify the entity is really changed
979     bool aNeedToSolveCopy = myNeedToSolve;
980     myNeedToSolve = false;
981
982     changeEntity(theEntity);
983
984     if (myNeedToSolve)  // the entity is changed
985     {
986       // Verify the entity is a point and add temporary constraint of permanency
987       boost::shared_ptr<GeomDataAPI_Point> aPoint = boost::dynamic_pointer_cast<GeomDataAPI_Point>(
988           theEntity);
989       boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D = boost::dynamic_pointer_cast<
990           GeomDataAPI_Point2D>(theEntity);
991       if (aPoint || aPoint2D)
992         addTemporaryConstraintWhereDragged(theEntity);
993     }
994
995     // Restore flag of changes
996     myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
997
998     if (myNeedToSolve)
999       updateRelatedConstraints(theEntity);
1000   }
1001 }
1002
1003 // ============================================================================
1004 //  Function: addTemporaryConstraintWhereDragged
1005 //  Class:    SketchSolver_ConstraintGroup
1006 //  Purpose:  add transient constraint SLVS_C_WHERE_DRAGGED for the entity, 
1007 //            which was moved by user
1008 // ============================================================================
1009 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
1010     boost::shared_ptr<ModelAPI_Attribute> theEntity)
1011 {
1012   // Find identifier of the entity
1013   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator anEntIter =
1014       myEntityAttrMap.find(theEntity);
1015   if (anEntIter == myEntityAttrMap.end())
1016     return;
1017
1018   // If this is a first dragged point, its parameters should be placed 
1019   // into Slvs_System::dragged field to avoid system inconsistense
1020   if (myTempPointWhereDragged.empty()) {
1021     int anEntPos = Search(anEntIter->second, myEntities);
1022     Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
1023     for (int i = 0; i < 4; i++, aDraggedParam++)
1024       if (*aDraggedParam != 0)
1025         myTempPointWhereDragged.push_back(*aDraggedParam);
1026     myTempPointWDrgdID = myEntities[anEntPos].h;
1027     return;
1028   }
1029
1030   // Get identifiers of all dragged points
1031   std::set<Slvs_hEntity> aDraggedPntID;
1032   aDraggedPntID.insert(myTempPointWDrgdID);
1033   std::list<Slvs_hConstraint>::iterator aTmpCoIter = myTempConstraints.begin();
1034   for (; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++) {
1035     unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
1036     if (aConstrPos < myConstraints.size())
1037       aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
1038   }
1039   // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
1040   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1041   for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++) {
1042     if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
1043       continue;  // the entity was not found in current set
1044
1045     // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
1046     std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
1047     for (; aDrgIter != aDraggedPntID.end(); aDrgIter++)
1048       if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
1049         return;  // the SLVS_C_WHERE_DRAGGED constraint already exists
1050   }
1051
1052   // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
1053   Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
1054                                                   myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
1055   myConstraints.push_back(aWDConstr);
1056   myTempConstraints.push_back(aWDConstr.h);
1057 }
1058
1059 // ============================================================================
1060 //  Function: removeTemporaryConstraints
1061 //  Class:    SketchSolver_ConstraintGroup
1062 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
1063 //            resolving the set of constraints
1064 // ============================================================================
1065 void SketchSolver_ConstraintGroup::removeTemporaryConstraints()
1066 {
1067   std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
1068   for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend();
1069       aTmpConstrIter++) {
1070     unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
1071     if (aConstrPos >= myConstraints.size())
1072       continue;
1073     myConstraints.erase(myConstraints.begin() + aConstrPos);
1074
1075     // If the removing constraint has higher index, decrease the indexer
1076     if (*aTmpConstrIter == myConstrMaxID)
1077       myConstrMaxID--;
1078   }
1079   myTempConstraints.clear();
1080
1081   // Clear basic dragged point
1082   myTempPointWhereDragged.clear();
1083 }
1084
1085 // ============================================================================
1086 //  Function: removeConstraint
1087 //  Class:    SketchSolver_ConstraintGroup
1088 //  Purpose:  remove constraint and all unused entities
1089 // ============================================================================
1090 void SketchSolver_ConstraintGroup::removeConstraint(
1091     boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
1092 {
1093   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::iterator anIterToRemove =
1094       myConstraintMap.find(theConstraint);
1095   if (anIterToRemove == myConstraintMap.end())
1096     return;
1097
1098   Slvs_hConstraint aCnstrToRemove = anIterToRemove->second;
1099   // Remove constraint from the map
1100   myConstraintMap.erase(anIterToRemove);
1101
1102   // Find unused entities
1103   int aConstrPos = Search(aCnstrToRemove, myConstraints);
1104   std::set<Slvs_hEntity> anEntToRemove;
1105   Slvs_hEntity aCnstEnt[] = { myConstraints[aConstrPos].ptA, myConstraints[aConstrPos].ptB,
1106       myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB };
1107   for (int i = 0; i < 4; i++)
1108     if (aCnstEnt[i] != 0)
1109       anEntToRemove.insert(aCnstEnt[i]);
1110   myConstraints.erase(myConstraints.begin() + aConstrPos);
1111   if (aCnstrToRemove == myConstrMaxID)
1112     myConstrMaxID--;
1113
1114   // Find all entities which are based on these unused
1115   std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
1116   for ( ; anEntIter != myEntities.end(); anEntIter++)
1117     if (anEntIter->type == SLVS_E_LINE_SEGMENT || anEntIter->type == SLVS_E_CIRCLE ||
1118         anEntIter->type == SLVS_E_ARC_OF_CIRCLE) {
1119       for (int i = 0; i < 4; i++)
1120         if (anEntToRemove.find(anEntIter->point[i]) != anEntToRemove.end()) {
1121           anEntToRemove.insert(anEntIter->h);
1122           for (int j = 0; j < 4; j++)
1123             if (anEntIter->param[j] != 0)
1124               anEntToRemove.insert(anEntIter->point[j]);
1125           break;
1126         }
1127     }
1128
1129   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1130   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
1131     Slvs_hEntity aEnts[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA, aConstrIter
1132         ->entityB };
1133     for (int i = 0; i < 4; i++)
1134       if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
1135         anEntToRemove.erase(aEnts[i]);
1136   }
1137
1138   if (anEntToRemove.empty())
1139     return;
1140
1141   // Remove unused entities
1142   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntAttrIter =
1143       myEntityAttrMap.begin();
1144   while (anEntAttrIter != myEntityAttrMap.end()) {
1145     if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end()) {
1146       std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator aRemovedIter =
1147           anEntAttrIter;
1148       anEntAttrIter++;
1149       myEntityAttrMap.erase(aRemovedIter);
1150     } else
1151       anEntAttrIter++;
1152   }
1153   std::map<FeaturePtr, Slvs_hEntity>::iterator anEntFeatIter = myEntityFeatMap.begin();
1154   while (anEntFeatIter != myEntityFeatMap.end()) {
1155     if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end()) {
1156       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = anEntFeatIter;
1157       anEntFeatIter++;
1158       myEntityFeatMap.erase(aRemovedIter);
1159     } else
1160       anEntFeatIter++;
1161   }
1162
1163   removeEntitiesById(anEntToRemove);
1164
1165   if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1166     myCoincidentPoints.clear();
1167 }
1168
1169 // ============================================================================
1170 //  Function: removeEntitiesById
1171 //  Class:    SketchSolver_ConstraintGroup
1172 //  Purpose:  Removes specified entities and their parameters
1173 // ============================================================================
1174 void SketchSolver_ConstraintGroup::removeEntitiesById(const std::set<Slvs_hEntity>& theEntities)
1175 {
1176   std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = theEntities.rbegin();
1177   for (; aRemIter != theEntities.rend(); aRemIter++) {
1178     unsigned int anEntPos = Search(*aRemIter, myEntities);
1179     if (anEntPos >= myEntities.size())
1180       continue;
1181     if (myEntities[anEntPos].param[0] != 0) {
1182       unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1183       if (aParamPos >= myParams.size())
1184         continue;
1185       int aNbParams = 0;
1186       while (myEntities[anEntPos].param[aNbParams] != 0)
1187         aNbParams++;
1188       if (myEntities[anEntPos].param[aNbParams - 1] == myParamMaxID)
1189         myParamMaxID -= aNbParams;
1190       myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1191       if (*aRemIter == myEntityMaxID)
1192         myEntityMaxID--;
1193     }
1194     myEntities.erase(myEntities.begin() + anEntPos);
1195     myEntOfConstr.erase(myEntOfConstr.begin() + anEntPos);
1196
1197     // Remove entity's ID from the lists of conincident points
1198     std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1199     for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1200       aCoPtIter->erase(*aRemIter);
1201   }
1202 }
1203
1204 // ============================================================================
1205 //  Function: addCoincidentPoints
1206 //  Class:    SketchSolver_ConstraintGroup
1207 //  Purpose:  add coincident point the appropriate list of such points
1208 // ============================================================================
1209 bool SketchSolver_ConstraintGroup::addCoincidentPoints(const Slvs_hEntity& thePoint1,
1210                                                        const Slvs_hEntity& thePoint2)
1211 {
1212   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1213   std::vector<std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1214   while (aCoPtIter != myCoincidentPoints.end()) {
1215     bool isFound[2] = {  // indicate which point ID was already in coincidence constraint
1216         aCoPtIter->find(thePoint1) != aCoPtIter->end(), aCoPtIter->find(thePoint2)
1217             != aCoPtIter->end(), };
1218     if (isFound[0] && isFound[1])  // points are already connected by coincidence constraints => no need additional one
1219       return false;
1220     if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1])) {
1221       if (aFirstFound != myCoincidentPoints.end()) {  // there are two groups of coincident points connected by created constraint => merge them
1222         int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1223         int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1224         aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1225         myCoincidentPoints.erase(aCoPtIter);
1226         aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1227         aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1228         continue;
1229       } else {
1230         aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1231         aFirstFound = aCoPtIter;
1232       }
1233     }
1234     aCoPtIter++;
1235   }
1236   // No points were found, need to create new set
1237   if (aFirstFound == myCoincidentPoints.end()) {
1238     std::set<Slvs_hEntity> aNewSet;
1239     aNewSet.insert(thePoint1);
1240     aNewSet.insert(thePoint2);
1241     myCoincidentPoints.push_back(aNewSet);
1242   }
1243
1244   return true;
1245 }
1246
1247 // ============================================================================
1248 //  Function: updateRelatedConstraints
1249 //  Class:    SketchSolver_ConstraintGroup
1250 //  Purpose:  emit the signal to update constraints
1251 // ============================================================================
1252 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1253     boost::shared_ptr<ModelAPI_Attribute> theEntity) const
1254 {
1255   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrIter =
1256       myConstraintMap.begin();
1257   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1258     std::list<boost::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1259         ->attributes(std::string());
1260
1261     std::list<boost::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1262     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1263       bool isUpd = (*anAttrIter == theEntity);
1264       boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = boost::dynamic_pointer_cast<
1265           ModelAPI_AttributeRefAttr>(*anAttrIter);
1266       if (aRefAttr && !aRefAttr->isObject() && aRefAttr->attr() == theEntity)
1267         isUpd = true;
1268
1269       if (isUpd) {
1270         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1271         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1272         break;
1273       }
1274     }
1275   }
1276 }
1277
1278 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1279     boost::shared_ptr<ModelAPI_Feature> theFeature) const
1280 {
1281   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrIter =
1282       myConstraintMap.begin();
1283   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1284     std::list<boost::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1285         ->attributes(std::string());
1286
1287     std::list<boost::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1288     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1289       boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = boost::dynamic_pointer_cast<
1290           ModelAPI_AttributeRefAttr>(*anAttrIter);
1291       if (aRefAttr && aRefAttr->isObject() && aRefAttr->object() == theFeature) {
1292         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1293         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1294         break;
1295       }
1296     }
1297   }
1298 }
1299
1300 // ========================================================
1301 // =========      Auxiliary functions       ===============
1302 // ========================================================
1303
1304 template<typename T>
1305 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1306 {
1307   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1308   int aVecSize = theEntities.size();
1309   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1310     aResIndex--;
1311   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1312     aResIndex++;
1313   if (aResIndex == -1)
1314     aResIndex = aVecSize;
1315   return aResIndex;
1316 }