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