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_Arc.h>
23 #include <SketchPlugin_ConstraintAngle.h>
24 #include <SketchPlugin_ConstraintCoincidence.h>
25 #include <SketchPlugin_ConstraintDistance.h>
26 #include <SketchPlugin_ConstraintEqual.h>
27 #include <SketchPlugin_ConstraintHorizontal.h>
28 #include <SketchPlugin_ConstraintLength.h>
29 #include <SketchPlugin_ConstraintFillet.h>
30 #include <SketchPlugin_ConstraintMirror.h>
31 #include <SketchPlugin_ConstraintParallel.h>
32 #include <SketchPlugin_ConstraintPerpendicular.h>
33 #include <SketchPlugin_ConstraintRadius.h>
34 #include <SketchPlugin_ConstraintRigid.h>
35 #include <SketchPlugin_ConstraintTangent.h>
36 #include <SketchPlugin_ConstraintVertical.h>
37 #include <SketchPlugin_MultiRotation.h>
38 #include <SketchPlugin_MultiTranslation.h>
44 /// \brief This class is used to give unique index to the groups
48 /// \brief Return vacant index
49 static GroupID NEW_GROUP() { return ++myGroupIndex; }
50 /// \brief Removes the index
51 static void REMOVE_GROUP(const GroupID& theIndex) {
52 if (myGroupIndex == theIndex)
59 static GroupID myGroupIndex; ///< index of the group
62 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
65 static void sendMessage(const char* theMessageName)
67 std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
68 new Events_Message(Events_Loop::eventByName(theMessageName)));
69 Events_Loop::loop()->send(aMessage);
72 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
74 std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
75 std::shared_ptr<ModelAPI_SolverFailedMessage>(
76 new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
77 aMessage->setObjects(theConflicting);
78 Events_Loop::loop()->send(aMessage);
83 // ========================================================
84 // ========= SketchSolver_Group ===============
85 // ========================================================
87 SketchSolver_Group::SketchSolver_Group(
88 std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
89 : myID(GroupIndexer::NEW_GROUP()),
90 myPrevResult(STATUS_UNKNOWN)
92 // Initialize workplane
93 myWorkplaneID = EID_UNKNOWN;
94 addWorkplane(theWorkplane);
97 SketchSolver_Group::~SketchSolver_Group()
99 myConstraints.clear();
100 GroupIndexer::REMOVE_GROUP(myID);
103 // ============================================================================
104 // Function: isBaseWorkplane
105 // Class: SketchSolver_Group
106 // Purpose: verify the group is based on the given workplane
107 // ============================================================================
108 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
110 return theWorkplane == mySketch;
113 // ============================================================================
114 // Function: isInteract
115 // Class: SketchSolver_Group
116 // Purpose: verify are there any entities in the group used by given constraint
117 // ============================================================================
118 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
120 // Empty group interacts with everything
123 // Check interaction with the storage
124 return myStorage->isInteract(theFeature);
127 // ============================================================================
128 // Function: changeConstraint
129 // Class: SketchSolver_Group
130 // Purpose: create/update the constraint in the group
131 // ============================================================================
132 bool SketchSolver_Group::changeConstraint(
133 std::shared_ptr<SketchPlugin_Constraint> theConstraint)
135 // There is no workplane yet, something wrong
136 if (myWorkplaneID == EID_UNKNOWN)
139 if (!theConstraint || !theConstraint->data())
142 if (!checkFeatureValidity(theConstraint))
145 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
146 myStorage->blockEvents(true);
148 bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
149 if (isNewConstraint) {
150 // Add constraint to the current group
151 SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
154 aConstraint->process(myStorage, getId(), getWorkplaneId());
155 if (!aConstraint->error().empty()) {
156 if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
157 return false; // some attribute are not initialized yet, don't show message
158 Events_Error::send(aConstraint->error(), this);
160 myConstraints[theConstraint] = aConstraint;
163 myConstraints[theConstraint]->update();
166 if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
167 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
168 theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
169 if (aRefAttr && aRefAttr->isObject()) {
170 std::shared_ptr<SketchPlugin_Feature> aFeature =
171 std::dynamic_pointer_cast<SketchPlugin_Feature>(
172 ModelAPI_Feature::feature(aRefAttr->object()));
174 SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
176 aConstraint->process(myStorage, getId(), getWorkplaneId());
177 setTemporary(aConstraint);
185 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
187 ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
188 for (; aCIt != theConstraints.end(); ++aCIt) {
189 if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
190 aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
191 && aCIt->second->isUsed(theFeature))
192 std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
196 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
198 if (!checkFeatureValidity(theFeature))
201 bool isBlocked = myStorage->isEventsBlocked();
203 myStorage->blockEvents(true);
205 myStorage->refresh(true);
206 bool isUpdated = myStorage->update(theFeature);
208 updateMultiConstraints(myConstraints, theFeature);
210 // events were not blocked before, the feature has not been updated,
211 // so it is necessary to revert blocking
212 if (!isUpdated && !isBlocked)
213 myStorage->blockEvents(false);
217 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
219 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
221 // Firstly, revert changes in the fixed entities
222 myStorage->blockEvents(true);
223 myStorage->refresh(true);
225 // Then, create temporary Fixed constraint
226 SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
229 aConstraint->process(myStorage, getId(), getWorkplaneId());
230 if (aConstraint->error().empty())
231 setTemporary(aConstraint);
233 // Secondly, search attributes of the feature in the list of the Multi constraints and update them
234 updateMultiConstraints(myConstraints, theFeature);
236 // Workaround to process arcs.
237 // When move unconstrained arc, add temporary constraint to fix radius.
238 if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
239 SolverConstraintPtr aFixedRadius = aBuilder->createFixedArcRadiusConstraint(theFeature);
241 aFixedRadius->process(myStorage, getId(), getWorkplaneId());
242 if (aFixedRadius->error().empty())
243 setTemporary(aFixedRadius);
248 // ============================================================================
249 // Function: addWorkplane
250 // Class: SketchSolver_Group
251 // Purpose: create workplane for the group
252 // ============================================================================
253 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
255 if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
256 return false; // the workplane already exists or the function parameter is not Sketch
258 mySketch = theSketch;
259 if (!updateWorkplane()) {
260 mySketch = CompositeFeaturePtr();
266 // ============================================================================
267 // Function: updateWorkplane
268 // Class: SketchSolver_Group
269 // Purpose: update parameters of workplane
270 // ============================================================================
271 bool SketchSolver_Group::updateWorkplane()
273 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
274 if (!myStorage) // Create storage if not exists
275 myStorage = aBuilder->createStorage(getId());
277 // sketch should be unchanged, set it out of current group
278 bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
280 EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
281 myWorkplaneID = anEntity->id();
286 // ============================================================================
287 // Function: resolveConstraints
288 // Class: SketchSolver_Group
289 // Purpose: solve the set of constraints for the current group
290 // ============================================================================
291 bool SketchSolver_Group::resolveConstraints()
293 bool aResolved = false;
294 bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
295 if (myStorage->isNeedToResolve() && !isGroupEmpty) {
297 mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
299 mySketchSolver->setGroup(myID);
300 mySketchSolver->calculateFailedConstraints(false);
301 myStorage->initializeSolver(mySketchSolver);
302 mySketchSolver->prepare();
304 SketchSolver_SolveStatus aResult = STATUS_OK;
306 if (myStorage->hasDuplicatedConstraint())
307 aResult = STATUS_INCONSISTENT;
309 // To avoid overconstraint situation, we will remove temporary constraints one-by-one
310 // and try to find the case without overconstraint
311 bool isLastChance = false;
313 aResult = mySketchSolver->solve();
314 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
316 // try to update parameters and resolve once again
317 ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
318 for (; aConstrIt != myConstraints.end(); ++aConstrIt)
319 aConstrIt->second->update();
322 removeTemporaryConstraints();
323 mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
324 myStorage->initializeSolver(mySketchSolver);
328 // Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
329 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
330 if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
331 // the error message should be changed before sending the message
332 sendMessage(EVENT_SOLVER_FAILED);
333 myPrevResult = STATUS_FAILED;
335 mySketchSolver->undo();
338 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) { // solution succeeded, store results into correspondent attributes
339 myStorage->refresh();
340 if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
341 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
342 // the error message should be changed before sending the message
343 sendMessage(EVENT_SOLVER_REPAIRED);
344 myPrevResult = STATUS_OK;
347 mySketchSolver->undo();
348 if (!myConstraints.empty()) {
349 // Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
350 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
351 if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
352 // Obtain list of conflicting constraints
353 std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
355 // the error message should be changed before sending the message
356 sendMessage(EVENT_SOLVER_FAILED, aConflicting);
357 myPrevResult = aResult;
363 } else if (!isGroupEmpty) {
364 // Check there are constraints Fixed. If they exist, update parameters by stored values
365 ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
366 for (; aCIt != myConstraints.end(); ++aCIt)
367 if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
371 if (aCIt != myConstraints.end())
372 myStorage->refresh();
374 removeTemporaryConstraints();
375 myStorage->blockEvents(false);
376 myStorage->setNeedToResolve(false);
380 // ============================================================================
381 // Function: mergeGroups
382 // Class: SketchSolver_Group
383 // Purpose: append specified group to the current group
384 // ============================================================================
385 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
387 // If specified group is empty, no need to merge
388 if (theGroup.isEmpty())
391 std::set<ObjectPtr> aConstraints;
392 ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
393 for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
394 aConstraints.insert(aConstrIter->first);
396 std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
397 std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
398 for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
399 ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
402 changeConstraint(aConstr);
406 // ============================================================================
407 // Function: splitGroup
408 // Class: SketchSolver_Group
409 // Purpose: divide the group into several subgroups
410 // ============================================================================
411 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
413 // New storage will be used in trimmed way to store the list of constraint interacted together.
414 StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
415 std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
417 // Obtain constraints, which should be separated
418 std::list<ConstraintPtr> anUnusedConstraints;
419 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
420 for ( ; aCIter != myConstraints.end(); aCIter++) {
421 if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
422 aNewStorage->addConstraint(aCIter->first, aDummyVec);
424 anUnusedConstraints.push_back(aCIter->first);
427 // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
428 std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
429 while (aUnuseIt != anUnusedConstraints.end()) {
430 if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
431 aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
432 anUnusedConstraints.erase(aUnuseIt);
433 aUnuseIt = anUnusedConstraints.begin();
439 std::list<SketchSolver_Group*>::iterator aCutsIter;
440 aUnuseIt = anUnusedConstraints.begin();
441 for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
442 // Remove unused constraints
443 removeConstraint(*aUnuseIt);
444 // Try to append constraint to already existent group
445 for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
446 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
447 (*aCutsIter)->changeConstraint(*aUnuseIt);
450 if (aCutsIter == theCuts.end()) {
452 SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
453 aGroup->changeConstraint(*aUnuseIt);
454 theCuts.push_back(aGroup);
456 // Find other groups interacting with constraint
457 std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
458 for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
459 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
460 (*aBaseGroupIt)->mergeGroups(**aCutsIter);
461 std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
462 theCuts.erase(aRemoveIt);
468 // ============================================================================
469 // Function: isConsistent
470 // Class: SketchSolver_Group
471 // Purpose: search removed entities and constraints
472 // ============================================================================
473 bool SketchSolver_Group::isConsistent()
475 if (isEmpty()) // no one constraint is initialized yet
478 // Check the features and constraint is the storage are valid
479 bool aResult = myStorage->isConsistent();
481 // additional check of consistency of the Fixed constraint,
482 // because they are not added to the storage
483 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
484 for (; aCIter != myConstraints.end(); ++aCIter)
485 if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
486 (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
492 // remove invalid constraints
493 std::set<ConstraintPtr> anInvalidConstraints;
494 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
495 for (; aCIter != myConstraints.end(); ++aCIter) {
496 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
497 anInvalidConstraints.insert(aCIter->first);
499 std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
500 for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
501 removeConstraint(*aRemoveIt);
502 // remove invalid features
503 myStorage->removeInvalidEntities();
508 // ============================================================================
509 // Function: removeTemporaryConstraints
510 // Class: SketchSolver_Group
511 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
512 // resolving the set of constraints
513 // ============================================================================
514 void SketchSolver_Group::removeTemporaryConstraints()
516 std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
517 for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
520 if (!myTempConstraints.empty())
521 myStorage->verifyFixed();
522 myStorage->setNeedToResolve(false);
523 myTempConstraints.clear();
526 // ============================================================================
527 // Function: removeConstraint
528 // Class: SketchSolver_Group
529 // Purpose: remove constraint and all unused entities
530 // ============================================================================
531 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
533 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
534 for (; aCIter != myConstraints.end(); aCIter++)
535 if (aCIter->first == theConstraint) {
536 aCIter->second->remove(); // the constraint is not fully removed
539 if (aCIter != myConstraints.end())
540 myConstraints.erase(aCIter);
543 // ============================================================================
544 // Function: setTemporary
545 // Class: SketchSolver_Group
546 // Purpose: append given constraint to the group of temporary constraints
547 // ============================================================================
548 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
550 myTempConstraints.insert(theConstraint);
554 // ============================================================================
555 // Function: checkFeatureValidity
556 // Class: SketchSolver_Group
557 // Purpose: verifies is the feature valid
558 // ============================================================================
559 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
561 if (!theFeature || !theFeature->data()->isValid())
564 SessionPtr aMgr = ModelAPI_Session::get();
565 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
566 return aFactory->validate(theFeature);
572 // =========== Auxiliary functions ========================================
573 static double featureToVal(FeaturePtr theFeature)
575 if (theFeature->getKind() == SketchPlugin_Sketch::ID())
576 return 0.0; // sketch
577 ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
579 return 1.0; // features (arc, circle, line, point)
581 const std::string& anID = aConstraint->getKind();
582 if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
583 AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
584 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
585 AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
586 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
587 if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
588 return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
591 if (anID == SketchPlugin_ConstraintDistance::ID() ||
592 anID == SketchPlugin_ConstraintLength::ID() ||
593 anID == SketchPlugin_ConstraintRadius::ID())
595 if (anID == SketchPlugin_ConstraintAngle::ID())
597 if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
598 anID == SketchPlugin_ConstraintVertical::ID() ||
599 anID == SketchPlugin_ConstraintParallel::ID() ||
600 anID == SketchPlugin_ConstraintPerpendicular::ID())
602 if (anID == SketchPlugin_ConstraintEqual::ID())
604 if (anID == SketchPlugin_ConstraintTangent::ID() ||
605 anID == SketchPlugin_ConstraintMirror::ID())
607 if (anID == SketchPlugin_ConstraintRigid::ID())
609 if (anID == SketchPlugin_MultiRotation::ID() ||
610 anID == SketchPlugin_MultiTranslation::ID())
613 // all other constraints are placed between Equal and Tangent constraints
617 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
619 return featureToVal(theFeature1) < featureToVal(theFeature2);
622 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
624 std::list<FeaturePtr> aResult;
625 std::list<FeaturePtr>::iterator aResIt;
627 std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
628 for (; anObjIter != theObjects.end(); ++anObjIter) {
629 // Operate sketch itself and SketchPlugin features only.
630 // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
631 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
634 std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
635 std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
636 if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
637 aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
640 // Find the place where to insert a feature
641 for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
642 if (isLess(aFeature, *aResIt))
644 aResult.insert(aResIt, aFeature);