]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SolveSpaceSolver/SolveSpaceSolver_Storage.cpp
Salome HOME
Fix some kind of crashes
[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     myDuplicatedConstraint(false)
49 {
50 }
51
52 bool SolveSpaceSolver_Storage::update(ConstraintWrapperPtr theConstraint)
53 {
54   bool isUpdated = false;
55   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
56       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
57   Slvs_Constraint aSlvsConstr = getConstraint((Slvs_hConstraint)aConstraint->id());
58   if (aSlvsConstr.h == SLVS_C_UNKNOWN)
59     aSlvsConstr = aConstraint->constraint();
60
61   // update value of constraint if exist
62   if (fabs(aSlvsConstr.valA - theConstraint->value()) > tolerance) {
63     aSlvsConstr.valA = theConstraint->value();
64     isUpdated = true;
65   }
66
67   // update constrained entities
68   Slvs_hEntity* aPnts[2] = {&aSlvsConstr.ptA, &aSlvsConstr.ptB};
69   Slvs_hEntity* anEnts[4] = {&aSlvsConstr.entityA, &aSlvsConstr.entityB,
70                              &aSlvsConstr.entityC, &aSlvsConstr.entityD};
71   int aPtInd = 0;
72   int aEntInd = 0;
73
74   std::list<EntityWrapperPtr> anEntities = theConstraint->entities();
75   std::list<EntityWrapperPtr>::iterator anIt = anEntities.begin();
76   for (; anIt != anEntities.end(); ++anIt) {
77     isUpdated = update(*anIt) || isUpdated;
78     // do not update constrained entities for Multi constraints
79     if (aSlvsConstr.type == SLVS_C_MULTI_ROTATION || aSlvsConstr.type == SLVS_C_MULTI_TRANSLATION)
80       continue;
81
82     Slvs_hEntity anID = (Slvs_hEntity)(*anIt)->id();
83     if ((*anIt)->type() == ENTITY_POINT) {
84       if (*(aPnts[aPtInd]) != anID) {
85         *(aPnts[aPtInd]) = anID;
86         isUpdated = true;
87       }
88       ++aPtInd;
89     } else {
90       if (*(anEnts[aEntInd]) != anID) {
91         *(anEnts[aEntInd]) = anID;
92         isUpdated = true;
93       }
94       ++aEntInd;
95     }
96   }
97
98   // update constraint itself (do not update constraints Multi)
99   if (aSlvsConstr.type != SLVS_C_MULTI_ROTATION && aSlvsConstr.type != SLVS_C_MULTI_TRANSLATION) {
100     if (aSlvsConstr.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
101       aSlvsConstr.wrkpl = myWorkplaneID;
102     if (aSlvsConstr.group == SLVS_G_UNKNOWN)
103       aSlvsConstr.group = (Slvs_hGroup)myGroupID;
104     bool hasDupConstraints = myDuplicatedConstraint;
105     Slvs_hConstraint aConstrID = updateConstraint(aSlvsConstr);
106     if (aSlvsConstr.h == SLVS_C_UNKNOWN) {
107       aConstraint->changeConstraint() = getConstraint(aConstrID);
108       isUpdated = true;
109       // check duplicated constraints based on different attributes
110       if (myDuplicatedConstraint && !hasDupConstraints && findSameConstraint(aConstraint))
111         myDuplicatedConstraint = false;
112     }
113   }
114   return isUpdated;
115 }
116
117 bool SolveSpaceSolver_Storage::update(EntityWrapperPtr theEntity)
118 {
119   bool isUpdated = false;
120   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
121       std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
122   Slvs_Entity aSlvsEnt = getEntity((Slvs_hEntity)anEntity->id());
123   if (aSlvsEnt.h == SLVS_E_UNKNOWN)
124     aSlvsEnt = anEntity->entity();
125
126   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
127   std::list<ParameterWrapperPtr>::iterator aPIt;
128   // if the entity is an attribute, need to update its coordinates
129   if (anEntity->baseAttribute()) {
130     BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
131     EntityWrapperPtr anUpdAttr = aBuilder->createAttribute(anEntity->baseAttribute(), GID_UNKNOWN);
132     if (anUpdAttr) {
133       std::list<ParameterWrapperPtr> anUpdParams = anUpdAttr->parameters();
134       std::list<ParameterWrapperPtr>::iterator anUpdIt = anUpdParams.begin();
135       for (aPIt = aParams.begin(); aPIt != aParams.end() && anUpdIt != anUpdParams.end();
136           ++aPIt, ++anUpdIt) {
137         (*aPIt)->update(*anUpdIt);
138       }
139     }
140   }
141
142   // update parameters
143   int anInd = 0;
144   for (aPIt = aParams.begin(); aPIt != aParams.end(); ++aPIt, ++anInd) {
145     assert(anInd < 4);
146     isUpdated = update(*aPIt) || isUpdated;
147     if (aSlvsEnt.param[anInd] != (Slvs_hEntity)(*aPIt)->id()) {
148       isUpdated = true;
149       aSlvsEnt.param[anInd] = (Slvs_hEntity)(*aPIt)->id();
150     }
151   }
152
153   // update sub-entities
154   std::list<EntityWrapperPtr> aSubEntities = theEntity->subEntities();
155   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
156   for (anInd = 0; aSIt != aSubEntities.end(); ++aSIt, ++anInd) {
157     assert(anInd < 4);
158     isUpdated = update(*aSIt) || isUpdated;
159
160     Slvs_hEntity anID = Slvs_hEntity((*aSIt)->id());
161     if ((*aSIt)->type() == ENTITY_NORMAL)
162       aSlvsEnt.normal = anID;
163     else if ((*aSIt)->type() == ENTITY_SCALAR)
164       aSlvsEnt.distance = anID;
165     else if (aSlvsEnt.point[anInd] != anID) {
166       aSlvsEnt.point[anInd] = anID;
167       if ((*aSIt)->baseAttribute())
168         SketchSolver_Storage::addEntity((*aSIt)->baseAttribute(), *aSIt);
169       isUpdated = true;
170     }
171   }
172   if (theEntity->type() == ENTITY_POINT && aSubEntities.size() == 1) {
173     // theEntity is based on SketchPlugin_Point => need to substitute its attribute instead
174     bool isNew = (aSlvsEnt.h == SLVS_E_UNKNOWN);
175     aSlvsEnt = getEntity(aSlvsEnt.point[0]);
176     if (isNew) {
177       anEntity->changeEntity() = aSlvsEnt;
178       isUpdated = true;
179     }
180   }
181
182   // update entity itself
183   if (aSlvsEnt.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
184     aSlvsEnt.wrkpl = myWorkplaneID;
185   if (aSlvsEnt.group == SLVS_G_UNKNOWN)
186     aSlvsEnt.group = (Slvs_hGroup)myGroupID;
187   Slvs_hEntity anEntID = updateEntity(aSlvsEnt);
188   if (aSlvsEnt.h == SLVS_E_UNKNOWN || isUpdated) {
189     anEntity->changeEntity() = getEntity(anEntID);
190     isUpdated = true;
191
192     if (anEntity->type() == ENTITY_SKETCH)
193       storeWorkplane(anEntity);
194   }
195
196   return isUpdated;
197 }
198
199 bool SolveSpaceSolver_Storage::update(ParameterWrapperPtr theParameter)
200 {
201   std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aParameter = 
202       std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(theParameter);
203   const Slvs_Param& aParam = getParameter((Slvs_hParam)aParameter->id());
204   if (aParam.h != SLVS_E_UNKNOWN && fabs(aParam.val - aParameter->value()) < tolerance)
205     return false;
206   Slvs_Param aParamToUpd = aParameter->parameter();
207   if (aParamToUpd.group == SLVS_G_UNKNOWN)
208     aParamToUpd.group = aParameter->isParametric() ? (Slvs_hGroup)GID_OUTOFGROUP : (Slvs_hGroup)myGroupID;
209   Slvs_hParam anID = updateParameter(aParamToUpd);
210   if (aParam.h == SLVS_E_UNKNOWN) // new parameter
211     aParameter->changeParameter() = getParameter(anID);
212   return true;
213 }
214
215 void SolveSpaceSolver_Storage::storeWorkplane(EntityWrapperPtr theSketch)
216 {
217   myWorkplaneID = (Slvs_hEntity)theSketch->id();
218
219   // Update sub-entities of the sketch
220   std::list<EntityWrapperPtr> aSubEntities = theSketch->subEntities();
221   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
222   for (; aSIt != aSubEntities.end(); ++aSIt) {
223     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSub =
224         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*aSIt);
225     aSub->changeEntity().wrkpl = myWorkplaneID;
226   }
227
228   // Update all stored entities
229   std::vector<Slvs_Entity>::iterator anIt = myEntities.begin();
230   for (; anIt != myEntities.end(); ++anIt)
231     anIt->wrkpl = myWorkplaneID;
232 }
233
234 void SolveSpaceSolver_Storage::changeGroup(EntityWrapperPtr theEntity, const GroupID& theGroup)
235 {
236   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
237   std::list<ParameterWrapperPtr>::iterator aPIt = aParams.begin();
238   for (; aPIt != aParams.end(); ++aPIt)
239     changeGroup(*aPIt, theGroup);
240
241   std::list<EntityWrapperPtr> aSubs = theEntity->subEntities();
242   std::list<EntityWrapperPtr>::iterator aSIt = aSubs.begin();
243   for (; aSIt != aSubs.end(); ++aSIt)
244     changeGroup(*aSIt, theGroup);
245
246   if (theEntity->group() != theGroup) {
247     theEntity->setGroup(theGroup);
248     int aPos = Search((Slvs_hEntity)theEntity->id(), myEntities);
249     if (aPos >= 0 && aPos < (int)myEntities.size()) {
250       myEntities[aPos].group = (Slvs_hGroup)theGroup;
251       setNeedToResolve(true);
252     }
253   }
254 }
255
256 void SolveSpaceSolver_Storage::changeGroup(ParameterWrapperPtr theParam, const GroupID& theGroup)
257 {
258   GroupID aGroup = theGroup;
259   if (theParam->isParametric())
260     aGroup = GID_OUTOFGROUP;
261   if (theParam->group() == aGroup)
262     return;
263
264   theParam->setGroup(aGroup);
265   int aPos = Search((Slvs_hParam)theParam->id(), myParameters);
266   if (aPos >= 0 && aPos < (int)myParameters.size()) {
267     myParameters[aPos].group = (Slvs_hGroup)aGroup;
268     setNeedToResolve(true);
269   }
270 }
271
272 void SolveSpaceSolver_Storage::addCoincidentPoints(
273     EntityWrapperPtr theMaster, EntityWrapperPtr theSlave)
274 {
275   if (theMaster->type() != ENTITY_POINT || theSlave->type() != ENTITY_POINT)
276     return;
277
278   // Search available coincidence
279   CoincidentPointsMap::iterator aMasterFound = myCoincidentPoints.find(theMaster);
280   CoincidentPointsMap::iterator aSlaveFound = myCoincidentPoints.find(theSlave);
281   if (aMasterFound == myCoincidentPoints.end() &&  aSlaveFound == myCoincidentPoints.end()) {
282     // try to find master and slave points in the lists of slaves of already existent coincidences
283     CoincidentPointsMap::iterator anIt = myCoincidentPoints.begin();
284     for (; anIt != myCoincidentPoints.end(); ++anIt) {
285       if (anIt->second.find(theMaster) != anIt->second.end())
286         aMasterFound = anIt;
287       else if (anIt->second.find(theSlave) != anIt->second.end())
288         aSlaveFound = anIt;
289
290       if (aMasterFound != myCoincidentPoints.end() &&  aSlaveFound != myCoincidentPoints.end())
291         break;
292     }
293   }
294
295   if (aMasterFound == myCoincidentPoints.end()) {
296     // create new group
297     myCoincidentPoints[theMaster] = std::set<EntityWrapperPtr>();
298     aMasterFound = myCoincidentPoints.find(theMaster);
299   } else if (aMasterFound == aSlaveFound)
300     return; // already coincident
301
302   if (aSlaveFound != myCoincidentPoints.end()) {
303     // A slave has been found, we need to attach all points coincident with it to the new master
304     std::set<EntityWrapperPtr> aNewSlaves = aSlaveFound->second;
305     aNewSlaves.insert(aSlaveFound->first);
306     myCoincidentPoints.erase(aSlaveFound);
307
308     std::set<EntityWrapperPtr>::const_iterator aSlIt = aNewSlaves.begin();
309     for (; aSlIt != aNewSlaves.end(); ++aSlIt)
310       addCoincidentPoints(theMaster, *aSlIt);
311   } else {
312     // Update the slave if it was used in constraints and features
313     replaceInFeatures(theSlave, theMaster);
314     replaceInConstraints(theSlave, theMaster);
315
316     // Remove slave entity (if the IDs are equal no need to remove slave entity, just update it)
317     if (theMaster->id() != theSlave->id())
318       removeEntity((Slvs_hEntity)theSlave->id());
319
320     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aPointMaster = 
321         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theMaster);
322     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aPointSlave = 
323         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theSlave);
324     aPointSlave->changeEntity() = aPointMaster->entity();
325     aPointSlave->setParameters(aPointMaster->parameters());
326
327     aMasterFound->second.insert(theSlave);
328   }
329 }
330
331 void SolveSpaceSolver_Storage::replaceInFeatures(
332     EntityWrapperPtr theSource, EntityWrapperPtr theDest)
333 {
334   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator anIt = myFeatureMap.begin();
335   for (; anIt != myFeatureMap.end(); ++anIt) {
336     if (!anIt->second)
337       continue;
338     bool isUpdated = false;
339     std::list<EntityWrapperPtr> aSubs = anIt->second->subEntities();
340     std::list<EntityWrapperPtr>::iterator aSubIt = aSubs.begin();
341     for (; aSubIt != aSubs.end(); ++aSubIt)
342       if ((*aSubIt)->id() == theSource->id()) {
343         (*aSubIt)->update(theDest);
344         isUpdated = true;
345       }
346
347     if (!isUpdated)
348       continue;
349
350     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aWrapper =
351         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(anIt->second);
352     // update SolveSpace entity
353     Slvs_Entity anEnt = aWrapper->entity();
354     for (int i = 0; i < 4; ++i)
355       if (anEnt.point[i] == (Slvs_hEntity)theSource->id())
356         anEnt.point[i] = (Slvs_hEntity)theDest->id();
357     anEnt.h = updateEntity(anEnt);
358     aWrapper->changeEntity() = anEnt;
359
360     // update sub-entities
361     aWrapper->setSubEntities(aSubs);
362   }
363 }
364
365 void SolveSpaceSolver_Storage::replaceInConstraints(
366     EntityWrapperPtr theSource, EntityWrapperPtr theDest)
367 {
368   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
369       anIt = myConstraintMap.begin();
370   std::list<ConstraintWrapperPtr>::const_iterator aCIt;
371   for (; anIt != myConstraintMap.end(); ++anIt)
372     for (aCIt = anIt->second.begin(); aCIt != anIt->second.end(); ++aCIt) {
373       // Do not process coincidence between points and "multi" constraints
374       // (these constraints are stored to keep the structure of constraints).
375       if ((*aCIt)->type() == CONSTRAINT_PT_PT_COINCIDENT ||
376           (*aCIt)->type() == CONSTRAINT_MULTI_ROTATION ||
377           (*aCIt)->type() == CONSTRAINT_MULTI_TRANSLATION)
378         continue;
379
380       bool isUpdated = false;
381       std::list<EntityWrapperPtr> aSubs = (*aCIt)->entities();
382       std::list<EntityWrapperPtr>::iterator aSubIt = aSubs.begin();
383       for (; aSubIt != aSubs.end(); ++aSubIt)
384         if ((*aSubIt)->id() == theSource->id()) {
385           (*aSubIt)->update(theDest);
386           isUpdated = true;
387         }
388
389       if (!isUpdated)
390         continue;
391
392       std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aWrapper =
393           std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(*aCIt);
394       // change constraint entities
395       Slvs_Constraint aConstr = aWrapper->constraint();
396       if (aConstr.ptA == (Slvs_hEntity)theSource->id())
397         aConstr.ptA = (Slvs_hEntity)theDest->id();
398       if (aConstr.ptB == (Slvs_hEntity)theSource->id())
399         aConstr.ptB = (Slvs_hEntity)theDest->id();
400
401       // check the constraint is duplicated
402       std::vector<Slvs_Constraint>::const_iterator aSlvsCIt = myConstraints.begin();
403       for (; aSlvsCIt != myConstraints.end(); ++aSlvsCIt)
404         if (aConstr.h != aSlvsCIt->h &&
405             aConstr.type == aSlvsCIt->type &&
406             aConstr.ptA == aSlvsCIt->ptA && aConstr.ptB == aSlvsCIt->ptB &&
407             aConstr.entityA == aSlvsCIt->entityA && aConstr.entityB == aSlvsCIt->entityB &&
408             aConstr.entityC == aSlvsCIt->entityC && aConstr.entityD == aSlvsCIt->entityD) {
409           Slvs_hConstraint anIDToRemove = aConstr.h;
410           aConstr = *aSlvsCIt;
411           int aShift = aSlvsCIt - myConstraints.begin();
412           removeConstraint(anIDToRemove);
413           aSlvsCIt = myConstraints.begin() + aShift - 1;
414           for (; aSlvsCIt != myConstraints.end(); ++aSlvsCIt)
415             if (aSlvsCIt->h == aConstr.h)
416               break;
417           break;
418         }
419
420       if (aSlvsCIt != myConstraints.end()) {
421         // constraint is duplicated, search its wrapper to add the mapping
422         std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
423             anIt2 = myConstraintMap.begin();
424         std::list<ConstraintWrapperPtr>::const_iterator aCIt2;
425         for (; anIt2 != myConstraintMap.end(); ++anIt2)
426           for (aCIt2 = anIt2->second.begin(); aCIt2 != anIt2->second.end(); ++aCIt2)
427             if ((Slvs_hConstraint)(*aCIt2)->id() == aConstr.h) {
428               addSameConstraints(*aCIt2, aWrapper);
429               break;
430             }
431       } else 
432         aConstr.h = updateConstraint(aConstr);
433       aWrapper->changeConstraint() = aConstr;
434
435       // update sub-entities
436       aWrapper->setEntities(aSubs);
437     }
438 }
439
440 void SolveSpaceSolver_Storage::addSameConstraints(ConstraintWrapperPtr theConstraint1,
441                                                   ConstraintWrapperPtr theConstraint2)
442 {
443   SameConstraintMap::iterator anIt = myEqualConstraints.begin();
444   for (; anIt != myEqualConstraints.end(); ++anIt) {
445     if (anIt->find(theConstraint1) != anIt->end()) {
446       anIt->insert(theConstraint2);
447       return;
448     }
449     else if (anIt->find(theConstraint2) != anIt->end()) {
450       anIt->insert(theConstraint1);
451       return;
452     }
453   }
454   // group not found => create new one
455   std::set<ConstraintWrapperPtr> aNewGroup;
456   aNewGroup.insert(theConstraint1);
457   aNewGroup.insert(theConstraint2);
458   myEqualConstraints.push_back(aNewGroup);
459 }
460
461 bool SolveSpaceSolver_Storage::findSameConstraint(ConstraintWrapperPtr theConstraint)
462 {
463   if (theConstraint->type() == CONSTRAINT_PT_PT_COINCIDENT ||
464       theConstraint->type() == CONSTRAINT_MULTI_ROTATION ||
465       theConstraint->type() == CONSTRAINT_MULTI_TRANSLATION)
466     return false;
467
468   const Slvs_Constraint& aCBase =
469       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint)->constraint();
470
471   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
472       aCIt = myConstraintMap.begin();
473   std::list<ConstraintWrapperPtr>::const_iterator aCWIt;
474   for (; aCIt != myConstraintMap.end(); ++aCIt)
475     for (aCWIt = aCIt->second.begin(); aCWIt != aCIt->second.end(); ++aCWIt) {
476       if ((*aCWIt)->type() == CONSTRAINT_PT_PT_COINCIDENT ||
477           (*aCWIt)->type() == CONSTRAINT_MULTI_ROTATION ||
478           (*aCWIt)->type() == CONSTRAINT_MULTI_TRANSLATION)
479         continue;
480       if ((*aCWIt)->type() == theConstraint->type()) {
481         const Slvs_Constraint& aCComp = std::dynamic_pointer_cast<
482             SolveSpaceSolver_ConstraintWrapper>(*aCWIt)->constraint();
483         if (aCBase.ptA == aCComp.ptA && aCBase.ptB == aCComp.ptB &&
484             aCBase.entityA == aCComp.entityA && aCBase.entityB == aCComp.entityB &&
485             aCBase.entityC == aCComp.entityC && aCBase.entityD == aCComp.entityD &&
486             fabs(aCBase.valA -aCComp.valA) < tolerance) {
487           addSameConstraints(*aCWIt, theConstraint);
488           return true;
489         }
490       }
491     }
492   return false;
493 }
494
495
496 EntityWrapperPtr SolveSpaceSolver_Storage::calculateMiddlePoint(
497     EntityWrapperPtr theBase, double theCoeff)
498 {
499   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
500
501   std::shared_ptr<GeomAPI_XY> aMidPoint;
502   if (theBase->type() == ENTITY_LINE) {
503     std::shared_ptr<GeomAPI_Pnt2d> aPoints[2];
504     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
505     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
506     for (int i = 0; i < 2; ++i, ++anIt)
507       aPoints[i] = aBuilder->point(*anIt);
508     aMidPoint = aPoints[0]->xy()->multiplied(1.0 - theCoeff)->added(
509         aPoints[1]->xy()->multiplied(theCoeff));
510   }
511   else if (theBase->type() == ENTITY_ARC) {
512     double theX, theY;
513     double anArcPoint[3][2];
514     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
515     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
516     for (int i = 0; i < 3; ++i, ++anIt) {
517       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aBuilder->point(*anIt);
518       anArcPoint[i][0] = aPoint->x();
519       anArcPoint[i][1] = aPoint->y();
520     }
521     // project last point of arc on the arc
522     double x = anArcPoint[1][0] - anArcPoint[0][0];
523     double y = anArcPoint[1][1] - anArcPoint[0][1];
524     double aRad = sqrt(x*x + y*y);
525     x = anArcPoint[2][0] - anArcPoint[0][0];
526     y = anArcPoint[2][1] - anArcPoint[0][1];
527     double aNorm = sqrt(x*x + y*y);
528     if (aNorm >= tolerance) {
529       anArcPoint[2][0] = x * aRad / aNorm;
530       anArcPoint[2][1] = y * aRad / aNorm;
531     }
532     anArcPoint[1][0] -= anArcPoint[0][0];
533     anArcPoint[1][1] -= anArcPoint[0][1];
534     if (theCoeff < tolerance) {
535       theX = anArcPoint[0][0] + anArcPoint[1][0];
536       theY = anArcPoint[0][1] + anArcPoint[1][1];
537     } else if (1 - theCoeff < tolerance) {
538       theX = anArcPoint[0][0] + anArcPoint[2][0];
539       theY = anArcPoint[0][1] + anArcPoint[2][1];
540     } else {
541       std::shared_ptr<GeomAPI_Dir2d> aStartDir(new GeomAPI_Dir2d(anArcPoint[1][0], anArcPoint[1][1]));
542       std::shared_ptr<GeomAPI_Dir2d> aEndDir(new GeomAPI_Dir2d(anArcPoint[2][0], anArcPoint[2][1]));
543       double anAngle = aStartDir->angle(aEndDir);
544       if (anAngle < 0)
545         anAngle += 2.0 * PI;
546       anAngle *= theCoeff;
547       double aCos = cos(anAngle);
548       double aSin = sin(anAngle);
549       theX = anArcPoint[0][0] + anArcPoint[1][0] * aCos - anArcPoint[1][1] * aSin;
550       theY = anArcPoint[0][1] + anArcPoint[1][0] * aSin + anArcPoint[1][1] * aCos;
551     }
552     aMidPoint = std::shared_ptr<GeomAPI_XY>(new GeomAPI_XY(theX, theY));
553   }
554
555   if (!aMidPoint)
556     return EntityWrapperPtr();
557
558   std::list<ParameterWrapperPtr> aParameters;
559   Slvs_Param aParam1 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->x());
560   aParam1.h = addParameter(aParam1);
561   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam1)));
562   Slvs_Param aParam2 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->y());
563   aParam2.h = addParameter(aParam2);
564   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam2)));
565   // Create entity (parameters are not filled)
566   Slvs_Entity anEntity = Slvs_MakePoint2d(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID,
567       (Slvs_hEntity)myWorkplaneID, aParam1.h, aParam2.h);
568   anEntity.h = addEntity(anEntity);
569
570   EntityWrapperPtr aResult(new SolveSpaceSolver_EntityWrapper(AttributePtr(), anEntity));
571   aResult->setParameters(aParameters);
572   return aResult;
573 }
574
575
576
577
578
579
580 Slvs_hParam SolveSpaceSolver_Storage::addParameter(const Slvs_Param& theParam)
581 {
582   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
583     // parameter is already used, rewrite it
584     return updateParameter(theParam);
585   }
586
587   Slvs_Param aParam = theParam;
588   if (aParam.h > myParamMaxID)
589     myParamMaxID = aParam.h;
590   else
591     aParam.h = ++myParamMaxID;
592   myParameters.push_back(aParam);
593   myNeedToResolve = true;
594   return aParam.h;
595 }
596
597 Slvs_hParam SolveSpaceSolver_Storage::updateParameter(const Slvs_Param& theParam)
598 {
599   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
600     // parameter already used, rewrite it
601     int aPos = Search(theParam.h, myParameters);
602     if (aPos >= 0 && aPos < (int)myParameters.size()) {
603       if (IsNotEqual(myParameters[aPos], theParam)) {
604         myUpdatedParameters.insert(theParam.h);
605         setNeedToResolve(true);
606       }
607       myParameters[aPos] = theParam;
608       return theParam.h;
609     }
610   }
611
612   // Parameter is not found, add new one
613   Slvs_Param aParam = theParam;
614   aParam.h = 0;
615   return addParameter(aParam);
616 }
617
618 bool SolveSpaceSolver_Storage::removeParameter(const Slvs_hParam& theParamID)
619 {
620   int aPos = Search(theParamID, myParameters);
621   if (aPos >= 0 && aPos < (int)myParameters.size()) {
622     // Firstly, search the parameter is not used elsewhere
623     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
624     for (; anEntIter != myEntities.end(); anEntIter++) {
625       for (int i = 0; i < 4; i++)
626         if (anEntIter->param[i] == theParamID)
627           return false;
628     }
629     // Remove parameter
630     myParameters.erase(myParameters.begin() + aPos);
631     myParamMaxID = myParameters.empty() ? SLVS_E_UNKNOWN : myParameters.back().h;
632     myNeedToResolve = true;
633   }
634   return true;
635 }
636
637 const Slvs_Param& SolveSpaceSolver_Storage::getParameter(const Slvs_hParam& theParamID) const
638 {
639   int aPos = Search(theParamID, myParameters);
640   if (aPos >= 0 && aPos < (int)myParameters.size())
641     return myParameters[aPos];
642
643   // Parameter is not found, return empty object
644   static Slvs_Param aDummy;
645   aDummy.h = 0;
646   return aDummy;
647 }
648
649
650 Slvs_hEntity SolveSpaceSolver_Storage::addEntity(const Slvs_Entity& theEntity)
651 {
652   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
653     // Entity is already used, rewrite it
654     return updateEntity(theEntity);
655   }
656
657   Slvs_Entity aEntity = theEntity;
658   if (aEntity.h > myEntityMaxID)
659     myEntityMaxID = aEntity.h;
660   else
661     aEntity.h = ++myEntityMaxID;
662   myEntities.push_back(aEntity);
663   myNeedToResolve = true;
664   return aEntity.h;
665 }
666
667 Slvs_hEntity SolveSpaceSolver_Storage::updateEntity(const Slvs_Entity& theEntity)
668 {
669   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
670     // Entity already used, rewrite it
671     int aPos = Search(theEntity.h, myEntities);
672     if (aPos >= 0 && aPos < (int)myEntities.size()) {
673       myNeedToResolve = myNeedToResolve || IsNotEqual(myEntities[aPos], theEntity);
674       myEntities[aPos] = theEntity;
675       return theEntity.h;
676     }
677   }
678
679   // Entity is not found, add new one
680   Slvs_Entity aEntity = theEntity;
681   aEntity.h = 0;
682   return addEntity(aEntity);
683 }
684
685 bool SolveSpaceSolver_Storage::removeEntity(const Slvs_hEntity& theEntityID)
686 {
687   bool aResult = true;
688   int aPos = Search(theEntityID, myEntities);
689   if (aPos >= 0 && aPos < (int)myEntities.size()) {
690     // Firstly, check the entity and its attributes is not used elsewhere
691     std::set<Slvs_hEntity> anEntAndSubs;
692     anEntAndSubs.insert(theEntityID);
693     for (int i = 0; i < 4; i++)
694       if (myEntities[aPos].point[i] != SLVS_E_UNKNOWN)
695         anEntAndSubs.insert(myEntities[aPos].point[i]);
696
697     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
698     for (; anEntIter != myEntities.end(); anEntIter++) {
699       if (anEntAndSubs.find(anEntIter->h) != anEntAndSubs.end())
700         continue;
701       for (int i = 0; i < 4; i++)
702         if (anEntAndSubs.find(anEntIter->point[i]) != anEntAndSubs.end())
703           return false;
704       if (anEntAndSubs.find(anEntIter->distance) != anEntAndSubs.end())
705         return false;
706     }
707     std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
708     for (; aConstrIter != myConstraints.end(); aConstrIter++) {
709       Slvs_hEntity anEntIDs[6] = {aConstrIter->ptA, aConstrIter->ptB,
710           aConstrIter->entityA, aConstrIter->entityB,
711           aConstrIter->entityC, aConstrIter->entityD};
712       for (int i = 0; i < 6; i++)
713         if (anEntAndSubs.find(anEntIDs[i]) != anEntAndSubs.end())
714           return false;
715     }
716     // The entity is not used, remove it and its parameters
717     Slvs_Entity anEntity = myEntities[aPos];
718     myEntities.erase(myEntities.begin() + aPos);
719     myEntityMaxID = myEntities.empty() ? SLVS_E_UNKNOWN : myEntities.back().h;
720     if (anEntity.distance != SLVS_E_UNKNOWN)
721       aResult = aResult && removeParameter(anEntity.distance);
722     for (int i = 0; i < 4; i++)
723       if (anEntity.param[i] != SLVS_E_UNKNOWN)
724         aResult = removeParameter(anEntity.param[i]) && aResult;
725     myNeedToResolve = true;
726   }
727   return aResult;
728 }
729
730 void SolveSpaceSolver_Storage::removeUnusedEntities()
731 {
732   std::set<Slvs_hEntity> anUnusedEntities;
733   std::vector<Slvs_Entity>::const_iterator aEIt = myEntities.begin();
734   for (; aEIt != myEntities.end(); ++aEIt) {
735     if (aEIt->h == aEIt->wrkpl) {
736       // don't remove workplane
737       anUnusedEntities.erase(aEIt->point[0]);
738       anUnusedEntities.erase(aEIt->normal);
739       continue;
740     }
741     anUnusedEntities.insert(aEIt->h);
742   }
743
744   std::vector<Slvs_Constraint>::const_iterator aCIt = myConstraints.begin();
745   for (; aCIt != myConstraints.end(); ++aCIt) {
746     Slvs_hEntity aSubs[6] = {
747         aCIt->entityA, aCIt->entityB,
748         aCIt->entityC, aCIt->entityD,
749         aCIt->ptA,     aCIt->ptB};
750     for (int i = 0; i < 6; i++) {
751       if (aSubs[i] != SLVS_E_UNKNOWN) {
752         anUnusedEntities.erase(aSubs[i]);
753         int aPos = Search(aSubs[i], myEntities);
754         if (aPos >= 0 && aPos < (int)myEntities.size()) {
755           for (int j = 0; j < 4; j++)
756             if (myEntities[aPos].point[j] != SLVS_E_UNKNOWN)
757               anUnusedEntities.erase(myEntities[aPos].point[j]);
758           if (myEntities[aPos].distance != SLVS_E_UNKNOWN)
759             anUnusedEntities.erase(myEntities[aPos].distance);
760         }
761       }
762     }
763   }
764
765   std::set<Slvs_hEntity>::const_iterator anEntIt = anUnusedEntities.begin();
766   while (anEntIt != anUnusedEntities.end()) {
767     int aPos = Search(*anEntIt, myEntities);
768     if (aPos < 0 && aPos >= (int)myEntities.size())
769       continue;
770     Slvs_Entity anEntity = myEntities[aPos];
771     // Remove entity if and only if all its parameters unused
772     bool isUsed = false;
773     if (anEntity.distance != SLVS_E_UNKNOWN && 
774       anUnusedEntities.find(anEntity.distance) == anUnusedEntities.end())
775       isUsed = true;
776     for (int i = 0; i < 4 && !isUsed; i++)
777       if (anEntity.point[i] != SLVS_E_UNKNOWN &&
778           anUnusedEntities.find(anEntity.point[i]) == anUnusedEntities.end())
779         isUsed = true;
780     if (isUsed) {
781       anUnusedEntities.erase(anEntity.distance);
782       for (int i = 0; i < 4; i++)
783         if (anEntity.point[i] != SLVS_E_UNKNOWN)
784           anUnusedEntities.erase(anEntity.point[i]);
785       std::set<Slvs_hEntity>::iterator aRemoveIt = anEntIt++;
786       anUnusedEntities.erase(aRemoveIt);
787       continue;
788     }
789     ++anEntIt;
790   }
791
792   for (anEntIt = anUnusedEntities.begin(); anEntIt != anUnusedEntities.end(); ++anEntIt) {
793     int aPos = Search(*anEntIt, myEntities);
794     if (aPos >= 0 && aPos < (int)myEntities.size()) {
795       // Remove entity and its parameters
796       Slvs_Entity anEntity = myEntities[aPos];
797       myEntities.erase(myEntities.begin() + aPos);
798       myEntityMaxID = myEntities.empty() ? SLVS_E_UNKNOWN : myEntities.back().h;
799       if (anEntity.distance != SLVS_E_UNKNOWN)
800         removeParameter(anEntity.distance);
801       for (int i = 0; i < 4; i++)
802         if (anEntity.param[i] != SLVS_E_UNKNOWN)
803           removeParameter(anEntity.param[i]);
804       for (int i = 0; i < 4; i++)
805         if (anEntity.point[i] != SLVS_E_UNKNOWN)
806           removeEntity(anEntity.point[i]);
807     }
808   }
809
810   if (!anUnusedEntities.empty())
811     myNeedToResolve = true;
812 }
813
814 bool SolveSpaceSolver_Storage::isUsedByConstraints(const Slvs_hEntity& theEntityID) const
815 {
816   std::vector<Slvs_Constraint>::const_iterator aCIt = myConstraints.begin();
817   for (; aCIt != myConstraints.end(); ++aCIt) {
818     Slvs_hEntity aSubs[6] = {
819         aCIt->entityA, aCIt->entityB,
820         aCIt->entityC, aCIt->entityD,
821         aCIt->ptA,     aCIt->ptB};
822     for (int i = 0; i < 6; i++)
823       if (aSubs[i] != SLVS_E_UNKNOWN && aSubs[i] == theEntityID)
824         return true;
825   }
826   return false;
827 }
828
829 const Slvs_Entity& SolveSpaceSolver_Storage::getEntity(const Slvs_hEntity& theEntityID) const
830 {
831   int aPos = Search(theEntityID, myEntities);
832   if (aPos >= 0 && aPos < (int)myEntities.size())
833     return myEntities[aPos];
834
835   // Entity is not found, return empty object
836   static Slvs_Entity aDummy;
837   aDummy.h = SLVS_E_UNKNOWN;
838   return aDummy;
839 }
840
841 Slvs_hEntity SolveSpaceSolver_Storage::copyEntity(const Slvs_hEntity& theCopied)
842 {
843   int aPos = Search(theCopied, myEntities);
844   if (aPos < 0 || aPos >= (int)myEntities.size())
845     return SLVS_E_UNKNOWN;
846
847   Slvs_Entity aCopy = myEntities[aPos];
848   aCopy.h = SLVS_E_UNKNOWN;
849   int i = 0;
850   while (aCopy.point[i] != SLVS_E_UNKNOWN) {
851     aCopy.point[i] = copyEntity(aCopy.point[i]);
852     i++;
853   }
854   if (aCopy.param[0] != SLVS_E_UNKNOWN) {
855     aPos = Search(aCopy.param[0], myParameters);
856     i = 0;
857     while (aCopy.param[i] != SLVS_E_UNKNOWN) {
858       Slvs_Param aNewParam = myParameters[aPos];
859       aNewParam.h = SLVS_E_UNKNOWN;
860       aCopy.param[i] = addParameter(aNewParam);
861       i++;
862       aPos++;
863     }
864   }
865   return addEntity(aCopy);
866 }
867
868 void SolveSpaceSolver_Storage::copyEntity(const Slvs_hEntity& theFrom, const Slvs_hEntity& theTo)
869 {
870   int aPosFrom = Search(theFrom, myEntities);
871   int aPosTo = Search(theTo, myEntities);
872   if (aPosFrom < 0 || aPosFrom >= (int)myEntities.size() || 
873       aPosTo < 0 || aPosTo >= (int)myEntities.size())
874     return;
875
876   Slvs_Entity aEntFrom = myEntities[aPosFrom];
877   Slvs_Entity aEntTo = myEntities[aPosTo];
878   int i = 0;
879   while (aEntFrom.point[i] != SLVS_E_UNKNOWN) {
880     copyEntity(aEntFrom.point[i], aEntTo.point[i]);
881     i++;
882   }
883   if (aEntFrom.param[0] != SLVS_E_UNKNOWN) {
884     aPosFrom = Search(aEntFrom.param[0], myParameters);
885     aPosTo = Search(aEntTo.param[0], myParameters);
886     i = 0;
887     while (aEntFrom.param[i] != SLVS_E_UNKNOWN) {
888       myParameters[aPosTo++].val = myParameters[aPosFrom++].val;
889       i++;
890     }
891   }
892 }
893
894
895 Slvs_hConstraint SolveSpaceSolver_Storage::addConstraint(const Slvs_Constraint& theConstraint)
896 {
897   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
898     // Constraint is already used, rewrite it
899     return updateConstraint(theConstraint);
900   }
901
902   Slvs_Constraint aConstraint = theConstraint;
903
904   // Find a constraint with same type uses same arguments to show user overconstraint situation
905   std::vector<Slvs_Constraint>::iterator aCIt = myConstraints.begin();
906   for (; aCIt != myConstraints.end(); aCIt++) {
907     if (aConstraint.type != aCIt->type)
908       continue;
909     if (aConstraint.ptA == aCIt->ptA && aConstraint.ptB == aCIt->ptB &&
910         aConstraint.entityA == aCIt->entityA && aConstraint.entityB == aCIt->entityB &&
911         aConstraint.entityC == aCIt->entityC && aConstraint.entityD == aCIt->entityD) {
912       myDuplicatedConstraint = true;
913       return aCIt->h;
914     }
915   }
916
917   if (aConstraint.h > myConstrMaxID)
918     myConstrMaxID = aConstraint.h;
919   else
920     aConstraint.h = ++myConstrMaxID;
921   myConstraints.push_back(aConstraint);
922   myNeedToResolve = true;
923   return aConstraint.h;
924 }
925
926 Slvs_hConstraint SolveSpaceSolver_Storage::updateConstraint(const Slvs_Constraint& theConstraint)
927 {
928   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
929     // Constraint already used, rewrite it
930     int aPos = Search(theConstraint.h, myConstraints);
931     if (aPos >= 0 && aPos < (int)myConstraints.size()) {
932       myNeedToResolve = myNeedToResolve || IsNotEqual(myConstraints[aPos], theConstraint);
933       myConstraints[aPos] = theConstraint;
934       return theConstraint.h;
935     }
936   }
937
938   // Constraint is not found, add new one
939   Slvs_Constraint aConstraint = theConstraint;
940   aConstraint.h = 0;
941   return addConstraint(aConstraint);
942 }
943
944 bool SolveSpaceSolver_Storage::removeConstraint(const Slvs_hConstraint& theConstraintID)
945 {
946   int aPos = Search(theConstraintID, myConstraints);
947   if (aPos >= 0 && aPos < (int)myConstraints.size()) {
948     Slvs_Constraint aConstraint = myConstraints[aPos];
949     myConstraints.erase(myConstraints.begin() + aPos);
950     myConstrMaxID = myConstraints.empty() ? SLVS_E_UNKNOWN : myConstraints.back().h;
951     myNeedToResolve = true;
952   }
953   return true;
954 }
955
956 const Slvs_Constraint& SolveSpaceSolver_Storage::getConstraint(const Slvs_hConstraint& theConstraintID) const
957 {
958   int aPos = Search(theConstraintID, myConstraints);
959   if (aPos >= 0 && aPos < (int)myConstraints.size())
960     return myConstraints[aPos];
961
962   // Constraint is not found, return empty object
963   static Slvs_Constraint aDummy;
964   aDummy.h = 0;
965   return aDummy;
966 }
967
968
969 void SolveSpaceSolver_Storage::initializeSolver(SolverPtr theSolver)
970 {
971   std::shared_ptr<SolveSpaceSolver_Solver> aSolver =
972       std::dynamic_pointer_cast<SolveSpaceSolver_Solver>(theSolver);
973   if (!aSolver)
974     return;
975
976   if (myExistArc)
977     processArcs();
978
979   if (myConstraints.empty()) {
980     // Adjust all arc to place their points correctly
981     std::vector<Slvs_Entity>::const_iterator anEntIt = myEntities.begin();
982     for (; anEntIt != myEntities.end(); ++anEntIt)
983       if (anEntIt->type == SLVS_E_ARC_OF_CIRCLE)
984         adjustArc(*anEntIt);
985   }
986
987   aSolver->setParameters(myParameters.data(), (int)myParameters.size());
988   aSolver->setEntities(myEntities.data(), (int)myEntities.size());
989   aSolver->setConstraints(myConstraints.data(), (int)myConstraints.size());
990 }
991
992
993 bool SolveSpaceSolver_Storage::removeCoincidence(ConstraintWrapperPtr theConstraint)
994 {
995   std::list<EntityWrapperPtr> aPoints = theConstraint->entities();
996   std::list<EntityWrapperPtr>::const_iterator aPIt;
997
998   CoincidentPointsMap::iterator aPtPtIt = myCoincidentPoints.begin();
999   for (; aPtPtIt != myCoincidentPoints.end(); ++aPtPtIt) {
1000     for (aPIt = aPoints.begin(); aPIt != aPoints.end(); ++aPIt)
1001       if (aPtPtIt->first == *aPIt ||
1002           aPtPtIt->second.find(*aPIt) != aPtPtIt->second.end())
1003         break;
1004     if (aPIt != aPoints.end())
1005       break;
1006   }
1007
1008   if (aPtPtIt == myCoincidentPoints.end())
1009     return true; // already removed
1010
1011   // Create new copies of coincident points
1012   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
1013   std::list<EntityWrapperPtr> aNewPoints;
1014   for (aPIt = aPoints.begin(); aPIt != aPoints.end(); ++aPIt)
1015     aNewPoints.push_back(aBuilder->createAttribute(
1016         (*aPIt)->baseAttribute(), myGroupID, myWorkplaneID));
1017
1018   // Find all points fallen out of group of coincident points
1019   std::map<EntityWrapperPtr, EntityWrapperPtr> aNotCoinc;
1020   aNotCoinc[aPtPtIt->first] = EntityWrapperPtr();
1021   std::set<EntityWrapperPtr>::const_iterator aTempIt = aPtPtIt->second.begin();
1022   for (; aTempIt != aPtPtIt->second.end(); ++aTempIt)
1023     aNotCoinc[*aTempIt] = EntityWrapperPtr();
1024   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::iterator
1025       aConstrIt = myConstraintMap.begin();
1026   for (; aConstrIt != myConstraintMap.end(); ++aConstrIt)
1027     if (aConstrIt->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
1028       AttributeRefAttrPtr aRefAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
1029           aConstrIt->first->attribute(SketchPlugin_Constraint::ENTITY_A()));
1030       AttributeRefAttrPtr aRefAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
1031           aConstrIt->first->attribute(SketchPlugin_Constraint::ENTITY_B()));
1032       if (!aRefAttrA || !aRefAttrB || aRefAttrA->isObject() || aRefAttrB->isObject())
1033         continue;
1034       std::map<AttributePtr, EntityWrapperPtr>::iterator
1035           aFound = myAttributeMap.find(aRefAttrA->attr());
1036       if (aFound != myAttributeMap.end())
1037         aNotCoinc.erase(aFound->second);
1038       aFound = myAttributeMap.find(aRefAttrB->attr());
1039       if (aFound != myAttributeMap.end())
1040         aNotCoinc.erase(aFound->second);
1041     }
1042   if (aNotCoinc.empty())
1043     return false;
1044   std::list<EntityWrapperPtr>::const_iterator aNewPIt;
1045   for (aPIt = aPoints.begin(), aNewPIt = aNewPoints.begin();
1046        aPIt != aPoints.end(); ++aPIt, ++aNewPIt) {
1047     if (aNotCoinc.find(*aPIt) != aNotCoinc.end())
1048       aNotCoinc[*aPIt] = *aNewPIt;
1049   }
1050
1051   // Find all features and constraints uses coincident points
1052   std::map<EntityWrapperPtr, EntityWrapperPtr>::iterator aNotCIt;
1053   std::set<EntityWrapperPtr> anUpdFeatures;
1054   std::map<FeaturePtr, EntityWrapperPtr>::iterator aFIt = myFeatureMap.begin();
1055   for (; aFIt != myFeatureMap.end(); ++aFIt) {
1056     if (!aFIt->second)
1057       continue; // avoid not completed arcs
1058     for (aNotCIt = aNotCoinc.begin(); aNotCIt != aNotCoinc.end(); ++aNotCIt) {
1059       if (!aNotCIt->second || !aFIt->second->isUsed(aNotCIt->first->baseAttribute()))
1060         continue;
1061       std::list<EntityWrapperPtr> aSubs = aFIt->second->subEntities();
1062       std::list<EntityWrapperPtr>::iterator aSIt = aSubs.begin();
1063       bool isUpd = false;
1064       for (; aSIt != aSubs.end(); ++aSIt)
1065         if (*aSIt == aNotCIt->first) {
1066           *aSIt = aNotCIt->second;
1067           isUpd = true;
1068         }
1069       if (isUpd) {
1070         aFIt->second->setSubEntities(aSubs);
1071         anUpdFeatures.insert(aFIt->second);
1072       }
1073     }
1074   }
1075   // update features
1076   std::set<EntityWrapperPtr>::iterator anUpdIt = anUpdFeatures.begin();
1077   for (; anUpdIt != anUpdFeatures.end(); ++anUpdIt)
1078     update(EntityWrapperPtr(*anUpdIt));
1079
1080   // remove not coincident points
1081   for (aNotCIt = aNotCoinc.begin(); aNotCIt != aNotCoinc.end(); ++aNotCIt) {
1082     if (aPtPtIt->second.size() <= 1) {
1083       myCoincidentPoints.erase(aPtPtIt);
1084       break;
1085     }
1086     if (aPtPtIt->first == aNotCIt->first) {
1087       std::set<EntityWrapperPtr> aSlaves = aPtPtIt->second;
1088       EntityWrapperPtr aNewMaster = *aSlaves.begin();
1089       aSlaves.erase(aSlaves.begin());
1090       myCoincidentPoints.erase(aPtPtIt);
1091       myCoincidentPoints[aNewMaster] = aSlaves;
1092       aPtPtIt = myCoincidentPoints.find(aNewMaster);
1093     } else
1094       aPtPtIt->second.erase(aNotCIt->first);
1095   }
1096   return true;
1097 }
1098
1099 bool SolveSpaceSolver_Storage::remove(ConstraintWrapperPtr theConstraint)
1100 {
1101   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
1102       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
1103
1104   // verify whether the constraint has duplicated
1105   SameConstraintMap::iterator anEqIt = myEqualConstraints.begin();
1106   for (; anEqIt != myEqualConstraints.end(); ++anEqIt)
1107     if (anEqIt->find(aConstraint) != anEqIt->end()) {
1108       anEqIt->erase(aConstraint);
1109       break;
1110     }
1111   if (anEqIt != myEqualConstraints.end())
1112     return true;
1113
1114   bool isFullyRemoved = removeConstraint((Slvs_hConstraint)aConstraint->id());
1115
1116   // remove point-point coincidence
1117   if (aConstraint->type() == CONSTRAINT_PT_PT_COINCIDENT)
1118     isFullyRemoved = removeCoincidence(theConstraint);
1119
1120   return SketchSolver_Storage::remove(theConstraint) && isFullyRemoved;
1121 }
1122
1123 bool SolveSpaceSolver_Storage::remove(EntityWrapperPtr theEntity)
1124 {
1125   if (!theEntity)
1126     return false;
1127
1128   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
1129         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
1130   bool isFullyRemoved = removeEntity((Slvs_hEntity)anEntity->id());
1131   return SketchSolver_Storage::remove(theEntity) && isFullyRemoved;
1132 }
1133
1134 bool SolveSpaceSolver_Storage::remove(ParameterWrapperPtr theParameter)
1135 {
1136   return removeParameter((Slvs_hParam)theParameter->id());
1137 }
1138
1139
1140 void SolveSpaceSolver_Storage::refresh(bool theFixedOnly) const
1141 {
1142   //blockEvents(true);
1143
1144   std::map<AttributePtr, EntityWrapperPtr>::const_iterator anIt = myAttributeMap.begin();
1145   std::list<ParameterWrapperPtr> aParams;
1146   std::list<ParameterWrapperPtr>::const_iterator aParIt;
1147   for (; anIt != myAttributeMap.end(); ++anIt) {
1148     if (!anIt->second)
1149       continue;
1150     // the external feature always should keep the up to date values, so, 
1151     // refresh from the solver is never needed
1152     if (anIt->first.get()) {
1153       std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
1154         std::dynamic_pointer_cast<SketchPlugin_Feature>(anIt->first->owner());
1155       if (aSketchFeature.get() && aSketchFeature->isExternal())
1156         continue;
1157       // not need to refresh here sketch's origin and normal vector
1158       CompositeFeaturePtr aSketch =
1159           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anIt->first->owner());
1160       if (aSketch)
1161         continue;
1162     }
1163
1164     // update parameter wrappers and obtain values of attributes
1165     aParams = anIt->second->parameters();
1166     double aCoords[3];
1167     bool isUpd[3] = {false};
1168     int i = 0;
1169     for (aParIt = aParams.begin(); i < 3 && aParIt != aParams.end(); ++aParIt, ++i) {
1170       std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aWrapper = 
1171           std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(*aParIt);
1172       if (!theFixedOnly || aWrapper->group() == GID_OUTOFGROUP || aWrapper->isParametric()) {
1173         aWrapper->changeParameter().val = getParameter((Slvs_hParam)aWrapper->id()).val;
1174         aCoords[i] = aWrapper->value();
1175         isUpd[i] = true;
1176       }
1177     }
1178     if (!isUpd[0] && !isUpd[1] && !isUpd[2])
1179       continue; // nothing is updated
1180
1181     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
1182         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anIt->first);
1183     if (aPoint2D) {
1184       if ((isUpd[0] && fabs(aPoint2D->x() - aCoords[0]) > tolerance) ||
1185           (isUpd[1] && fabs(aPoint2D->y() - aCoords[1]) > tolerance)) {
1186         if (!isUpd[0]) aCoords[0] = aPoint2D->x();
1187         if (!isUpd[1]) aCoords[1] = aPoint2D->y();
1188         aPoint2D->setValue(aCoords[0], aCoords[1]);
1189         // Find points coincident with this one (probably not in GID_OUTOFGROUP)
1190         std::map<AttributePtr, EntityWrapperPtr>::const_iterator aLocIt;
1191         if (theFixedOnly) 
1192           aLocIt = myAttributeMap.begin();
1193         else {
1194           aLocIt = anIt;
1195           ++aLocIt;
1196         }
1197         for (; aLocIt != myAttributeMap.end(); ++aLocIt) {
1198           if (!aLocIt->second)
1199             continue;
1200           std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
1201             std::dynamic_pointer_cast<SketchPlugin_Feature>(aLocIt->first->owner());
1202           if (aSketchFeature && aSketchFeature->isExternal())
1203             continue;
1204           if (anIt->second->id() == aLocIt->second->id()) {
1205             aPoint2D = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aLocIt->first);
1206             aPoint2D->setValue(aCoords[0], aCoords[1]);
1207           }
1208         }
1209       }
1210       continue;
1211     }
1212     AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anIt->first);
1213     if (aScalar) {
1214       if (isUpd[0] && fabs(aScalar->value() - aCoords[0]) > tolerance)
1215         aScalar->setValue(aCoords[0]);
1216       continue;
1217     }
1218     std::shared_ptr<GeomDataAPI_Point> aPoint =
1219         std::dynamic_pointer_cast<GeomDataAPI_Point>(anIt->first);
1220     if (aPoint) {
1221       if ((isUpd[0] && fabs(aPoint->x() - aCoords[0]) > tolerance) ||
1222           (isUpd[1] && fabs(aPoint->y() - aCoords[1]) > tolerance) ||
1223           (isUpd[2] && fabs(aPoint->z() - aCoords[2]) > tolerance))
1224         if (!isUpd[0]) aCoords[0] = aPoint->x();
1225         if (!isUpd[1]) aCoords[1] = aPoint->y();
1226         if (!isUpd[2]) aCoords[2] = aPoint->z();
1227         aPoint->setValue(aCoords[0], aCoords[1], aCoords[2]);
1228       continue;
1229     }
1230   }
1231
1232   //blockEvents(false);
1233 }
1234
1235 void SolveSpaceSolver_Storage::verifyFixed()
1236 {
1237   std::map<AttributePtr, EntityWrapperPtr>::iterator anAttrIt = myAttributeMap.begin();
1238   for (; anAttrIt != myAttributeMap.end(); ++anAttrIt) {
1239     if (!anAttrIt->second)
1240       continue;
1241     const std::list<ParameterWrapperPtr>& aParameters = anAttrIt->second->parameters();
1242     std::list<ParameterWrapperPtr>::const_iterator aParIt = aParameters.begin();
1243     for (; aParIt != aParameters.end(); ++aParIt)
1244       if ((*aParIt)->group() == GID_OUTOFGROUP) {
1245         Slvs_Param aParam = getParameter((Slvs_hParam)(*aParIt)->id());
1246         if (aParam.group != (Slvs_hParam)GID_OUTOFGROUP) {
1247           aParam.group = (Slvs_hParam)GID_OUTOFGROUP;
1248           updateParameter(aParam);
1249         }
1250       }
1251   }
1252 }
1253
1254
1255 void SolveSpaceSolver_Storage::adjustArc(const Slvs_Entity& theArc)
1256 {
1257   double anArcPoints[3][2];
1258   double aDist[3] = {0.0};
1259   bool isFixed[3] = {false};
1260   for (int i = 0; i < 3; ++i) {
1261     Slvs_Entity aPoint = getEntity(theArc.point[i]);
1262     isFixed[i] = (aPoint.group != (Slvs_hGroup)myGroupID);
1263     anArcPoints[i][0] = getParameter(aPoint.param[0]).val;
1264     anArcPoints[i][1] = getParameter(aPoint.param[1]).val;
1265     if (i > 0) {
1266       anArcPoints[i][0] -= anArcPoints[0][0];
1267       anArcPoints[i][1] -= anArcPoints[0][1];
1268       aDist[i] = sqrt(anArcPoints[i][0] * anArcPoints[i][0] + 
1269                       anArcPoints[i][1] * anArcPoints[i][1]);
1270     }
1271   }
1272
1273   if (fabs(aDist[1] - aDist[2]) < tolerance)
1274     return;
1275
1276   int anInd = 2;
1277   while (anInd > 0 && isFixed[anInd])
1278     --anInd;
1279   if (anInd < 1)
1280     return; // adjust only start or end point of the arc
1281
1282   anArcPoints[anInd][0] /= aDist[anInd];
1283   anArcPoints[anInd][1] /= aDist[anInd];
1284
1285   Slvs_Entity aPoint = getEntity(theArc.point[anInd]);
1286   for (int i = 0; i < 2; ++i) {
1287     Slvs_Param aParam = getParameter(aPoint.param[i]);
1288     aParam.val = anArcPoints[0][i] + aDist[3-anInd] * anArcPoints[anInd][i];
1289     updateParameter(aParam);
1290   }
1291 }
1292
1293
1294
1295
1296
1297
1298
1299 // ========================================================
1300 // =========      Auxiliary functions       ===============
1301 // ========================================================
1302
1303 template<typename T>
1304 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1305 {
1306   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1307   int aVecSize = theEntities.size();
1308   if (theEntities.empty())
1309     return 1;
1310   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1311     aResIndex--;
1312   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1313     aResIndex++;
1314   if (aResIndex == -1 || (aResIndex < aVecSize && theEntities[aResIndex].h != theEntityID))
1315     aResIndex = aVecSize;
1316   return aResIndex;
1317 }
1318
1319 bool IsNotEqual(const Slvs_Param& theParam1, const Slvs_Param& theParam2)
1320 {
1321   return fabs(theParam1.val - theParam2.val) > tolerance;
1322 }
1323
1324 bool IsNotEqual(const Slvs_Entity& theEntity1, const Slvs_Entity& theEntity2)
1325 {
1326   int i = 0;
1327   for (; theEntity1.param[i] != 0 && i < 4; i++)
1328     if (theEntity1.param[i] != theEntity2.param[i])
1329       return true;
1330   i = 0;
1331   for (; theEntity1.point[i] != 0 && i < 4; i++)
1332     if (theEntity1.point[i] != theEntity2.point[i])
1333       return true;
1334   return false;
1335 }
1336
1337 bool IsNotEqual(const Slvs_Constraint& theConstraint1, const Slvs_Constraint& theConstraint2)
1338 {
1339   return theConstraint1.ptA != theConstraint2.ptA ||
1340          theConstraint1.ptB != theConstraint2.ptB ||
1341          theConstraint1.entityA != theConstraint2.entityA ||
1342          theConstraint1.entityB != theConstraint2.entityB ||
1343          theConstraint1.entityC != theConstraint2.entityC ||
1344          theConstraint1.entityD != theConstraint2.entityD ||
1345          fabs(theConstraint1.valA - theConstraint2.valA) > tolerance;
1346 }