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