Salome HOME
Update groups merging (issue #933)
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
index b51828ba9d0eb78e560f1d934f11f9801a4642a3..c965b8ee98e11f690d6f06b899160864e33142a7 100644 (file)
 #include <GeomDataAPI_Point.h>
 #include <GeomDataAPI_Point2D.h>
 #include <ModelAPI_AttributeDouble.h>
+#include <ModelAPI_AttributeString.h>
 #include <ModelAPI_Document.h>
 #include <ModelAPI_Events.h>
 #include <ModelAPI_ResultConstruction.h>
+#include <ModelAPI_Session.h>
+#include <ModelAPI_Validator.h>
 
 #include <SketchPlugin_Constraint.h>
-#include <SketchPlugin_ConstraintFillet.h>
-#include <SketchPlugin_ConstraintLength.h>
+#include <SketchPlugin_ConstraintAngle.h>
 #include <SketchPlugin_ConstraintCoincidence.h>
+#include <SketchPlugin_ConstraintDistance.h>
+#include <SketchPlugin_ConstraintEqual.h>
+#include <SketchPlugin_ConstraintHorizontal.h>
+#include <SketchPlugin_ConstraintLength.h>
+#include <SketchPlugin_ConstraintFillet.h>
 #include <SketchPlugin_ConstraintMirror.h>
+#include <SketchPlugin_ConstraintParallel.h>
+#include <SketchPlugin_ConstraintPerpendicular.h>
+#include <SketchPlugin_ConstraintRadius.h>
 #include <SketchPlugin_ConstraintRigid.h>
+#include <SketchPlugin_ConstraintTangent.h>
+#include <SketchPlugin_ConstraintVertical.h>
 #include <SketchPlugin_Feature.h>
+#include <SketchPlugin_MultiRotation.h>
+#include <SketchPlugin_MultiTranslation.h>
+#include <SketchPlugin_Sketch.h>
 
 #include <SketchPlugin_Arc.h>
 #include <SketchPlugin_Circle.h>
@@ -63,6 +78,14 @@ private:
 Slvs_hGroup GroupIndexer::myGroupIndex = 0;
 
 
+static void sendMessage(const char* theMessageName)
+{
+  std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
+      new Events_Message(Events_Loop::eventByName(theMessageName)));
+  Events_Loop::loop()->send(aMessage);
+}
+
+
 
 // ========================================================
 // =========  SketchSolver_Group  ===============
@@ -70,7 +93,8 @@ Slvs_hGroup GroupIndexer::myGroupIndex = 0;
 
 SketchSolver_Group::SketchSolver_Group(
     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
-    : myID(GroupIndexer::NEW_GROUP())
+    : myID(GroupIndexer::NEW_GROUP()),
+      myPrevSolved(true)
 {
   // Initialize workplane
   myWorkplaneID = SLVS_E_UNKNOWN;
@@ -178,7 +202,11 @@ bool SketchSolver_Group::changeConstraint(
   if (!theConstraint)
     return false;
 
-  if (myConstraints.find(theConstraint) == myConstraints.end()) {
+  if (!checkFeatureValidity(theConstraint))
+    return false;
+
+  bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
+  if (isNewConstraint) {
     // Add constraint to the current group
     SolverConstraintPtr aConstraint =
         SketchSolver_Builder::getInstance()->createConstraint(theConstraint);
@@ -203,8 +231,13 @@ bool SketchSolver_Group::changeConstraint(
         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoinc2 =
           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aConstraint);
         if (aCoincidence != aCoinc2 && aCoincidence->isCoincide(aCoinc2)) {
-          aCoincidence->attach(aCoinc2);
-          aConstraint = aCoincidence;
+          aCoinc2->attach(aCoincidence);
+          // update other coincidences
+          ConstraintConstraintMap::iterator anIt = aCIter;
+          for (++anIt; anIt != myConstraints.end(); ++anIt)
+            if (anIt->second == aCIter->second)
+              anIt->second = aCoinc2;
+          aCIter->second = aCoinc2;
         }
       }
     }
@@ -214,7 +247,7 @@ bool SketchSolver_Group::changeConstraint(
     myConstraints[theConstraint]->update();
 
   // Fix base features for fillet
-  if (theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
+  if (isNewConstraint && theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
     std::list<AttributePtr> anAttrList =
         theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
     std::list<AttributePtr>::iterator anAttrIter = anAttrList.begin();
@@ -230,14 +263,25 @@ bool SketchSolver_Group::changeConstraint(
         continue;
       aConstraint->setGroup(this);
       aConstraint->setStorage(myStorage);
-      myTempConstraints.insert(aConstraint);
+      setTemporary(aConstraint);
     }
   }
-  // Fix base features for mirror
+  // Fix mirror line
   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
-    AttributeRefListPtr aRefList = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
-        theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_B()));
-    fixFeaturesList(aRefList);
+    AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
+        theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
+    if (aRefAttr && aRefAttr->isObject()) {
+      FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
+      if (aFeature) {
+        SolverConstraintPtr aConstraint =
+            SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
+        if (aConstraint) {
+          aConstraint->setGroup(this);
+          aConstraint->setStorage(myStorage);
+          setTemporary(aConstraint);
+        }
+      }
+    }
   }
 
   if (!myFeatureStorage)
@@ -248,8 +292,34 @@ bool SketchSolver_Group::changeConstraint(
 }
 
 
+void SketchSolver_Group::updateConstraints()
+{
+  std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
+
+  ConstraintConstraintMap::iterator anIt = myConstraints.begin();
+  for (; anIt != myConstraints.end(); ++anIt) {
+    if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
+      continue;
+    if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
+        anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
+      aPostponed.insert(anIt->second);
+    else
+      anIt->second->update();
+  }
+
+  // Update postponed constraints
+  std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
+  for (; aSCIter != aPostponed.end(); ++aSCIter)
+    (*aSCIter)->update();
+
+  myChangedConstraints.clear();
+}
+
 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
 {
+  if (!checkFeatureValidity(theFeature))
+    return false;
+
   std::set<ConstraintPtr> aConstraints =
       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
   if (aConstraints.empty())
@@ -257,22 +327,30 @@ bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> the
   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
   for (; aCIter != aConstraints.end(); aCIter++) {
     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
-    aSolConIter->second->update();
+    if (aSolConIter == myConstraints.end() || !aSolConIter->first->data() ||
+        !aSolConIter->first->data()->isValid())
+      continue;
+    myFeatureStorage->changeFeature(theFeature, aSolConIter->first);
+
+    aSolConIter->second->addFeature(theFeature);
+    myChangedConstraints.insert(aSolConIter->first);
   }
   return true;
 }
 
 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
 {
-  updateFeature(theFeature);
-  // Temporary rigid constraint
+  // Firstly, create temporary rigid constraint
   SolverConstraintPtr aConstraint =
-      SketchSolver_Builder::getInstance()->createRigidConstraint(theFeature);
+      SketchSolver_Builder::getInstance()->createMovementConstraint(theFeature);
   if (!aConstraint)
     return;
   aConstraint->setGroup(this);
   aConstraint->setStorage(myStorage);
-  myTempConstraints.insert(aConstraint);
+  if (aConstraint->error().empty())
+    setTemporary(aConstraint);
+  // Secondly, update the feature
+  updateFeature(theFeature);
 }
 
 // ============================================================================
@@ -284,17 +362,32 @@ void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
 {
   std::list<ObjectPtr> aList = theList->list();
   std::list<ObjectPtr>::iterator anIt = aList.begin();
+  std::list<FeaturePtr> aFeatures;
+  // Sort features, at begining there are features used by Equal constraint
   for (; anIt != aList.end(); anIt++) {
     if (!(*anIt))
       continue;
     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
+    std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(aFeature);
+    std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
+    for (; aCIter != aConstraints.end(); aCIter++)
+      if ((*aCIter)->getKind() == SketchPlugin_ConstraintEqual::ID())
+        break;
+    if (aCIter != aConstraints.end())
+      aFeatures.push_front(aFeature);
+    else
+      aFeatures.push_back(aFeature);
+  }
+
+  std::list<FeaturePtr>::iterator aFeatIter = aFeatures.begin();
+  for (; aFeatIter != aFeatures.end(); aFeatIter++) {
     SolverConstraintPtr aConstraint =
-        SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
+        SketchSolver_Builder::getInstance()->createRigidConstraint(*aFeatIter);
     if (!aConstraint)
       continue;
     aConstraint->setGroup(this);
     aConstraint->setStorage(myStorage);
-    myTempConstraints.insert(aConstraint);
+    setTemporary(aConstraint);
   }
 }
 
@@ -378,20 +471,66 @@ bool SketchSolver_Group::updateWorkplane()
 // ============================================================================
 bool SketchSolver_Group::resolveConstraints()
 {
+  if (!myChangedConstraints.empty())
+    updateConstraints();
+
   bool aResolved = false;
   if (myStorage->isNeedToResolve() && !isEmpty()) {
     myConstrSolver.setGroupID(myID);
     myStorage->initializeSolver(myConstrSolver);
 
-    int aResult = myConstrSolver.solve();
+    int aResult = SLVS_RESULT_OKAY;
+    try {
+      if (myStorage->hasDuplicatedConstraint())
+        aResult = SLVS_RESULT_INCONSISTENT;
+      else {
+        // To avoid overconstraint situation, we will remove temporary constraints one-by-one
+        // and try to find the case without overconstraint
+        bool isLastChance = false;
+        int aNbTemp = myStorage->numberTemporary();
+        while (true) {
+          aResult = myConstrSolver.solve();
+          if (aResult == SLVS_RESULT_OKAY || isLastChance)
+            break;
+          if (aNbTemp <= 0) {
+            // try to update parameters and resolve once again
+            ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
+            for (; aConstrIt != myConstraints.end(); ++aConstrIt)
+              aConstrIt->second->update();
+            isLastChance = true;
+          } else
+            aNbTemp = myStorage->deleteTemporaryConstraint();
+          myStorage->initializeSolver(myConstrSolver);
+        }
+      }
+    } catch (...) {
+//      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
+      if (myPrevSolved) {
+        sendMessage(EVENT_SOLVER_FAILED);
+        myPrevSolved = false;
+      }
+      getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
+      return false;
+    }
     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
       myFeatureStorage->blockEvents(true);
       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
       for (; aConstrIter != myConstraints.end(); aConstrIter++)
         aConstrIter->second->refresh();
       myFeatureStorage->blockEvents(false);
-    } else if (!myConstraints.empty())
-      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
+      if (!myPrevSolved) {
+        sendMessage(EVENT_SOLVER_REPAIRED);
+        myPrevSolved = true;
+      }
+      getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
+    } else if (!myConstraints.empty()) {
+//      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
+      if (myPrevSolved) {
+        sendMessage(EVENT_SOLVER_FAILED);
+        myPrevSolved = false;
+      }
+      getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
+    }
 
     aResolved = true;
   }
@@ -413,9 +552,19 @@ void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
   if (!myFeatureStorage)
     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
 
+  std::set<ObjectPtr> aConstraints;
   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
-    changeConstraint(aConstrIter->first);
+    aConstraints.insert(aConstrIter->first);
+
+  std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
+  std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
+  for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
+    ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
+    if (!aConstr)
+      continue;
+    changeConstraint(aConstr);
+  }
 }
 
 // ============================================================================
@@ -484,22 +633,15 @@ bool SketchSolver_Group::isConsistent()
   bool aResult = myFeatureStorage->isConsistent();
   if (!aResult) {
     // remove invalid entities
+    std::set<ConstraintPtr> anInvalidConstraints;
     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
-    while (aCIter != myConstraints.end()) {
-      std::list<ConstraintPtr> aConstraints = aCIter->second->constraints();
-      std::list<ConstraintPtr>::iterator anIt = aConstraints.begin();
-      for (; anIt != aConstraints.end(); anIt++)
-        if (!(*anIt)->data() || !(*anIt)->data()->isValid())
-          if (aCIter->second->remove(*anIt)) {
-            // the constraint is fully removed, detach it from the list
-            ConstraintConstraintMap::iterator aTmpIt = aCIter++;
-            myFeatureStorage->removeConstraint(aTmpIt->first);
-            myConstraints.erase(aTmpIt);
-            break;
-          }
-      if (anIt == aConstraints.end())
-        aCIter++;
+    for (; aCIter != myConstraints.end(); ++aCIter) {
+      if (!aCIter->first->data() || !aCIter->first->data()->isValid())
+        anInvalidConstraints.insert(aCIter->first);
     }
+    std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
+    for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
+      removeConstraint(*aRemoveIt);
   }
   return aResult;
 }
@@ -513,6 +655,8 @@ bool SketchSolver_Group::isConsistent()
 void SketchSolver_Group::removeTemporaryConstraints()
 {
   myTempConstraints.clear();
+  while (myStorage->numberTemporary())
+    myStorage->deleteTemporaryConstraint();
   // Clean lists of removed entities in the storage
   std::set<Slvs_hParam> aRemPar;
   std::set<Slvs_hEntity> aRemEnt;
@@ -528,14 +672,153 @@ void SketchSolver_Group::removeTemporaryConstraints()
 // ============================================================================
 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
 {
+  bool isFullyRemoved = true;
   myFeatureStorage->removeConstraint(theConstraint);
   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
   for (; aCIter != myConstraints.end(); aCIter++)
     if (aCIter->second->hasConstraint(theConstraint)) {
       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
-        aCIter = myConstraints.end();
+        isFullyRemoved = false;
       break;
     }
-  if (aCIter != myConstraints.end())
+  if (aCIter == myConstraints.end())
+    return;
+
+  if (isFullyRemoved)
     myConstraints.erase(aCIter);
+  else if (aCIter != myConstraints.end() &&
+           aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
+    // Update multicoincidence
+    std::list<ConstraintPtr> aMultiCoinc;
+    SolverConstraintPtr aCoincidence = aCIter->second;
+    while (aCIter != myConstraints.end()) {
+      if (aCIter->second != aCoincidence) {
+        ++aCIter;
+        continue;
+      }
+      if (aCIter->first != theConstraint)
+        aMultiCoinc.push_back(aCIter->first);
+      aCIter->second->remove(aCIter->first);
+      ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
+      myConstraints.erase(aRemoveIt);
+    }
+
+    std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
+    for (; anIt != aMultiCoinc.end(); ++anIt)
+      changeConstraint(*anIt);
+  }
 }
+
+// ============================================================================
+//  Function: isComplexConstraint
+//  Class:    SketchSolver_Group
+//  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
+// ============================================================================
+bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
+{
+  return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
+         theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
+         theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
+}
+
+// ============================================================================
+//  Function: setTemporary
+//  Class:    SketchSolver_Group
+//  Purpose:  append given constraint to th group of temporary constraints
+// ============================================================================
+void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
+{
+  theConstraint->makeTemporary();
+  myTempConstraints.insert(theConstraint);
+}
+
+
+// ============================================================================
+//  Function: checkFeatureValidity
+//  Class:    SketchSolver_Group
+//  Purpose:  verifies is the feature valid
+// ============================================================================
+bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
+{
+  if (!theFeature || !theFeature->data()->isValid())
+    return true;
+
+  SessionPtr aMgr = ModelAPI_Session::get();
+  ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
+  return aFactory->validate(theFeature);
+}
+
+
+
+
+
+// ===========   Auxiliary functions   ========================================
+static double featureToVal(FeaturePtr theFeature)
+{
+  if (theFeature->getKind() == SketchPlugin_Sketch::ID())
+    return 0.0; // sketch
+  ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
+  if (!aConstraint)
+    return 1.0; // features (arc, circle, line, point)
+
+  const std::string& anID = aConstraint->getKind();
+  if (anID == SketchPlugin_ConstraintCoincidence::ID())
+    return 2.0;
+  if (anID == SketchPlugin_ConstraintDistance::ID() ||
+      anID == SketchPlugin_ConstraintLength::ID() ||
+      anID == SketchPlugin_ConstraintRadius::ID() ||
+      anID == SketchPlugin_ConstraintAngle::ID())
+    return 3.0;
+  if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
+      anID == SketchPlugin_ConstraintVertical::ID() ||
+      anID == SketchPlugin_ConstraintParallel::ID() ||
+      anID == SketchPlugin_ConstraintPerpendicular::ID())
+    return 4.0;
+  if (anID == SketchPlugin_ConstraintEqual::ID())
+    return 5.0;
+  if (anID == SketchPlugin_ConstraintTangent::ID() ||
+      anID == SketchPlugin_ConstraintMirror::ID())
+    return 6.0;
+  if (anID == SketchPlugin_ConstraintRigid::ID())
+    return 7.0;
+  if (anID == SketchPlugin_MultiRotation::ID() ||
+      anID == SketchPlugin_MultiTranslation::ID())
+    return 8.0;
+
+  // all other constraints are placed between Equal and Tangent constraints
+  return 5.5;
+}
+
+static bool operator< (FeaturePtr theFeature1, FeaturePtr theFeature2)
+{
+  return featureToVal(theFeature1) < featureToVal(theFeature2);
+}
+
+std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
+{
+  std::list<FeaturePtr> aResult;
+  std::list<FeaturePtr>::iterator aResIt;
+
+  std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
+  for (; anObjIter != theObjects.end(); ++anObjIter) {
+    // Operate sketch itself and SketchPlugin features only.
+    // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
+    FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
+    if (!aFeature)
+      continue;
+    std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
+        std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
+    if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
+        aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
+      continue;
+
+    // Find the place where to insert a feature
+    for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
+      if (aFeature < *aResIt)
+        break;
+    aResult.insert(aResIt, aFeature);
+  }
+
+  return aResult;
+}
+