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 myStorage->blockEvents(true);
216 myStorage->refresh(true);
217 bool isUpdated = myStorage->update(theFeature);
219 updateMultiConstraints(myConstraints, theFeature);
223 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
225 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
227 // Firstly, revert changes in the fixed entities
228 myStorage->blockEvents(true);
229 myStorage->refresh(true);
231 // Then, create temporary Fixed constraint
232 SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
235 aConstraint->process(myStorage, getId(), getWorkplaneId());
236 if (aConstraint->error().empty())
237 setTemporary(aConstraint);
239 // Secondly, search attributes of the feature in the list of the Multi constraints and update them
240 updateMultiConstraints(myConstraints, theFeature);
243 // ============================================================================
244 // Function: addWorkplane
245 // Class: SketchSolver_Group
246 // Purpose: create workplane for the group
247 // ============================================================================
248 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
250 if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
251 return false; // the workplane already exists or the function parameter is not Sketch
253 mySketch = theSketch;
254 if (!updateWorkplane()) {
255 mySketch = CompositeFeaturePtr();
261 // ============================================================================
262 // Function: updateWorkplane
263 // Class: SketchSolver_Group
264 // Purpose: update parameters of workplane
265 // ============================================================================
266 bool SketchSolver_Group::updateWorkplane()
268 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
269 if (!myStorage) // Create storage if not exists
270 myStorage = aBuilder->createStorage(getId());
272 // sketch should be unchanged, set it out of current group
273 bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
275 EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
276 myWorkplaneID = anEntity->id();
281 // ============================================================================
282 // Function: resolveConstraints
283 // Class: SketchSolver_Group
284 // Purpose: solve the set of constraints for the current group
285 // ============================================================================
286 bool SketchSolver_Group::resolveConstraints()
288 if (!myChangedConstraints.empty())
291 bool aResolved = false;
292 bool isGroupEmpty = isEmpty();
293 if (myStorage->isNeedToResolve() && !isGroupEmpty) {
295 mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
297 mySketchSolver->setGroup(myID);
298 mySketchSolver->calculateFailedConstraints(false);
299 myStorage->initializeSolver(mySketchSolver);
300 mySketchSolver->prepare();
302 SketchSolver_SolveStatus aResult = STATUS_OK;
304 if (myStorage->hasDuplicatedConstraint())
305 aResult = STATUS_INCONSISTENT;
307 // To avoid overconstraint situation, we will remove temporary constraints one-by-one
308 // and try to find the case without overconstraint
309 bool isLastChance = false;
311 aResult = mySketchSolver->solve();
312 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
314 // try to update parameters and resolve once again
315 ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
316 for (; aConstrIt != myConstraints.end(); ++aConstrIt)
317 aConstrIt->second->update();
320 removeTemporaryConstraints();
321 mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
322 myStorage->initializeSolver(mySketchSolver);
326 // Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
327 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
329 // the error message should be changed before sending the message
330 sendMessage(EVENT_SOLVER_FAILED);
331 myPrevSolved = false;
333 mySketchSolver->undo();
336 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) { // solution succeeded, store results into correspondent attributes
337 myStorage->refresh();
339 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
340 // the error message should be changed before sending the message
341 sendMessage(EVENT_SOLVER_REPAIRED);
345 mySketchSolver->undo();
346 if (!myConstraints.empty()) {
347 // Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
348 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
350 // the error message should be changed before sending the message
351 sendMessage(EVENT_SOLVER_FAILED);
352 myPrevSolved = false;
358 } else if (!isGroupEmpty) {
359 // Check there are constraints Fixed. If they exist, update parameters by stored values
360 ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
361 for (; aCIt != myConstraints.end(); ++aCIt)
362 if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
366 if (aCIt != myConstraints.end())
367 myStorage->refresh();
369 removeTemporaryConstraints();
370 myStorage->blockEvents(false);
371 myStorage->setNeedToResolve(false);
375 // ============================================================================
376 // Function: mergeGroups
377 // Class: SketchSolver_Group
378 // Purpose: append specified group to the current group
379 // ============================================================================
380 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
382 // If specified group is empty, no need to merge
383 if (theGroup.isEmpty())
386 std::set<ObjectPtr> aConstraints;
387 ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
388 for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
389 aConstraints.insert(aConstrIter->first);
391 std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
392 std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
393 for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
394 ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
397 changeConstraint(aConstr);
401 // ============================================================================
402 // Function: splitGroup
403 // Class: SketchSolver_Group
404 // Purpose: divide the group into several subgroups
405 // ============================================================================
406 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
408 // New storage will be used in trimmed way to store the list of constraint interacted together.
409 StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
410 std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
412 // Obtain constraints, which should be separated
413 std::list<ConstraintPtr> anUnusedConstraints;
414 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
415 for ( ; aCIter != myConstraints.end(); aCIter++) {
416 if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
417 aNewStorage->addConstraint(aCIter->first, aDummyVec);
419 anUnusedConstraints.push_back(aCIter->first);
422 // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
423 std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
424 while (aUnuseIt != anUnusedConstraints.end()) {
425 if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
426 aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
427 anUnusedConstraints.erase(aUnuseIt);
428 aUnuseIt = anUnusedConstraints.begin();
434 std::list<SketchSolver_Group*>::iterator aCutsIter;
435 aUnuseIt = anUnusedConstraints.begin();
436 for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
437 // Remove unused constraints
438 removeConstraint(*aUnuseIt);
439 // Try to append constraint to already existent group
440 for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
441 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
442 (*aCutsIter)->changeConstraint(*aUnuseIt);
445 if (aCutsIter == theCuts.end()) {
447 SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
448 aGroup->changeConstraint(*aUnuseIt);
449 theCuts.push_back(aGroup);
451 // Find other groups interacting with constraint
452 std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
453 for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
454 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
455 (*aBaseGroupIt)->mergeGroups(**aCutsIter);
456 std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
457 theCuts.erase(aRemoveIt);
463 // ============================================================================
464 // Function: isConsistent
465 // Class: SketchSolver_Group
466 // Purpose: search removed entities and constraints
467 // ============================================================================
468 bool SketchSolver_Group::isConsistent()
470 if (isEmpty()) // no one constraint is initialized yet
473 // Check the features and constraint is the storage are valid
474 bool aResult = myStorage->isConsistent();
476 // additional check of consistency of the Fixed constraint,
477 // because they are not added to the storage
478 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
479 for (; aCIter != myConstraints.end(); ++aCIter)
480 if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
481 (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
487 // remove invalid constraints
488 std::set<ConstraintPtr> anInvalidConstraints;
489 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
490 for (; aCIter != myConstraints.end(); ++aCIter) {
491 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
492 anInvalidConstraints.insert(aCIter->first);
494 std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
495 for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
496 removeConstraint(*aRemoveIt);
497 // remove invalid features
498 myStorage->removeInvalidEntities();
503 // ============================================================================
504 // Function: removeTemporaryConstraints
505 // Class: SketchSolver_Group
506 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
507 // resolving the set of constraints
508 // ============================================================================
509 void SketchSolver_Group::removeTemporaryConstraints()
511 std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
512 for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
515 if (!myTempConstraints.empty())
516 myStorage->verifyFixed();
517 myStorage->setNeedToResolve(false);
518 myTempConstraints.clear();
521 // ============================================================================
522 // Function: removeConstraint
523 // Class: SketchSolver_Group
524 // Purpose: remove constraint and all unused entities
525 // ============================================================================
526 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
528 bool isFullyRemoved = true;
529 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
530 for (; aCIter != myConstraints.end(); aCIter++)
531 if (aCIter->first == theConstraint) {
532 aCIter->second->remove(); // the constraint is not fully removed
535 if (aCIter != myConstraints.end())
536 myConstraints.erase(aCIter);
539 // ============================================================================
540 // Function: isComplexConstraint
541 // Class: SketchSolver_Group
542 // Purpose: verifies the constraint is complex, i.e. it needs another constraints to be created before
543 // ============================================================================
544 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
546 return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
547 theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
548 theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
551 // ============================================================================
552 // Function: setTemporary
553 // Class: SketchSolver_Group
554 // Purpose: append given constraint to the group of temporary constraints
555 // ============================================================================
556 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
558 myTempConstraints.insert(theConstraint);
562 // ============================================================================
563 // Function: checkFeatureValidity
564 // Class: SketchSolver_Group
565 // Purpose: verifies is the feature valid
566 // ============================================================================
567 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
569 if (!theFeature || !theFeature->data()->isValid())
572 SessionPtr aMgr = ModelAPI_Session::get();
573 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
574 return aFactory->validate(theFeature);
580 // =========== Auxiliary functions ========================================
581 static double featureToVal(FeaturePtr theFeature)
583 if (theFeature->getKind() == SketchPlugin_Sketch::ID())
584 return 0.0; // sketch
585 ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
587 return 1.0; // features (arc, circle, line, point)
589 const std::string& anID = aConstraint->getKind();
590 if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
591 AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
592 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
593 AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
594 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
595 if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
596 return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
599 if (anID == SketchPlugin_ConstraintDistance::ID() ||
600 anID == SketchPlugin_ConstraintLength::ID() ||
601 anID == SketchPlugin_ConstraintRadius::ID())
603 if (anID == SketchPlugin_ConstraintAngle::ID())
605 if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
606 anID == SketchPlugin_ConstraintVertical::ID() ||
607 anID == SketchPlugin_ConstraintParallel::ID() ||
608 anID == SketchPlugin_ConstraintPerpendicular::ID())
610 if (anID == SketchPlugin_ConstraintEqual::ID())
612 if (anID == SketchPlugin_ConstraintTangent::ID() ||
613 anID == SketchPlugin_ConstraintMirror::ID())
615 if (anID == SketchPlugin_ConstraintRigid::ID())
617 if (anID == SketchPlugin_MultiRotation::ID() ||
618 anID == SketchPlugin_MultiTranslation::ID())
621 // all other constraints are placed between Equal and Tangent constraints
625 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
627 return featureToVal(theFeature1) < featureToVal(theFeature2);
630 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
632 std::list<FeaturePtr> aResult;
633 std::list<FeaturePtr>::iterator aResIt;
635 std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
636 for (; anObjIter != theObjects.end(); ++anObjIter) {
637 // Operate sketch itself and SketchPlugin features only.
638 // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
639 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
642 std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
643 std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
644 if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
645 aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
648 // Find the place where to insert a feature
649 for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
650 if (isLess(aFeature, *aResIt))
652 aResult.insert(aResIt, aFeature);