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