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