Salome HOME
SolveSpaceSolver: do not update IDs of sub-entities for the Multi constraints
[modules/shaper.git] / src / SketchSolver / SolveSpaceSolver / SolveSpaceSolver_Storage.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SolveSpaceSolver_Storage.cpp
4 // Created: 18 Mar 2015
5 // Author:  Artem ZHIDKOV
6
7 #include <SolveSpaceSolver_Storage.h>
8 #include <SolveSpaceSolver_ConstraintWrapper.h>
9 #include <SolveSpaceSolver_EntityWrapper.h>
10 #include <SolveSpaceSolver_ParameterWrapper.h>
11 #include <SolveSpaceSolver_Builder.h>
12
13 #include <GeomAPI_Dir2d.h>
14 #include <GeomAPI_Pnt2d.h>
15 #include <GeomAPI_XY.h>
16 #include <math.h>
17 #include <assert.h>
18
19 #include <GeomDataAPI_Point.h>
20 #include <GeomDataAPI_Point2D.h>
21 #include <ModelAPI_AttributeDouble.h>
22
23 /** \brief Search the entity/parameter with specified ID in the list of elements
24  *  \param[in] theEntityID unique ID of the element
25  *  \param[in] theEntities list of elements
26  *  \return position of the found element or -1 if the element is not found
27  */
28 template<typename T>
29 static int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities);
30
31 /// \brief Compare two parameters to be different
32 static bool IsNotEqual(const Slvs_Param& theParam1, const Slvs_Param& theParam2);
33 /// \brief Compare two entities to be different
34 static bool IsNotEqual(const Slvs_Entity& theEntity1, const Slvs_Entity& theEntity2);
35 /// \brief Compare two constraints to be different
36 static bool IsNotEqual(const Slvs_Constraint& theConstraint1, const Slvs_Constraint& theConstraint2);
37
38
39 SolveSpaceSolver_Storage::SolveSpaceSolver_Storage(const GroupID& theGroup)
40   : SketchSolver_Storage(theGroup),
41     myWorkplaneID(SLVS_E_UNKNOWN),
42     myParamMaxID(SLVS_E_UNKNOWN),
43     myEntityMaxID(SLVS_E_UNKNOWN),
44     myConstrMaxID(SLVS_C_UNKNOWN),
45     myFixed(SLVS_E_UNKNOWN),
46     myDuplicatedConstraint(false)
47 {
48 }
49
50 bool SolveSpaceSolver_Storage::update(ConstraintWrapperPtr& theConstraint)
51 {
52   bool isUpdated = false;
53   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
54       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
55   Slvs_Constraint aSlvsConstr = getConstraint((Slvs_hConstraint)aConstraint->id());
56   if (aSlvsConstr.h == SLVS_C_UNKNOWN)
57     aSlvsConstr = aConstraint->constraint();
58
59   // update value of constraint if exist
60   if (fabs(aSlvsConstr.valA - theConstraint->value()) > tolerance) {
61     aSlvsConstr.valA = theConstraint->value();
62     isUpdated = true;
63   }
64
65   // update constrained entities
66   Slvs_hEntity* aPnts[2] = {&aSlvsConstr.ptA, &aSlvsConstr.ptB};
67   Slvs_hEntity* anEnts[4] = {&aSlvsConstr.entityA, &aSlvsConstr.entityB,
68                              &aSlvsConstr.entityC, &aSlvsConstr.entityD};
69   int aPtInd = 0;
70   int aEntInd = 0;
71
72   std::list<EntityWrapperPtr> anEntities = theConstraint->entities();
73   std::list<EntityWrapperPtr>::iterator anIt = anEntities.begin();
74   for (; anIt != anEntities.end(); ++anIt) {
75     isUpdated = update(*anIt) || isUpdated;
76     // do not update constrained entities for Multi constraints
77     if (aSlvsConstr.type == SLVS_C_MULTI_ROTATION || aSlvsConstr.type != SLVS_C_MULTI_TRANSLATION)
78       continue;
79
80     Slvs_hEntity anID = (Slvs_hEntity)(*anIt)->id();
81     if ((*anIt)->type() == ENTITY_POINT) {
82       if (*(aPnts[aPtInd]) != anID) {
83         *(aPnts[aPtInd]) = anID;
84         isUpdated = true;
85       }
86       ++aPtInd;
87     } else {
88       if (*(anEnts[aEntInd]) != anID) {
89         *(anEnts[aEntInd]) = anID;
90         isUpdated = true;
91       }
92       ++aEntInd;
93     }
94   }
95
96   // update constraint itself (do not update constraints Multi)
97   if (aSlvsConstr.type != SLVS_C_MULTI_ROTATION && aSlvsConstr.type != SLVS_C_MULTI_TRANSLATION) {
98     if (aSlvsConstr.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
99       aSlvsConstr.wrkpl = myWorkplaneID;
100     if (aSlvsConstr.group == SLVS_G_UNKNOWN)
101       aSlvsConstr.group = (Slvs_hGroup)myGroupID;
102     Slvs_hConstraint aConstrID = updateConstraint(aSlvsConstr);
103     if (aSlvsConstr.h == SLVS_C_UNKNOWN) {
104       aConstraint->changeConstraint() = getConstraint(aConstrID);
105       isUpdated = true;
106     }
107   }
108   return isUpdated;
109 }
110
111 bool SolveSpaceSolver_Storage::update(EntityWrapperPtr& theEntity)
112 {
113   bool isUpdated = false;
114   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
115       std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
116   Slvs_Entity aSlvsEnt = getEntity((Slvs_hEntity)anEntity->id());
117   if (aSlvsEnt.h == SLVS_E_UNKNOWN)
118     aSlvsEnt = anEntity->entity();
119
120   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
121   std::list<ParameterWrapperPtr>::iterator aPIt;
122   // if the entity is an attribute, need to update its coordinates
123   if (anEntity->baseAttribute()) {
124     BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
125     EntityWrapperPtr anUpdAttr = aBuilder->createAttribute(anEntity->baseAttribute(), GID_UNKNOWN);
126     if (anUpdAttr) {
127       std::list<ParameterWrapperPtr> anUpdParams = anUpdAttr->parameters();
128       std::list<ParameterWrapperPtr>::iterator anUpdIt = anUpdParams.begin();
129       for (aPIt = aParams.begin(); aPIt != aParams.end() && anUpdIt != anUpdParams.end();
130           ++aPIt, ++anUpdIt) {
131         (*aPIt)->update(*anUpdIt);
132       }
133     }
134   }
135
136   // update parameters
137   int anInd = 0;
138   for (aPIt = aParams.begin(); aPIt != aParams.end(); ++aPIt, ++anInd) {
139     assert(anInd < 4);
140     isUpdated = update(*aPIt) || isUpdated;
141     if (aSlvsEnt.param[anInd] != (Slvs_hEntity)(*aPIt)->id()) {
142       isUpdated = true;
143       aSlvsEnt.param[anInd] = (Slvs_hEntity)(*aPIt)->id();
144     }
145   }
146
147   // update sub-entities
148   std::list<EntityWrapperPtr> aSubEntities = theEntity->subEntities();
149   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
150   for (anInd = 0; aSIt != aSubEntities.end(); ++aSIt, ++anInd) {
151     assert(anInd < 4);
152     isUpdated = update(*aSIt) || isUpdated;
153
154     Slvs_hEntity anID = Slvs_hEntity((*aSIt)->id());
155     if ((*aSIt)->type() == ENTITY_NORMAL)
156       aSlvsEnt.normal = anID;
157     else if ((*aSIt)->type() == ENTITY_SCALAR)
158       aSlvsEnt.distance = anID;
159     else if (aSlvsEnt.point[anInd] != anID) {
160       aSlvsEnt.point[anInd] = anID;
161       isUpdated = true;
162     }
163   }
164
165   // update entity itself
166   if (aSlvsEnt.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
167     aSlvsEnt.wrkpl = myWorkplaneID;
168   if (aSlvsEnt.group == SLVS_G_UNKNOWN)
169     aSlvsEnt.group = (Slvs_hGroup)myGroupID;
170   Slvs_hEntity anEntID = updateEntity(aSlvsEnt);
171   if (aSlvsEnt.h == SLVS_E_UNKNOWN) {
172     anEntity->changeEntity() = getEntity(anEntID);
173     isUpdated = true;
174
175     if (anEntity->type() == ENTITY_SKETCH)
176       storeWorkplane(anEntity);
177   }
178   return isUpdated;
179 }
180
181 bool SolveSpaceSolver_Storage::update(ParameterWrapperPtr& theParameter)
182 {
183   std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aParameter = 
184       std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(theParameter);
185   const Slvs_Param& aParam = getParameter((Slvs_hParam)aParameter->id());
186   if (aParam.h != SLVS_E_UNKNOWN && fabs(aParam.val - aParameter->value()) < tolerance)
187     return false;
188   Slvs_Param aParamToUpd = aParameter->parameter();
189   if (aParamToUpd.group == SLVS_G_UNKNOWN)
190     aParamToUpd.group = aParameter->isParametric() ? (Slvs_hGroup)GID_OUTOFGROUP : (Slvs_hGroup)myGroupID;
191   Slvs_hParam anID = updateParameter(aParamToUpd);
192   if (aParam.h == SLVS_E_UNKNOWN) // new parameter
193     aParameter->changeParameter() = getParameter(anID);
194   return true;
195 }
196
197 void SolveSpaceSolver_Storage::storeWorkplane(EntityWrapperPtr theSketch)
198 {
199   myWorkplaneID = (Slvs_hEntity)theSketch->id();
200
201   // Update sub-entities of the sketch
202   std::list<EntityWrapperPtr> aSubEntities = theSketch->subEntities();
203   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
204   for (; aSIt != aSubEntities.end(); ++aSIt) {
205     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSub =
206         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*aSIt);
207     aSub->changeEntity().wrkpl = myWorkplaneID;
208   }
209
210   // Update all stored entities
211   std::vector<Slvs_Entity>::iterator anIt = myEntities.begin();
212   for (; anIt != myEntities.end(); ++anIt)
213     anIt->wrkpl = myWorkplaneID;
214 }
215
216 void SolveSpaceSolver_Storage::changeGroup(EntityWrapperPtr theEntity, const GroupID& theGroup)
217 {
218   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
219   std::list<ParameterWrapperPtr>::iterator aPIt = aParams.begin();
220   for (; aPIt != aParams.end(); ++aPIt)
221     changeGroup(*aPIt, theGroup);
222
223   std::list<EntityWrapperPtr> aSubs = theEntity->subEntities();
224   std::list<EntityWrapperPtr>::iterator aSIt = aSubs.begin();
225   for (; aSIt != aSubs.end(); ++aSIt)
226     changeGroup(*aSIt, theGroup);
227
228   if (theEntity->group() != theGroup) {
229     theEntity->setGroup(theGroup);
230     int aPos = Search((Slvs_hEntity)theEntity->id(), myEntities);
231     if (aPos >= 0 && aPos < (int)myEntities.size()) {
232       myEntities[aPos].group = (Slvs_hGroup)theGroup;
233       setNeedToResolve(true);
234     }
235   }
236 }
237
238 void SolveSpaceSolver_Storage::changeGroup(ParameterWrapperPtr theParam, const GroupID& theGroup)
239 {
240   GroupID aGroup = theGroup;
241   if (theParam->isParametric())
242     aGroup = GID_OUTOFGROUP;
243   if (theParam->group() == aGroup)
244     return;
245
246   theParam->setGroup(aGroup);
247   int aPos = Search((Slvs_hParam)theParam->id(), myParameters);
248   if (aPos >= 0 && aPos < (int)myParameters.size()) {
249     myParameters[aPos].group = (Slvs_hGroup)aGroup;
250     setNeedToResolve(true);
251   }
252 }
253
254 void SolveSpaceSolver_Storage::addCoincidentPoints(
255     EntityWrapperPtr theMaster, EntityWrapperPtr theSlave)
256 {
257   if (theMaster->type() != ENTITY_POINT || theSlave->type() != ENTITY_POINT)
258     return;
259
260   // Search available coincidence
261   CoincidentPointsMap::iterator aMasterFound = myCoincidentPoints.find(theMaster);
262   CoincidentPointsMap::iterator aSlaveFound = myCoincidentPoints.find(theSlave);
263   if (aMasterFound == myCoincidentPoints.end() &&  aSlaveFound == myCoincidentPoints.end()) {
264     // try to find master and slave points in the lists of slaves of already existent coincidences
265     CoincidentPointsMap::iterator anIt = myCoincidentPoints.begin();
266     for (; anIt != myCoincidentPoints.end(); ++anIt) {
267       if (anIt->second.find(theMaster) != anIt->second.end())
268         aMasterFound = anIt;
269       else if (anIt->second.find(theSlave) != anIt->second.end())
270         aSlaveFound = anIt;
271
272       if (aMasterFound != myCoincidentPoints.end() &&  aSlaveFound != myCoincidentPoints.end())
273         break;
274     }
275   }
276
277   if (aMasterFound == myCoincidentPoints.end()) {
278     // create new group
279     myCoincidentPoints[theMaster] = std::set<EntityWrapperPtr>();
280     aMasterFound = myCoincidentPoints.find(theMaster);
281   } else if (aMasterFound == aSlaveFound)
282     return; // already coincident
283
284   if (aSlaveFound != myCoincidentPoints.end()) {
285     // A slave has been found, we need to attach all points coincident with it to the new master
286     std::set<EntityWrapperPtr> aNewSlaves = aSlaveFound->second;
287     aNewSlaves.insert(aSlaveFound->first);
288     myCoincidentPoints.erase(aSlaveFound);
289
290     std::set<EntityWrapperPtr>::const_iterator aSlIt = aNewSlaves.begin();
291     for (; aSlIt != aNewSlaves.end(); ++aSlIt)
292       addCoincidentPoints(theMaster, *aSlIt);
293   } else {
294     // Update the slave if it was used in constraints and features
295     replaceInFeatures(theSlave, theMaster);
296     replaceInConstraints(theSlave, theMaster);
297
298     // Remove slave entity
299     removeEntity((Slvs_hEntity)theSlave->id());
300
301     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aPointMaster = 
302         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theMaster);
303     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aPointSlave = 
304         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theSlave);
305     aPointSlave->changeEntity() = aPointMaster->entity();
306     aPointSlave->setParameters(aPointMaster->parameters());
307
308     aMasterFound->second.insert(theSlave);
309   }
310 }
311
312 void SolveSpaceSolver_Storage::replaceInFeatures(
313     EntityWrapperPtr theSource, EntityWrapperPtr theDest)
314 {
315   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator anIt = myFeatureMap.begin();
316   for (; anIt != myFeatureMap.end(); ++anIt) {
317     bool isUpdated = false;
318     std::list<EntityWrapperPtr> aSubs = anIt->second->subEntities();
319     std::list<EntityWrapperPtr>::iterator aSubIt = aSubs.begin();
320     for (; aSubIt != aSubs.end(); ++aSubIt)
321       if ((*aSubIt)->id() == theSource->id()) {
322         (*aSubIt)->update(theDest);
323         isUpdated = true;
324       }
325
326     if (!isUpdated)
327       continue;
328
329     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aWrapper =
330         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(anIt->second);
331     // update SolveSpace entity
332     Slvs_Entity anEnt = aWrapper->entity();
333     for (int i = 0; i < 4; ++i)
334       if (anEnt.point[i] == (Slvs_hEntity)theSource->id())
335         anEnt.point[i] = (Slvs_hEntity)theDest->id();
336     anEnt.h = updateEntity(anEnt);
337     aWrapper->changeEntity() = anEnt;
338
339     // update sub-entities
340     aWrapper->setSubEntities(aSubs);
341   }
342 }
343
344 void SolveSpaceSolver_Storage::replaceInConstraints(
345     EntityWrapperPtr theSource, EntityWrapperPtr theDest)
346 {
347   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
348       anIt = myConstraintMap.begin();
349   std::list<ConstraintWrapperPtr>::const_iterator aCIt;
350   for (; anIt != myConstraintMap.end(); ++anIt)
351     for (aCIt = anIt->second.begin(); aCIt != anIt->second.end(); ++aCIt) {
352       // Do not process coincidence between points
353       // (these constraints are stored to keep the structure of constraints).
354       if ((*aCIt)->type() == CONSTRAINT_PT_PT_COINCIDENT)
355         continue;
356
357       bool isUpdated = false;
358       std::list<EntityWrapperPtr> aSubs = (*aCIt)->entities();
359       std::list<EntityWrapperPtr>::iterator aSubIt = aSubs.begin();
360       for (; aSubIt != aSubs.end(); ++aSubIt)
361         if ((*aSubIt)->id() == theSource->id()) {
362           (*aSubIt)->update(theDest);
363           isUpdated = true;
364         }
365
366       if (!isUpdated)
367         continue;
368
369       std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aWrapper =
370           std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(*aCIt);
371       // change constraint entities
372       Slvs_Constraint aConstr = aWrapper->constraint();
373       if (aConstr.ptA == (Slvs_hEntity)theSource->id())
374         aConstr.ptA = (Slvs_hEntity)theDest->id();
375       if (aConstr.ptB == (Slvs_hEntity)theSource->id())
376         aConstr.ptB = (Slvs_hEntity)theDest->id();
377
378       // check the constraint is duplicated
379       std::vector<Slvs_Constraint>::const_iterator aSlvsCIt = myConstraints.begin();
380       for (; aSlvsCIt != myConstraints.end(); ++aSlvsCIt)
381         if (aConstr.h != aSlvsCIt->h &&
382             aConstr.type == aSlvsCIt->type &&
383             aConstr.ptA == aSlvsCIt->ptA && aConstr.ptB == aSlvsCIt->ptB &&
384             aConstr.entityA == aSlvsCIt->entityA && aConstr.entityB == aSlvsCIt->entityB &&
385             aConstr.entityC == aSlvsCIt->entityC && aConstr.entityD == aSlvsCIt->entityD) {
386           removeConstraint(aConstr.h);
387           aConstr = *aSlvsCIt;
388           break;
389         }
390
391       if (aSlvsCIt != myConstraints.end()) {
392         // constraint is duplicated, search its wrapper to add the mapping
393         std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
394             anIt2 = myConstraintMap.begin();
395         std::list<ConstraintWrapperPtr>::const_iterator aCIt2;
396         for (; anIt2 != myConstraintMap.end(); ++anIt2)
397           for (aCIt2 = anIt2->second.begin(); aCIt2 != anIt2->second.end(); ++aCIt2)
398             if ((Slvs_hConstraint)(*aCIt2)->id() == aConstr.h) {
399               addSameConstraints(*aCIt2, aWrapper);
400               break;
401             }
402       } else 
403         aConstr.h = updateConstraint(aConstr);
404       aWrapper->changeConstraint() = aConstr;
405
406       // update sub-entities
407       aWrapper->setEntities(aSubs);
408     }
409 }
410
411 void SolveSpaceSolver_Storage::addSameConstraints(ConstraintWrapperPtr theConstraint1,
412                                                   ConstraintWrapperPtr theConstraint2)
413 {
414   SameConstraintMap::iterator anIt = myEqualConstraints.begin();
415   for (; anIt != myEqualConstraints.end(); ++anIt) {
416     if (anIt->find(theConstraint1) != anIt->end()) {
417       anIt->insert(theConstraint2);
418       return;
419     }
420     else if (anIt->find(theConstraint2) != anIt->end()) {
421       anIt->insert(theConstraint1);
422       return;
423     }
424   }
425   // group not found => create new one
426   std::set<ConstraintWrapperPtr> aNewGroup;
427   aNewGroup.insert(theConstraint1);
428   aNewGroup.insert(theConstraint2);
429   myEqualConstraints.push_back(aNewGroup);
430 }
431
432
433 EntityWrapperPtr SolveSpaceSolver_Storage::calculateMiddlePoint(
434     EntityWrapperPtr theBase, double theCoeff)
435 {
436   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
437
438   std::shared_ptr<GeomAPI_XY> aMidPoint;
439   if (theBase->type() == ENTITY_LINE) {
440     std::shared_ptr<GeomAPI_Pnt2d> aPoints[2];
441     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
442     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
443     for (int i = 0; i < 2; ++i, ++anIt)
444       aPoints[i] = aBuilder->point(*anIt);
445     aMidPoint = aPoints[0]->xy()->multiplied(1.0 - theCoeff)->added(
446         aPoints[1]->xy()->multiplied(theCoeff));
447   }
448   else if (theBase->type() == ENTITY_ARC) {
449     double theX, theY;
450     double anArcPoint[3][2];
451     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
452     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
453     for (int i = 0; i < 3; ++i, ++anIt) {
454       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aBuilder->point(*anIt);
455       anArcPoint[i][0] = aPoint->x();
456       anArcPoint[i][1] = aPoint->y();
457     }
458     // project last point of arc on the arc
459     double x = anArcPoint[1][0] - anArcPoint[0][0];
460     double y = anArcPoint[1][1] - anArcPoint[0][1];
461     double aRad = sqrt(x*x + y*y);
462     x = anArcPoint[2][0] - anArcPoint[0][0];
463     y = anArcPoint[2][1] - anArcPoint[0][1];
464     double aNorm = sqrt(x*x + y*y);
465     if (aNorm >= tolerance) {
466       anArcPoint[2][0] = x * aRad / aNorm;
467       anArcPoint[2][1] = y * aRad / aNorm;
468     }
469     anArcPoint[1][0] -= anArcPoint[0][0];
470     anArcPoint[1][1] -= anArcPoint[0][1];
471     if (theCoeff < tolerance) {
472       theX = anArcPoint[0][0] + anArcPoint[1][0];
473       theY = anArcPoint[0][1] + anArcPoint[1][1];
474     } else if (1 - theCoeff < tolerance) {
475       theX = anArcPoint[0][0] + anArcPoint[2][0];
476       theY = anArcPoint[0][1] + anArcPoint[2][1];
477     } else {
478       std::shared_ptr<GeomAPI_Dir2d> aStartDir(new GeomAPI_Dir2d(anArcPoint[1][0], anArcPoint[1][1]));
479       std::shared_ptr<GeomAPI_Dir2d> aEndDir(new GeomAPI_Dir2d(anArcPoint[2][0], anArcPoint[2][1]));
480       double anAngle = aStartDir->angle(aEndDir);
481       if (anAngle < 0)
482         anAngle += 2.0 * PI;
483       anAngle *= theCoeff;
484       double aCos = cos(anAngle);
485       double aSin = sin(anAngle);
486       theX = anArcPoint[0][0] + anArcPoint[1][0] * aCos - anArcPoint[1][1] * aSin;
487       theY = anArcPoint[0][1] + anArcPoint[1][0] * aSin + anArcPoint[1][1] * aCos;
488     }
489     aMidPoint = std::shared_ptr<GeomAPI_XY>(new GeomAPI_XY(theX, theY));
490   }
491
492   if (!aMidPoint)
493     return EntityWrapperPtr();
494
495   std::list<ParameterWrapperPtr> aParameters;
496   Slvs_Param aParam1 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->x());
497   aParam1.h = addParameter(aParam1);
498   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam1)));
499   Slvs_Param aParam2 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->y());
500   aParam2.h = addParameter(aParam2);
501   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam2)));
502   // Create entity (parameters are not filled)
503   Slvs_Entity anEntity = Slvs_MakePoint2d(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID,
504       (Slvs_hEntity)myWorkplaneID, aParam1.h, aParam2.h);
505   anEntity.h = addEntity(anEntity);
506
507   EntityWrapperPtr aResult(new SolveSpaceSolver_EntityWrapper(AttributePtr(), anEntity));
508   aResult->setParameters(aParameters);
509   return aResult;
510 }
511
512
513
514
515
516
517 Slvs_hParam SolveSpaceSolver_Storage::addParameter(const Slvs_Param& theParam)
518 {
519   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
520     // parameter is already used, rewrite it
521     return updateParameter(theParam);
522   }
523
524   Slvs_Param aParam = theParam;
525   if (aParam.h > myParamMaxID)
526     myParamMaxID = aParam.h;
527   else
528     aParam.h = ++myParamMaxID;
529   myParameters.push_back(aParam);
530   myNeedToResolve = true;
531   return aParam.h;
532 }
533
534 Slvs_hParam SolveSpaceSolver_Storage::updateParameter(const Slvs_Param& theParam)
535 {
536   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
537     // parameter already used, rewrite it
538     int aPos = Search(theParam.h, myParameters);
539     if (aPos >= 0 && aPos < (int)myParameters.size()) {
540       if (IsNotEqual(myParameters[aPos], theParam)) {
541         myUpdatedParameters.insert(theParam.h);
542         setNeedToResolve(true);
543       }
544       myParameters[aPos] = theParam;
545       return theParam.h;
546     }
547   }
548
549   // Parameter is not found, add new one
550   Slvs_Param aParam = theParam;
551   aParam.h = 0;
552   return addParameter(aParam);
553 }
554
555 bool SolveSpaceSolver_Storage::removeParameter(const Slvs_hParam& theParamID)
556 {
557   int aPos = Search(theParamID, myParameters);
558   if (aPos >= 0 && aPos < (int)myParameters.size()) {
559     // Firstly, search the parameter is not used elsewhere
560     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
561     for (; anEntIter != myEntities.end(); anEntIter++) {
562       for (int i = 0; i < 4; i++)
563         if (anEntIter->param[i] == theParamID)
564           return false;
565     }
566     // Remove parameter
567     myParameters.erase(myParameters.begin() + aPos);
568     myParamMaxID = myParameters.empty() ? SLVS_E_UNKNOWN : myParameters.back().h;
569     myNeedToResolve = true;
570   }
571   return true;
572 }
573
574 const Slvs_Param& SolveSpaceSolver_Storage::getParameter(const Slvs_hParam& theParamID) const
575 {
576   int aPos = Search(theParamID, myParameters);
577   if (aPos >= 0 && aPos < (int)myParameters.size())
578     return myParameters[aPos];
579
580   // Parameter is not found, return empty object
581   static Slvs_Param aDummy;
582   aDummy.h = 0;
583   return aDummy;
584 }
585
586
587 Slvs_hEntity SolveSpaceSolver_Storage::addEntity(const Slvs_Entity& theEntity)
588 {
589   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
590     // Entity is already used, rewrite it
591     return updateEntity(theEntity);
592   }
593
594   Slvs_Entity aEntity = theEntity;
595   if (aEntity.h > myEntityMaxID)
596     myEntityMaxID = aEntity.h;
597   else
598     aEntity.h = ++myEntityMaxID;
599   myEntities.push_back(aEntity);
600   myNeedToResolve = true;
601   return aEntity.h;
602 }
603
604 Slvs_hEntity SolveSpaceSolver_Storage::updateEntity(const Slvs_Entity& theEntity)
605 {
606   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
607     // Entity already used, rewrite it
608     int aPos = Search(theEntity.h, myEntities);
609     if (aPos >= 0 && aPos < (int)myEntities.size()) {
610       myNeedToResolve = myNeedToResolve || IsNotEqual(myEntities[aPos], theEntity);
611       myEntities[aPos] = theEntity;
612       return theEntity.h;
613     }
614   }
615
616   // Entity is not found, add new one
617   Slvs_Entity aEntity = theEntity;
618   aEntity.h = 0;
619   return addEntity(aEntity);
620 }
621
622 bool SolveSpaceSolver_Storage::removeEntity(const Slvs_hEntity& theEntityID)
623 {
624   bool aResult = true;
625   int aPos = Search(theEntityID, myEntities);
626   if (aPos >= 0 && aPos < (int)myEntities.size()) {
627     // Firstly, check the entity and its attributes is not used elsewhere
628     std::set<Slvs_hEntity> anEntAndSubs;
629     anEntAndSubs.insert(theEntityID);
630     for (int i = 0; i < 4; i++)
631       if (myEntities[aPos].point[i] != SLVS_E_UNKNOWN)
632         anEntAndSubs.insert(myEntities[aPos].point[i]);
633
634     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
635     for (; anEntIter != myEntities.end(); anEntIter++) {
636       if (anEntAndSubs.find(anEntIter->h) != anEntAndSubs.end())
637         continue;
638       for (int i = 0; i < 4; i++)
639         if (anEntAndSubs.find(anEntIter->point[i]) != anEntAndSubs.end())
640           return false;
641       if (anEntAndSubs.find(anEntIter->distance) != anEntAndSubs.end())
642         return false;
643     }
644     std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
645     for (; aConstrIter != myConstraints.end(); aConstrIter++) {
646       Slvs_hEntity anEntIDs[6] = {aConstrIter->ptA, aConstrIter->ptB,
647           aConstrIter->entityA, aConstrIter->entityB,
648           aConstrIter->entityC, aConstrIter->entityD};
649       for (int i = 0; i < 6; i++)
650         if (anEntAndSubs.find(anEntIDs[i]) != anEntAndSubs.end())
651           return false;
652     }
653     // The entity is not used, remove it and its parameters
654     Slvs_Entity anEntity = myEntities[aPos];
655     myEntities.erase(myEntities.begin() + aPos);
656     myEntityMaxID = myEntities.empty() ? SLVS_E_UNKNOWN : myEntities.back().h;
657     if (anEntity.distance != SLVS_E_UNKNOWN)
658       aResult = aResult && removeParameter(anEntity.distance);
659     for (int i = 0; i < 4; i++)
660       if (anEntity.param[i] != SLVS_E_UNKNOWN)
661         aResult = removeParameter(anEntity.param[i]) && aResult;
662     for (int i = 0; i < 4; i++)
663       if (anEntity.point[i] != SLVS_E_UNKNOWN)
664         aResult = removeEntity(anEntity.point[i]) && aResult;
665     myNeedToResolve = true;
666   }
667   return aResult;
668 }
669
670 void SolveSpaceSolver_Storage::removeUnusedEntities()
671 {
672   std::set<Slvs_hEntity> anUnusedEntities;
673   std::vector<Slvs_Entity>::const_iterator aEIt = myEntities.begin();
674   for (; aEIt != myEntities.end(); ++aEIt) {
675     if (aEIt->h == aEIt->wrkpl) {
676       // don't remove workplane
677       anUnusedEntities.erase(aEIt->point[0]);
678       anUnusedEntities.erase(aEIt->normal);
679       continue;
680     }
681     anUnusedEntities.insert(aEIt->h);
682   }
683
684   std::vector<Slvs_Constraint>::const_iterator aCIt = myConstraints.begin();
685   for (; aCIt != myConstraints.end(); ++aCIt) {
686     Slvs_hEntity aSubs[6] = {
687         aCIt->entityA, aCIt->entityB,
688         aCIt->entityC, aCIt->entityD,
689         aCIt->ptA,     aCIt->ptB};
690     for (int i = 0; i < 6; i++) {
691       if (aSubs[i] != SLVS_E_UNKNOWN) {
692         anUnusedEntities.erase(aSubs[i]);
693         int aPos = Search(aSubs[i], myEntities);
694         if (aPos >= 0 && aPos < (int)myEntities.size()) {
695           for (int j = 0; j < 4; j++)
696             if (myEntities[aPos].point[j] != SLVS_E_UNKNOWN)
697               anUnusedEntities.erase(myEntities[aPos].point[j]);
698           if (myEntities[aPos].distance != SLVS_E_UNKNOWN)
699             anUnusedEntities.erase(myEntities[aPos].distance);
700         }
701       }
702     }
703   }
704
705   std::set<Slvs_hEntity>::const_iterator anEntIt = anUnusedEntities.begin();
706   while (anEntIt != anUnusedEntities.end()) {
707     int aPos = Search(*anEntIt, myEntities);
708     if (aPos < 0 && aPos >= (int)myEntities.size())
709       continue;
710     Slvs_Entity anEntity = myEntities[aPos];
711     // Remove entity if and only if all its parameters unused
712     bool isUsed = false;
713     if (anEntity.distance != SLVS_E_UNKNOWN && 
714       anUnusedEntities.find(anEntity.distance) == anUnusedEntities.end())
715       isUsed = true;
716     for (int i = 0; i < 4 && !isUsed; i++)
717       if (anEntity.point[i] != SLVS_E_UNKNOWN &&
718           anUnusedEntities.find(anEntity.point[i]) == anUnusedEntities.end())
719         isUsed = true;
720     if (isUsed) {
721       anUnusedEntities.erase(anEntity.distance);
722       for (int i = 0; i < 4; i++)
723         if (anEntity.point[i] != SLVS_E_UNKNOWN)
724           anUnusedEntities.erase(anEntity.point[i]);
725       std::set<Slvs_hEntity>::iterator aRemoveIt = anEntIt++;
726       anUnusedEntities.erase(aRemoveIt);
727       continue;
728     }
729     ++anEntIt;
730   }
731
732   for (anEntIt = anUnusedEntities.begin(); anEntIt != anUnusedEntities.end(); ++anEntIt) {
733     int aPos = Search(*anEntIt, myEntities);
734     if (aPos >= 0 && aPos < (int)myEntities.size()) {
735       // Remove entity and its parameters
736       Slvs_Entity anEntity = myEntities[aPos];
737       myEntities.erase(myEntities.begin() + aPos);
738       myEntityMaxID = myEntities.empty() ? SLVS_E_UNKNOWN : myEntities.back().h;
739       if (anEntity.distance != SLVS_E_UNKNOWN)
740         removeParameter(anEntity.distance);
741       for (int i = 0; i < 4; i++)
742         if (anEntity.param[i] != SLVS_E_UNKNOWN)
743           removeParameter(anEntity.param[i]);
744       for (int i = 0; i < 4; i++)
745         if (anEntity.point[i] != SLVS_E_UNKNOWN)
746           removeEntity(anEntity.point[i]);
747     }
748   }
749
750   if (!anUnusedEntities.empty())
751     myNeedToResolve = true;
752 }
753
754 bool SolveSpaceSolver_Storage::isUsedByConstraints(const Slvs_hEntity& theEntityID) const
755 {
756   std::vector<Slvs_Constraint>::const_iterator aCIt = myConstraints.begin();
757   for (; aCIt != myConstraints.end(); ++aCIt) {
758     Slvs_hEntity aSubs[6] = {
759         aCIt->entityA, aCIt->entityB,
760         aCIt->entityC, aCIt->entityD,
761         aCIt->ptA,     aCIt->ptB};
762     for (int i = 0; i < 6; i++)
763       if (aSubs[i] != SLVS_E_UNKNOWN && aSubs[i] == theEntityID)
764         return true;
765   }
766   return false;
767 }
768
769 const Slvs_Entity& SolveSpaceSolver_Storage::getEntity(const Slvs_hEntity& theEntityID) const
770 {
771   int aPos = Search(theEntityID, myEntities);
772   if (aPos >= 0 && aPos < (int)myEntities.size())
773     return myEntities[aPos];
774
775   // Entity is not found, return empty object
776   static Slvs_Entity aDummy;
777   aDummy.h = SLVS_E_UNKNOWN;
778   return aDummy;
779 }
780
781 Slvs_hEntity SolveSpaceSolver_Storage::copyEntity(const Slvs_hEntity& theCopied)
782 {
783   int aPos = Search(theCopied, myEntities);
784   if (aPos < 0 || aPos >= (int)myEntities.size())
785     return SLVS_E_UNKNOWN;
786
787   Slvs_Entity aCopy = myEntities[aPos];
788   aCopy.h = SLVS_E_UNKNOWN;
789   int i = 0;
790   while (aCopy.point[i] != SLVS_E_UNKNOWN) {
791     aCopy.point[i] = copyEntity(aCopy.point[i]);
792     i++;
793   }
794   if (aCopy.param[0] != SLVS_E_UNKNOWN) {
795     aPos = Search(aCopy.param[0], myParameters);
796     i = 0;
797     while (aCopy.param[i] != SLVS_E_UNKNOWN) {
798       Slvs_Param aNewParam = myParameters[aPos];
799       aNewParam.h = SLVS_E_UNKNOWN;
800       aCopy.param[i] = addParameter(aNewParam);
801       i++;
802       aPos++;
803     }
804   }
805   return addEntity(aCopy);
806 }
807
808 void SolveSpaceSolver_Storage::copyEntity(const Slvs_hEntity& theFrom, const Slvs_hEntity& theTo)
809 {
810   int aPosFrom = Search(theFrom, myEntities);
811   int aPosTo = Search(theTo, myEntities);
812   if (aPosFrom < 0 || aPosFrom >= (int)myEntities.size() || 
813       aPosTo < 0 || aPosTo >= (int)myEntities.size())
814     return;
815
816   Slvs_Entity aEntFrom = myEntities[aPosFrom];
817   Slvs_Entity aEntTo = myEntities[aPosTo];
818   int i = 0;
819   while (aEntFrom.point[i] != SLVS_E_UNKNOWN) {
820     copyEntity(aEntFrom.point[i], aEntTo.point[i]);
821     i++;
822   }
823   if (aEntFrom.param[0] != SLVS_E_UNKNOWN) {
824     aPosFrom = Search(aEntFrom.param[0], myParameters);
825     aPosTo = Search(aEntTo.param[0], myParameters);
826     i = 0;
827     while (aEntFrom.param[i] != SLVS_E_UNKNOWN) {
828       myParameters[aPosTo++].val = myParameters[aPosFrom++].val;
829       i++;
830     }
831   }
832 }
833
834
835 bool SolveSpaceSolver_Storage::isPointFixed(
836     const Slvs_hEntity& thePointID, Slvs_hConstraint& theFixed, bool theAccurate) const
837 {
838   // Search the set of coincident points
839   std::set<Slvs_hEntity> aCoincident;
840   aCoincident.insert(thePointID);
841
842   // Check whether one of coincident points is out-of-group
843   std::set<Slvs_hEntity>::const_iterator aCoincIt = aCoincident.begin();
844   for (; aCoincIt != aCoincident.end(); ++aCoincIt) {
845     Slvs_Entity aPoint = getEntity(*aCoincIt);
846     if (aPoint.group == SLVS_G_OUTOFGROUP)
847       return true;
848   }
849
850   // Search the Rigid constraint
851   theFixed = SLVS_C_UNKNOWN;
852   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
853   for (; aConstrIter != myConstraints.end(); aConstrIter++)
854     if (aConstrIter->type == SLVS_C_WHERE_DRAGGED &&
855         aCoincident.find(aConstrIter->ptA) != aCoincident.end()) {
856       theFixed = aConstrIter->h;
857       if (aConstrIter->ptA == thePointID)
858         return true;
859     }
860   if (theFixed != SLVS_C_UNKNOWN)
861     return true;
862
863   if (theAccurate) {
864     // Try to find the fixed entity which uses such point or its coincidence
865     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
866     for (; anEntIter != myEntities.end(); anEntIter++) {
867       for (int i = 0; i < 4; i++) {
868         Slvs_hEntity aPt = anEntIter->point[i];
869         if (aPt != SLVS_E_UNKNOWN &&
870             (aPt == thePointID || aCoincident.find(aPt) != aCoincident.end())) {
871           if (isEntityFixed(anEntIter->h, true))
872             return true;
873         }
874       }
875     }
876   }
877   return SLVS_E_UNKNOWN;
878 }
879
880 bool SolveSpaceSolver_Storage::isEntityFixed(const Slvs_hEntity& theEntityID, bool theAccurate) const
881 {
882   int aPos = Search(theEntityID, myEntities);
883   if (aPos < 0 || aPos >= (int)myEntities.size())
884     return false;
885
886   // Firstly, find how many points are under Rigid constraint
887   int aNbFixed = 0;
888   for (int i = 0; i < 4; i++) {
889     Slvs_hEntity aPoint = myEntities[aPos].point[i];
890     if (aPoint == SLVS_E_UNKNOWN)
891       continue;
892
893     std::set<Slvs_hEntity> aCoincident;
894     aCoincident.insert(aPoint);
895
896     // Search the Rigid constraint
897     std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
898     for (; aConstrIter != myConstraints.end(); aConstrIter++)
899       if (aConstrIter->type == SLVS_C_WHERE_DRAGGED &&
900           aCoincident.find(aConstrIter->ptA) != aCoincident.end())
901         aNbFixed++;
902   }
903
904   std::list<Slvs_Constraint> aList;
905   std::list<Slvs_Constraint>::iterator anIt;
906   Slvs_hConstraint aTempID; // used in isPointFixed() method
907
908   if (myEntities[aPos].type == SLVS_E_LINE_SEGMENT) {
909     if (aNbFixed == 2)
910       return true;
911     else if (aNbFixed == 0 || !theAccurate)
912       return false;
913     // Additional check (the line may be fixed if it is used by different constraints):
914     // 1. The line is used in Equal constraint, another entity is fixed and there is a fixed point on line
915     aList = getConstraintsByType(SLVS_C_PT_ON_LINE);
916     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
917       if (anIt->entityA == theEntityID && isPointFixed(anIt->ptA, aTempID))
918         break;
919     if (anIt != aList.end()) {
920       aList = getConstraintsByType(SLVS_C_EQUAL_LENGTH_LINES);
921       aList.splice(aList.end(), getConstraintsByType(SLVS_C_EQUAL_LINE_ARC_LEN));
922       for (anIt = aList.begin(); anIt != aList.end(); anIt++)
923         if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
924           Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
925           if (isEntityFixed(anOther, false))
926             return true;
927         }
928     }
929     // 2. The line is used in Parallel/Perpendicular/Vertical/Horizontal and Length constraints
930     aList = getConstraintsByType(SLVS_C_PARALLEL);
931     aList.splice(aList.end(), getConstraintsByType(SLVS_C_PERPENDICULAR));
932     aList.splice(aList.end(), getConstraintsByType(SLVS_C_VERTICAL));
933     aList.splice(aList.end(), getConstraintsByType(SLVS_C_HORIZONTAL));
934     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
935       if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
936         Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
937         if (isEntityFixed(anOther, false))
938           break;
939       }
940     if (anIt != aList.end()) {
941       aList = getConstraintsByType(SLVS_C_PT_PT_DISTANCE);
942       for (anIt = aList.begin(); anIt != aList.end(); anIt++)
943         if ((anIt->ptA == myEntities[aPos].point[0] && anIt->ptB == myEntities[aPos].point[1]) ||
944             (anIt->ptA == myEntities[aPos].point[1] && anIt->ptB == myEntities[aPos].point[0]))
945           return true;
946     }
947     // 3. Another verifiers ...
948   } else if (myEntities[aPos].type == SLVS_E_CIRCLE) {
949     if (aNbFixed == 0)
950       return false;
951     // Search for Diameter constraint
952     aList = getConstraintsByType(SLVS_C_DIAMETER);
953     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
954       if (anIt->entityA == theEntityID)
955         return true;
956     if (!theAccurate)
957       return false;
958     // Additional check (the circle may be fixed if it is used by different constraints):
959     // 1. The circle is used in Equal constraint and another entity is fixed
960     aList = getConstraintsByType(SLVS_C_EQUAL_RADIUS);
961     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
962       if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
963         Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
964         if (isEntityFixed(anOther, false))
965           return true;
966       }
967     // 2. Another verifiers ...
968   } else if (myEntities[aPos].type == SLVS_E_ARC_OF_CIRCLE) {
969     if (aNbFixed > 2)
970       return true;
971     else if (aNbFixed <= 1)
972       return false;
973     // Search for Diameter constraint
974     aList = getConstraintsByType(SLVS_C_DIAMETER);
975     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
976       if (anIt->entityA == theEntityID)
977         return true;
978     if (!theAccurate)
979       return false;
980     // Additional check (the arc may be fixed if it is used by different constraints):
981     // 1. The arc is used in Equal constraint and another entity is fixed
982     aList = getConstraintsByType(SLVS_C_EQUAL_RADIUS);
983     aList.splice(aList.end(), getConstraintsByType(SLVS_C_EQUAL_LINE_ARC_LEN));
984     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
985       if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
986         Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
987         if (isEntityFixed(anOther, false))
988           return true;
989       }
990     // 2. Another verifiers ...
991   }
992   return false;
993 }
994
995
996 Slvs_hConstraint SolveSpaceSolver_Storage::addConstraint(const Slvs_Constraint& theConstraint)
997 {
998   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
999     // Constraint is already used, rewrite it
1000     return updateConstraint(theConstraint);
1001   }
1002
1003   Slvs_Constraint aConstraint = theConstraint;
1004
1005   // Find a constraint with same type uses same arguments to show user overconstraint situation
1006   std::vector<Slvs_Constraint>::iterator aCIt = myConstraints.begin();
1007   for (; aCIt != myConstraints.end(); aCIt++) {
1008     if (aConstraint.type != aCIt->type)
1009       continue;
1010     if (aConstraint.ptA == aCIt->ptA && aConstraint.ptB == aCIt->ptB &&
1011         aConstraint.entityA == aCIt->entityA && aConstraint.entityB == aCIt->entityB &&
1012         aConstraint.entityC == aCIt->entityC && aConstraint.entityD == aCIt->entityD)
1013       myDuplicatedConstraint = true;
1014   }
1015
1016   if (aConstraint.h > myConstrMaxID)
1017     myConstrMaxID = aConstraint.h;
1018   else
1019     aConstraint.h = ++myConstrMaxID;
1020   myConstraints.push_back(aConstraint);
1021   myNeedToResolve = true;
1022   return aConstraint.h;
1023 }
1024
1025 Slvs_hConstraint SolveSpaceSolver_Storage::updateConstraint(const Slvs_Constraint& theConstraint)
1026 {
1027   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
1028     // Constraint already used, rewrite it
1029     int aPos = Search(theConstraint.h, myConstraints);
1030     if (aPos >= 0 && aPos < (int)myConstraints.size()) {
1031       myNeedToResolve = myNeedToResolve || IsNotEqual(myConstraints[aPos], theConstraint);
1032       myConstraints[aPos] = theConstraint;
1033       return theConstraint.h;
1034     }
1035   }
1036
1037   // Constraint is not found, add new one
1038   Slvs_Constraint aConstraint = theConstraint;
1039   aConstraint.h = 0;
1040   return addConstraint(aConstraint);
1041 }
1042
1043 bool SolveSpaceSolver_Storage::removeConstraint(const Slvs_hConstraint& theConstraintID)
1044 {
1045   bool aResult = true;
1046   int aPos = Search(theConstraintID, myConstraints);
1047   if (aPos >= 0 && aPos < (int)myConstraints.size()) {
1048     Slvs_Constraint aConstraint = myConstraints[aPos];
1049     myConstraints.erase(myConstraints.begin() + aPos);
1050     myConstrMaxID = myConstraints.empty() ? SLVS_E_UNKNOWN : myConstraints.back().h;
1051     myNeedToResolve = true;
1052
1053     // Remove all entities
1054     Slvs_hEntity anEntities[6] = {aConstraint.ptA, aConstraint.ptB,
1055         aConstraint.entityA, aConstraint.entityB,
1056         aConstraint.entityC, aConstraint.entityD};
1057     for (int i = 0; i < 6; i++)
1058       if (anEntities[i] != SLVS_E_UNKNOWN)
1059         aResult = removeEntity(anEntities[i]) && aResult;
1060     // remove temporary fixed point, if available
1061     if (myFixed == theConstraintID)
1062       myFixed = SLVS_E_UNKNOWN;
1063     if (myDuplicatedConstraint) {
1064       // Check the duplicated constraints are still available
1065       myDuplicatedConstraint = false;
1066       std::vector<Slvs_Constraint>::const_iterator anIt1 = myConstraints.begin();
1067       std::vector<Slvs_Constraint>::const_iterator anIt2 = myConstraints.begin();
1068       for (; anIt1 != myConstraints.end() && !myDuplicatedConstraint; anIt1++)
1069         for (anIt2 = anIt1+1; anIt2 != myConstraints.end() && !myDuplicatedConstraint; anIt2++) {
1070           if (anIt1->type != anIt2->type)
1071             continue;
1072           if (anIt1->ptA == anIt2->ptA && anIt1->ptB == anIt2->ptB &&
1073               anIt1->entityA == anIt2->entityA && anIt1->entityB == anIt2->entityB &&
1074               anIt1->entityC == anIt2->entityC && anIt1->entityD == anIt2->entityD)
1075             myDuplicatedConstraint = true;
1076         }
1077     }
1078   }
1079   return aResult;
1080 }
1081
1082 const Slvs_Constraint& SolveSpaceSolver_Storage::getConstraint(const Slvs_hConstraint& theConstraintID) const
1083 {
1084   int aPos = Search(theConstraintID, myConstraints);
1085   if (aPos >= 0 && aPos < (int)myConstraints.size())
1086     return myConstraints[aPos];
1087
1088   // Constraint is not found, return empty object
1089   static Slvs_Constraint aDummy;
1090   aDummy.h = 0;
1091   return aDummy;
1092 }
1093
1094 std::list<Slvs_Constraint> SolveSpaceSolver_Storage::getConstraintsByType(int theConstraintType) const
1095 {
1096   std::list<Slvs_Constraint> aResult;
1097   std::vector<Slvs_Constraint>::const_iterator aCIter = myConstraints.begin();
1098   for (; aCIter != myConstraints.end(); aCIter++)
1099     if (aCIter->type == theConstraintType)
1100       aResult.push_back(*aCIter);
1101   return aResult;
1102 }
1103
1104
1105 void SolveSpaceSolver_Storage::addConstraintWhereDragged(const Slvs_hConstraint& theConstraintID)
1106 {
1107   if (myFixed != SLVS_E_UNKNOWN)
1108     return; // the point is already fixed
1109   int aPos = Search(theConstraintID, myConstraints);
1110   if (aPos >= 0 && aPos < (int)myConstraints.size())
1111     myFixed = theConstraintID;
1112 }
1113
1114 void SolveSpaceSolver_Storage::addTemporaryConstraint(const Slvs_hConstraint& theConstraintID)
1115 {
1116   myTemporaryConstraints.insert(theConstraintID);
1117 }
1118
1119 void SolveSpaceSolver_Storage::removeAllTemporary()
1120 {
1121   myTemporaryConstraints.clear();
1122 }
1123
1124 size_t SolveSpaceSolver_Storage::removeTemporary(size_t theNbConstraints)
1125 {
1126   if (myTemporaryConstraints.empty())
1127     return 0;
1128   // Search the point-on-line or a non-rigid constraint
1129   std::set<Slvs_hConstraint>::iterator aCIt = myTemporaryConstraints.begin();
1130   for (; aCIt != myTemporaryConstraints.end(); aCIt++) {
1131     int aPos = Search(*aCIt, myConstraints);
1132     if (aPos >= (int)myConstraints.size() || myConstraints[aPos].type != SLVS_C_WHERE_DRAGGED)
1133       break;
1134     std::vector<Slvs_Constraint>::iterator anIt = myConstraints.begin();
1135     for (; anIt != myConstraints.end(); anIt++)
1136       if (anIt->type == SLVS_C_PT_ON_LINE && anIt->ptA == myConstraints[aPos].ptA)
1137         break;
1138     if (anIt != myConstraints.end())
1139       break;
1140   }
1141   if (aCIt == myTemporaryConstraints.end())
1142     aCIt = myTemporaryConstraints.begin();
1143   bool aNewFixed = false;
1144
1145   size_t aNbRemain = theNbConstraints;
1146   while (aNbRemain > 0 && aCIt != myTemporaryConstraints.end()) {
1147     aNewFixed = aNewFixed || (*aCIt == myFixed);
1148     --aNbRemain;
1149
1150     std::set<Slvs_hConstraint>::iterator aRemoveIt = aCIt++;
1151     removeConstraint(*aRemoveIt);
1152     myTemporaryConstraints.erase(aRemoveIt);
1153     if (aCIt == myTemporaryConstraints.end())
1154       aCIt = myTemporaryConstraints.begin();
1155   }
1156
1157   if (aNewFixed) {
1158     for (aCIt = myTemporaryConstraints.begin(); aCIt != myTemporaryConstraints.end(); aCIt++) {
1159       int aPos = Search(*aCIt, myConstraints);
1160       if (myConstraints[aPos].type == SLVS_C_WHERE_DRAGGED) {
1161         myFixed = *aCIt;
1162         break;
1163       }
1164     }
1165   }
1166   return myTemporaryConstraints.size();
1167 }
1168
1169 bool SolveSpaceSolver_Storage::isTemporary(const Slvs_hConstraint& theConstraintID) const
1170 {
1171   return myTemporaryConstraints.find(theConstraintID) != myTemporaryConstraints.end();
1172 }
1173
1174
1175
1176 void SolveSpaceSolver_Storage::initializeSolver(SolverPtr theSolver)
1177 {
1178   std::shared_ptr<SolveSpaceSolver_Solver> aSolver =
1179       std::dynamic_pointer_cast<SolveSpaceSolver_Solver>(theSolver);
1180   if (!aSolver)
1181     return;
1182
1183   if (myConstraints.empty()) {
1184     // Adjust all arc to place their points correctly
1185     std::vector<Slvs_Entity>::const_iterator anEntIt = myEntities.begin();
1186     for (; anEntIt != myEntities.end(); ++anEntIt)
1187       if (anEntIt->type == SLVS_E_ARC_OF_CIRCLE)
1188         adjustArc(*anEntIt);
1189   }
1190
1191   aSolver->setParameters(myParameters.data(), (int)myParameters.size());
1192   aSolver->setEntities(myEntities.data(), (int)myEntities.size());
1193
1194   // Copy constraints excluding the fixed one
1195   std::vector<Slvs_Constraint> aConstraints = myConstraints;
1196   if (myFixed != SLVS_E_UNKNOWN) {
1197     Slvs_hEntity aFixedPoint = SLVS_E_UNKNOWN;
1198     std::vector<Slvs_Constraint>::iterator anIt = aConstraints.begin();
1199     for (; anIt != aConstraints.end(); anIt++)
1200       if (anIt->h == myFixed) {
1201         aFixedPoint = anIt->ptA;
1202         aConstraints.erase(anIt);
1203         break;
1204       }
1205     // set dragged parameters
1206     int aPos = Search(aFixedPoint, myEntities);
1207     aSolver->setDraggedParameters(myEntities[aPos].param);
1208   }
1209   aSolver->setConstraints(aConstraints.data(), (int)aConstraints.size());
1210 }
1211
1212
1213 bool SolveSpaceSolver_Storage::isEqual(
1214     const Slvs_hEntity& thePoint1, const Slvs_hEntity& thePoint2) const
1215 {
1216   // Precise checking of coincidence: verify that points have equal coordinates
1217   int aEnt1Pos = Search(thePoint1, myEntities);
1218   int aEnt2Pos = Search(thePoint2, myEntities);
1219   if (aEnt1Pos >= 0 && aEnt1Pos < (int)myEntities.size() &&
1220       aEnt2Pos >= 0 && aEnt2Pos < (int)myEntities.size()) {
1221     double aDist[2];
1222     int aParamPos;
1223     for (int i = 0; i < 2; i++) {
1224       aParamPos = Search(myEntities[aEnt1Pos].param[i], myParameters);
1225       aDist[i] = myParameters[aParamPos].val;
1226       aParamPos = Search(myEntities[aEnt2Pos].param[i], myParameters);
1227       aDist[i] -= myParameters[aParamPos].val;
1228     }
1229     if (aDist[0] * aDist[0] + aDist[1] * aDist[1] < tolerance * tolerance)
1230       return true;
1231   }
1232   return false;
1233 }
1234
1235
1236 std::vector<Slvs_hConstraint> SolveSpaceSolver_Storage::fixEntity(const Slvs_hEntity& theEntity)
1237 {
1238   std::vector<Slvs_hConstraint> aNewConstraints;
1239
1240   int aPos = Search(theEntity, myEntities);
1241   if (aPos >= 0 && aPos < (int)myEntities.size()) {
1242     switch (myEntities[aPos].type) {
1243     case SLVS_E_POINT_IN_2D:
1244     case SLVS_E_POINT_IN_3D:
1245       fixPoint(myEntities[aPos], aNewConstraints);
1246       break;
1247     case SLVS_E_LINE_SEGMENT:
1248       fixLine(myEntities[aPos], aNewConstraints);
1249       break;
1250     case SLVS_E_CIRCLE:
1251       fixCircle(myEntities[aPos], aNewConstraints);
1252       break;
1253     case SLVS_E_ARC_OF_CIRCLE:
1254       fixArc(myEntities[aPos], aNewConstraints);
1255       break;
1256     default:
1257       break;
1258     }
1259   }
1260
1261   return aNewConstraints;
1262 }
1263
1264 void SolveSpaceSolver_Storage::fixPoint(const Slvs_Entity& thePoint,
1265     std::vector<Slvs_hConstraint>& theCreated)
1266 {
1267   Slvs_Constraint aConstraint;
1268   Slvs_hConstraint aConstrID = SLVS_E_UNKNOWN;
1269   bool isFixed = isPointFixed(thePoint.h, aConstrID, true);
1270   bool isForceUpdate = (isFixed && isTemporary(aConstrID));
1271   if (!isForceUpdate) { // create new constraint
1272     if (isFixed) return;
1273     aConstraint = Slvs_MakeConstraint(SLVS_E_UNKNOWN, thePoint.group, SLVS_C_WHERE_DRAGGED, thePoint.wrkpl,
1274         0.0, thePoint.h, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
1275     aConstraint.h = addConstraint(aConstraint);
1276     theCreated.push_back(aConstraint.h);
1277   } else { // update already existent constraint
1278     if (!isFixed || aConstrID == SLVS_E_UNKNOWN)
1279       return;
1280     int aPos = Search(aConstrID, myConstraints);
1281     if (aPos >= 0 && aPos < (int)myConstraints.size())
1282       myConstraints[aPos].ptA = thePoint.h;
1283   }
1284 }
1285
1286 void SolveSpaceSolver_Storage::fixLine(const Slvs_Entity& theLine,
1287     std::vector<Slvs_hConstraint>& theCreated)
1288 {
1289   Slvs_Entity aPoint[2] = {
1290       getEntity(theLine.point[0]),
1291       getEntity(theLine.point[1])
1292   };
1293
1294   Slvs_Constraint anEqual;
1295   if (isAxisParallel(theLine.h)) {
1296     // Fix one point and a line length
1297     Slvs_hConstraint aFixed;
1298     if (!isPointFixed(theLine.point[0], aFixed, true) &&
1299         !isPointFixed(theLine.point[1], aFixed, true))
1300       fixPoint(aPoint[0], theCreated);
1301     if (!isUsedInEqual(theLine.h, anEqual)) {
1302       // Check the distance is not set yet
1303       std::vector<Slvs_Constraint>::const_iterator aDistIt = myConstraints.begin();
1304       for (; aDistIt != myConstraints.end(); ++aDistIt)
1305         if ((aDistIt->type == SLVS_C_PT_PT_DISTANCE) &&
1306            ((aDistIt->ptA == theLine.point[0] && aDistIt->ptB == theLine.point[1]) ||
1307             (aDistIt->ptA == theLine.point[1] && aDistIt->ptB == theLine.point[0])))
1308           return;
1309       // Calculate distance between points on the line
1310       double aCoords[4];
1311       for (int i = 0; i < 2; i++)
1312         for (int j = 0; j < 2; j++) {
1313           Slvs_Param aParam = getParameter(aPoint[i].param[j]);
1314           aCoords[2*i+j] = aParam.val;
1315         }
1316
1317       double aLength = sqrt((aCoords[2] - aCoords[0]) * (aCoords[2] - aCoords[0]) + 
1318                             (aCoords[3] - aCoords[1]) * (aCoords[3] - aCoords[1]));
1319       // fix line length
1320       Slvs_Constraint aDistance = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theLine.group,
1321           SLVS_C_PT_PT_DISTANCE, theLine.wrkpl, aLength,
1322           theLine.point[0], theLine.point[1], SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
1323       aDistance.h = addConstraint(aDistance);
1324       theCreated.push_back(aDistance.h);
1325     }
1326     return;
1327   }
1328   else if (isUsedInEqual(theLine.h, anEqual)) {
1329     // Check another entity of Equal is already fixed
1330     Slvs_hEntity anOtherEntID = anEqual.entityA == theLine.h ? anEqual.entityB : anEqual.entityA;
1331     if (isEntityFixed(anOtherEntID, true)) {
1332       // Fix start point of the line (if end point is not fixed yet) ...
1333       Slvs_hConstraint anEndFixedID = SLVS_E_UNKNOWN;
1334       bool isFixed = isPointFixed(theLine.point[1], anEndFixedID, true);
1335       if (isFixed == SLVS_E_UNKNOWN)
1336         fixPoint(aPoint[0], theCreated);
1337       // ...  and create fixed point lying on this line
1338       Slvs_hEntity aPointToCopy = anEndFixedID == SLVS_E_UNKNOWN ? theLine.point[1] : theLine.point[0];
1339       // Firstly, search already fixed point on line
1340       bool isPonLineFixed = false;
1341       Slvs_hEntity aFixedPoint;
1342       std::vector<Slvs_Constraint>::const_iterator aPLIter = myConstraints.begin();
1343       for (; aPLIter != myConstraints.end() && !isPonLineFixed; ++aPLIter)
1344         if (aPLIter->type == SLVS_C_PT_ON_LINE && aPLIter->entityA == theLine.h) {
1345           isPonLineFixed = isPointFixed(aPLIter->ptA, anEndFixedID);
1346           aFixedPoint = aPLIter->ptA;
1347         }
1348
1349       if (isPonLineFixed) { // update existent constraint
1350         copyEntity(aPointToCopy, aFixedPoint);
1351       } else { // create new constraint
1352         Slvs_hEntity aCopied = copyEntity(aPointToCopy);
1353         Slvs_Constraint aPonLine = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theLine.group, SLVS_C_PT_ON_LINE,
1354             theLine.wrkpl, 0.0, aCopied, SLVS_E_UNKNOWN, theLine.h, SLVS_E_UNKNOWN);
1355         aPonLine.h = addConstraint(aPonLine);
1356         theCreated.push_back(aPonLine.h);
1357         fixPoint(getEntity(aCopied), theCreated);
1358       }
1359       return;
1360     }
1361   }
1362
1363   // Fix both points
1364   for (int i = 0; i < 2; i++)
1365     fixPoint(aPoint[i], theCreated);
1366 }
1367
1368 void SolveSpaceSolver_Storage::fixCircle(const Slvs_Entity& theCircle,
1369     std::vector<Slvs_hConstraint>& theCreated)
1370 {
1371   bool isFixRadius = true;
1372   // Verify the arc is under Equal constraint
1373   Slvs_Constraint anEqual;
1374   if (isUsedInEqual(theCircle.h, anEqual)) {
1375     // Check another entity of Equal is already fixed
1376     Slvs_hEntity anOtherEntID = anEqual.entityA == theCircle.h ? anEqual.entityB : anEqual.entityA;
1377     if (isEntityFixed(anOtherEntID, true))
1378       isFixRadius = false;
1379   }
1380
1381   fixPoint(getEntity(theCircle.point[0]), theCreated);
1382
1383   if (isFixRadius) {
1384     // Search the radius is already fixed
1385     std::vector<Slvs_Constraint>::const_iterator aDiamIter = myConstraints.begin();
1386     for (; aDiamIter != myConstraints.end(); ++aDiamIter)
1387       if (aDiamIter->type == SLVS_C_DIAMETER && aDiamIter->entityA == theCircle.h)
1388         return;
1389
1390     // Fix radius of a circle
1391     const Slvs_Entity& aRadEnt = getEntity(theCircle.distance);
1392     double aRadius = getParameter(aRadEnt.param[0]).val;
1393     Slvs_Constraint aFixedR = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theCircle.group, SLVS_C_DIAMETER,
1394         theCircle.wrkpl, aRadius * 2.0, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, theCircle.h, SLVS_E_UNKNOWN);
1395     aFixedR.h = addConstraint(aFixedR);
1396     theCreated.push_back(aFixedR.h);
1397   }
1398 }
1399
1400 void SolveSpaceSolver_Storage::fixArc(const Slvs_Entity& theArc,
1401     std::vector<Slvs_hConstraint>& theCreated)
1402 {
1403   Slvs_Entity aPoint[3] = {
1404       getEntity(theArc.point[0]),
1405       getEntity(theArc.point[1]),
1406       getEntity(theArc.point[2])
1407   };
1408
1409   bool isFixRadius = true;
1410   std::list<Slvs_Entity> aPointsToFix;
1411   aPointsToFix.push_back(aPoint[1]);
1412   aPointsToFix.push_back(aPoint[2]);
1413
1414   // Verify the arc is under Equal constraint
1415   Slvs_Constraint anEqual;
1416   if (isUsedInEqual(theArc.h, anEqual)) {
1417     // Check another entity of Equal is already fixed
1418     Slvs_hEntity anOtherEntID = anEqual.entityA == theArc.h ? anEqual.entityB : anEqual.entityA;
1419     if (isEntityFixed(anOtherEntID, true)) {
1420       isFixRadius = false;
1421       Slvs_Entity anOtherEntity = getEntity(anOtherEntID);
1422       if (anOtherEntity.type == SLVS_E_LINE_SEGMENT) {
1423         aPointsToFix.pop_back();
1424         aPointsToFix.push_back(aPoint[0]);
1425       }
1426     }
1427   }
1428
1429   Slvs_hConstraint aConstrID;
1430   int aNbPointsToFix = 2; // number of fixed points for the arc
1431   if (isPointFixed(theArc.point[0], aConstrID, true))
1432     aNbPointsToFix--;
1433
1434   double anArcPoints[3][2];
1435   for (int i = 0; i < 3; i++) {
1436     const Slvs_Entity& aPointOnArc = getEntity(theArc.point[i]);
1437     for (int j = 0; j < 2; j++)
1438       anArcPoints[i][j] = getParameter(aPointOnArc.param[j]).val;
1439   }
1440
1441   // Radius of the arc
1442   std::shared_ptr<GeomAPI_Pnt2d> aCenter(new GeomAPI_Pnt2d(anArcPoints[0][0], anArcPoints[0][1]));
1443   std::shared_ptr<GeomAPI_Pnt2d> aStart(new GeomAPI_Pnt2d(anArcPoints[1][0], anArcPoints[1][1]));
1444   double aRadius = aCenter->distance(aStart);
1445
1446   // Update end point of the arc to be on a curve
1447   std::shared_ptr<GeomAPI_Pnt2d> anEnd(new GeomAPI_Pnt2d(anArcPoints[2][0], anArcPoints[2][1]));
1448   double aDistance = anEnd->distance(aCenter);
1449   std::shared_ptr<GeomAPI_XY> aDir = anEnd->xy()->decreased(aCenter->xy());
1450   if (aDistance < tolerance)
1451     aDir = aStart->xy()->decreased(aCenter->xy())->multiplied(-1.0);
1452   else
1453     aDir = aDir->multiplied(aRadius / aDistance);
1454   double xy[2] = {aCenter->x() + aDir->x(), aCenter->y() + aDir->y()};
1455   const Slvs_Entity& aEndPoint = getEntity(theArc.point[2]);
1456   for (int i = 0; i < 2; i++) {
1457     Slvs_Param aParam = getParameter(aEndPoint.param[i]);
1458     aParam.val = xy[i];
1459     updateParameter(aParam);
1460   }
1461
1462   std::list<Slvs_Entity>::iterator aPtIt = aPointsToFix.begin();
1463   for (; aNbPointsToFix > 0; aPtIt++, aNbPointsToFix--)
1464     fixPoint(*aPtIt, theCreated);
1465
1466   if (isFixRadius) {
1467     // Fix radius of the arc
1468     bool isExists = false;
1469     std::vector<Slvs_Constraint>::iterator anIt = myConstraints.begin();
1470     for (; anIt != myConstraints.end() && !isExists; ++anIt)
1471       if (anIt->type == SLVS_C_DIAMETER && anIt->entityA == theArc.h)
1472         isExists = true;
1473     if (!isExists) {
1474       Slvs_Constraint aFixedR = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theArc.group, SLVS_C_DIAMETER,
1475           theArc.wrkpl, aRadius * 2.0, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, theArc.h, SLVS_E_UNKNOWN);
1476       aFixedR.h = addConstraint(aFixedR);
1477       theCreated.push_back(aFixedR.h);
1478     }
1479   }
1480 }
1481
1482
1483 bool SolveSpaceSolver_Storage::isAxisParallel(const Slvs_hEntity& theEntity) const
1484 {
1485   std::vector<Slvs_Constraint>::const_iterator anIter = myConstraints.begin();
1486   for (; anIter != myConstraints.end(); anIter++)
1487     if ((anIter->type == SLVS_C_HORIZONTAL || anIter->type == SLVS_C_VERTICAL) && 
1488         anIter->entityA == theEntity)
1489       return true;
1490   return false;
1491 }
1492
1493 bool SolveSpaceSolver_Storage::isUsedInEqual(
1494     const Slvs_hEntity& theEntity, Slvs_Constraint& theEqual) const
1495 {
1496   // Check the entity is used in Equal constraint
1497   std::vector<Slvs_Constraint>::const_iterator anEqIter = myConstraints.begin();
1498   for (; anEqIter != myConstraints.end(); anEqIter++)
1499     if ((anEqIter->type == SLVS_C_EQUAL_LENGTH_LINES ||
1500          anEqIter->type == SLVS_C_EQUAL_LINE_ARC_LEN ||
1501          anEqIter->type == SLVS_C_EQUAL_RADIUS) &&
1502        (anEqIter->entityA == theEntity || anEqIter->entityB == theEntity)) {
1503       theEqual = *anEqIter;
1504       return true;
1505     }
1506   return false;
1507 }
1508
1509 void SolveSpaceSolver_Storage::setTemporary(ConstraintPtr theConstraint)
1510 {
1511   // TODO
1512 }
1513
1514 bool SolveSpaceSolver_Storage::removeConstraint(ConstraintPtr theConstraint)
1515 {
1516   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::iterator
1517       aFound = myConstraintMap.find(theConstraint);
1518   if (aFound == myConstraintMap.end())
1519     return true; // no constraint, already deleted
1520
1521   // Remove constraint
1522   std::list<ConstraintWrapperPtr> aConstrList = aFound->second;
1523   myConstraintMap.erase(aFound);
1524   // Remove SolveSpace constraints
1525   bool isFullyRemoved = true;
1526   std::list<ConstraintWrapperPtr>::iterator anIt = aConstrList.begin();
1527   while (anIt != aConstrList.end()) {
1528     if (remove(*anIt)) {
1529       std::list<ConstraintWrapperPtr>::iterator aRemoveIt = anIt++;
1530       aConstrList.erase(aRemoveIt);
1531     } else {
1532       isFullyRemoved = false;
1533       ++anIt;
1534     }
1535   }
1536   if (!isFullyRemoved)
1537     myConstraintMap[theConstraint] = aConstrList;
1538   return isFullyRemoved;
1539 }
1540
1541 template <class ENT_TYPE>
1542 static bool isUsed(ConstraintWrapperPtr theConstraint, ENT_TYPE theEntity)
1543 {
1544   std::list<EntityWrapperPtr>::const_iterator anEntIt = theConstraint->entities().begin();
1545   for (; anEntIt != theConstraint->entities().end(); ++anEntIt)
1546     if (std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*anEntIt)->isBase(theEntity))
1547       return true;
1548   return false;
1549 }
1550
1551 static bool isUsed(EntityWrapperPtr theFeature, AttributePtr theSubEntity)
1552 {
1553   std::list<EntityWrapperPtr>::const_iterator aSubIt = theFeature->subEntities().begin();
1554   for (; aSubIt != theFeature->subEntities().end(); ++aSubIt)
1555     if (std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*aSubIt)->isBase(theSubEntity))
1556       return true;
1557   return false;
1558 }
1559
1560 bool SolveSpaceSolver_Storage::isUsed(FeaturePtr theFeature) const
1561 {
1562   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
1563       aCIt = myConstraintMap.begin();
1564   std::list<ConstraintWrapperPtr>::const_iterator aCWIt;
1565   for (; aCIt != myConstraintMap.end(); ++aCIt)
1566     for (aCWIt = aCIt->second.begin(); aCWIt != aCIt->second.end(); ++aCWIt)
1567       if (::isUsed(*aCWIt, theFeature))
1568         return true;
1569   // check attributes
1570   std::list<AttributePtr> anAttrList = theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
1571   std::list<AttributePtr>::const_iterator anIt = anAttrList.begin();
1572   for (; anIt != anAttrList.end(); ++anIt)
1573     if (isUsed(*anIt))
1574       return true;
1575   return false;
1576 }
1577
1578 bool SolveSpaceSolver_Storage::isUsed(AttributePtr theAttribute) const
1579 {
1580   AttributePtr anAttribute = theAttribute;
1581   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttribute);
1582   if (aRefAttr) {
1583     if (aRefAttr->isObject())
1584       return isUsed(ModelAPI_Feature::feature(aRefAttr->object()));
1585     else
1586       anAttribute = aRefAttr->attr();
1587   }
1588
1589   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
1590       aCIt = myConstraintMap.begin();
1591   std::list<ConstraintWrapperPtr>::const_iterator aCWIt;
1592   for (; aCIt != myConstraintMap.end(); ++aCIt)
1593     for (aCWIt = aCIt->second.begin(); aCWIt != aCIt->second.end(); ++aCWIt)
1594       if (::isUsed(*aCWIt, anAttribute))
1595         return true;
1596   return false;
1597 }
1598
1599
1600 bool SolveSpaceSolver_Storage::removeEntity(FeaturePtr theFeature)
1601 {
1602   std::map<FeaturePtr, EntityWrapperPtr>::iterator aFound = myFeatureMap.find(theFeature);
1603   if (aFound == myFeatureMap.end())
1604     return false; // feature not found, nothing to delete
1605
1606   // Check the feature is not used by constraints
1607   if (isUsed(theFeature))
1608     return false; // the feature is used, don't remove it
1609
1610   // Remove feature
1611   EntityWrapperPtr anEntity = aFound->second;
1612   myFeatureMap.erase(aFound);
1613   if (remove(anEntity))
1614     return true;
1615   // feature is not removed, revert operation
1616   myFeatureMap[theFeature] = anEntity;
1617   return false;
1618 }
1619
1620 bool SolveSpaceSolver_Storage::removeEntity(AttributePtr theAttribute)
1621 {
1622   std::map<AttributePtr, EntityWrapperPtr>::iterator aFound = myAttributeMap.find(theAttribute);
1623   if (aFound == myAttributeMap.end())
1624     return false; // attribute not found, nothing to delete
1625
1626   // Check the attribute is not used by constraints
1627   if (isUsed(theAttribute))
1628     return false; // the attribute is used, don't remove it
1629   // Check the attribute is not used by other features
1630   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFIt = myFeatureMap.begin();
1631   for (; aFIt != myFeatureMap.end(); ++aFIt)
1632     if (::isUsed(aFIt->second, theAttribute)) // the attribute is used, don't remove it
1633       return false;
1634
1635   // Remove attribute
1636   EntityWrapperPtr anEntity = aFound->second;
1637   myAttributeMap.erase(aFound);
1638   if (remove(anEntity))
1639     return true;
1640   // attribute is not removed, revert operation
1641   myAttributeMap[theAttribute] = anEntity;
1642   return false;
1643 }
1644
1645
1646 bool SolveSpaceSolver_Storage::remove(ConstraintWrapperPtr theConstraint)
1647 {
1648   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
1649       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
1650
1651   // verify whether the constraint has duplicated
1652   SameConstraintMap::iterator anEqIt = myEqualConstraints.begin();
1653   for (; anEqIt != myEqualConstraints.end(); ++anEqIt)
1654     if (anEqIt->find(aConstraint) != anEqIt->end()) {
1655       anEqIt->erase(aConstraint);
1656       break;
1657     }
1658   if (anEqIt != myEqualConstraints.end())
1659     return true;
1660
1661   bool isFullyRemoved = removeConstraint((Slvs_hConstraint)aConstraint->id());
1662
1663   std::list<EntityWrapperPtr>::const_iterator anIt = aConstraint->entities().begin();
1664   for (; anIt != aConstraint->entities().end(); ++anIt) {
1665     std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
1666         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*anIt);
1667     FeaturePtr aBaseFeature = anEntity->baseFeature();
1668     if (aBaseFeature)
1669       isFullyRemoved = removeEntity(aBaseFeature) && isFullyRemoved;
1670     else
1671       isFullyRemoved = removeEntity(anEntity->baseAttribute()) && isFullyRemoved;
1672   }
1673
1674   return isFullyRemoved;
1675 }
1676
1677 bool SolveSpaceSolver_Storage::remove(EntityWrapperPtr theEntity)
1678 {
1679   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
1680         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
1681   bool isFullyRemoved = removeEntity((Slvs_hEntity)anEntity->id());
1682
1683   std::list<EntityWrapperPtr>::const_iterator anEntIt = anEntity->subEntities().begin();
1684   for (; anEntIt != anEntity->subEntities().end(); ++anEntIt) {
1685     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSubEntity = 
1686         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*anEntIt);
1687     FeaturePtr aBaseFeature = aSubEntity->baseFeature();
1688     if (aBaseFeature)
1689       isFullyRemoved = removeEntity(aBaseFeature) && isFullyRemoved;
1690     else
1691       isFullyRemoved = removeEntity(aSubEntity->baseAttribute()) && isFullyRemoved;
1692   }
1693
1694   std::list<ParameterWrapperPtr>::const_iterator aParIt = anEntity->parameters().begin();
1695   for (; aParIt != anEntity->parameters().end(); ++aParIt)
1696     isFullyRemoved = remove(*aParIt) && isFullyRemoved;
1697   return isFullyRemoved;
1698 }
1699
1700 bool SolveSpaceSolver_Storage::remove(ParameterWrapperPtr theParameter)
1701 {
1702   return removeParameter((Slvs_hParam)theParameter->id());
1703 }
1704
1705
1706 void SolveSpaceSolver_Storage::refresh(bool theFixedOnly) const
1707 {
1708   blockEvents(true);
1709
1710   std::map<AttributePtr, EntityWrapperPtr>::const_iterator anIt = myAttributeMap.begin();
1711   std::list<ParameterWrapperPtr> aParams;
1712   std::list<ParameterWrapperPtr>::const_iterator aParIt;
1713   for (; anIt != myAttributeMap.end(); ++anIt) {
1714     // the external feature always should keep the up to date values, so, 
1715     // refresh from the solver is never needed
1716     if (anIt->first.get()) {
1717       std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
1718         std::dynamic_pointer_cast<SketchPlugin_Feature>(anIt->first->owner());
1719       if (aSketchFeature.get() && aSketchFeature->isExternal())
1720         continue;
1721     }
1722
1723     // update parameter wrappers and obtain values of attributes
1724     aParams = anIt->second->parameters();
1725     double aCoords[3];
1726     bool isUpd[3] = {false};
1727     int i = 0;
1728     for (aParIt = aParams.begin(); i < 3 && aParIt != aParams.end(); ++aParIt, ++i) {
1729       std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aWrapper = 
1730           std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(*aParIt);
1731       if (!theFixedOnly || aWrapper->group() == GID_OUTOFGROUP || aWrapper->isParametric()) {
1732         aWrapper->changeParameter().val = getParameter((Slvs_hParam)aWrapper->id()).val;
1733         aCoords[i] = aWrapper->value();
1734         isUpd[i] = true;
1735       }
1736     }
1737     if (!isUpd[0] && !isUpd[1] && !isUpd[2])
1738       continue; // nothing is updated
1739
1740     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
1741         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anIt->first);
1742     if (aPoint2D) {
1743       if ((isUpd[0] && fabs(aPoint2D->x() - aCoords[0]) > tolerance) ||
1744           (isUpd[1] && fabs(aPoint2D->y() - aCoords[1]) > tolerance)) {
1745         if (!isUpd[0]) aCoords[0] = aPoint2D->x();
1746         if (!isUpd[1]) aCoords[1] = aPoint2D->y();
1747         aPoint2D->setValue(aCoords[0], aCoords[1]);
1748         // Find points coincident with this one (probably not in GID_OUTOFGROUP)
1749         std::map<AttributePtr, EntityWrapperPtr>::const_iterator aLocIt =
1750             theFixedOnly ? myAttributeMap.begin() : anIt;
1751         for (++aLocIt; aLocIt != myAttributeMap.end(); ++aLocIt)
1752           if (anIt->second->id() == aLocIt->second->id()) {
1753             aPoint2D = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aLocIt->first);
1754             aPoint2D->setValue(aCoords[0], aCoords[1]);
1755           }
1756       }
1757       continue;
1758     }
1759     AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anIt->first);
1760     if (aScalar) {
1761       if (isUpd[0] && fabs(aScalar->value() - aCoords[0]) > tolerance)
1762         aScalar->setValue(aCoords[0]);
1763       continue;
1764     }
1765     std::shared_ptr<GeomDataAPI_Point> aPoint =
1766         std::dynamic_pointer_cast<GeomDataAPI_Point>(anIt->first);
1767     if (aPoint) {
1768       if ((isUpd[0] && fabs(aPoint->x() - aCoords[0]) > tolerance) ||
1769           (isUpd[1] && fabs(aPoint->y() - aCoords[1]) > tolerance) ||
1770           (isUpd[2] && fabs(aPoint->z() - aCoords[2]) > tolerance))
1771         if (!isUpd[0]) aCoords[0] = aPoint->x();
1772         if (!isUpd[1]) aCoords[1] = aPoint->y();
1773         if (!isUpd[2]) aCoords[2] = aPoint->z();
1774         aPoint->setValue(aCoords[0], aCoords[1], aCoords[2]);
1775       continue;
1776     }
1777   }
1778
1779   blockEvents(false);
1780 }
1781
1782 void SolveSpaceSolver_Storage::verifyFixed()
1783 {
1784   std::map<AttributePtr, EntityWrapperPtr>::iterator anAttrIt = myAttributeMap.begin();
1785   for (; anAttrIt != myAttributeMap.end(); ++anAttrIt) {
1786     const std::list<ParameterWrapperPtr>& aParameters = anAttrIt->second->parameters();
1787     std::list<ParameterWrapperPtr>::const_iterator aParIt = aParameters.begin();
1788     for (; aParIt != aParameters.end(); ++aParIt)
1789       if ((*aParIt)->group() == GID_OUTOFGROUP) {
1790         Slvs_Param aParam = getParameter((Slvs_hParam)(*aParIt)->id());
1791         if (aParam.group != (Slvs_hParam)GID_OUTOFGROUP) {
1792           aParam.group = (Slvs_hParam)GID_OUTOFGROUP;
1793           updateParameter(aParam);
1794         }
1795       }
1796   }
1797 }
1798
1799
1800 void SolveSpaceSolver_Storage::adjustArc(const Slvs_Entity& theArc)
1801 {
1802   double anArcPoints[3][2];
1803   double aDist[3] = {0.0};
1804   bool isFixed[3] = {false};
1805   for (int i = 0; i < 3; ++i) {
1806     Slvs_Entity aPoint = getEntity(theArc.point[i]);
1807     isFixed[i] = (aPoint.group != (Slvs_hGroup)myGroupID);
1808     anArcPoints[i][0] = getParameter(aPoint.param[0]).val;
1809     anArcPoints[i][1] = getParameter(aPoint.param[1]).val;
1810     if (i > 0) {
1811       anArcPoints[i][0] -= anArcPoints[0][0];
1812       anArcPoints[i][1] -= anArcPoints[0][1];
1813       aDist[i] = sqrt(anArcPoints[i][0] * anArcPoints[i][0] + 
1814                       anArcPoints[i][1] * anArcPoints[i][1]);
1815     }
1816   }
1817
1818   if (fabs(aDist[1] - aDist[2]) < tolerance)
1819     return;
1820
1821   int anInd = 2;
1822   while (anInd > 0 && isFixed[anInd])
1823     --anInd;
1824   if (anInd < 1)
1825     return; // adjust only start or end point of the arc
1826
1827   anArcPoints[anInd][0] /= aDist[anInd];
1828   anArcPoints[anInd][1] /= aDist[anInd];
1829
1830   Slvs_Entity aPoint = getEntity(theArc.point[anInd]);
1831   for (int i = 0; i < 2; ++i) {
1832     Slvs_Param aParam = getParameter(aPoint.param[i]);
1833     aParam.val = anArcPoints[0][i] + aDist[3-anInd] * anArcPoints[anInd][i];
1834     updateParameter(aParam);
1835   }
1836 }
1837
1838
1839
1840
1841
1842
1843
1844 // ========================================================
1845 // =========      Auxiliary functions       ===============
1846 // ========================================================
1847
1848 template<typename T>
1849 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1850 {
1851   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1852   int aVecSize = theEntities.size();
1853   if (theEntities.empty())
1854     return 1;
1855   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1856     aResIndex--;
1857   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1858     aResIndex++;
1859   if (aResIndex == -1 || (aResIndex < aVecSize && theEntities[aResIndex].h != theEntityID))
1860     aResIndex = aVecSize;
1861   return aResIndex;
1862 }
1863
1864 bool IsNotEqual(const Slvs_Param& theParam1, const Slvs_Param& theParam2)
1865 {
1866   return fabs(theParam1.val - theParam2.val) > tolerance;
1867 }
1868
1869 bool IsNotEqual(const Slvs_Entity& theEntity1, const Slvs_Entity& theEntity2)
1870 {
1871   int i = 0;
1872   for (; theEntity1.param[i] != 0 && i < 4; i++)
1873     if (theEntity1.param[i] != theEntity2.param[i])
1874       return true;
1875   i = 0;
1876   for (; theEntity1.point[i] != 0 && i < 4; i++)
1877     if (theEntity1.point[i] != theEntity2.point[i])
1878       return true;
1879   return false;
1880 }
1881
1882 bool IsNotEqual(const Slvs_Constraint& theConstraint1, const Slvs_Constraint& theConstraint2)
1883 {
1884   return theConstraint1.ptA != theConstraint2.ptA ||
1885          theConstraint1.ptB != theConstraint2.ptB ||
1886          theConstraint1.entityA != theConstraint2.entityA ||
1887          theConstraint1.entityB != theConstraint2.entityB ||
1888          theConstraint1.entityC != theConstraint2.entityC ||
1889          theConstraint1.entityD != theConstraint2.entityD ||
1890          fabs(theConstraint1.valA - theConstraint2.valA) > tolerance;
1891 }