Salome HOME
28d5550ab198b94e2490468c2d60027ad1c0a986
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "SketchSolver_Group.h"
21 #include <SketchSolver_Error.h>
22 #include <SketchSolver_Manager.h>
23
24 #include <PlaneGCSSolver_Solver.h>
25 #include <PlaneGCSSolver_Storage.h>
26 #include <PlaneGCSSolver_Tools.h>
27
28 #include <Events_InfoMessage.h>
29 #include <ModelAPI_AttributeString.h>
30 #include <ModelAPI_Events.h>
31 #include <SketchPlugin_ConstraintMirror.h>
32 #include <SketchPlugin_ConstraintRigid.h>
33 #include <SketchPlugin_MultiRotation.h>
34 #include <SketchPlugin_MultiTranslation.h>
35
36 #include <Config_Translator.h>
37
38
39 static void sendMessage(const char* theMessageName)
40 {
41   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
42       new Events_Message(Events_Loop::eventByName(theMessageName)));
43   Events_Loop::loop()->send(aMessage);
44 }
45
46 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
47 {
48   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
49       std::shared_ptr<ModelAPI_SolverFailedMessage>(
50       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
51   aMessage->setObjects(theConflicting);
52   Events_Loop::loop()->send(aMessage);
53 }
54
55 static void sendMessage(const char* theMessageName,
56                         const CompositeFeaturePtr& theSketch,
57                         const int theDOF)
58 {
59   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
60       std::shared_ptr<ModelAPI_SolverFailedMessage>(
61       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
62
63   std::set<ObjectPtr> anObjects;
64   anObjects.insert(theSketch);
65   aMessage->setObjects(anObjects);
66   aMessage->dof(theDOF);
67
68   Events_Loop::loop()->send(aMessage);
69 }
70
71
72
73 // ========================================================
74 // =========       SketchSolver_Group       ===============
75 // ========================================================
76
77 SketchSolver_Group::SketchSolver_Group(const CompositeFeaturePtr& theWorkplane)
78   : myPrevResult(PlaneGCSSolver_Solver::STATUS_UNKNOWN),
79     myDOF(-1),
80     myIsEventsBlocked(false),
81     myMultiConstraintUpdateStack(0)
82 {
83   mySketchSolver = SolverPtr(new PlaneGCSSolver_Solver);
84   myStorage = StoragePtr(new PlaneGCSSolver_Storage(mySketchSolver));
85   updateSketch(theWorkplane);
86 }
87
88 SketchSolver_Group::~SketchSolver_Group()
89 {
90   myConstraints.clear();
91   // send the message that there is no more conflicting constraints
92   if (!myConflictingConstraints.empty()) {
93     sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
94     myConflictingConstraints.clear();
95   }
96 }
97
98 // ============================================================================
99 //  Function: changeConstraint
100 //  Class:    SketchSolver_Group
101 //  Purpose:  create/update the constraint in the group
102 // ============================================================================
103 bool SketchSolver_Group::changeConstraint(
104     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
105 {
106   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
107   if (isNewConstraint) {
108     // Add constraint to the current group
109     SolverConstraintPtr aConstraint = PlaneGCSSolver_Tools::createConstraint(theConstraint);
110     if (!aConstraint)
111       return false;
112     aConstraint->process(myStorage, myIsEventsBlocked);
113     if (!aConstraint->error().empty()) {
114       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
115         return false; // some attribute are not initialized yet, don't show message
116       Events_InfoMessage("SketchSolver_Group", aConstraint->error(), this).send();
117     }
118     myConstraints[theConstraint] = aConstraint;
119   }
120   else
121     myConstraints[theConstraint]->update();
122
123   // constraint is created/updated => reset stack of "multi" constraints updates
124   myMultiConstraintUpdateStack = 0;
125   return true;
126 }
127
128 bool SketchSolver_Group::updateSketch(CompositeFeaturePtr theSketch)
129 {
130   static const double THE_TOLERANCE = 1.e-7;
131   bool isChanged = theSketch != mySketch;
132
133   AttributePointPtr anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
134       theSketch->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
135   AttributeDirPtr aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
136       theSketch->attribute(SketchPlugin_Sketch::NORM_ID()));
137   AttributeDirPtr aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
138       theSketch->attribute(SketchPlugin_Sketch::DIRX_ID()));
139
140   isChanged = isChanged
141       || (mySketchOrigin && anOrigin && anOrigin->pnt()->distance(mySketchOrigin) > THE_TOLERANCE)
142       || (mySketchNormal && aNorm && aNorm->xyz()->distance(mySketchNormal->xyz()) > THE_TOLERANCE)
143       || (mySketchXDir && aDirX && aDirX->xyz()->distance(mySketchXDir->xyz()) > THE_TOLERANCE);
144
145   if (isChanged) {
146     mySketch = theSketch;
147     mySketchOrigin = anOrigin->pnt();
148     mySketchNormal = aNorm->dir();
149     mySketchXDir = aDirX->dir();
150
151     myStorage->notify(theSketch);
152   }
153   return true;
154 }
155
156 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
157 {
158   return myStorage->update(theFeature);
159 }
160
161 template <class Type>
162 static SolverConstraintPtr move(StoragePtr theStorage,
163                                 SolverPtr theSketchSolver,
164                                 int theSketchDOF,
165                                 bool theEventsBlocked,
166                                 Type theFeatureOrPoint,
167                                 const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
168                                 const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
169 {
170   bool isEntityExists = (theStorage->entity(theFeatureOrPoint).get() != 0);
171   if (theSketchDOF == 0 && isEntityExists) {
172     // avoid moving elements of fully constrained sketch
173     theStorage->refresh();
174     return SolverConstraintPtr();
175   }
176
177   // Create temporary Fixed constraint
178   std::shared_ptr<SketchSolver_ConstraintMovement> aConstraint =
179       PlaneGCSSolver_Tools::createMovementConstraint(theFeatureOrPoint);
180   if (aConstraint) {
181     SolverConstraintPtr(aConstraint)->process(theStorage, theEventsBlocked);
182     if (aConstraint->error().empty()) {
183       aConstraint->startPoint(theFrom);
184       theStorage->adjustParametrizationOfArcs();
185       theSketchSolver->initialize();
186       aConstraint->moveTo(theTo);
187       theStorage->setNeedToResolve(true);
188     } else
189       theStorage->notify(aConstraint->movedFeature());
190   }
191
192   return aConstraint;
193 }
194
195 bool SketchSolver_Group::moveFeature(FeaturePtr theFeature,
196                                      const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
197                                      const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
198 {
199   SolverConstraintPtr aConstraint =
200       move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theFeature, theFrom, theTo);
201   setTemporary(aConstraint);
202   return true;
203 }
204
205 bool SketchSolver_Group::movePoint(AttributePtr theAttribute,
206                                    const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
207                                    const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
208 {
209   SolverConstraintPtr aConstraint =
210       move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theAttribute, theFrom, theTo);
211   setTemporary(aConstraint);
212   return true;
213 }
214
215 // ============================================================================
216 //  Function: resolveConstraints
217 //  Class:    SketchSolver_Group
218 //  Purpose:  solve the set of constraints for the current group
219 // ============================================================================
220 bool SketchSolver_Group::resolveConstraints()
221 {
222   static const int MAX_STACK_SIZE = 5;
223   // check the "Multi" constraints do not drop sketch into infinite loop
224   if (myMultiConstraintUpdateStack > MAX_STACK_SIZE) {
225     myMultiConstraintUpdateStack = 0;
226     myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
227     // generate error message due to loop update of the sketch
228     getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
229       ->setValue(SketchSolver_Error::INFINITE_LOOP());
230     sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
231     return false;
232   }
233
234   bool aResolved = false;
235   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
236   if (myStorage->isNeedToResolve() &&
237       (!isGroupEmpty || !myConflictingConstraints.empty() ||
238         myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED)) {
239
240     PlaneGCSSolver_Solver::SolveStatus aResult = PlaneGCSSolver_Solver::STATUS_OK;
241     try {
242       if (!isGroupEmpty) {
243         myStorage->adjustParametrizationOfArcs();
244         aResult = mySketchSolver->solve();
245       }
246       if (aResult == PlaneGCSSolver_Solver::STATUS_FAILED &&
247           !myTempConstraints.empty()) {
248         mySketchSolver->undo();
249         removeTemporaryConstraints();
250         aResult = mySketchSolver->solve();
251       }
252       // check degenerated geometry after constraints resolving
253       if (aResult == PlaneGCSSolver_Solver::STATUS_OK)
254         aResult = myStorage->checkDegeneratedGeometry();
255     } catch (...) {
256       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
257         ->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
258       if (myPrevResult == PlaneGCSSolver_Solver::STATUS_OK ||
259           myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
260         // the error message should be changed before sending the message
261         sendMessage(EVENT_SOLVER_FAILED);
262         myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
263       }
264       mySketchSolver->undo();
265       return false;
266     }
267     // solution succeeded, store results into correspondent attributes
268     if (aResult == PlaneGCSSolver_Solver::STATUS_OK ||
269         aResult == PlaneGCSSolver_Solver::STATUS_EMPTYSET) {
270       myStorage->setNeedToResolve(false);
271       myStorage->refresh();
272
273       // additional check that copied entities used in Mirror and other "Multi" constraints
274       // is not connected with their originals by constraints.
275       myMultiConstraintUpdateStack += 1;
276       aResolved = true;
277       if (myStorage->isNeedToResolve())
278         aResolved = resolveConstraints();
279
280       if (aResolved) {
281         myMultiConstraintUpdateStack -= 1;
282
283         if (myPrevResult != PlaneGCSSolver_Solver::STATUS_OK ||
284             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
285           getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
286           std::set<ObjectPtr> aConflicting = myConflictingConstraints;
287           myConflictingConstraints.clear();
288           myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
289           // the error message should be changed before sending the message
290           sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
291         }
292       }
293
294       // show degrees of freedom
295       computeDoF();
296     } else {
297       mySketchSolver->undo();
298       if (!myConstraints.empty()) {
299         // the error message should be changed before sending the message
300         const std::string& aErrorMsg = aResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED ?
301                                        SketchSolver_Error::DEGENERATED_GEOMETRY() :
302                                        SketchSolver_Error::CONSTRAINTS();
303         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(aErrorMsg);
304         if (myPrevResult != aResult ||
305             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN ||
306             myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED) {
307           // Obtain list of conflicting constraints
308           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
309
310           if (!myConflictingConstraints.empty()) {
311             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
312             for (; anIt != aConflicting.end(); ++anIt)
313               myConflictingConstraints.erase(*anIt);
314             if (!myConflictingConstraints.empty()) {
315               // some constraints does not conflict, send corresponding message
316               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
317             }
318           }
319           myConflictingConstraints = aConflicting;
320           if (!myConflictingConstraints.empty())
321             sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
322           myPrevResult = aResult;
323         }
324       }
325
326       // show degrees of freedom only if the degenerated geometry appears
327       if (aResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED)
328         computeDoF();
329     }
330
331   }
332   else if (isGroupEmpty && isWorkplaneValid()) {
333     // clear error related to previously degenerated entities
334     if (myPrevResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED) {
335       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
336       myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
337       // the error message should be changed before sending the message
338       myConflictingConstraints.clear();
339       sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
340     }
341
342     computeDoF();
343   }
344   removeTemporaryConstraints();
345   myStorage->setNeedToResolve(false);
346   return aResolved;
347 }
348
349 // ============================================================================
350 //  Function: computeDoF
351 //  Class:    SketchSolver_Group
352 //  Purpose:  compute DoF of the sketch and set corresponding field
353 // ============================================================================
354 void SketchSolver_Group::computeDoF()
355 {
356   std::ostringstream aDoFMsg;
357   static const std::string aMsgContext("Sketch");
358   int aDoF = mySketchSolver->dof();
359   /// "DoF = 0" content of string value is used in PartSet by Sketch edit
360   /// If it is changed, it should be corrected also there
361   if (aDoF == 0) {
362     static const std::string aMsgDoF("Sketch is fully fixed (DoF = 0)");
363     aDoFMsg << Config_Translator::translate(aMsgContext, aMsgDoF).c_str();
364   } else {
365     static const std::string aMsgDoF("DoF (degrees of freedom) = %1");
366     Events_InfoMessage aMsg(aMsgContext, aMsgDoF);
367     aMsg.arg(aDoF);
368     aDoFMsg << Config_Translator::translate(aMsg).c_str();
369   }
370   mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aDoFMsg.str());
371
372   if (aDoF > 0 && myDOF <= 0)
373     sendMessage(EVENT_SKETCH_UNDER_CONSTRAINED, mySketch, aDoF);
374   else if (aDoF == 0 && myDOF != 0)
375     sendMessage(EVENT_SKETCH_FULLY_CONSTRAINED, mySketch, aDoF);
376   else if (aDoF < 0)
377     sendMessage(EVENT_SKETCH_OVER_CONSTRAINED, mySketch, aDoF);
378
379   myDOF = aDoF;
380 }
381
382 // ============================================================================
383 //  Function: repairConsistency
384 //  Class:    SketchSolver_Group
385 //  Purpose:  search removed entities and constraints
386 // ============================================================================
387 void SketchSolver_Group::repairConsistency()
388 {
389   if (!areConstraintsValid() || !myStorage->areFeaturesValid()) {
390     // remove invalid constraints
391     std::set<ConstraintPtr> anInvalidConstraints;
392     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
393     for (; aCIter != myConstraints.end(); ++aCIter) {
394       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
395         anInvalidConstraints.insert(aCIter->first);
396     }
397     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
398     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
399       removeConstraint(*aRemoveIt);
400
401     // remove invalid features
402     myStorage->removeInvalidEntities();
403
404     // show DoF
405     computeDoF();
406   }
407 }
408
409 // ============================================================================
410 //  Function: removeTemporaryConstraints
411 //  Class:    SketchSolver_Group
412 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
413 //            resolving the set of constraints
414 // ============================================================================
415 void SketchSolver_Group::removeTemporaryConstraints()
416 {
417   if (!myTempConstraints.empty()) {
418     mySketchSolver->removeConstraint(CID_MOVEMENT);
419
420     std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
421     for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
422       (*aTmpIt)->remove();
423
424     myTempConstraints.clear();
425   }
426
427   myStorage->setNeedToResolve(false);
428 }
429
430 // ============================================================================
431 //  Function: removeConstraint
432 //  Class:    SketchSolver_Group
433 //  Purpose:  remove constraint and all unused entities
434 // ============================================================================
435 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
436 {
437   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
438   for (; aCIter != myConstraints.end(); aCIter++)
439     if (aCIter->first == theConstraint) {
440       aCIter->second->remove(); // the constraint is not fully removed
441
442       // constraint is removed => reset stack of "multi" constraints updates
443       myMultiConstraintUpdateStack = 0;
444       break;
445     }
446   if (aCIter != myConstraints.end())
447     myConstraints.erase(aCIter);
448 }
449
450 // ============================================================================
451 //  Function: setTemporary
452 //  Class:    SketchSolver_Group
453 //  Purpose:  append given constraint to the group of temporary constraints
454 // ============================================================================
455 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
456 {
457   if (theConstraint)
458     myTempConstraints.insert(theConstraint);
459 }
460
461 // ============================================================================
462 //  Function: blockEvents
463 //  Class:    SketchSolver_Group
464 //  Purpose:  block or unblock events from features in this group
465 // ============================================================================
466 void SketchSolver_Group::blockEvents(bool isBlocked)
467 {
468   if (myIsEventsBlocked == isBlocked)
469     return;
470
471   // block/unblock events from the features in the storage
472   myStorage->blockEvents(isBlocked);
473
474   // block/unblock events from constraints
475   ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
476   for (; aCIt != myConstraints.end(); ++aCIt)
477     aCIt->second->blockEvents(isBlocked);
478
479   myIsEventsBlocked = isBlocked;
480 }
481
482 bool SketchSolver_Group::areConstraintsValid() const
483 {
484   // Check the constraints are valid
485   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
486   for (; aCIter != myConstraints.end(); ++aCIter)
487     if (!aCIter->first->data() || !aCIter->first->data()->isValid())
488       return false;
489   return true;
490 }