Salome HOME
fa98e284e79c2d4482bd83a15b4cf2e545e65647
[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 bool SketchSolver_Group::moveFeature(FeaturePtr theFeature)
119 {
120   bool isFeatureExists = (myStorage->entity(theFeature).get() != 0);
121   if (myDOF == 0 && isFeatureExists) {
122     // avoid moving elements of fully constrained sketch
123     myStorage->refresh();
124     return true;
125   }
126
127   // Create temporary Fixed constraint
128   SolverConstraintPtr aConstraint = PlaneGCSSolver_Tools::createMovementConstraint(theFeature);
129   if (!aConstraint)
130     return false;
131   aConstraint->process(myStorage, myIsEventsBlocked);
132   if (aConstraint->error().empty())
133     setTemporary(aConstraint);
134   else
135     myStorage->notify(theFeature);
136
137   return true;
138 }
139
140 // ============================================================================
141 //  Function: resolveConstraints
142 //  Class:    SketchSolver_Group
143 //  Purpose:  solve the set of constraints for the current group
144 // ============================================================================
145 bool SketchSolver_Group::resolveConstraints()
146 {
147   // check the "Multi" constraints do not drop sketch into infinite loop
148   if (myMultiConstraintUpdateStack > 1) {
149     myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
150     // generate error message due to loop update of the sketch
151     getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
152       ->setValue(SketchSolver_Error::INFINITE_LOOP());
153     sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
154     return false;
155   }
156
157   bool aResolved = false;
158   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
159   if (myStorage->isNeedToResolve() &&
160       (!isGroupEmpty || !myConflictingConstraints.empty() ||
161         myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED)) {
162
163     PlaneGCSSolver_Solver::SolveStatus aResult = PlaneGCSSolver_Solver::STATUS_OK;
164     try {
165       if (!isGroupEmpty && myMultiConstraintUpdateStack <= 1)
166         aResult = mySketchSolver->solve();
167     } catch (...) {
168       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
169         ->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
170       if (myPrevResult == PlaneGCSSolver_Solver::STATUS_OK ||
171           myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
172         // the error message should be changed before sending the message
173         sendMessage(EVENT_SOLVER_FAILED);
174         myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
175       }
176       mySketchSolver->undo();
177       return false;
178     }
179     // solution succeeded, store results into correspondent attributes
180     if (aResult == PlaneGCSSolver_Solver::STATUS_OK ||
181         aResult == PlaneGCSSolver_Solver::STATUS_EMPTYSET) {
182       myStorage->setNeedToResolve(false);
183       myStorage->refresh();
184
185       // additional check that copied entities used in Mirror and other "Multi" constraints
186       // is not connected with their originals by constraints.
187       myMultiConstraintUpdateStack += 1;
188       updateMultiConstraints();
189       aResolved = true;
190       if (myStorage->isNeedToResolve())
191         aResolved = resolveConstraints();
192
193       if (aResolved) {
194         myMultiConstraintUpdateStack -= 1;
195
196         if (myPrevResult != PlaneGCSSolver_Solver::STATUS_OK ||
197             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
198           getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
199           std::set<ObjectPtr> aConflicting = myConflictingConstraints;
200           myConflictingConstraints.clear();
201           myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
202           // the error message should be changed before sending the message
203           sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
204         }
205       }
206
207       // show degrees of freedom
208       computeDoF();
209     } else {
210       mySketchSolver->undo();
211       if (!myConstraints.empty()) {
212         // the error message should be changed before sending the message
213         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
214           ->setValue(SketchSolver_Error::CONSTRAINTS());
215         if (myPrevResult != aResult ||
216             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN ||
217             myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED) {
218           // Obtain list of conflicting constraints
219           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
220
221           if (!myConflictingConstraints.empty()) {
222             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
223             for (; anIt != aConflicting.end(); ++anIt)
224               myConflictingConstraints.erase(*anIt);
225             if (!myConflictingConstraints.empty()) {
226               // some constraints does not conflict, send corresponding message
227               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
228             }
229           }
230           myConflictingConstraints = aConflicting;
231           if (!myConflictingConstraints.empty())
232             sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
233           myPrevResult = aResult;
234         }
235       }
236     }
237
238   } else if (isGroupEmpty && isWorkplaneValid())
239     computeDoF();
240   removeTemporaryConstraints();
241   myStorage->setNeedToResolve(false);
242   return aResolved;
243 }
244
245 // ============================================================================
246 //  Function: computeDoF
247 //  Class:    SketchSolver_Group
248 //  Purpose:  compute DoF of the sketch and set corresponding field
249 // ============================================================================
250 void SketchSolver_Group::computeDoF()
251 {
252   std::ostringstream aDoFMsg;
253   int aDoF = mySketchSolver->dof();
254   if (aDoF == 0)
255     aDoFMsg << "Sketch is fully fixed (DoF = 0)";
256   else
257     aDoFMsg << "DoF (degrees of freedom) = " << aDoF;
258   mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aDoFMsg.str());
259
260   if (aDoF > 0 && myDOF == 0)
261     sendMessage(EVENT_SKETCH_UNDER_CONSTRAINED, mySketch, aDoF);
262   else if (aDoF == 0 && myDOF > 0)
263     sendMessage(EVENT_SKETCH_FULLY_CONSTRAINED, mySketch, aDoF);
264   else if (aDoF < 0)
265     sendMessage(EVENT_SKETCH_OVER_CONSTRAINED, mySketch, aDoF);
266
267   myDOF = aDoF;
268 }
269
270 // ============================================================================
271 //  Function: repairConsistency
272 //  Class:    SketchSolver_Group
273 //  Purpose:  search removed entities and constraints
274 // ============================================================================
275 void SketchSolver_Group::repairConsistency()
276 {
277   if (!myStorage->isConsistent()) {
278     // remove invalid constraints
279     std::set<ConstraintPtr> anInvalidConstraints;
280     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
281     for (; aCIter != myConstraints.end(); ++aCIter) {
282       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
283         anInvalidConstraints.insert(aCIter->first);
284     }
285     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
286     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
287       removeConstraint(*aRemoveIt);
288
289     // remove invalid features
290     myStorage->removeInvalidEntities();
291
292     // show DoF
293     computeDoF();
294   }
295 }
296
297 // ============================================================================
298 //  Function: removeTemporaryConstraints
299 //  Class:    SketchSolver_Group
300 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
301 //            resolving the set of constraints
302 // ============================================================================
303 void SketchSolver_Group::removeTemporaryConstraints()
304 {
305   if (!myTempConstraints.empty()) {
306     mySketchSolver->removeConstraint(CID_MOVEMENT);
307
308     std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
309     for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
310       (*aTmpIt)->remove();
311
312     myTempConstraints.clear();
313   }
314
315   myStorage->setNeedToResolve(false);
316 }
317
318 // ============================================================================
319 //  Function: removeConstraint
320 //  Class:    SketchSolver_Group
321 //  Purpose:  remove constraint and all unused entities
322 // ============================================================================
323 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
324 {
325   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
326   for (; aCIter != myConstraints.end(); aCIter++)
327     if (aCIter->first == theConstraint) {
328       aCIter->second->remove(); // the constraint is not fully removed
329
330       // constraint is removed => reset stack of "multi" constraints updates
331       myMultiConstraintUpdateStack = 0;
332       break;
333     }
334   if (aCIter != myConstraints.end())
335     myConstraints.erase(aCIter);
336 }
337
338 // ============================================================================
339 //  Function: setTemporary
340 //  Class:    SketchSolver_Group
341 //  Purpose:  append given constraint to the group of temporary constraints
342 // ============================================================================
343 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
344 {
345   myTempConstraints.insert(theConstraint);
346 }
347
348 // ============================================================================
349 //  Function: blockEvents
350 //  Class:    SketchSolver_Group
351 //  Purpose:  block or unblock events from features in this group
352 // ============================================================================
353 void SketchSolver_Group::blockEvents(bool isBlocked)
354 {
355   if (myIsEventsBlocked == isBlocked)
356     return;
357
358   // block/unblock events from the features in the storage
359   myStorage->blockEvents(isBlocked);
360
361   // block/unblock events from constraints
362   ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
363   for (; aCIt != myConstraints.end(); ++aCIt)
364     aCIt->second->blockEvents(isBlocked);
365
366   myIsEventsBlocked = isBlocked;
367 }
368
369 // ============================================================================
370 //  Function: updateMultiConstraints
371 //  Class:    SketchSolver_Group
372 //  Purpose:  update multi constraints
373 // ============================================================================
374 void SketchSolver_Group::updateMultiConstraints()
375 {
376   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
377   for (; anIt != myConstraints.end(); ++anIt) {
378     if (anIt->first->getKind() == SketchPlugin_ConstraintMirror::ID() ||
379         anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
380         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
381       anIt->second->update();
382   }
383 }