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