1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: SketchSolver_Group.cpp
4 // Created: 27 May 2014
5 // Author: Artem ZHIDKOV
7 #include "SketchSolver_Group.h"
9 #include <SketchSolver_Constraint.h>
10 #include <SketchSolver_ConstraintCoincidence.h>
11 #include <SketchSolver_ConstraintMulti.h>
12 #include <SketchSolver_Error.h>
13 #include <SketchSolver_Manager.h>
15 #include <Events_Error.h>
16 #include <Events_Loop.h>
17 #include <ModelAPI_AttributeString.h>
18 #include <ModelAPI_Events.h>
19 #include <ModelAPI_Session.h>
20 #include <ModelAPI_Validator.h>
22 #include <SketchPlugin_ConstraintAngle.h>
23 #include <SketchPlugin_ConstraintCoincidence.h>
24 #include <SketchPlugin_ConstraintDistance.h>
25 #include <SketchPlugin_ConstraintEqual.h>
26 #include <SketchPlugin_ConstraintHorizontal.h>
27 #include <SketchPlugin_ConstraintLength.h>
28 #include <SketchPlugin_ConstraintFillet.h>
29 #include <SketchPlugin_ConstraintMirror.h>
30 #include <SketchPlugin_ConstraintParallel.h>
31 #include <SketchPlugin_ConstraintPerpendicular.h>
32 #include <SketchPlugin_ConstraintRadius.h>
33 #include <SketchPlugin_ConstraintRigid.h>
34 #include <SketchPlugin_ConstraintTangent.h>
35 #include <SketchPlugin_ConstraintVertical.h>
36 #include <SketchPlugin_MultiRotation.h>
37 #include <SketchPlugin_MultiTranslation.h>
43 /// \brief This class is used to give unique index to the groups
47 /// \brief Return vacant index
48 static GroupID NEW_GROUP() { return ++myGroupIndex; }
49 /// \brief Removes the index
50 static void REMOVE_GROUP(const GroupID& theIndex) {
51 if (myGroupIndex == theIndex)
58 static GroupID myGroupIndex; ///< index of the group
61 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
64 static void sendMessage(const char* theMessageName)
66 std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
67 new Events_Message(Events_Loop::eventByName(theMessageName)));
68 Events_Loop::loop()->send(aMessage);
73 // ========================================================
74 // ========= SketchSolver_Group ===============
75 // ========================================================
77 SketchSolver_Group::SketchSolver_Group(
78 std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
79 : myID(GroupIndexer::NEW_GROUP()),
82 // Initialize workplane
83 myWorkplaneID = EID_UNKNOWN;
84 addWorkplane(theWorkplane);
87 SketchSolver_Group::~SketchSolver_Group()
89 myConstraints.clear();
90 GroupIndexer::REMOVE_GROUP(myID);
93 // ============================================================================
94 // Function: isBaseWorkplane
95 // Class: SketchSolver_Group
96 // Purpose: verify the group is based on the given workplane
97 // ============================================================================
98 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
100 return theWorkplane == mySketch;
103 // ============================================================================
104 // Function: isInteract
105 // Class: SketchSolver_Group
106 // Purpose: verify are there any entities in the group used by given constraint
107 // ============================================================================
108 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
110 // Empty group interacts with everything
113 // Check interaction with the storage
114 return myStorage->isInteract(theFeature);
117 // ============================================================================
118 // Function: changeConstraint
119 // Class: SketchSolver_Group
120 // Purpose: create/update the constraint in the group
121 // ============================================================================
122 bool SketchSolver_Group::changeConstraint(
123 std::shared_ptr<SketchPlugin_Constraint> theConstraint)
125 // There is no workplane yet, something wrong
126 if (myWorkplaneID == EID_UNKNOWN)
129 if (!theConstraint || !theConstraint->data())
132 if (!checkFeatureValidity(theConstraint))
135 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
136 myStorage->blockEvents(true);
138 bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
139 if (isNewConstraint) {
140 // Add constraint to the current group
141 SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
144 aConstraint->process(myStorage, getId(), getWorkplaneId());
145 if (!aConstraint->error().empty()) {
146 if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
147 return false; // some attribute are not initialized yet, don't show message
148 Events_Error::send(aConstraint->error(), this);
150 myConstraints[theConstraint] = aConstraint;
153 myConstraints[theConstraint]->update();
156 if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
157 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
158 theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
159 if (aRefAttr && aRefAttr->isObject()) {
160 std::shared_ptr<SketchPlugin_Feature> aFeature =
161 std::dynamic_pointer_cast<SketchPlugin_Feature>(
162 ModelAPI_Feature::feature(aRefAttr->object()));
164 SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
166 aConstraint->process(myStorage, getId(), getWorkplaneId());
167 setTemporary(aConstraint);
176 void SketchSolver_Group::updateConstraints()
178 std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
180 ConstraintConstraintMap::iterator anIt = myConstraints.begin();
181 for (; anIt != myConstraints.end(); ++anIt) {
182 if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
184 if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
185 anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
186 aPostponed.insert(anIt->second);
188 anIt->second->update();
191 // Update postponed constraints
192 std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
193 for (; aSCIter != aPostponed.end(); ++aSCIter)
194 (*aSCIter)->update();
196 myChangedConstraints.clear();
199 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
201 ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
202 for (; aCIt != theConstraints.end(); ++aCIt) {
203 if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
204 aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
205 && aCIt->second->isUsed(theFeature))
206 std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
210 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
212 if (!checkFeatureValidity(theFeature))
215 bool isBlocked = myStorage->isEventsBlocked();
217 myStorage->blockEvents(true);
219 myStorage->refresh(true);
220 bool isUpdated = myStorage->update(theFeature);
222 updateMultiConstraints(myConstraints, theFeature);
224 // events were not blocked before, the feature has not been updated,
225 // so it is necessary to revert blocking
226 if (!isUpdated && !isBlocked)
227 myStorage->blockEvents(false);
231 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
233 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
235 // Firstly, revert changes in the fixed entities
236 myStorage->blockEvents(true);
237 myStorage->refresh(true);
239 // Then, create temporary Fixed constraint
240 SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
243 aConstraint->process(myStorage, getId(), getWorkplaneId());
244 if (aConstraint->error().empty())
245 setTemporary(aConstraint);
247 // Secondly, search attributes of the feature in the list of the Multi constraints and update them
248 updateMultiConstraints(myConstraints, theFeature);
251 // ============================================================================
252 // Function: addWorkplane
253 // Class: SketchSolver_Group
254 // Purpose: create workplane for the group
255 // ============================================================================
256 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
258 if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
259 return false; // the workplane already exists or the function parameter is not Sketch
261 mySketch = theSketch;
262 if (!updateWorkplane()) {
263 mySketch = CompositeFeaturePtr();
269 // ============================================================================
270 // Function: updateWorkplane
271 // Class: SketchSolver_Group
272 // Purpose: update parameters of workplane
273 // ============================================================================
274 bool SketchSolver_Group::updateWorkplane()
276 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
277 if (!myStorage) // Create storage if not exists
278 myStorage = aBuilder->createStorage(getId());
280 // sketch should be unchanged, set it out of current group
281 bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
283 EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
284 myWorkplaneID = anEntity->id();
289 // ============================================================================
290 // Function: resolveConstraints
291 // Class: SketchSolver_Group
292 // Purpose: solve the set of constraints for the current group
293 // ============================================================================
294 bool SketchSolver_Group::resolveConstraints()
296 if (!myChangedConstraints.empty())
299 bool aResolved = false;
300 bool isGroupEmpty = isEmpty();
301 if (myStorage->isNeedToResolve() && !isGroupEmpty) {
303 mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
305 mySketchSolver->setGroup(myID);
306 mySketchSolver->calculateFailedConstraints(false);
307 myStorage->initializeSolver(mySketchSolver);
308 mySketchSolver->prepare();
310 SketchSolver_SolveStatus aResult = STATUS_OK;
312 if (myStorage->hasDuplicatedConstraint())
313 aResult = STATUS_INCONSISTENT;
315 // To avoid overconstraint situation, we will remove temporary constraints one-by-one
316 // and try to find the case without overconstraint
317 bool isLastChance = false;
319 aResult = mySketchSolver->solve();
320 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
322 // try to update parameters and resolve once again
323 ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
324 for (; aConstrIt != myConstraints.end(); ++aConstrIt)
325 aConstrIt->second->update();
328 removeTemporaryConstraints();
329 mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
330 myStorage->initializeSolver(mySketchSolver);
334 // Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
335 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
337 // the error message should be changed before sending the message
338 sendMessage(EVENT_SOLVER_FAILED);
339 myPrevSolved = false;
341 mySketchSolver->undo();
344 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) { // solution succeeded, store results into correspondent attributes
345 myStorage->refresh();
347 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
348 // the error message should be changed before sending the message
349 sendMessage(EVENT_SOLVER_REPAIRED);
353 mySketchSolver->undo();
354 if (!myConstraints.empty()) {
355 // Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
356 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
358 // the error message should be changed before sending the message
359 sendMessage(EVENT_SOLVER_FAILED);
360 myPrevSolved = false;
366 } else if (!isGroupEmpty) {
367 // Check there are constraints Fixed. If they exist, update parameters by stored values
368 ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
369 for (; aCIt != myConstraints.end(); ++aCIt)
370 if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
374 if (aCIt != myConstraints.end())
375 myStorage->refresh();
377 removeTemporaryConstraints();
378 myStorage->blockEvents(false);
379 myStorage->setNeedToResolve(false);
383 // ============================================================================
384 // Function: mergeGroups
385 // Class: SketchSolver_Group
386 // Purpose: append specified group to the current group
387 // ============================================================================
388 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
390 // If specified group is empty, no need to merge
391 if (theGroup.isEmpty())
394 std::set<ObjectPtr> aConstraints;
395 ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
396 for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
397 aConstraints.insert(aConstrIter->first);
399 std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
400 std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
401 for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
402 ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
405 changeConstraint(aConstr);
409 // ============================================================================
410 // Function: splitGroup
411 // Class: SketchSolver_Group
412 // Purpose: divide the group into several subgroups
413 // ============================================================================
414 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
416 // New storage will be used in trimmed way to store the list of constraint interacted together.
417 StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
418 std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
420 // Obtain constraints, which should be separated
421 std::list<ConstraintPtr> anUnusedConstraints;
422 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
423 for ( ; aCIter != myConstraints.end(); aCIter++) {
424 if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
425 aNewStorage->addConstraint(aCIter->first, aDummyVec);
427 anUnusedConstraints.push_back(aCIter->first);
430 // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
431 std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
432 while (aUnuseIt != anUnusedConstraints.end()) {
433 if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
434 aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
435 anUnusedConstraints.erase(aUnuseIt);
436 aUnuseIt = anUnusedConstraints.begin();
442 std::list<SketchSolver_Group*>::iterator aCutsIter;
443 aUnuseIt = anUnusedConstraints.begin();
444 for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
445 // Remove unused constraints
446 removeConstraint(*aUnuseIt);
447 // Try to append constraint to already existent group
448 for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
449 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
450 (*aCutsIter)->changeConstraint(*aUnuseIt);
453 if (aCutsIter == theCuts.end()) {
455 SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
456 aGroup->changeConstraint(*aUnuseIt);
457 theCuts.push_back(aGroup);
459 // Find other groups interacting with constraint
460 std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
461 for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
462 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
463 (*aBaseGroupIt)->mergeGroups(**aCutsIter);
464 std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
465 theCuts.erase(aRemoveIt);
471 // ============================================================================
472 // Function: isConsistent
473 // Class: SketchSolver_Group
474 // Purpose: search removed entities and constraints
475 // ============================================================================
476 bool SketchSolver_Group::isConsistent()
478 if (isEmpty()) // no one constraint is initialized yet
481 // Check the features and constraint is the storage are valid
482 bool aResult = myStorage->isConsistent();
484 // additional check of consistency of the Fixed constraint,
485 // because they are not added to the storage
486 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
487 for (; aCIter != myConstraints.end(); ++aCIter)
488 if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
489 (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
495 // remove invalid constraints
496 std::set<ConstraintPtr> anInvalidConstraints;
497 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
498 for (; aCIter != myConstraints.end(); ++aCIter) {
499 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
500 anInvalidConstraints.insert(aCIter->first);
502 std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
503 for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
504 removeConstraint(*aRemoveIt);
505 // remove invalid features
506 myStorage->removeInvalidEntities();
511 // ============================================================================
512 // Function: removeTemporaryConstraints
513 // Class: SketchSolver_Group
514 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
515 // resolving the set of constraints
516 // ============================================================================
517 void SketchSolver_Group::removeTemporaryConstraints()
519 std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
520 for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
523 if (!myTempConstraints.empty())
524 myStorage->verifyFixed();
525 myStorage->setNeedToResolve(false);
526 myTempConstraints.clear();
529 // ============================================================================
530 // Function: removeConstraint
531 // Class: SketchSolver_Group
532 // Purpose: remove constraint and all unused entities
533 // ============================================================================
534 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
536 bool isFullyRemoved = true;
537 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
538 for (; aCIter != myConstraints.end(); aCIter++)
539 if (aCIter->first == theConstraint) {
540 aCIter->second->remove(); // the constraint is not fully removed
543 if (aCIter != myConstraints.end())
544 myConstraints.erase(aCIter);
547 // ============================================================================
548 // Function: isComplexConstraint
549 // Class: SketchSolver_Group
550 // Purpose: verifies the constraint is complex, i.e. it needs another constraints to be created before
551 // ============================================================================
552 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
554 return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
555 theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
556 theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
559 // ============================================================================
560 // Function: setTemporary
561 // Class: SketchSolver_Group
562 // Purpose: append given constraint to the group of temporary constraints
563 // ============================================================================
564 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
566 myTempConstraints.insert(theConstraint);
570 // ============================================================================
571 // Function: checkFeatureValidity
572 // Class: SketchSolver_Group
573 // Purpose: verifies is the feature valid
574 // ============================================================================
575 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
577 if (!theFeature || !theFeature->data()->isValid())
580 SessionPtr aMgr = ModelAPI_Session::get();
581 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
582 return aFactory->validate(theFeature);
588 // =========== Auxiliary functions ========================================
589 static double featureToVal(FeaturePtr theFeature)
591 if (theFeature->getKind() == SketchPlugin_Sketch::ID())
592 return 0.0; // sketch
593 ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
595 return 1.0; // features (arc, circle, line, point)
597 const std::string& anID = aConstraint->getKind();
598 if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
599 AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
600 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
601 AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
602 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
603 if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
604 return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
607 if (anID == SketchPlugin_ConstraintDistance::ID() ||
608 anID == SketchPlugin_ConstraintLength::ID() ||
609 anID == SketchPlugin_ConstraintRadius::ID())
611 if (anID == SketchPlugin_ConstraintAngle::ID())
613 if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
614 anID == SketchPlugin_ConstraintVertical::ID() ||
615 anID == SketchPlugin_ConstraintParallel::ID() ||
616 anID == SketchPlugin_ConstraintPerpendicular::ID())
618 if (anID == SketchPlugin_ConstraintEqual::ID())
620 if (anID == SketchPlugin_ConstraintTangent::ID() ||
621 anID == SketchPlugin_ConstraintMirror::ID())
623 if (anID == SketchPlugin_ConstraintRigid::ID())
625 if (anID == SketchPlugin_MultiRotation::ID() ||
626 anID == SketchPlugin_MultiTranslation::ID())
629 // all other constraints are placed between Equal and Tangent constraints
633 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
635 return featureToVal(theFeature1) < featureToVal(theFeature2);
638 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
640 std::list<FeaturePtr> aResult;
641 std::list<FeaturePtr>::iterator aResIt;
643 std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
644 for (; anObjIter != theObjects.end(); ++anObjIter) {
645 // Operate sketch itself and SketchPlugin features only.
646 // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
647 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
650 std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
651 std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
652 if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
653 aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
656 // Find the place where to insert a feature
657 for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
658 if (isLess(aFeature, *aResIt))
660 aResult.insert(aResIt, aFeature);