Salome HOME
b51828ba9d0eb78e560f1d934f11f9801a4642a3
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SketchSolver_Group.cpp
4 // Created: 27 May 2014
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchSolver_Group.h"
8
9 #include <SketchSolver_Builder.h>
10 #include <SketchSolver_Constraint.h>
11 #include <SketchSolver_ConstraintCoincidence.h>
12 #include <SketchSolver_Error.h>
13
14 #include <Events_Error.h>
15 #include <Events_Loop.h>
16 #include <GeomAPI_XY.h>
17 #include <GeomAPI_Dir2d.h>
18 #include <GeomAPI_Pnt2d.h>
19 #include <GeomDataAPI_Dir.h>
20 #include <GeomDataAPI_Point.h>
21 #include <GeomDataAPI_Point2D.h>
22 #include <ModelAPI_AttributeDouble.h>
23 #include <ModelAPI_Document.h>
24 #include <ModelAPI_Events.h>
25 #include <ModelAPI_ResultConstruction.h>
26
27 #include <SketchPlugin_Constraint.h>
28 #include <SketchPlugin_ConstraintFillet.h>
29 #include <SketchPlugin_ConstraintLength.h>
30 #include <SketchPlugin_ConstraintCoincidence.h>
31 #include <SketchPlugin_ConstraintMirror.h>
32 #include <SketchPlugin_ConstraintRigid.h>
33 #include <SketchPlugin_Feature.h>
34
35 #include <SketchPlugin_Arc.h>
36 #include <SketchPlugin_Circle.h>
37 #include <SketchPlugin_Line.h>
38 #include <SketchPlugin_Point.h>
39 #include <SketchPlugin_Sketch.h>
40
41 #include <math.h>
42 #include <assert.h>
43
44
45 /// \brief This class is used to give unique index to the groups
46 class GroupIndexer
47 {
48 public:
49   /// \brief Return vacant index
50   static Slvs_hGroup NEW_GROUP() { return ++myGroupIndex; }
51   /// \brief Removes the index
52   static void REMOVE_GROUP(const Slvs_hGroup& theIndex) {
53     if (myGroupIndex == theIndex)
54       myGroupIndex--;
55   }
56
57 private:
58   GroupIndexer() {};
59
60   static Slvs_hGroup myGroupIndex; ///< index of the group
61 };
62
63 Slvs_hGroup GroupIndexer::myGroupIndex = 0;
64
65
66
67 // ========================================================
68 // =========  SketchSolver_Group  ===============
69 // ========================================================
70
71 SketchSolver_Group::SketchSolver_Group(
72     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
73     : myID(GroupIndexer::NEW_GROUP())
74 {
75   // Initialize workplane
76   myWorkplaneID = SLVS_E_UNKNOWN;
77 #ifndef NDEBUG
78   assert(addWorkplane(theWorkplane));
79 #else
80   addWorkplane(theWorkplane);
81 #endif
82 }
83
84 SketchSolver_Group::~SketchSolver_Group()
85 {
86   myConstraints.clear();
87   GroupIndexer::REMOVE_GROUP(myID);
88 }
89
90 // ============================================================================
91 //  Function: isBaseWorkplane
92 //  Class:    SketchSolver_Group
93 //  Purpose:  verify the group is based on the given workplane
94 // ============================================================================
95 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
96 {
97   return theWorkplane == mySketch;
98 }
99
100 // ============================================================================
101 //  Function: isInteract
102 //  Class:    SketchSolver_Group
103 //  Purpose:  verify are there any entities in the group used by given constraint
104 // ============================================================================
105 bool SketchSolver_Group::isInteract(
106     std::shared_ptr<SketchPlugin_Feature> theFeature) const
107 {
108   // Empty group interacts with everything
109   if (isEmpty()) return true;
110   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
111   if (aConstraint)
112     return myFeatureStorage->isInteract(aConstraint);
113   return myFeatureStorage->isInteract(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
114 }
115
116 // ============================================================================
117 //  Function: getFeatureId
118 //  Class:    SketchSolver_Group
119 //  Purpose:  Find the identifier of the feature, if it already exists in the group
120 // ============================================================================
121 Slvs_hEntity SketchSolver_Group::getFeatureId(FeaturePtr theFeature) const
122 {
123   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
124   if (!myFeatureStorage)
125     return aResult;
126   std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(theFeature);
127   if (aConstraints.empty())
128     return aResult;
129   std::set<ConstraintPtr>::iterator aConstrIter = aConstraints.begin();
130   for (; aConstrIter != aConstraints.end(); aConstrIter++) {
131     ConstraintConstraintMap::const_iterator aCIter = myConstraints.find(*aConstrIter);
132     if (aCIter == myConstraints.end())
133       continue;
134     aResult = aCIter->second->getId(theFeature);
135     if (aResult != SLVS_E_UNKNOWN)
136       return aResult;
137   }
138   return SLVS_E_UNKNOWN;
139 }
140
141 // ============================================================================
142 //  Function: getAttributeId
143 //  Class:    SketchSolver_Group
144 //  Purpose:  Find the identifier of the attribute, if it already exists in the group
145 // ============================================================================
146 Slvs_hEntity SketchSolver_Group::getAttributeId(AttributePtr theAttribute) const
147 {
148   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
149   if (!myFeatureStorage)
150     return aResult;
151   std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(theAttribute);
152   if (aConstraints.empty())
153     return aResult;
154   std::set<ConstraintPtr>::iterator aConstrIter = aConstraints.begin();
155   for (; aConstrIter != aConstraints.end(); aConstrIter++) {
156     ConstraintConstraintMap::const_iterator aCIter = myConstraints.find(*aConstrIter);
157     if (aCIter == myConstraints.end())
158       continue;
159     aResult = aCIter->second->getId(theAttribute);
160     if (aResult != SLVS_E_UNKNOWN)
161       return aResult;
162   }
163   return SLVS_E_UNKNOWN;
164 }
165
166 // ============================================================================
167 //  Function: changeConstraint
168 //  Class:    SketchSolver_Group
169 //  Purpose:  create/update the constraint in the group
170 // ============================================================================
171 bool SketchSolver_Group::changeConstraint(
172     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
173 {
174   // There is no workplane yet, something wrong
175   if (myWorkplaneID == SLVS_E_UNKNOWN)
176     return false;
177
178   if (!theConstraint)
179     return false;
180
181   if (myConstraints.find(theConstraint) == myConstraints.end()) {
182     // Add constraint to the current group
183     SolverConstraintPtr aConstraint =
184         SketchSolver_Builder::getInstance()->createConstraint(theConstraint);
185     if (!aConstraint)
186       return false;
187     aConstraint->setGroup(this);
188     aConstraint->setStorage(myStorage);
189     if (!aConstraint->error().empty()) {
190       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
191         return false; // some attribute are not initialized yet, don't show message
192       Events_Error::send(aConstraint->error(), this);
193     }
194
195     // Additional verification of coincidence of several points
196     if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
197       ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
198       for (; aCIter != myConstraints.end(); aCIter++) {
199         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoincidence =
200           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aCIter->second);
201         if (!aCoincidence)
202           continue;
203         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoinc2 =
204           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aConstraint);
205         if (aCoincidence != aCoinc2 && aCoincidence->isCoincide(aCoinc2)) {
206           aCoincidence->attach(aCoinc2);
207           aConstraint = aCoincidence;
208         }
209       }
210     }
211     myConstraints[theConstraint] = aConstraint;
212   }
213   else
214     myConstraints[theConstraint]->update();
215
216   // Fix base features for fillet
217   if (theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
218     std::list<AttributePtr> anAttrList =
219         theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
220     std::list<AttributePtr>::iterator anAttrIter = anAttrList.begin();
221     for (; anAttrIter != anAttrList.end(); anAttrIter++) {
222       AttributeRefAttrPtr aRefAttr =
223           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
224       if (!aRefAttr || !aRefAttr->isObject())
225         continue;
226       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
227       SolverConstraintPtr aConstraint =
228           SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
229       if (!aConstraint)
230         continue;
231       aConstraint->setGroup(this);
232       aConstraint->setStorage(myStorage);
233       myTempConstraints.insert(aConstraint);
234     }
235   }
236   // Fix base features for mirror
237   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
238     AttributeRefListPtr aRefList = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
239         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_B()));
240     fixFeaturesList(aRefList);
241   }
242
243   if (!myFeatureStorage)
244     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
245   myFeatureStorage->changeConstraint(theConstraint);
246
247   return true;
248 }
249
250
251 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
252 {
253   std::set<ConstraintPtr> aConstraints =
254       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
255   if (aConstraints.empty())
256     return false;
257   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
258   for (; aCIter != aConstraints.end(); aCIter++) {
259     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
260     aSolConIter->second->update();
261   }
262   return true;
263 }
264
265 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
266 {
267   updateFeature(theFeature);
268   // Temporary rigid constraint
269   SolverConstraintPtr aConstraint =
270       SketchSolver_Builder::getInstance()->createRigidConstraint(theFeature);
271   if (!aConstraint)
272     return;
273   aConstraint->setGroup(this);
274   aConstraint->setStorage(myStorage);
275   myTempConstraints.insert(aConstraint);
276 }
277
278 // ============================================================================
279 //  Function: fixFeaturesList
280 //  Class:    SketchSolver_Group
281 //  Purpose:  Apply temporary rigid constraints for the list of features
282 // ============================================================================
283 void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
284 {
285   std::list<ObjectPtr> aList = theList->list();
286   std::list<ObjectPtr>::iterator anIt = aList.begin();
287   for (; anIt != aList.end(); anIt++) {
288     if (!(*anIt))
289       continue;
290     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
291     SolverConstraintPtr aConstraint =
292         SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
293     if (!aConstraint)
294       continue;
295     aConstraint->setGroup(this);
296     aConstraint->setStorage(myStorage);
297     myTempConstraints.insert(aConstraint);
298   }
299 }
300
301 // ============================================================================
302 //  Function: addWorkplane
303 //  Class:    SketchSolver_Group
304 //  Purpose:  create workplane for the group
305 // ============================================================================
306 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
307 {
308   if (myWorkplaneID != SLVS_E_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
309     return false;  // the workplane already exists or the function parameter is not Sketch
310
311   mySketch = theSketch;
312   updateWorkplane();
313   return true;
314 }
315
316 // ============================================================================
317 //  Function: updateWorkplane
318 //  Class:    SketchSolver_Group
319 //  Purpose:  update parameters of workplane
320 // ============================================================================
321 bool SketchSolver_Group::updateWorkplane()
322 {
323   if (!myStorage) // Create storage if not exists
324     myStorage = StoragePtr(new SketchSolver_Storage);
325   SketchSolver_Builder* aBuilder = SketchSolver_Builder::getInstance();
326
327   std::vector<Slvs_Entity> anEntities;
328   std::vector<Slvs_Param> aParams;
329   if (!aBuilder->createWorkplane(mySketch, anEntities, aParams))
330     return false;
331
332   if (myWorkplaneID == SLVS_E_UNKNOWN) {
333     myWorkplaneID = anEntities.back().h;
334     // Add new workplane elements
335     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
336     for (; aParIter != aParams.end(); aParIter++) {
337       aParIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
338       aParIter->group = myID;
339       aParIter->h = myStorage->addParameter(*aParIter);
340     }
341     std::vector<Slvs_Entity>::iterator anEntIter = anEntities.begin();
342     for (; anEntIter != anEntities.end(); anEntIter++) {
343       anEntIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
344       anEntIter->group = myID;
345       anEntIter->wrkpl = myWorkplaneID;
346       for (int i = 0; i < 4; i++)
347         if (anEntIter->param[i] != SLVS_E_UNKNOWN)
348           anEntIter->param[i] = aParams[anEntIter->param[i]-1].h;
349       for (int i = 0; i < 4; i++)
350         if (anEntIter->point[i] != SLVS_E_UNKNOWN)
351           anEntIter->point[i] = anEntities[anEntIter->point[i]-1].h;
352       anEntIter->h = myStorage->addEntity(*anEntIter);
353     }
354   } else {
355     // Update existent workplane
356     const Slvs_Entity& aWP = myStorage->getEntity(myWorkplaneID);
357     const Slvs_Entity& anOrigin = myStorage->getEntity(aWP.point[0]);
358     const Slvs_Entity& aNormal = myStorage->getEntity(aWP.normal);
359     // Get parameters and update them
360     Slvs_hParam aWPParams[7] = {
361         anOrigin.param[0], anOrigin.param[1], anOrigin.param[2],
362         aNormal.param[0], aNormal.param[1], aNormal.param[2], aNormal.param[3]
363       };
364     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
365     for (int i = 0; aParIter != aParams.end(); aParIter++, i++) {
366       Slvs_Param aParam = myStorage->getParameter(aWPParams[i]);
367       aParam.val = aParIter->val;
368       myStorage->updateParameter(aParam);
369     }
370   }
371   return myWorkplaneID > 0;
372 }
373
374 // ============================================================================
375 //  Function: resolveConstraints
376 //  Class:    SketchSolver_Group
377 //  Purpose:  solve the set of constraints for the current group
378 // ============================================================================
379 bool SketchSolver_Group::resolveConstraints()
380 {
381   bool aResolved = false;
382   if (myStorage->isNeedToResolve() && !isEmpty()) {
383     myConstrSolver.setGroupID(myID);
384     myStorage->initializeSolver(myConstrSolver);
385
386     int aResult = myConstrSolver.solve();
387     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
388       myFeatureStorage->blockEvents(true);
389       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
390       for (; aConstrIter != myConstraints.end(); aConstrIter++)
391         aConstrIter->second->refresh();
392       myFeatureStorage->blockEvents(false);
393     } else if (!myConstraints.empty())
394       Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
395
396     aResolved = true;
397   }
398   removeTemporaryConstraints();
399   myStorage->setNeedToResolve(false);
400   return aResolved;
401 }
402
403 // ============================================================================
404 //  Function: mergeGroups
405 //  Class:    SketchSolver_Group
406 //  Purpose:  append specified group to the current group
407 // ============================================================================
408 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
409 {
410   // If specified group is empty, no need to merge
411   if (theGroup.isEmpty())
412     return;
413   if (!myFeatureStorage)
414     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
415
416   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
417   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
418     changeConstraint(aConstrIter->first);
419 }
420
421 // ============================================================================
422 //  Function: splitGroup
423 //  Class:    SketchSolver_Group
424 //  Purpose:  divide the group into several subgroups
425 // ============================================================================
426 void SketchSolver_Group::splitGroup(std::vector<SketchSolver_Group*>& theCuts)
427 {
428   // Obtain constraints, which should be separated
429   FeatureStoragePtr aNewFeatStorage(new SketchSolver_FeatureStorage);
430   std::vector<ConstraintPtr> anUnusedConstraints;
431   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
432   for ( ; aCIter != myConstraints.end(); aCIter++) {
433     std::list<ConstraintPtr> aBaseConstraints = aCIter->second->constraints();
434     std::list<ConstraintPtr>::iterator anIter = aBaseConstraints.begin();
435     for (; anIter != aBaseConstraints.end(); anIter++)
436       if (aNewFeatStorage->isInteract(*anIter)) {
437         aNewFeatStorage->changeConstraint(*anIter);
438       } else
439         anUnusedConstraints.push_back(*anIter);
440   }
441
442   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
443   std::vector<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
444   while (aUnuseIt != anUnusedConstraints.end()) {
445     if (aNewFeatStorage->isInteract(*aUnuseIt)) {
446       size_t aShift = aUnuseIt - anUnusedConstraints.begin();
447       anUnusedConstraints.erase(aUnuseIt);
448       aUnuseIt = anUnusedConstraints.begin() + aShift;
449       continue;
450     }
451     aUnuseIt++;
452   }
453
454   std::vector<SketchSolver_Group*>::iterator aCutsIter;
455   aUnuseIt = anUnusedConstraints.begin();
456   for ( ; aUnuseIt != anUnusedConstraints.end(); aUnuseIt++) {
457     // Remove unused constraints
458     removeConstraint(*aUnuseIt);
459     // Try to append constraint to already existent group
460     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); aCutsIter++)
461       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
462         (*aCutsIter)->changeConstraint(*aUnuseIt);
463         break;
464       }
465     if (aCutsIter == theCuts.end()) {
466       // Add new group
467       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
468       aGroup->changeConstraint(*aUnuseIt);
469       theCuts.push_back(aGroup);
470     }
471   }
472 }
473
474 // ============================================================================
475 //  Function: isConsistent
476 //  Class:    SketchSolver_Group
477 //  Purpose:  search removed entities and constraints
478 // ============================================================================
479 bool SketchSolver_Group::isConsistent()
480 {
481   if (!myFeatureStorage) // no one constraint is initialized yet
482     return true;
483
484   bool aResult = myFeatureStorage->isConsistent();
485   if (!aResult) {
486     // remove invalid entities
487     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
488     while (aCIter != myConstraints.end()) {
489       std::list<ConstraintPtr> aConstraints = aCIter->second->constraints();
490       std::list<ConstraintPtr>::iterator anIt = aConstraints.begin();
491       for (; anIt != aConstraints.end(); anIt++)
492         if (!(*anIt)->data() || !(*anIt)->data()->isValid())
493           if (aCIter->second->remove(*anIt)) {
494             // the constraint is fully removed, detach it from the list
495             ConstraintConstraintMap::iterator aTmpIt = aCIter++;
496             myFeatureStorage->removeConstraint(aTmpIt->first);
497             myConstraints.erase(aTmpIt);
498             break;
499           }
500       if (anIt == aConstraints.end())
501         aCIter++;
502     }
503   }
504   return aResult;
505 }
506
507 // ============================================================================
508 //  Function: removeTemporaryConstraints
509 //  Class:    SketchSolver_Group
510 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
511 //            resolving the set of constraints
512 // ============================================================================
513 void SketchSolver_Group::removeTemporaryConstraints()
514 {
515   myTempConstraints.clear();
516   // Clean lists of removed entities in the storage
517   std::set<Slvs_hParam> aRemPar;
518   std::set<Slvs_hEntity> aRemEnt;
519   std::set<Slvs_hConstraint> aRemCon;
520   myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
521   myStorage->setNeedToResolve(false);
522 }
523
524 // ============================================================================
525 //  Function: removeConstraint
526 //  Class:    SketchSolver_Group
527 //  Purpose:  remove constraint and all unused entities
528 // ============================================================================
529 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
530 {
531   myFeatureStorage->removeConstraint(theConstraint);
532   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
533   for (; aCIter != myConstraints.end(); aCIter++)
534     if (aCIter->second->hasConstraint(theConstraint)) {
535       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
536         aCIter = myConstraints.end();
537       break;
538     }
539   if (aCIter != myConstraints.end())
540     myConstraints.erase(aCIter);
541 }