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