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