1 // Copyright (C) 2014-2019 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include "SketchSolver_Group.h"
21 #include <SketchSolver_Error.h>
22 #include <SketchSolver_Manager.h>
24 #include <PlaneGCSSolver_Solver.h>
25 #include <PlaneGCSSolver_Storage.h>
26 #include <PlaneGCSSolver_Tools.h>
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>
36 #include <Config_Translator.h>
39 static void sendMessage(const char* theMessageName)
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);
46 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
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);
55 static void sendMessage(const char* theMessageName,
56 const CompositeFeaturePtr& theSketch,
59 std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
60 std::shared_ptr<ModelAPI_SolverFailedMessage>(
61 new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
63 std::set<ObjectPtr> anObjects;
64 anObjects.insert(theSketch);
65 aMessage->setObjects(anObjects);
66 aMessage->dof(theDOF);
68 Events_Loop::loop()->send(aMessage);
73 // ========================================================
74 // ========= SketchSolver_Group ===============
75 // ========================================================
77 SketchSolver_Group::SketchSolver_Group(const CompositeFeaturePtr& theWorkplane)
78 : myPrevResult(PlaneGCSSolver_Solver::STATUS_UNKNOWN),
80 myIsEventsBlocked(false),
81 myMultiConstraintUpdateStack(0)
83 mySketchSolver = SolverPtr(new PlaneGCSSolver_Solver);
84 myStorage = StoragePtr(new PlaneGCSSolver_Storage(mySketchSolver));
85 updateSketch(theWorkplane);
88 SketchSolver_Group::~SketchSolver_Group()
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();
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)
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);
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();
118 myConstraints[theConstraint] = aConstraint;
121 myConstraints[theConstraint]->update();
123 // constraint is created/updated => reset stack of "multi" constraints updates
124 myMultiConstraintUpdateStack = 0;
128 bool SketchSolver_Group::updateSketch(CompositeFeaturePtr theSketch)
130 static const double THE_TOLERANCE = 1.e-7;
131 bool isChanged = theSketch != mySketch;
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()));
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);
146 mySketch = theSketch;
147 mySketchOrigin = anOrigin->pnt();
148 mySketchNormal = aNorm->dir();
149 mySketchXDir = aDirX->dir();
151 myStorage->notify(theSketch);
156 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
158 return myStorage->update(theFeature);
161 template <class Type>
162 static SolverConstraintPtr move(StoragePtr theStorage,
163 SolverPtr theSketchSolver,
165 bool theEventsBlocked,
166 Type theFeatureOrPoint,
167 const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
168 const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
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();
177 // Create temporary Fixed constraint
178 std::shared_ptr<SketchSolver_ConstraintMovement> aConstraint =
179 PlaneGCSSolver_Tools::createMovementConstraint(theFeatureOrPoint);
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);
189 theStorage->notify(aConstraint->movedFeature());
195 bool SketchSolver_Group::moveFeature(FeaturePtr theFeature,
196 const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
197 const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
199 SolverConstraintPtr aConstraint =
200 move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theFeature, theFrom, theTo);
201 setTemporary(aConstraint);
205 bool SketchSolver_Group::movePoint(AttributePtr theAttribute,
206 const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
207 const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
209 SolverConstraintPtr aConstraint =
210 move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theAttribute, theFrom, theTo);
211 setTemporary(aConstraint);
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()
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);
234 bool aResolved = false;
235 bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
236 if (myStorage->isNeedToResolve() &&
237 (!isGroupEmpty || !myConflictingConstraints.empty() ||
238 myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED)) {
240 PlaneGCSSolver_Solver::SolveStatus aResult = PlaneGCSSolver_Solver::STATUS_OK;
243 myStorage->adjustParametrizationOfArcs();
244 aResult = mySketchSolver->solve();
246 if (aResult == PlaneGCSSolver_Solver::STATUS_FAILED &&
247 !myTempConstraints.empty()) {
248 mySketchSolver->undo();
249 removeTemporaryConstraints();
250 aResult = mySketchSolver->solve();
252 // check degenerated geometry after constraints resolving
253 if (aResult == PlaneGCSSolver_Solver::STATUS_OK)
254 aResult = myStorage->checkDegeneratedGeometry();
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;
264 mySketchSolver->undo();
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();
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;
277 if (myStorage->isNeedToResolve())
278 aResolved = resolveConstraints();
281 myMultiConstraintUpdateStack -= 1;
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);
294 // show degrees of freedom
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);
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);
319 myConflictingConstraints = aConflicting;
320 if (!myConflictingConstraints.empty())
321 sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
322 myPrevResult = aResult;
326 // show degrees of freedom only if the degenerated geometry appears
327 if (aResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED)
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);
344 removeTemporaryConstraints();
345 myStorage->setNeedToResolve(false);
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()
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
362 // static const std::string aMsgDoF("Sketch is fully fixed (DoF = 0)");
363 // aDoFMsg = Config_Translator::translate(aMsgContext, aMsgDoF);
365 // static const std::string aMsgDoF("DoF (degrees of freedom) = %1");
366 // Events_InfoMessage aMsg(aMsgContext, aMsgDoF);
367 // aMsg.addParameter(aDoF);
368 // aDoFMsg = Config_Translator::translate(aMsg);
370 //// store Unicode value for translated message about DoF
371 //size_t aLen = aDoFMsg.size();
372 //std::wstring aWStr(aLen, L'#');
373 //mbstowcs(&aWStr[0], aDoFMsg.c_str(), aLen);
374 //mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aWStr);
376 std::ostringstream aStr;
378 mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aStr.str());
380 if (aDoF > 0 && myDOF <= 0)
381 sendMessage(EVENT_SKETCH_UNDER_CONSTRAINED, mySketch, aDoF);
382 else if (aDoF == 0 && myDOF != 0)
383 sendMessage(EVENT_SKETCH_FULLY_CONSTRAINED, mySketch, aDoF);
385 sendMessage(EVENT_SKETCH_OVER_CONSTRAINED, mySketch, aDoF);
390 // ============================================================================
391 // Function: repairConsistency
392 // Class: SketchSolver_Group
393 // Purpose: search removed entities and constraints
394 // ============================================================================
395 void SketchSolver_Group::repairConsistency()
397 if (!areConstraintsValid() || !myStorage->areFeaturesValid()) {
398 // remove invalid constraints
399 std::set<ConstraintPtr> anInvalidConstraints;
400 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
401 for (; aCIter != myConstraints.end(); ++aCIter) {
402 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
403 anInvalidConstraints.insert(aCIter->first);
405 std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
406 for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
407 removeConstraint(*aRemoveIt);
409 // remove invalid features
410 myStorage->removeInvalidEntities();
417 // ============================================================================
418 // Function: removeTemporaryConstraints
419 // Class: SketchSolver_Group
420 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
421 // resolving the set of constraints
422 // ============================================================================
423 void SketchSolver_Group::removeTemporaryConstraints()
425 if (!myTempConstraints.empty()) {
426 mySketchSolver->removeConstraint(CID_MOVEMENT);
428 std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
429 for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
432 myTempConstraints.clear();
435 myStorage->setNeedToResolve(false);
438 // ============================================================================
439 // Function: removeConstraint
440 // Class: SketchSolver_Group
441 // Purpose: remove constraint and all unused entities
442 // ============================================================================
443 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
445 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
446 for (; aCIter != myConstraints.end(); aCIter++)
447 if (aCIter->first == theConstraint) {
448 aCIter->second->remove(); // the constraint is not fully removed
450 // constraint is removed => reset stack of "multi" constraints updates
451 myMultiConstraintUpdateStack = 0;
454 if (aCIter != myConstraints.end())
455 myConstraints.erase(aCIter);
458 // ============================================================================
459 // Function: setTemporary
460 // Class: SketchSolver_Group
461 // Purpose: append given constraint to the group of temporary constraints
462 // ============================================================================
463 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
466 myTempConstraints.insert(theConstraint);
469 // ============================================================================
470 // Function: blockEvents
471 // Class: SketchSolver_Group
472 // Purpose: block or unblock events from features in this group
473 // ============================================================================
474 void SketchSolver_Group::blockEvents(bool isBlocked)
476 if (myIsEventsBlocked == isBlocked)
479 // block/unblock events from the features in the storage
480 myStorage->blockEvents(isBlocked);
482 // block/unblock events from constraints
483 ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
484 for (; aCIt != myConstraints.end(); ++aCIt)
485 aCIt->second->blockEvents(isBlocked);
487 myIsEventsBlocked = isBlocked;
490 bool SketchSolver_Group::areConstraintsValid() const
492 // Check the constraints are valid
493 ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
494 for (; aCIter != myConstraints.end(); ++aCIter)
495 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
500 void SketchSolver_Group::underconstrainedFeatures(std::set<ObjectPtr>& theFeatures) const
502 myStorage->getUnderconstrainedGeometry(theFeatures);