]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_Group.cpp
Salome HOME
Task 2.4. Ability to modify the radius of circles and arcs of circle with the mouse
[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 #include <SketchSolver_Error.h>
9 #include <SketchSolver_Manager.h>
10
11 #include <PlaneGCSSolver_Solver.h>
12 #include <PlaneGCSSolver_Storage.h>
13 #include <PlaneGCSSolver_Tools.h>
14
15 #include <Events_InfoMessage.h>
16 #include <ModelAPI_AttributeString.h>
17 #include <ModelAPI_Events.h>
18 #include <SketchPlugin_ConstraintMirror.h>
19 #include <SketchPlugin_ConstraintRigid.h>
20 #include <SketchPlugin_MultiRotation.h>
21 #include <SketchPlugin_MultiTranslation.h>
22
23
24 static void sendMessage(const char* theMessageName)
25 {
26   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
27       new Events_Message(Events_Loop::eventByName(theMessageName)));
28   Events_Loop::loop()->send(aMessage);
29 }
30
31 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
32 {
33   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
34       std::shared_ptr<ModelAPI_SolverFailedMessage>(
35       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
36   aMessage->setObjects(theConflicting);
37   Events_Loop::loop()->send(aMessage);
38 }
39
40 static void sendMessage(const char* theMessageName,
41                         const CompositeFeaturePtr& theSketch,
42                         const int theDOF)
43 {
44   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
45       std::shared_ptr<ModelAPI_SolverFailedMessage>(
46       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
47
48   std::set<ObjectPtr> anObjects;
49   anObjects.insert(theSketch);
50   aMessage->setObjects(anObjects);
51   aMessage->dof(theDOF);
52
53   Events_Loop::loop()->send(aMessage);
54 }
55
56
57
58 // ========================================================
59 // =========       SketchSolver_Group       ===============
60 // ========================================================
61
62 SketchSolver_Group::SketchSolver_Group(const CompositeFeaturePtr& theWorkplane)
63   : mySketch(theWorkplane),
64     myPrevResult(PlaneGCSSolver_Solver::STATUS_UNKNOWN),
65     myDOF(0),
66     myIsEventsBlocked(false),
67     myMultiConstraintUpdateStack(0)
68 {
69   mySketchSolver = SolverPtr(new PlaneGCSSolver_Solver);
70   myStorage = StoragePtr(new PlaneGCSSolver_Storage(mySketchSolver));
71 }
72
73 SketchSolver_Group::~SketchSolver_Group()
74 {
75   myConstraints.clear();
76   // send the message that there is no more conflicting constraints
77   if (!myConflictingConstraints.empty()) {
78     sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
79     myConflictingConstraints.clear();
80   }
81 }
82
83 // ============================================================================
84 //  Function: changeConstraint
85 //  Class:    SketchSolver_Group
86 //  Purpose:  create/update the constraint in the group
87 // ============================================================================
88 bool SketchSolver_Group::changeConstraint(
89     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
90 {
91   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
92   if (isNewConstraint) {
93     // Add constraint to the current group
94     SolverConstraintPtr aConstraint = PlaneGCSSolver_Tools::createConstraint(theConstraint);
95     if (!aConstraint)
96       return false;
97     aConstraint->process(myStorage, myIsEventsBlocked);
98     if (!aConstraint->error().empty()) {
99       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
100         return false; // some attribute are not initialized yet, don't show message
101       Events_InfoMessage("SketchSolver_Group", aConstraint->error(), this).send();
102     }
103     myConstraints[theConstraint] = aConstraint;
104   }
105   else
106     myConstraints[theConstraint]->update();
107
108   // constraint is created/updated => reset stack of "multi" constraints updates
109   myMultiConstraintUpdateStack = 0;
110   return true;
111 }
112
113 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
114 {
115   return myStorage->update(theFeature);
116 }
117
118 template <class Type>
119 static SolverConstraintPtr move(StoragePtr theStorage,
120                                 SolverPtr theSketchSolver,
121                                 int theSketchDOF,
122                                 bool theEventsBlocked,
123                                 Type theFeatureOrPoint,
124                                 const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
125                                 const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
126 {
127   bool isEntityExists = (theStorage->entity(theFeatureOrPoint).get() != 0);
128   if (theSketchDOF == 0 && isEntityExists) {
129     // avoid moving elements of fully constrained sketch
130     theStorage->refresh();
131     return SolverConstraintPtr();
132   }
133
134   // Create temporary Fixed constraint
135   std::shared_ptr<SketchSolver_ConstraintMovement> aConstraint =
136       PlaneGCSSolver_Tools::createMovementConstraint(theFeatureOrPoint);
137   if (aConstraint) {
138     SolverConstraintPtr(aConstraint)->process(theStorage, theEventsBlocked);
139     if (aConstraint->error().empty()) {
140       aConstraint->startPoint(theFrom);
141       theSketchSolver->initialize();
142       aConstraint->moveTo(theTo);
143       theStorage->setNeedToResolve(true);
144     } else
145       theStorage->notify(aConstraint->movedFeature());
146   }
147
148   return aConstraint;
149 }
150
151 bool SketchSolver_Group::moveFeature(FeaturePtr theFeature,
152                                      const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
153                                      const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
154 {
155   SolverConstraintPtr aConstraint =
156       move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theFeature, theFrom, theTo);
157   setTemporary(aConstraint);
158   return true;
159 }
160
161 bool SketchSolver_Group::movePoint(AttributePtr theAttribute,
162                                    const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
163                                    const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
164 {
165   SolverConstraintPtr aConstraint =
166       move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theAttribute, theFrom, theTo);
167   setTemporary(aConstraint);
168   return true;
169 }
170
171 // ============================================================================
172 //  Function: resolveConstraints
173 //  Class:    SketchSolver_Group
174 //  Purpose:  solve the set of constraints for the current group
175 // ============================================================================
176 bool SketchSolver_Group::resolveConstraints()
177 {
178   static const int MAX_STACK_SIZE = 5;
179   // check the "Multi" constraints do not drop sketch into infinite loop
180   if (myMultiConstraintUpdateStack > MAX_STACK_SIZE) {
181     myMultiConstraintUpdateStack = 0;
182     myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
183     // generate error message due to loop update of the sketch
184     getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
185       ->setValue(SketchSolver_Error::INFINITE_LOOP());
186     sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
187     return false;
188   }
189
190   bool aResolved = false;
191   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
192   if (myStorage->isNeedToResolve() &&
193       (!isGroupEmpty || !myConflictingConstraints.empty() ||
194         myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED)) {
195
196     PlaneGCSSolver_Solver::SolveStatus aResult = PlaneGCSSolver_Solver::STATUS_OK;
197     try {
198       if (!isGroupEmpty)
199         aResult = mySketchSolver->solve();
200       if (aResult == PlaneGCSSolver_Solver::STATUS_FAILED &&
201           !myTempConstraints.empty()) {
202         mySketchSolver->undo();
203         removeTemporaryConstraints();
204         aResult = mySketchSolver->solve();
205       }
206     } catch (...) {
207       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
208         ->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
209       if (myPrevResult == PlaneGCSSolver_Solver::STATUS_OK ||
210           myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
211         // the error message should be changed before sending the message
212         sendMessage(EVENT_SOLVER_FAILED);
213         myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
214       }
215       mySketchSolver->undo();
216       return false;
217     }
218     // solution succeeded, store results into correspondent attributes
219     if (aResult == PlaneGCSSolver_Solver::STATUS_OK ||
220         aResult == PlaneGCSSolver_Solver::STATUS_EMPTYSET) {
221       myStorage->setNeedToResolve(false);
222       myStorage->refresh();
223
224       // additional check that copied entities used in Mirror and other "Multi" constraints
225       // is not connected with their originals by constraints.
226       myMultiConstraintUpdateStack += 1;
227       aResolved = true;
228       if (myStorage->isNeedToResolve())
229         aResolved = resolveConstraints();
230
231       if (aResolved) {
232         myMultiConstraintUpdateStack -= 1;
233
234         if (myPrevResult != PlaneGCSSolver_Solver::STATUS_OK ||
235             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
236           getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
237           std::set<ObjectPtr> aConflicting = myConflictingConstraints;
238           myConflictingConstraints.clear();
239           myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
240           // the error message should be changed before sending the message
241           sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
242         }
243       }
244
245       // show degrees of freedom
246       computeDoF();
247     } else {
248       mySketchSolver->undo();
249       if (!myConstraints.empty()) {
250         // the error message should be changed before sending the message
251         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
252           ->setValue(SketchSolver_Error::CONSTRAINTS());
253         if (myPrevResult != aResult ||
254             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN ||
255             myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED) {
256           // Obtain list of conflicting constraints
257           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
258
259           if (!myConflictingConstraints.empty()) {
260             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
261             for (; anIt != aConflicting.end(); ++anIt)
262               myConflictingConstraints.erase(*anIt);
263             if (!myConflictingConstraints.empty()) {
264               // some constraints does not conflict, send corresponding message
265               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
266             }
267           }
268           myConflictingConstraints = aConflicting;
269           if (!myConflictingConstraints.empty())
270             sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
271           myPrevResult = aResult;
272         }
273       }
274     }
275
276   } else if (isGroupEmpty && isWorkplaneValid())
277     computeDoF();
278   removeTemporaryConstraints();
279   myStorage->setNeedToResolve(false);
280   return aResolved;
281 }
282
283 // ============================================================================
284 //  Function: computeDoF
285 //  Class:    SketchSolver_Group
286 //  Purpose:  compute DoF of the sketch and set corresponding field
287 // ============================================================================
288 void SketchSolver_Group::computeDoF()
289 {
290   std::ostringstream aDoFMsg;
291   int aDoF = mySketchSolver->dof();
292   /// "DoF = 0" content of string value is used in PartSet by Sketch edit
293   /// If it is changed, it should be corrected also there
294   if (aDoF == 0)
295     aDoFMsg << "Sketch is fully fixed (DoF = 0)";
296   else
297     aDoFMsg << "DoF (degrees of freedom) = " << aDoF;
298   mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aDoFMsg.str());
299
300   if (aDoF > 0 && myDOF == 0)
301     sendMessage(EVENT_SKETCH_UNDER_CONSTRAINED, mySketch, aDoF);
302   else if (aDoF == 0 && myDOF > 0)
303     sendMessage(EVENT_SKETCH_FULLY_CONSTRAINED, mySketch, aDoF);
304   else if (aDoF < 0)
305     sendMessage(EVENT_SKETCH_OVER_CONSTRAINED, mySketch, aDoF);
306
307   myDOF = aDoF;
308 }
309
310 // ============================================================================
311 //  Function: repairConsistency
312 //  Class:    SketchSolver_Group
313 //  Purpose:  search removed entities and constraints
314 // ============================================================================
315 void SketchSolver_Group::repairConsistency()
316 {
317   if (!areConstraintsValid() || !myStorage->areFeaturesValid()) {
318     // remove invalid constraints
319     std::set<ConstraintPtr> anInvalidConstraints;
320     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
321     for (; aCIter != myConstraints.end(); ++aCIter) {
322       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
323         anInvalidConstraints.insert(aCIter->first);
324     }
325     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
326     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
327       removeConstraint(*aRemoveIt);
328
329     // remove invalid features
330     myStorage->removeInvalidEntities();
331
332     // show DoF
333     computeDoF();
334   }
335 }
336
337 // ============================================================================
338 //  Function: removeTemporaryConstraints
339 //  Class:    SketchSolver_Group
340 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
341 //            resolving the set of constraints
342 // ============================================================================
343 void SketchSolver_Group::removeTemporaryConstraints()
344 {
345   if (!myTempConstraints.empty()) {
346     mySketchSolver->removeConstraint(CID_MOVEMENT);
347
348     std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
349     for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
350       (*aTmpIt)->remove();
351
352     myTempConstraints.clear();
353   }
354
355   myStorage->setNeedToResolve(false);
356 }
357
358 // ============================================================================
359 //  Function: removeConstraint
360 //  Class:    SketchSolver_Group
361 //  Purpose:  remove constraint and all unused entities
362 // ============================================================================
363 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
364 {
365   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
366   for (; aCIter != myConstraints.end(); aCIter++)
367     if (aCIter->first == theConstraint) {
368       aCIter->second->remove(); // the constraint is not fully removed
369
370       // constraint is removed => reset stack of "multi" constraints updates
371       myMultiConstraintUpdateStack = 0;
372       break;
373     }
374   if (aCIter != myConstraints.end())
375     myConstraints.erase(aCIter);
376 }
377
378 // ============================================================================
379 //  Function: setTemporary
380 //  Class:    SketchSolver_Group
381 //  Purpose:  append given constraint to the group of temporary constraints
382 // ============================================================================
383 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
384 {
385   if (theConstraint)
386     myTempConstraints.insert(theConstraint);
387 }
388
389 // ============================================================================
390 //  Function: blockEvents
391 //  Class:    SketchSolver_Group
392 //  Purpose:  block or unblock events from features in this group
393 // ============================================================================
394 void SketchSolver_Group::blockEvents(bool isBlocked)
395 {
396   if (myIsEventsBlocked == isBlocked)
397     return;
398
399   // block/unblock events from the features in the storage
400   myStorage->blockEvents(isBlocked);
401
402   // block/unblock events from constraints
403   ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
404   for (; aCIt != myConstraints.end(); ++aCIt)
405     aCIt->second->blockEvents(isBlocked);
406
407   myIsEventsBlocked = isBlocked;
408 }
409
410 bool SketchSolver_Group::areConstraintsValid() const
411 {
412   // Check the constraints are valid
413   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
414   for (; aCIter != myConstraints.end(); ++aCIter)
415     if (!aCIter->first->data() || !aCIter->first->data()->isValid())
416       return false;
417   return true;
418 }