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