Salome HOME
updated copyright message
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
index 9447f1e1efd410d80bdadbdaea240fd9ac80d86f..232c8525ece08d701693e8bbdadceae8b46a9b48 100644 (file)
@@ -1,66 +1,39 @@
-// Copyright (C) 2014-20xx CEA/DEN, EDF R&D
-
-// File:    SketchSolver_Group.cpp
-// Created: 27 May 2014
-// Author:  Artem ZHIDKOV
+// Copyright (C) 2014-2023  CEA, EDF
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
 
 #include "SketchSolver_Group.h"
-
-#include <SketchSolver_Constraint.h>
-#include <SketchSolver_ConstraintCoincidence.h>
-#include <SketchSolver_ConstraintMulti.h>
 #include <SketchSolver_Error.h>
 #include <SketchSolver_Manager.h>
 
+#include <PlaneGCSSolver_Solver.h>
+#include <PlaneGCSSolver_Storage.h>
+#include <PlaneGCSSolver_Tools.h>
+
 #include <Events_InfoMessage.h>
-#include <Events_Loop.h>
 #include <ModelAPI_AttributeString.h>
 #include <ModelAPI_Events.h>
-#include <ModelAPI_Session.h>
-#include <ModelAPI_Validator.h>
-
-#include <SketchPlugin_Arc.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_ConstraintSplit.h>
-#include <SketchPlugin_ConstraintTangent.h>
-#include <SketchPlugin_ConstraintVertical.h>
 #include <SketchPlugin_MultiRotation.h>
 #include <SketchPlugin_MultiTranslation.h>
 
-#include <math.h>
-#include <assert.h>
-
-
-/// \brief This class is used to give unique index to the groups
-class GroupIndexer
-{
-public:
-  /// \brief Return vacant index
-  static GroupID NEW_GROUP() { return ++myGroupIndex; }
-  /// \brief Removes the index
-  static void REMOVE_GROUP(const GroupID& theIndex) {
-    if (myGroupIndex == theIndex)
-      myGroupIndex--;
-  }
-
-private:
-  GroupIndexer() {};
-
-  static GroupID myGroupIndex; ///< index of the group
-};
-
-GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
+#include <Config_Translator.h>
 
 
 static void sendMessage(const char* theMessageName)
@@ -79,26 +52,42 @@ static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& t
   Events_Loop::loop()->send(aMessage);
 }
 
+static void sendMessage(const char* theMessageName,
+                        const CompositeFeaturePtr& theSketch,
+                        const int theDOF)
+{
+  std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
+      std::shared_ptr<ModelAPI_SolverFailedMessage>(
+      new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
+
+  std::set<ObjectPtr> anObjects;
+  anObjects.insert(theSketch);
+  aMessage->setObjects(anObjects);
+  aMessage->dof(theDOF);
+
+  Events_Loop::loop()->send(aMessage);
+}
+
 
 
 // ========================================================
-// =========  SketchSolver_Group  ===============
+// =========       SketchSolver_Group       ===============
 // ========================================================
 
-SketchSolver_Group::SketchSolver_Group(
-    std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
-    : myID(GroupIndexer::NEW_GROUP()),
-      myPrevResult(STATUS_UNKNOWN)
+SketchSolver_Group::SketchSolver_Group(const CompositeFeaturePtr& theWorkplane)
+  : myPrevResult(PlaneGCSSolver_Solver::STATUS_UNKNOWN),
+    myDOF(-1),
+    myIsEventsBlocked(false),
+    myMultiConstraintUpdateStack(0)
 {
-  // Initialize workplane
-  myWorkplaneID = EID_UNKNOWN;
-  addWorkplane(theWorkplane);
+  mySketchSolver = SolverPtr(new PlaneGCSSolver_Solver);
+  myStorage = StoragePtr(new PlaneGCSSolver_Storage(mySketchSolver));
+  updateSketch(theWorkplane);
 }
 
 SketchSolver_Group::~SketchSolver_Group()
 {
   myConstraints.clear();
-  GroupIndexer::REMOVE_GROUP(myID);
   // send the message that there is no more conflicting constraints
   if (!myConflictingConstraints.empty()) {
     sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
@@ -106,49 +95,6 @@ SketchSolver_Group::~SketchSolver_Group()
   }
 }
 
-// ============================================================================
-//  Function: isBaseWorkplane
-//  Class:    SketchSolver_Group
-//  Purpose:  verify the group is based on the given workplane
-// ============================================================================
-bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
-{
-  return theWorkplane == mySketch;
-}
-
-// ============================================================================
-//  Function: isInteract
-//  Class:    SketchSolver_Group
-//  Purpose:  verify are there any entities in the group used by given constraint
-// ============================================================================
-bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
-{
-  // Empty group interacts with everything
-  if (isEmpty())
-    return true;
-  // Check interaction with the storage
-  bool isInteracted = myStorage->isInteract(theFeature);
-  ConstraintConstraintMap::const_iterator anIt = myConstraints.begin();
-  for (; !isInteracted && anIt != myConstraints.end(); ++anIt)
-    if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
-        anIt->first->getKind() == SketchPlugin_MultiTranslation::ID()) {
-      isInteracted = anIt->second->isUsed(theFeature);
-      if (isInteracted)
-        break;
-      // if theFeature is a constraint, check its attributes
-      ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
-      if (!aConstraint)
-        continue;
-      for (int i = 0; i < 4 && !isInteracted; ++i) {
-        AttributeRefAttrPtr aRefAttr = aConstraint->refattr(aConstraint->ATTRIBUTE(i));
-        if (!aRefAttr)
-          continue;
-        isInteracted = anIt->second->isUsed((AttributePtr)aRefAttr);
-      }
-    }
-  return isInteracted;
-}
-
 // ============================================================================
 //  Function: changeConstraint
 //  Class:    SketchSolver_Group
@@ -157,181 +103,125 @@ bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
 bool SketchSolver_Group::changeConstraint(
     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
 {
-  // There is no workplane yet, something wrong
-  if (myWorkplaneID == EID_UNKNOWN)
-    return false;
-
-  if (!theConstraint || !theConstraint->data())
-    return false;
-
-  if (!checkFeatureValidity(theConstraint))
-    return false;
-
-  BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
-  myStorage->blockEvents(true);
-
   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
   if (isNewConstraint) {
     // Add constraint to the current group
-    SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
+    SolverConstraintPtr aConstraint = PlaneGCSSolver_Tools::createConstraint(theConstraint);
     if (!aConstraint)
       return false;
-    aConstraint->process(myStorage, getId(), getWorkplaneId());
+    aConstraint->process(myStorage, myIsEventsBlocked);
     if (!aConstraint->error().empty()) {
       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
         return false; // some attribute are not initialized yet, don't show message
       Events_InfoMessage("SketchSolver_Group", aConstraint->error(), this).send();
     }
     myConstraints[theConstraint] = aConstraint;
-
-    if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID())
-      notifyCoincidenceChanged(myConstraints[theConstraint]);
   }
   else
     myConstraints[theConstraint]->update();
 
-  // Fix mirror line
-  if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
-    AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
-        theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
-    if (aRefAttr && aRefAttr->isObject()) {
-      std::shared_ptr<SketchPlugin_Feature> aFeature =
-          std::dynamic_pointer_cast<SketchPlugin_Feature>(
-          ModelAPI_Feature::feature(aRefAttr->object()));
-      if (aFeature) {
-        SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
-        if (aConstraint) {
-          aConstraint->process(myStorage, getId(), getWorkplaneId());
-          setTemporary(aConstraint);
-        }
-      }
-    }
-  }
+  // constraint is created/updated => reset stack of "multi" constraints updates
+  myMultiConstraintUpdateStack = 0;
   return true;
 }
 
-// Update constraints if they contain specific feature
-static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
-{
-  ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
-  for (; aCIt != theConstraints.end(); ++aCIt) {
-    SketchSolver_ConstraintType aType = aCIt->second->getType();
-    if ((aType == CONSTRAINT_MULTI_ROTATION ||
-         aType == CONSTRAINT_MULTI_TRANSLATION)
-        && aCIt->second->isUsed(theFeature))
-      std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
-    else if ((aType == CONSTRAINT_TANGENT_CIRCLE_LINE ||
-              aType == CONSTRAINT_SYMMETRIC || aType == CONSTRAINT_ANGLE)
-             && aCIt->second->isUsed(theFeature))
-      aCIt->second->update();
-  }
-}
-
-// Recalculate slave features of the Multi constraints
-static void updateMultiConstraints(ConstraintConstraintMap& theConstraints)
+bool SketchSolver_Group::updateSketch(CompositeFeaturePtr theSketch)
 {
-  ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
-  for (; aCIt != theConstraints.end(); ++aCIt) {
-    SketchSolver_ConstraintType aType = aCIt->second->getType();
-    if ((aType == CONSTRAINT_MULTI_ROTATION ||
-         aType == CONSTRAINT_MULTI_TRANSLATION))
-      std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
+  static const double THE_TOLERANCE = 1.e-7;
+  bool isChanged = theSketch != mySketch;
+
+  AttributePointPtr anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
+      theSketch->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
+  AttributeDirPtr aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
+      theSketch->attribute(SketchPlugin_Sketch::NORM_ID()));
+  AttributeDirPtr aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
+      theSketch->attribute(SketchPlugin_Sketch::DIRX_ID()));
+
+  isChanged = isChanged
+      || (mySketchOrigin && anOrigin && anOrigin->pnt()->distance(mySketchOrigin) > THE_TOLERANCE)
+      || (mySketchNormal && aNorm && aNorm->xyz()->distance(mySketchNormal->xyz()) > THE_TOLERANCE)
+      || (mySketchXDir && aDirX && aDirX->xyz()->distance(mySketchXDir->xyz()) > THE_TOLERANCE);
+
+  if (isChanged) {
+    mySketch = theSketch;
+    mySketchOrigin = anOrigin->pnt();
+    mySketchNormal = aNorm->dir();
+    mySketchXDir = aDirX->dir();
+
+    myStorage->notify(theSketch);
   }
+  return true;
 }
 
 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
 {
-  if (!checkFeatureValidity(theFeature))
-    return false;
-
-  bool isBlocked = myStorage->isEventsBlocked();
-  if (!isBlocked)
-    myStorage->blockEvents(true);
-
-  myStorage->refresh(true);
-  bool isUpdated = myStorage->update(theFeature);
-
-  updateMultiConstraints(myConstraints, theFeature);
-
-  // events were not blocked before, the feature has not been updated,
-  // so it is necessary to revert blocking
-  if (!isUpdated && !isBlocked)
-    myStorage->blockEvents(false);
-  return isUpdated;
+  return myStorage->update(theFeature);
 }
 
-bool SketchSolver_Group::moveFeature(FeaturePtr theFeature)
+template <class Type>
+static SolverConstraintPtr move(StoragePtr theStorage,
+                                SolverPtr theSketchSolver,
+                                int theSketchDOF,
+                                bool theEventsBlocked,
+                                Type theFeatureOrPoint,
+                                const EntityWrapperPtr& theSolverEntity,
+                                const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
+                                const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
 {
-  BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
-
-  // Firstly, revert changes in the fixed entities
-  myStorage->blockEvents(true);
-  myStorage->refresh(true);
-
-  // Secondly, search attributes of the feature in the list of the Multi constraints and update them
-  updateMultiConstraints(myConstraints, theFeature);
+  bool isEntityExists = (theSolverEntity.get() != 0);
+  if (theSketchDOF == 0 && isEntityExists) {
+    // avoid moving elements of fully constrained sketch
+    theStorage->refresh();
+    return SolverConstraintPtr();
+  }
 
-  // Then, create temporary Fixed constraint
-  SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
-  if (!aConstraint)
-    return false;
-  aConstraint->process(myStorage, getId(), getWorkplaneId());
-  if (aConstraint->error().empty())
-    setTemporary(aConstraint);
-
-  // Workaround to process arcs.
-  // When move unconstrained arc, add temporary constraint to fix radius.
-  if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
-    bool hasDup = myStorage->hasDuplicatedConstraint();
-    SolverConstraintPtr aFixedRadius = aBuilder->createFixedArcRadiusConstraint(theFeature);
-    if (aFixedRadius) {
-      aFixedRadius->process(myStorage, getId(), getWorkplaneId());
-      hasDup = myStorage->hasDuplicatedConstraint() && !hasDup;
-      if (aFixedRadius->error().empty() && !hasDup)
-        setTemporary(aFixedRadius);
-      else
-        aFixedRadius->remove();
-    }
+  // Create temporary Fixed constraint
+  std::shared_ptr<SketchSolver_ConstraintMovement> aConstraint =
+      PlaneGCSSolver_Tools::createMovementConstraint(theFeatureOrPoint);
+  if (aConstraint) {
+    SolverConstraintPtr(aConstraint)->process(theStorage, theEventsBlocked);
+    if (aConstraint->error().empty()) {
+      aConstraint->startPoint(theFrom);
+      theStorage->adjustParametrizationOfArcs();
+      theSketchSolver->initialize();
+      aConstraint->moveTo(theTo);
+      theStorage->setNeedToResolve(true);
+    } else
+      theStorage->notify(aConstraint->movedFeature());
   }
-  return true;
+
+  return aConstraint;
 }
 
-// ============================================================================
-//  Function: addWorkplane
-//  Class:    SketchSolver_Group
-//  Purpose:  create workplane for the group
-// ============================================================================
-bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
+bool SketchSolver_Group::moveFeature(FeaturePtr theFeature,
+                                     const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
+                                     const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
 {
-  if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
-    return false;  // the workplane already exists or the function parameter is not Sketch
-
-  mySketch = theSketch;
-  if (!updateWorkplane()) {
-    mySketch = CompositeFeaturePtr();
-    return false;
-  }
+  EntityWrapperPtr anEntity = myStorage->entity(theFeature);
+  SolverConstraintPtr aConstraint = move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked,
+                                         theFeature, anEntity, theFrom, theTo);
+  setTemporary(aConstraint);
   return true;
 }
 
-// ============================================================================
-//  Function: updateWorkplane
-//  Class:    SketchSolver_Group
-//  Purpose:  update parameters of workplane
-// ============================================================================
-bool SketchSolver_Group::updateWorkplane()
+bool SketchSolver_Group::movePoint(AttributePtr theAttribute,
+                                   const int thePointIndex,
+                                   const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
+                                   const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
 {
-  BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
-  if (!myStorage) // Create storage if not exists
-    myStorage = aBuilder->createStorage(getId());
-
-  // sketch should be unchanged, set it out of current group
-  bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
-  if (isUpdated) {
-    EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
-    myWorkplaneID = anEntity->id();
+  EntityWrapperPtr anEntity = myStorage->entity(theAttribute);
+  SolverConstraintPtr aConstraint;
+  if (thePointIndex < 0) {
+    aConstraint = move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked,
+                       theAttribute, anEntity, theFrom, theTo);
+  }
+  else {
+    aConstraint = move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked,
+                       std::pair<AttributePtr, int>(theAttribute, thePointIndex), anEntity,
+                       theFrom, theTo);
   }
-  return isUpdated;
+  setTemporary(aConstraint);
+  return true;
 }
 
 // ============================================================================
@@ -341,79 +231,95 @@ bool SketchSolver_Group::updateWorkplane()
 // ============================================================================
 bool SketchSolver_Group::resolveConstraints()
 {
+  static const int MAX_STACK_SIZE = 5;
+  // check the "Multi" constraints do not drop sketch into infinite loop
+  if (myMultiConstraintUpdateStack > MAX_STACK_SIZE) {
+    myMultiConstraintUpdateStack = 0;
+    myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
+    // generate error message due to loop update of the sketch
+    getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
+      ->setValue(SketchSolver_Error::INFINITE_LOOP());
+    sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
+    return false;
+  }
+
   bool aResolved = false;
   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
   if (myStorage->isNeedToResolve() &&
-      (!isGroupEmpty || !myConflictingConstraints.empty() || myPrevResult == STATUS_FAILED)) {
-    if (!mySketchSolver)
-      mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
+      (!isGroupEmpty || !myConflictingConstraints.empty() ||
+        myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED)) {
 
-    mySketchSolver->setGroup(myID);
-    mySketchSolver->calculateFailedConstraints(false);
-    myStorage->initializeSolver(mySketchSolver);
-    mySketchSolver->prepare();
-
-    SketchSolver_SolveStatus aResult = STATUS_OK;
+    PlaneGCSSolver_Solver::SolveStatus aResult = PlaneGCSSolver_Solver::STATUS_OK;
     try {
-      if (myStorage->hasDuplicatedConstraint())
-        aResult = STATUS_INCONSISTENT;
-      else if (!isGroupEmpty) {
-        // To avoid overconstraint situation, we will remove temporary constraints one-by-one
-        // and try to find the case without overconstraint
-        bool isLastChance = false;
-        while (true) {
-          aResult = mySketchSolver->solve();
-          if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
-            break;
-////          // try to update parameters and resolve once again
-////          ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
-////          for (; aConstrIt != myConstraints.end(); ++aConstrIt)
-////            aConstrIt->second->update();
-          isLastChance = true;
-
-          removeTemporaryConstraints();
-          mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
-          myStorage->initializeSolver(mySketchSolver);
-        }
+      if (!isGroupEmpty) {
+        myStorage->adjustParametrizationOfArcs();
+        aResult = mySketchSolver->solve();
       }
+      if (aResult == PlaneGCSSolver_Solver::STATUS_FAILED &&
+          !myTempConstraints.empty()) {
+        mySketchSolver->undo();
+        removeTemporaryConstraints();
+        aResult = mySketchSolver->solve();
+      }
+      // check degenerated geometry after constraints resolving
+      if (aResult == PlaneGCSSolver_Solver::STATUS_OK)
+        aResult = myStorage->checkDegeneratedGeometry();
     } catch (...) {
-//      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
-      getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
-      if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
+      getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
+        ->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
+      if (myPrevResult == PlaneGCSSolver_Solver::STATUS_OK ||
+          myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
         // the error message should be changed before sending the message
         sendMessage(EVENT_SOLVER_FAILED);
-        myPrevResult = STATUS_FAILED;
+        myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
       }
       mySketchSolver->undo();
       return false;
     }
-    if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) {  // solution succeeded, store results into correspondent attributes
+    // solution succeeded, store results into correspondent attributes
+    if (aResult == PlaneGCSSolver_Solver::STATUS_OK ||
+        aResult == PlaneGCSSolver_Solver::STATUS_EMPTYSET) {
       myStorage->setNeedToResolve(false);
       myStorage->refresh();
-      updateMultiConstraints(myConstraints);
-      if (myStorage->isNeedToResolve()) // multi-constraints updated some parameters, need to store them
-        myStorage->refresh();
-
-      if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
-        getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
-        std::set<ObjectPtr> aConflicting = myConflictingConstraints;
-        myConflictingConstraints.clear();
-        myPrevResult = STATUS_OK;
-        // the error message should be changed before sending the message
-        sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
+
+      // additional check that copied entities used in Mirror and other "Multi" constraints
+      // is not connected with their originals by constraints.
+      myMultiConstraintUpdateStack += 1;
+      aResolved = true;
+      if (myStorage->isNeedToResolve())
+        aResolved = resolveConstraints();
+
+      if (aResolved) {
+        myMultiConstraintUpdateStack -= 1;
+
+        if (myPrevResult != PlaneGCSSolver_Solver::STATUS_OK ||
+            myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
+          getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
+          std::set<ObjectPtr> aConflicting = myConflictingConstraints;
+          myConflictingConstraints.clear();
+          myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
+          // the error message should be changed before sending the message
+          sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
+        }
       }
+
+      // show degrees of freedom
+      computeDoF();
     } else {
       mySketchSolver->undo();
       if (!myConstraints.empty()) {
         // the error message should be changed before sending the message
-        getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
-        if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
+        const std::string& aErrorMsg = aResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED ?
+                                       SketchSolver_Error::DEGENERATED_GEOMETRY() :
+                                       SketchSolver_Error::CONSTRAINTS();
+        getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(aErrorMsg);
+        if (myPrevResult != aResult ||
+            myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN ||
+            myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED) {
           // Obtain list of conflicting constraints
           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
 
-          if (myConflictingConstraints.empty())
-            sendMessage(EVENT_SOLVER_FAILED, aConflicting);
-          else {
+          if (!myConflictingConstraints.empty()) {
             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
             for (; anIt != aConflicting.end(); ++anIt)
               myConflictingConstraints.erase(*anIt);
@@ -423,153 +329,85 @@ bool SketchSolver_Group::resolveConstraints()
             }
           }
           myConflictingConstraints = aConflicting;
+          if (!myConflictingConstraints.empty())
+            sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
           myPrevResult = aResult;
         }
       }
+
+      // show degrees of freedom only if the degenerated geometry appears,
+      // or if DoF is not computed yet
+      if (aResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED || myDOF < 0)
+        computeDoF();
     }
 
-    aResolved = true;
-  } else if (!isGroupEmpty) {
-    // Check there are constraints Fixed. If they exist, update parameters by stored values
-    ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
-    for (; aCIt != myConstraints.end(); ++aCIt)
-      if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
-        aResolved = true;
-        break;
-      }
-    if (aCIt != myConstraints.end())
-      myStorage->refresh();
+  }
+  else if (isGroupEmpty && isWorkplaneValid()) {
+    // clear error related to previously degenerated entities
+    if (myPrevResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED) {
+      getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
+      myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
+      // the error message should be changed before sending the message
+      myConflictingConstraints.clear();
+      sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
+    }
+
+    computeDoF();
   }
   removeTemporaryConstraints();
-  myStorage->blockEvents(false);
   myStorage->setNeedToResolve(false);
   return aResolved;
 }
 
 // ============================================================================
-//  Function: mergeGroups
+//  Function: computeDoF
 //  Class:    SketchSolver_Group
-//  Purpose:  append specified group to the current group
+//  Purpose:  compute DoF of the sketch and set corresponding field
 // ============================================================================
-void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
+void SketchSolver_Group::computeDoF()
 {
-  // If specified group is empty, no need to merge
-  if (theGroup.isEmpty())
-    return;
-
-  std::set<ObjectPtr> aConstraints;
-  ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
-  for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
-    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);
-  }
-}
-
-// ============================================================================
-//  Function: splitGroup
-//  Class:    SketchSolver_Group
-//  Purpose:  divide the group into several subgroups
-// ============================================================================
-void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
-{
-  // New storage will be used in trimmed way to store the list of constraint interacted together.
-  StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
-  std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
-
-  // Obtain constraints, which should be separated
-  std::list<ConstraintPtr> anUnusedConstraints;
-  ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
-  for ( ; aCIter != myConstraints.end(); aCIter++) {
-    if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
-      aNewStorage->addConstraint(aCIter->first, aDummyVec);
-    else
-      anUnusedConstraints.push_back(aCIter->first);
-  }
-
-  // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
-  std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
-  while (aUnuseIt != anUnusedConstraints.end()) {
-    if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
-      aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
-      anUnusedConstraints.erase(aUnuseIt);
-      aUnuseIt = anUnusedConstraints.begin();
-      continue;
-    }
-    aUnuseIt++;
-  }
-
-  std::list<SketchSolver_Group*>::iterator aCutsIter;
-  // Remove unused constraints
-  for (aUnuseIt = anUnusedConstraints.begin(); aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt)
-    removeConstraint(*aUnuseIt);
-
-  SketchSolver_Group* aBaseGroup;
-  for (aUnuseIt = anUnusedConstraints.begin(); aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
-    aBaseGroup = 0;
-    aCutsIter = theCuts.begin();
-    // Try to append constraint to the current group
-    if (isInteract(*aUnuseIt)) {
-      changeConstraint(*aUnuseIt);
-      aBaseGroup = this;
-    } else {
-      // Try to append constraint to already existent group
-      for (; aCutsIter != theCuts.end(); ++aCutsIter)
-        if ((*aCutsIter)->isInteract(*aUnuseIt)) {
-          (*aCutsIter)->changeConstraint(*aUnuseIt);
-          break;
-        }
-    }
-
-    if (aCutsIter == theCuts.end() && !aBaseGroup) {
-      // Add new group
-      SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
-      aGroup->changeConstraint(*aUnuseIt);
-      theCuts.push_back(aGroup);
-    } else {
-      if (!aBaseGroup)
-        aBaseGroup = *aCutsIter++;
-      // Find other groups interacting with constraint
-      for (; aCutsIter != theCuts.end(); ++aCutsIter)
-        if ((*aCutsIter)->isInteract(*aUnuseIt)) {
-          aBaseGroup->mergeGroups(**aCutsIter);
-          std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
-          theCuts.erase(aRemoveIt);
-        }
-    }
-  }
+  std::string aDoFMsg;
+  static const std::string aMsgContext("Sketch");
+  int aDoF = mySketchSolver->dof();
+  /// "DoF = 0" content of string value is used in PartSet by Sketch edit
+  /// If it is changed, it should be corrected also there
+  //if (aDoF == 0) {
+  //  static const std::string aMsgDoF("Sketch is fully fixed (DoF = 0)");
+  //  aDoFMsg = Config_Translator::translate(aMsgContext, aMsgDoF);
+  //} else {
+  //  static const std::string aMsgDoF("DoF (degrees of freedom) = %1");
+  //  Events_InfoMessage aMsg(aMsgContext, aMsgDoF);
+  //  aMsg.addParameter(aDoF);
+  //  aDoFMsg = Config_Translator::translate(aMsg);
+  //}
+  //// store Unicode value for translated message about DoF
+  //size_t aLen = aDoFMsg.size();
+  //std::wstring aWStr(aLen, L'#');
+  //mbstowcs(&aWStr[0], aDoFMsg.c_str(), aLen);
+  //mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aWStr);
+
+  std::ostringstream aStr;
+  aStr << aDoF;
+  mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aStr.str());
+
+  if (aDoF > 0 && myDOF <= 0)
+    sendMessage(EVENT_SKETCH_UNDER_CONSTRAINED, mySketch, aDoF);
+  else if (aDoF == 0 && myDOF != 0)
+    sendMessage(EVENT_SKETCH_FULLY_CONSTRAINED, mySketch, aDoF);
+  else if (aDoF < 0)
+    sendMessage(EVENT_SKETCH_OVER_CONSTRAINED, mySketch, aDoF);
+
+  myDOF = aDoF;
 }
 
 // ============================================================================
-//  Function: isConsistent
+//  Function: repairConsistency
 //  Class:    SketchSolver_Group
 //  Purpose:  search removed entities and constraints
 // ============================================================================
-bool SketchSolver_Group::isConsistent()
+void SketchSolver_Group::repairConsistency()
 {
-  if (isEmpty()) // no one constraint is initialized yet
-    return true;
-
-  // Check the features and constraint is the storage are valid
-  bool aResult = myStorage->isConsistent();
-  if (aResult) {
-    // additional check of consistency of the Fixed constraint,
-    // because they are not added to the storage
-    ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
-    for (; aCIter != myConstraints.end(); ++aCIter)
-      if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
-         (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
-        aResult = false;
-        break;
-      }
-  }
-  if (!aResult) {
+  if (!areConstraintsValid() || !myStorage->areFeaturesValid()) {
     // remove invalid constraints
     std::set<ConstraintPtr> anInvalidConstraints;
     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
@@ -580,10 +418,13 @@ bool SketchSolver_Group::isConsistent()
     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
       removeConstraint(*aRemoveIt);
+
     // remove invalid features
     myStorage->removeInvalidEntities();
+
+    // show DoF
+    computeDoF();
   }
-  return aResult;
 }
 
 // ============================================================================
@@ -594,14 +435,17 @@ bool SketchSolver_Group::isConsistent()
 // ============================================================================
 void SketchSolver_Group::removeTemporaryConstraints()
 {
-  std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
-  for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
-    (*aTmpIt)->remove();
+  if (!myTempConstraints.empty()) {
+    mySketchSolver->removeConstraint(CID_MOVEMENT);
+
+    std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
+    for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
+      (*aTmpIt)->remove();
+
+    myTempConstraints.clear();
+  }
 
-  if (!myTempConstraints.empty())
-    myStorage->verifyFixed();
   myStorage->setNeedToResolve(false);
-  myTempConstraints.clear();
 }
 
 // ============================================================================
@@ -615,8 +459,9 @@ void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
   for (; aCIter != myConstraints.end(); aCIter++)
     if (aCIter->first == theConstraint) {
       aCIter->second->remove(); // the constraint is not fully removed
-      if (aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID())
-        notifyCoincidenceChanged(aCIter->second);
+
+      // constraint is removed => reset stack of "multi" constraints updates
+      myMultiConstraintUpdateStack = 0;
       break;
     }
   if (aCIter != myConstraints.end())
@@ -630,114 +475,42 @@ void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
 // ============================================================================
 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
 {
-  myTempConstraints.insert(theConstraint);
+  if (theConstraint)
+    myTempConstraints.insert(theConstraint);
 }
 
-
 // ============================================================================
-//  Function: checkFeatureValidity
+//  Function: blockEvents
 //  Class:    SketchSolver_Group
-//  Purpose:  verifies is the feature valid
+//  Purpose:  block or unblock events from features in this group
 // ============================================================================
-bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
+void SketchSolver_Group::blockEvents(bool isBlocked)
 {
-  if (!theFeature || !theFeature->data()->isValid())
-    return true;
-
-  SessionPtr aMgr = ModelAPI_Session::get();
-  ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
-  return aFactory->validate(theFeature);
-}
-
+  if (myIsEventsBlocked == isBlocked)
+    return;
 
+  // block/unblock events from the features in the storage
+  myStorage->blockEvents(isBlocked);
 
+  // block/unblock events from constraints
+  ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
+  for (; aCIt != myConstraints.end(); ++aCIt)
+    aCIt->second->blockEvents(isBlocked);
 
-// ===========   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()) {
-    AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
-        aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
-    AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
-        aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
-    if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
-      return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
-    return 2.5;
-  }
-  if (anID == SketchPlugin_ConstraintDistance::ID() ||
-      anID == SketchPlugin_ConstraintLength::ID() ||
-      anID == SketchPlugin_ConstraintRadius::ID())
-    return 3.0;
-  if (anID == SketchPlugin_ConstraintAngle::ID())
-    return 3.5;
-  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;
+  myIsEventsBlocked = isBlocked;
 }
 
-static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
+bool SketchSolver_Group::areConstraintsValid() const
 {
-  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 and Split 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() ||
-        aFeature->getKind() == SketchPlugin_ConstraintSplit::ID())
-      continue;
-
-    // Find the place where to insert a feature
-    for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
-      if (isLess(aFeature, *aResIt))
-        break;
-    aResult.insert(aResIt, aFeature);
-  }
-
-  return aResult;
+  // Check the constraints are valid
+  ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
+  for (; aCIter != myConstraints.end(); ++aCIter)
+    if (!aCIter->first->data() || !aCIter->first->data()->isValid())
+      return false;
+  return true;
 }
 
-void SketchSolver_Group::notifyCoincidenceChanged(SolverConstraintPtr theCoincidence)
+void SketchSolver_Group::underconstrainedFeatures(std::set<ObjectPtr>& theFeatures) const
 {
-  const std::list<EntityWrapperPtr>& aCoincident = theCoincidence->attributes();
-  EntityWrapperPtr anAttr1 = aCoincident.front();
-  EntityWrapperPtr anAttr2 = aCoincident.back();
-
-  ConstraintConstraintMap::iterator anIt = myConstraints.begin();
-  for (; anIt != myConstraints.end(); ++anIt)
-    anIt->second->notifyCoincidenceChanged(anAttr1, anAttr2);
+  myStorage->getUnderconstrainedGeometry(theFeatures);
 }