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