Salome HOME
Fixes for the issue #2375 model with dump/import script
[modules/shaper.git] / src / Selector / Selector_Selector.cpp
index c4b6539d15de652d258ad359b10ce610df76002d..d4b1f2319dda33d32486ca82442853d911c44858 100644 (file)
@@ -20,6 +20,9 @@
 
 #include <Selector_Selector.h>
 
+#include <Selector_NameGenerator.h>
+#include <Selector_NExplode.h>
+
 #include <TDF_ChildIDIterator.hxx>
 #include <TopoDS_Iterator.hxx>
 #include <TopoDS_Builder.hxx>
@@ -35,6 +38,7 @@
 #include <TDataStd_Integer.hxx>
 #include <TDataStd_ReferenceArray.hxx>
 #include <TDataStd_IntegerArray.hxx>
+#include <TDataStd_Name.hxx>
 
 #include <list>
 
@@ -47,9 +51,12 @@ static const Standard_GUID kSHAPE_TYPE("864b3267-cb9d-4107-bf58-c3ce1775b171");
 static const Standard_GUID kBASE_ARRAY("7c515b1a-9549-493d-9946-a4933a22f45f");
 // array of the neighbor levels
 static const Standard_GUID kLEVELS_ARRAY("ee4c4b45-e859-4e86-aa4f-6eac68e0ca1f");
+// weak index (integer) of the sub-shape
+static const Standard_GUID kWEAK_INDEX("e9373a61-cabc-4ee8-aabf-aea47c62ed87");
 
 Selector_Selector::Selector_Selector(TDF_Label theLab) : myLab(theLab)
 {
+  myWeakIndex = -1;
 }
 
 TDF_Label Selector_Selector::label()
@@ -124,10 +131,15 @@ static void findNeighbors(const TopoDS_Shape theContext, const TopoDS_Shape theV
     aNBConnectors.Add(aValExp.Current());
   }
 
+  TopTools_MapOfShape alreadyProcessed;
+  alreadyProcessed.Add(theValue);
+
   for(int aLevel = 1; aLevel <= theLevel; aLevel++) {
     TopoDS_ListOfShape aGoodCandidates;
     TopExp_Explorer aCandidate(theContext, theValue.ShapeType());
     for(; aCandidate.More(); aCandidate.Next()) {
+      if (alreadyProcessed.Contains(aCandidate.Current()))
+        continue;
       TopExp_Explorer aCandConnector(aCandidate.Current(), aConnectorType);
       for(; aCandConnector.More(); aCandConnector.Next()) {
         if (aNBConnectors.Contains(aCandConnector.Current())) // candidate is neighbor
@@ -147,6 +159,7 @@ static void findNeighbors(const TopoDS_Shape theContext, const TopoDS_Shape theV
         for(; aGoodConnector.More(); aGoodConnector.Next()) {
           aNBConnectors.Add(aGoodConnector.Current());
         }
+        alreadyProcessed.Add(aGood.Value());
       }
     }
   }
@@ -186,6 +199,7 @@ static const TopoDS_Shape findNeighbor(const TopoDS_Shape theContext,
           }
         }
       }
+      aFirst = false;
     }
   }
   if (aMatches.IsEmpty())
@@ -237,7 +251,22 @@ bool Selector_Selector::select(const TopoDS_Shape theContext, const TopoDS_Shape
     return false;
   // check the value shape can be named as it is, or it is needed to construct it from the
   // higher level shapes (like a box vertex by faces that form this vertex)
-  if (!TNaming_Tool::HasLabel(myLab, theValue)) {
+  bool aIsFound = TNaming_Tool::HasLabel(myLab, theValue);
+  if (aIsFound) { // additional check for selection and delete evolution only: also could not use
+    aIsFound = false;
+    for(TNaming_SameShapeIterator aShapes(theValue, myLab); aShapes.More(); aShapes.Next())
+    {
+      Handle(TNaming_NamedShape) aNS;
+      if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
+        if (aNS->Evolution() == TNaming_MODIFY || aNS->Evolution() == TNaming_GENERATED ||
+            aNS->Evolution() == TNaming_PRIMITIVE) {
+          aIsFound = true;
+          break;
+        }
+      }
+    }
+  }
+  if (!aIsFound) {
     TopAbs_ShapeEnum aSelectionType = theValue.ShapeType();
     myShapeType = aSelectionType;
     if (aSelectionType == TopAbs_COMPOUND || aSelectionType == TopAbs_COMPSOLID ||
@@ -253,16 +282,25 @@ bool Selector_Selector::select(const TopoDS_Shape theContext, const TopoDS_Shape
     }
 
     // try to find the shape of the higher level type in the context shape
-    while(aSelectionType != TopAbs_FACE) {
-      if (aSelectionType == TopAbs_VERTEX) aSelectionType = TopAbs_EDGE;
-      else if (aSelectionType == TopAbs_EDGE) aSelectionType = TopAbs_FACE;
+    bool aFacesTried = false; // for identification of vertices, faces are tried, then edges
+    TopoDS_ListOfShape aLastCommon; // to store the commons not good, but may be used for weak
+    TopTools_MapOfShape aLastIntersectors;
+    while(aSelectionType != TopAbs_FACE || !aFacesTried) {
+      if (aSelectionType == TopAbs_FACE) {
+        if (theValue.ShapeType() != TopAbs_VERTEX)
+          break;
+        aFacesTried = true;
+        aSelectionType = TopAbs_EDGE;
+      } else
+        aSelectionType = TopAbs_FACE;
       TopTools_MapOfShape anIntersectors; // shapes of aSelectionType that contain theValue
       TopoDS_ListOfShape anIntList; // same as anIntersectors
       for(TopExp_Explorer aSelExp(theContext, aSelectionType); aSelExp.More(); aSelExp.Next()) {
         TopExp_Explorer aSubExp(aSelExp.Current(), theValue.ShapeType());
         for(; aSubExp.More(); aSubExp.Next()) {
           if (aSubExp.Current().IsSame(theValue)) {
-            anIntersectors.Add(aSelExp.Current());
+            if (anIntersectors.Add(aSelExp.Current()))
+              anIntList.Append(aSelExp.Current());
             break;
           }
         }
@@ -272,7 +310,7 @@ bool Selector_Selector::select(const TopoDS_Shape theContext, const TopoDS_Shape
       commonShapes(anIntList, theValue.ShapeType(), aCommon);
       if (aCommon.Extent() == 1 && aCommon.First().IsSame(theValue)) {
         // name the intersectors
-        std::list<Selector_Selector> aSubSelList;
+        mySubSelList.clear();
         TopTools_MapOfShape::Iterator anInt(anIntersectors);
         for (; anInt.More(); anInt.Next()) {
           if (!selectBySubSelector(theContext, anInt.Value())) {
@@ -282,7 +320,10 @@ bool Selector_Selector::select(const TopoDS_Shape theContext, const TopoDS_Shape
         if (!anInt.More()) { // all intersectors were correctly named
           myType = SELTYPE_INTERSECT;
           return true;
-        }
+          }
+      } else if (aCommon.Extent() > 1 && aLastCommon.IsEmpty())  {
+        aLastCommon = aCommon;
+        aLastIntersectors = anIntersectors;
       }
     }
 
@@ -310,7 +351,7 @@ bool Selector_Selector::select(const TopoDS_Shape theContext, const TopoDS_Shape
       if (!aResult.IsNull() && aResult.IsSame(theValue)) {
         std::list<std::pair<TopoDS_Shape, int> >::iterator aNBIter = aNBs.begin();
         for(; aNBIter != aNBs.end(); aNBIter++) {
-          if (!selectBySubSelector(theContext, aNBIter->first)) {
+          if (!selectBySubSelector(theContext, aNBIter->first, false)) {
             return false; // something is wrong because before this selection was ok
           }
           myNBLevel.push_back(aNBIter->second);
@@ -320,6 +361,57 @@ bool Selector_Selector::select(const TopoDS_Shape theContext, const TopoDS_Shape
         return true;
       }
     }
+
+    // weak naming to distinguish commons coming from intersection
+    if (aLastCommon.Extent() > 1) {
+      Selector_NExplode aNexp(aLastCommon);
+      myWeakIndex = aNexp.index(theValue);
+      if (myWeakIndex != -1) {
+        // name the intersectors
+        mySubSelList.clear();
+        TopTools_MapOfShape::Iterator anInt(aLastIntersectors);
+        for (; anInt.More(); anInt.Next()) {
+          if (!selectBySubSelector(theContext, anInt.Value())) {
+            break; // if some selector is failed, stop and search another solution
+          }
+        }
+        if (!anInt.More()) { // all intersectors were correctly named
+          myType = SELTYPE_INTERSECT;
+          return true;
+        }
+      }
+    }
+
+    // pure weak naming
+    myType = SELTYPE_WEAK_NAMING;
+    Selector_NExplode aNexp(theContext, theValue.ShapeType());
+    myWeakIndex = aNexp.index(theValue);
+    if (myWeakIndex != -1) {
+      myShapeType = theValue.ShapeType();
+      // searching for context shape label to store in myFinal
+      myFinal.Nullify();
+      if (TNaming_Tool::HasLabel(myLab, theContext)) {
+        for(TNaming_SameShapeIterator aShapes(theContext, myLab); aShapes.More(); aShapes.Next())
+        {
+          Handle(TNaming_NamedShape) aNS;
+          if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
+            TNaming_Evolution anEvolution = aNS->Evolution();
+            if (anEvolution == TNaming_PRIMITIVE || anEvolution == TNaming_GENERATED ||
+                anEvolution == TNaming_MODIFY) {
+              // check this is a new shape
+              for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
+                if (aNSIter.NewShape().IsSame(theContext)) {
+                  myFinal = aNS->Label();
+                  break;
+                }
+              }
+            }
+          }
+        }
+      }
+      return true; // could be final empty (in case it is called recursively) or not
+    }
+
     return false;
   }
   // searching for the base shapes of the value
@@ -377,9 +469,70 @@ bool Selector_Selector::select(const TopoDS_Shape theContext, const TopoDS_Shape
     findBases(aModifList.First(), theValue, true, myBases);
     if (!myBases.IsEmpty()) {
       myFinal = aModifList.First()->Label();
-      myType = SELTYPE_MODIFICATION;
-      return !myBases.IsEmpty();
+      TopoDS_ListOfShape aCommon;
+      findModificationResult(aCommon);
+      // trying to search by neighbours
+      if (aCommon.Extent() > 1) { // more complicated selection
+        if (!theUseNeighbors)
+          return false;
+
+        // searching by neighbours
+        std::list<std::pair<TopoDS_Shape, int> > aNBs;//neighbor sub-shape -> level of neighborhood
+        for(int aLevel = 1; true; aLevel++) {
+          TopTools_MapOfShape aNewNB;
+          findNeighbors(theContext, theValue, aLevel, aNewNB);
+          if (aNewNB.Extent() == 0) { // there are no neighbors of the given level, stop iteration
+            break;
+          }
+          // check which can be named correctly, without by neighbors type
+          for(TopTools_MapOfShape::Iterator aNBIter(aNewNB); aNBIter.More(); ) {
+            Selector_Selector aSelector(myLab.FindChild(1));
+            if (aSelector.select(theContext, aNBIter.Value(), false)) {// add to list of good NBs
+              aNBs.push_back(std::pair<TopoDS_Shape, int>(aNBIter.Value(), aLevel));
+            }
+            aNewNB.Remove(aNBIter.Key());
+            aNBIter.Initialize(aNewNB);
+          }
+          TopoDS_Shape aResult = findNeighbor(theContext, aNBs);
+          if (!aResult.IsNull() && aResult.IsSame(theValue)) {
+            std::list<std::pair<TopoDS_Shape, int> >::iterator aNBIter = aNBs.begin();
+            for(; aNBIter != aNBs.end(); aNBIter++) {
+              if (!selectBySubSelector(theContext, aNBIter->first)) {
+                return false; // something is wrong because before this selection was ok
+              }
+              myNBLevel.push_back(aNBIter->second);
+
+            }
+            myType = SELTYPE_FILTER_BY_NEIGHBOR;
+            return true;
+          }
+        }
+        // filter by neighbours did not help
+        if (aCommon.Extent() > 1) { // weak naming between the common results
+          Selector_NExplode aNexp(aCommon);
+          myWeakIndex = aNexp.index(theValue);
+          if (myWeakIndex == -1)
+            return false;
+        }
+      }
+    }
+    myType = SELTYPE_MODIFICATION;
+    if (myBases.IsEmpty()) { // selection based on the external shape, weak name by finals compound
+      TopoDS_ListOfShape aCommon;
+      myFinal = aModifList.First()->Label();
+      Handle(TNaming_NamedShape) aNS;
+      myFinal.FindAttribute(TNaming_NamedShape::GetID(), aNS);
+      for(TNaming_Iterator aFinalIter(aNS); aFinalIter.More(); aFinalIter.Next()) {
+        const TopoDS_Shape& aNewShape = aFinalIter.NewShape();
+        if (!aNewShape.IsNull())
+          aCommon.Append(aNewShape);
+      }
+      Selector_NExplode aNexp(aCommon);
+      myWeakIndex = aNexp.index(theValue);
+      if (myWeakIndex == -1)
+        return false;
     }
+    return true;
   }
 
   // not found a good result
@@ -399,6 +552,9 @@ void Selector_Selector::store()
     for(; aSubSel != mySubSelList.end(); aSubSel++) {
       aSubSel->store();
     }
+    if (myWeakIndex != -1) {
+      TDataStd_Integer::Set(myLab, kWEAK_INDEX, myWeakIndex);
+    }
     break;
   }
   case SELTYPE_PRIMITIVE: {
@@ -415,6 +571,9 @@ void Selector_Selector::store()
       anArray->SetValue(anIndex, aBIter.Value());
     }
     anArray->SetValue(myBases.Extent(), myFinal); // final is in the end of array
+    if (myWeakIndex != -1) {
+      TDataStd_Integer::Set(myLab, kWEAK_INDEX, myWeakIndex);
+    }
     break;
   }
   case SELTYPE_FILTER_BY_NEIGHBOR: {
@@ -431,6 +590,18 @@ void Selector_Selector::store()
     for(; aSubSel != mySubSelList.end(); aSubSel++) {
       aSubSel->store();
     }
+    break;
+  }
+  case SELTYPE_WEAK_NAMING: {
+    TDataStd_Integer::Set(myLab, kWEAK_INDEX, myWeakIndex);
+    TDataStd_Integer::Set(myLab, kSHAPE_TYPE, (int)myShapeType);
+    // store myFinal in the base array
+    if (!myFinal.IsNull()) {
+      Handle(TDataStd_ReferenceArray) anArray =
+        TDataStd_ReferenceArray::Set(myLab, kBASE_ARRAY, 0, 0);
+      anArray->SetValue(0, myFinal);
+    }
+    break;
   }
   default: { // unknown case
     break;
@@ -459,6 +630,10 @@ bool Selector_Selector::restore()
       if (!mySubSelList.back().restore())
         aSubResult = false;
     }
+    Handle(TDataStd_Integer) aWeakInt;
+    if (myLab.FindAttribute(kWEAK_INDEX, aWeakInt)) {
+      myWeakIndex = aWeakInt->Get();
+    }
     return aSubResult;
   }
   case SELTYPE_PRIMITIVE: {
@@ -477,6 +652,10 @@ bool Selector_Selector::restore()
         myBases.Append(anArray->Value(anIndex));
       }
       myFinal = anArray->Value(anUpper);
+      Handle(TDataStd_Integer) aWeakInt;
+      if (myLab.FindAttribute(kWEAK_INDEX, aWeakInt)) {
+        myWeakIndex = aWeakInt->Get();
+      }
       return true;
     }
     return false;
@@ -503,6 +682,21 @@ bool Selector_Selector::restore()
     }
     return true;
   }
+  case SELTYPE_WEAK_NAMING: {
+    Handle(TDataStd_Integer) aWeakInt;
+    if (!myLab.FindAttribute(kWEAK_INDEX, aWeakInt))
+      return false;
+    myWeakIndex = aWeakInt->Get();
+    Handle(TDataStd_Integer) aShapeTypeAttr;
+    if (!myLab.FindAttribute(kSHAPE_TYPE, aShapeTypeAttr))
+      return false;
+    myShapeType = TopAbs_ShapeEnum(aShapeTypeAttr->Get());
+    Handle(TDataStd_ReferenceArray) anArray;
+    if (myLab.FindAttribute(kBASE_ARRAY, anArray)) {
+      myFinal = anArray->Value(0);
+    }
+    return true;
+  }
   default: { // unknown case
   }
   }
@@ -523,7 +717,29 @@ static void findFinals(const TopoDS_Shape& theBase, const TDF_Label& theFinal,
       }
     }
   }
+}
 
+void Selector_Selector::findModificationResult(TopoDS_ListOfShape& theCommon) {
+  for(TDF_LabelList::Iterator aBase(myBases); aBase.More(); aBase.Next()) {
+    TopTools_MapOfShape aFinals;
+    for(TNaming_Iterator aBaseShape(aBase.Value()); aBaseShape.More(); aBaseShape.Next())
+      findFinals(aBaseShape.NewShape(), myFinal, aFinals);
+    if (!aFinals.IsEmpty()) {
+      if (theCommon.IsEmpty()) { // just copy all to common
+        for(TopTools_MapOfShape::Iterator aFinal(aFinals); aFinal.More(); aFinal.Next()) {
+          theCommon.Append(aFinal.Key());
+        }
+      } else { // keep only shapes presented in both lists
+        for(TopoDS_ListOfShape::Iterator aCommon(theCommon); aCommon.More(); ) {
+          if (aFinals.Contains(aCommon.Value())) {
+            aCommon.Next();
+          } else { // common is not found, remove it
+            theCommon.Remove(aCommon);
+          }
+        }
+      }
+    }
+  }
 }
 
 bool Selector_Selector::solve(const TopoDS_Shape& theContext)
@@ -578,9 +794,16 @@ bool Selector_Selector::solve(const TopoDS_Shape& theContext)
     }
     TopoDS_ListOfShape aCommon; // common sub shapes in each sub-selector (a result)
     commonShapes(aSubSelectorShapes, myShapeType, aCommon);
-    if (aCommon.Extent() != 1)
-      return false;
-    aResult = aCommon.First();
+    if (aCommon.Extent() != 1) {
+      if (myWeakIndex != -1) {
+        Selector_NExplode aNexp(aCommon);
+        aResult = aNexp.shape(myWeakIndex);
+      } else {
+        return false;
+      }
+    } else {
+      aResult = aCommon.First();
+    }
     break;
   }
   case SELTYPE_PRIMITIVE: {
@@ -588,31 +811,31 @@ bool Selector_Selector::solve(const TopoDS_Shape& theContext)
     if (myFinal.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
       aResult = aNS->Get();
     }
+    break;
   }
   case SELTYPE_MODIFICATION: {
-    TopoDS_ListOfShape aFinalsCommon; // final shapes presented in all results from bases
-    for(TDF_LabelList::Iterator aBase(myBases); aBase.More(); aBase.Next()) {
-      TopTools_MapOfShape aFinals;
-      for(TNaming_Iterator aBaseShape(aBase.Value()); aBaseShape.More(); aBaseShape.Next())
-        findFinals(aBaseShape.NewShape(), myFinal, aFinals);
-      if (!aFinals.IsEmpty()) {
-        if (aFinalsCommon.IsEmpty()) { // just copy all to common
-          for(TopTools_MapOfShape::Iterator aFinal(aFinals); aFinal.More(); aFinal.Next()) {
-            aFinalsCommon.Append(aFinal.Key());
-          }
-        } else { // keep only shapes presented in both lists
-          for(TopoDS_ListOfShape::Iterator aCommon(aFinalsCommon); aCommon.More(); ) {
-            if (aFinals.Contains(aCommon.Value())) {
-              aCommon.Next();
-            } else { // common is not found, remove it
-              aFinalsCommon.Remove(aCommon);
-            }
-          }
-        }
+    if (myBases.IsEmpty() && myWeakIndex) { // weak name by the final shapes index
+      TopoDS_ListOfShape aCommon;
+      Handle(TNaming_NamedShape) aNS;
+      myFinal.FindAttribute(TNaming_NamedShape::GetID(), aNS);
+      for(TNaming_Iterator aFinalIter(aNS); aFinalIter.More(); aFinalIter.Next()) {
+        const TopoDS_Shape& aNewShape = aFinalIter.NewShape();
+        if (!aNewShape.IsNull())
+          aCommon.Append(aNewShape);
+      }
+      Selector_NExplode aNexp(aCommon);
+      aResult = aNexp.shape(myWeakIndex);
+    } else { // standard case
+      TopoDS_ListOfShape aFinalsCommon; // final shapes presented in all results from bases
+      findModificationResult(aFinalsCommon);
+      if (aFinalsCommon.Extent() == 1) // only in this case result is valid: found only one shape
+        aResult = aFinalsCommon.First();
+      else if (aFinalsCommon.Extent() > 1 && myWeakIndex) {
+        Selector_NExplode aNExp(aFinalsCommon);
+        aResult = aNExp.shape(myWeakIndex);
       }
     }
-    if (aFinalsCommon.Extent() == 1) // only in this case result is valid: found only one shape
-      aResult = aFinalsCommon.First();
+    break;
   }
   case SELTYPE_FILTER_BY_NEIGHBOR: {
     std::list<std::pair<TopoDS_Shape, int> > aNBs; /// neighbor sub-shape -> level of neighborhood
@@ -625,6 +848,22 @@ bool Selector_Selector::solve(const TopoDS_Shape& theContext)
       aNBs.push_back(std::pair<TopoDS_Shape, int>(aSubSel->value(), *aLevel));
     }
     aResult = findNeighbor(theContext, aNBs);
+    break;
+  }
+  case SELTYPE_WEAK_NAMING: {
+    TopoDS_Shape aContext;
+    if (myFinal.IsNull()) {
+      aContext = theContext;
+    } else {
+      Handle(TNaming_NamedShape) aNS;
+      if (myFinal.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
+        aContext = aNS->Get();
+      }
+    }
+    if (!aContext.IsNull()) {
+      Selector_NExplode aNexp(aContext, myShapeType);
+      aResult = aNexp.shape(myWeakIndex);
+    }
   }
   default: { // unknown case
   }
@@ -646,10 +885,227 @@ TopoDS_Shape Selector_Selector::value()
   return TopoDS_Shape(); // empty, error shape
 }
 
-bool Selector_Selector::selectBySubSelector(const TopoDS_Shape theContext, const TopoDS_Shape theValue)
+static const std::string kWEAK_NAME_IDENTIFIER = "weak_name_";
+static const std::string kPUREWEAK_NAME_IDENTIFIER = "_weak_name_";
+
+std::string Selector_Selector::name(Selector_NameGenerator* theNameGenerator) {
+  switch(myType) {
+  case SELTYPE_CONTAINER:
+  case SELTYPE_INTERSECT: {
+    std::string aResult;
+    // add names of sub-components one by one in "[]" +optionally [weak_name_1]
+    std::list<Selector_Selector>::iterator aSubSel = mySubSelList.begin();
+    for(; aSubSel != mySubSelList.end(); aSubSel++) {
+      aResult += '[';
+      aResult += aSubSel->name(theNameGenerator);
+      aResult += ']';
+    }
+    if (myWeakIndex != -1) {
+      std::ostringstream aWeakStr;
+      aWeakStr<<"["<<kWEAK_NAME_IDENTIFIER<<myWeakIndex<<"]";
+      aResult += aWeakStr.str();
+    }
+    return aResult;
+  }
+  case SELTYPE_PRIMITIVE: {
+    Handle(TDataStd_Name) aName;
+    if (!myFinal.FindAttribute(TDataStd_Name::GetID(), aName))
+      return "";
+    return theNameGenerator->contextName(myFinal) + "/" +
+      std::string(TCollection_AsciiString(aName->Get()).ToCString());
+  }
+  case SELTYPE_MODIFICATION: {
+    // final&base1&base2 +optionally: [weak_name_1]
+    std::string aResult;
+    Handle(TDataStd_Name) aName;
+    if (!myFinal.FindAttribute(TDataStd_Name::GetID(), aName))
+      return "";
+    aResult += theNameGenerator->contextName(myFinal) + "/" +
+      std::string(TCollection_AsciiString(aName->Get()).ToCString());
+    for(TDF_LabelList::iterator aBase = myBases.begin(); aBase != myBases.end(); aBase++) {
+      if (!aBase->FindAttribute(TDataStd_Name::GetID(), aName))
+        return "";
+      aResult += "&";
+      aResult += theNameGenerator->contextName(*aBase) + "/" +
+        std::string(TCollection_AsciiString(aName->Get()).ToCString());
+    }
+    if (myWeakIndex != -1) {
+      std::ostringstream aWeakStr;
+      aWeakStr<<"&"<<kWEAK_NAME_IDENTIFIER<<myWeakIndex;
+      aResult += aWeakStr.str();
+    }
+    return aResult;
+  }
+  case SELTYPE_FILTER_BY_NEIGHBOR: {
+    // (nb1)level_if_more_than_1(nb2)level_if_more_than_1(nb3)level_if_more_than_1
+    std::string aResult;
+    std::list<int>::iterator aLevel = myNBLevel.begin();
+    std::list<Selector_Selector>::iterator aSubSel = mySubSelList.begin();
+    for(; aSubSel != mySubSelList.end(); aSubSel++, aLevel++) {
+      aResult += "(" + aSubSel->name(theNameGenerator) + ")";
+      if (*aLevel > 1) {
+        std::ostringstream aLevelStr;
+        aLevelStr<<*aLevel;
+        aResult += aLevelStr.str();
+      }
+    }
+    return aResult;
+  }
+  case SELTYPE_WEAK_NAMING: {
+    // _weak_naming_1_Context
+    std::ostringstream aWeakStr;
+    aWeakStr<<kPUREWEAK_NAME_IDENTIFIER<<myWeakIndex;
+    std::string aResult = aWeakStr.str();
+    if (!myFinal.IsNull())
+      aResult += "_" + theNameGenerator->contextName(myFinal);
+    return aResult;
+  }
+  default: { // unknown case
+  }
+  };
+  return "";
+}
+
+TDF_Label Selector_Selector::restoreByName(
+  std::string theName, const TopAbs_ShapeEnum theShapeType,
+  Selector_NameGenerator* theNameGenerator)
+{
+  if (theName[0] == '[') { // intersection or container
+    switch(theShapeType) {
+    case TopAbs_COMPOUND:
+    case TopAbs_COMPSOLID:
+    case TopAbs_SHELL:
+    case TopAbs_WIRE:
+      myType = SELTYPE_CONTAINER;
+      break;
+    case TopAbs_VERTEX:
+    case TopAbs_EDGE:
+    case TopAbs_FACE:
+      myType = SELTYPE_INTERSECT;
+      break;
+    default:
+      return TDF_Label(); // unknown case
+    }
+    myShapeType = theShapeType;
+    TDF_Label aContext;
+    for(size_t aStart = 0; aStart != std::string::npos;
+        aStart = theName.find('[', aStart + 1)) {
+      size_t anEndPos = theName.find(']', aStart + 1);
+      if (anEndPos != std::string::npos) {
+        std::string aSubStr = theName.substr(aStart + 1, anEndPos - aStart - 1);
+        if (aSubStr.find(kWEAK_NAME_IDENTIFIER) == 0) { // weak name identifier
+          std::string aWeakIndex = aSubStr.substr(kWEAK_NAME_IDENTIFIER.size());
+          myWeakIndex = atoi(aWeakIndex.c_str());
+          continue;
+        }
+        mySubSelList.push_back(Selector_Selector(myLab.FindChild(int(mySubSelList.size()) + 1)));
+        TDF_Label aSubContext =
+          mySubSelList.back().restoreByName(aSubStr, theShapeType, theNameGenerator);
+        if (aSubContext.IsNull())
+          return aSubContext; // invalid sub-selection parsing
+        if (!aContext.IsNull() && !aContext.IsEqual(aSubContext)) {
+          if (!theNameGenerator->isLater(aContext, aSubContext))
+            aContext = aSubContext;
+        } else {
+          aContext = aSubContext;
+        }
+      } else
+        return TDF_Label(); // invalid parentheses
+    }
+    return aContext;
+  } else if (theName[0] == '(') { // filter by neighbours
+    myType = SELTYPE_FILTER_BY_NEIGHBOR;
+    TDF_Label aContext;
+    for(size_t aStart = 0; aStart != std::string::npos;
+      aStart = theName.find('(', aStart + 1)) {
+      size_t anEndPos = theName.find(')', aStart + 1);
+      if (anEndPos != std::string::npos) {
+        std::string aSubStr = theName.substr(aStart + 1, anEndPos - aStart - 1);
+        mySubSelList.push_back(Selector_Selector(myLab.FindChild(int(mySubSelList.size()) + 1)));
+        TDF_Label aSubContext =
+          mySubSelList.back().restoreByName(aSubStr, theShapeType, theNameGenerator);
+        if (aSubContext.IsNull())
+          return aSubContext; // invalid sub-selection parsing
+        if (!aContext.IsNull() && !aContext.IsEqual(aSubContext)) {
+          if (!theNameGenerator->isLater(aContext, aSubContext))
+            aContext = aSubContext;
+        } else {
+          aContext = aSubContext;
+        }
+        // searching for the level index
+        std::string aLevel;
+        for(anEndPos++; anEndPos != std::string::npos &&
+                        theName[anEndPos] != '(' && theName[anEndPos] != 0;
+            anEndPos++) {
+          aLevel += theName[anEndPos];
+        }
+        if (aLevel.empty())
+          myNBLevel.push_back(1); // by default it is 1
+        else {
+          int aNum = atoi(aLevel.c_str());
+          if (aNum > 0)
+            myNBLevel.push_back(aNum);
+          else
+            return TDF_Label(); // invalid number
+        }
+      } else
+        return TDF_Label(); // invalid parentheses
+    }
+    return aContext;
+  } if (theName.find(kPUREWEAK_NAME_IDENTIFIER) == 0) { // weak naming identifier
+    myType = SELTYPE_WEAK_NAMING;
+    std::string aWeakIndex = theName.substr(kPUREWEAK_NAME_IDENTIFIER.size());
+    std::size_t aContextPosition = aWeakIndex.find("_");
+    myWeakIndex = atoi(aWeakIndex.c_str());
+    myShapeType = theShapeType;
+    TDF_Label aContext;
+    if (aContextPosition != std::string::npos) { // context is also defined
+      std::string aContextName = aWeakIndex.substr(aContextPosition + 1);
+      theNameGenerator->restoreContext(aContextName, aContext, myFinal);
+    }
+    return aContext;
+  } else if (theName.find('&') == std::string::npos) { // wihtout '&' it can be only primitive
+    myType = SELTYPE_PRIMITIVE;
+    TDF_Label aContext;
+    if (theNameGenerator->restoreContext(theName, aContext, myFinal)) {
+      if (!myFinal.IsNull())
+        return aContext;
+    }
+  } else { // modification
+    myType = SELTYPE_MODIFICATION;
+    TDF_Label aContext;
+    for(size_t anEnd, aStart = 0; aStart != std::string::npos; aStart = anEnd) {
+      if (aStart != 0)
+        aStart++;
+      anEnd = theName.find('&', aStart);
+      std::string aSubStr =
+        theName.substr(aStart, anEnd == std::string::npos ? anEnd : anEnd - aStart);
+      if (aSubStr.find(kWEAK_NAME_IDENTIFIER) == 0) { // weak name identifier
+        std::string aWeakIndex = aSubStr.substr(kWEAK_NAME_IDENTIFIER.size());
+        myWeakIndex = atoi(aWeakIndex.c_str());
+        continue;
+      }
+      TDF_Label aSubContext, aValue;
+      if (!theNameGenerator->restoreContext(aSubStr, aSubContext, aValue))
+        return TDF_Label(); // can not restore
+      if(aSubContext.IsNull() || aValue.IsNull())
+        return TDF_Label(); // can not restore
+      if (myFinal.IsNull()) {
+        myFinal = aValue;
+        aContext = aSubContext;
+      } else
+        myBases.Append(aValue);
+    }
+    return aContext;
+  }
+  return TDF_Label();
+}
+
+bool Selector_Selector::selectBySubSelector(
+  const TopoDS_Shape theContext, const TopoDS_Shape theValue, const bool theUseNeighbors)
 {
   mySubSelList.push_back(Selector_Selector(myLab.FindChild(int(mySubSelList.size()) + 1)));
-  if (!mySubSelList.back().select(theContext, theValue)) {
+  if (!mySubSelList.back().select(theContext, theValue, theUseNeighbors)) {
     mySubSelList.clear(); // if one of the selector is failed, all become invalid
     return false;
   }