]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_SelectionNaming.cpp
Salome HOME
Issue #1739: Naming on faces not correct
[modules/shaper.git] / src / Model / Model_SelectionNaming.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_SelectionNaming.cpp
4 // Created:     11 Aug 2015
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_SelectionNaming.h"
8 #include "Model_Document.h"
9 #include "Model_Objects.h"
10 #include <ModelAPI_Feature.h>
11 #include <Events_InfoMessage.h>
12 #include <ModelAPI_Session.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <ModelAPI_ResultBody.h>
17 #include <GeomAPI_Wire.h>
18
19 #include <TopoDS_Iterator.hxx>
20 #include <TopoDS.hxx>
21 #include <TopoDS_Compound.hxx>
22 #include <TopExp.hxx>
23 #include <TopExp_Explorer.hxx>
24 #include <TopTools_ListOfShape.hxx>
25 #include <TopTools_MapOfShape.hxx>
26 #include <TopTools_IndexedMapOfShape.hxx>
27 #include <TopTools_ListIteratorOfListOfShape.hxx>
28 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
29 #include <TopTools_MapIteratorOfMapOfShape.hxx>
30 #include <BRep_Builder.hxx>
31 #include <TNaming_Iterator.hxx>
32 #include <TNaming_Tool.hxx>
33 #include <TNaming_NamedShape.hxx>
34 #include <TNaming_Localizer.hxx>
35 #include <TDataStd_Name.hxx>
36 #include <TColStd_MapOfTransient.hxx>
37 #include <algorithm>
38 #include <stdexcept>
39
40 #ifdef DEB_NAMING
41 #include <BRepTools.hxx>
42 #endif
43
44 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
45 {
46   myLab = theSelectionLab;
47 }
48
49 std::string Model_SelectionNaming::getShapeName(
50   std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
51   const bool theAddContextName)
52 {
53   std::string aName;
54   // check if the subShape is already in DF
55   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
56   Handle(TDataStd_Name) anAttr;
57   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
58     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
59       aName = TCollection_AsciiString(anAttr->Get()).ToCString();
60       // indexes are added to sub-shapes not primitives (primitives must not be located at the same label)
61       if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && theAddContextName) {
62         const TDF_Label& aLabel = aNS->Label();//theDoc->findNamingName(aName);
63         static const std::string aPostFix("_");
64         TNaming_Iterator anItL(aNS);
65         for(int i = 1; anItL.More(); anItL.Next(), i++) {
66           if(anItL.NewShape() == theShape) {
67             aName += aPostFix;
68             aName += TCollection_AsciiString (i).ToCString();
69             break;
70           }
71         }
72       }
73       if (theAddContextName && aName.find("/") == std::string::npos) { // searching for the context object
74         for(TDF_Label anObjL = aNS->Label(); anObjL.Depth() > 4; anObjL = anObjL.Father()) {
75           int aDepth = anObjL.Depth();
76           if (aDepth == 5 || aDepth == 7) {
77             ObjectPtr anObj = theDoc->objects()->object(anObjL);
78             if (anObj) {
79               aName = anObj->data()->name() + "/" + aName;
80             }
81           }
82         }
83       }
84     }
85   }
86   return aName;
87 }
88
89 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
90 {
91   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
92   TopoDS_Compound aCmp;
93   BRep_Builder BB;
94   BB.MakeCompound(aCmp);
95   TopTools_ListIteratorOfListOfShape it(theAncestors);
96   for(;it.More();it.Next()) {
97     BB.Add(aCmp, it.Value());
98     theSMap.Add(it.Value());
99   }
100   int aNumber(0);
101   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
102   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
103   for (int i = 1; i <= aMap2.Extent(); i++) {
104     const TopoDS_Shape& aKey = aMap2.FindKey(i);
105     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
106     if(anAncestors.Extent() > 1) aNumber++;
107   }
108   if(aNumber > 1) return false;
109   return true;
110 }
111
112 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
113   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
114   const bool theAnotherDoc)
115 {
116   std::string aName("Undefined name");
117   if(!theContext.get() || theContext->shape()->isNull()) 
118     return !theDefaultName.empty() ? theDefaultName : aName;
119   
120   // if it is in result of another part
121   std::shared_ptr<Model_Document> aDoc = 
122     std::dynamic_pointer_cast<Model_Document>(theContext->document());
123   if (theContext->groupName() == ModelAPI_ResultPart::group()) {
124     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
125     int anIndex;
126     if (theSubSh.get())
127       return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
128     else 
129       return aPart->data()->name();
130   }
131
132   if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
133     // but if it is in another Part, add this part name
134     std::string aPartName;
135     if (theAnotherDoc)
136       aPartName = theContext->document()->kind() + "/"; // PartSet
137     return aPartName + theContext->data()->name();
138   }
139   TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
140   TopoDS_Shape aContext  = theContext->shape()->impl<TopoDS_Shape>();
141 #ifdef DEB_NAMING
142   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
143     BRepTools::Write(aSubShape, "Selection.brep");
144     BRepTools::Write(aContext, "Context.brep");
145   }
146 #endif
147
148   // add the result name to the name of the shape (it was in BodyBuilder, but did not work on Result rename)
149   bool isNeedContextName = theContext->shape().get() && !theContext->shape()->isEqual(theSubSh);
150
151   // check if the subShape is already in DF
152   aName = getShapeName(aDoc, aSubShape, isNeedContextName);
153   if(aName.empty() ) { // not in the document!
154     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
155     switch (aType) {
156     case TopAbs_FACE:
157       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged             
158       break;
159     case TopAbs_EDGE:
160       {
161         // name structure: F1 & F2 [& F3 & F4], where F1 & F2 the faces which gives the Edge in trivial case
162         // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces      
163         if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
164           aName = "Degenerated_Edge";
165           break;
166         }    
167         TopTools_IndexedDataMapOfShapeListOfShape aMap;
168         TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
169         TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
170         bool isTrivialCase(true);
171         if(aMap.Contains(aSubShape)) {
172           const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
173           // check that it is not a trivial case (F1 & F2: aNumber = 1)
174           isTrivialCase = isTrivial(anAncestors, aSMap);                
175         } else 
176           break;
177         TopTools_ListOfShape aListOfNbs;
178         if(!isTrivialCase) { // find Neighbors
179           TNaming_Localizer aLocalizer;
180           TopTools_MapOfShape aMap3;
181           aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
182           //int n = aMap3.Extent();
183           TopTools_MapIteratorOfMapOfShape it(aMap3);
184           for(;it.More();it.Next()) {
185             const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
186             //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
187             const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
188             TopTools_ListIteratorOfListOfShape it2(aList);
189             for(;it2.More();it2.Next()) {
190               if(aSMap.Contains(it2.Value())) continue; // skip this Face
191               aListOfNbs.Append(it2.Value());
192             }
193           }
194         }  // else a trivial case
195
196         // build name of the sub-shape Edge
197         for(int i=1; i <= aSMap.Extent(); i++) {
198           const TopoDS_Shape& aFace = aSMap.FindKey(i);
199           std::string aFaceName = getShapeName(aDoc, aFace, isNeedContextName);
200           if(i == 1)
201             aName = aFaceName;
202           else 
203             aName += "&" + aFaceName;
204         }
205         TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
206         for (;itl.More();itl.Next()) {
207           std::string aFaceName = getShapeName(aDoc, itl.Value(), isNeedContextName);
208           aName += "&" + aFaceName;
209         }                 
210       }
211       break;
212
213     case TopAbs_VERTEX:
214       // name structure (Monifold Topology): 
215       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
216       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
217       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
218       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
219       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
220       //                   or compound of 2 open faces.
221       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
222       //                   two independent edges (wire or compound)
223       // implemented 2 first cases
224       {
225         TopTools_IndexedDataMapOfShapeListOfShape aMap;
226         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
227         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
228         TopTools_ListOfShape aList;
229         TopTools_MapOfShape aFMap;
230         // fix is below
231         TopTools_ListIteratorOfListOfShape itl2(aList2);
232         for (int i = 1;itl2.More();itl2.Next(),i++) {
233           if(aFMap.Add(itl2.Value()))
234             aList.Append(itl2.Value());
235         }
236         int n = aList.Extent();
237         bool isByFaces = n >= 3;
238         if(!isByFaces) { // open topology case or Compound case => via edges
239           TopTools_IndexedDataMapOfShapeListOfShape aMap;
240           TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
241           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
242           if(aList22.Extent() >= 2)  { // regular solution
243
244             // bug! duplication; fix is below
245             aFMap.Clear();
246             TopTools_ListOfShape aListE;
247             TopTools_ListIteratorOfListOfShape itl2(aList22);
248             for (int i = 1;itl2.More();itl2.Next(),i++) {
249               if(aFMap.Add(itl2.Value()))
250                 aListE.Append(itl2.Value());
251             }
252             n = aListE.Extent();
253             TopTools_ListIteratorOfListOfShape itl(aListE);
254             for (int i = 1;itl.More();itl.Next(),i++) {
255               const TopoDS_Shape& anEdge = itl.Value();
256               std::string anEdgeName = getShapeName(aDoc, anEdge, isNeedContextName);
257               if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
258                 isByFaces = true;
259                 aName.clear();
260                 break;
261               }
262               if(i == 1)
263                 aName = anEdgeName;
264               else 
265                 aName += "&" + anEdgeName;
266             }
267           }//reg
268           else { // dangle vertex: if(aList22.Extent() == 1)
269             //it should be already in DF
270           }
271         } 
272         if (isByFaces) {
273           TopTools_ListIteratorOfListOfShape itl(aList);
274           for (int i = 1;itl.More();itl.Next(),i++) {
275             const TopoDS_Shape& aFace = itl.Value();
276             std::string aFaceName = getShapeName(aDoc, aFace, isNeedContextName);
277             if(i == 1)
278               aName = aFaceName;
279             else 
280               aName += "&" + aFaceName;
281           }
282         }
283       }
284       break;
285     }
286   }
287
288   return aName;
289 }
290
291 TopAbs_ShapeEnum translateType (const std::string& theType)
292 {
293   // map from the textual shape types to OCCT enumeration
294   static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
295
296   if(aShapeTypes.size() == 0) {
297     aShapeTypes["compound"]   = TopAbs_COMPOUND;
298     aShapeTypes["compounds"]  = TopAbs_COMPOUND;
299     aShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
300     aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
301     aShapeTypes["solid"]      = TopAbs_SOLID;
302     aShapeTypes["solids"]     = TopAbs_SOLID;
303     aShapeTypes["shell"]      = TopAbs_SHELL;
304     aShapeTypes["shells"]     = TopAbs_SHELL;
305     aShapeTypes["face"]       = TopAbs_FACE;
306     aShapeTypes["faces"]      = TopAbs_FACE;
307     aShapeTypes["wire"]       = TopAbs_WIRE;
308     aShapeTypes["wires"]      = TopAbs_WIRE;
309     aShapeTypes["edge"]       = TopAbs_EDGE;
310     aShapeTypes["edges"]      = TopAbs_EDGE;
311     aShapeTypes["vertex"]     = TopAbs_VERTEX;
312     aShapeTypes["vertices"]   = TopAbs_VERTEX;
313     aShapeTypes["COMPOUND"]   = TopAbs_COMPOUND;
314     aShapeTypes["COMPOUNDS"]  = TopAbs_COMPOUND;
315     aShapeTypes["COMPSOLID"]  = TopAbs_COMPSOLID;
316     aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
317     aShapeTypes["SOLID"]      = TopAbs_SOLID;
318     aShapeTypes["SOLIDS"]     = TopAbs_SOLID;
319     aShapeTypes["SHELL"]      = TopAbs_SHELL;
320     aShapeTypes["SHELLS"]     = TopAbs_SHELL;
321     aShapeTypes["FACE"]       = TopAbs_FACE;
322     aShapeTypes["FACES"]      = TopAbs_FACE;
323     aShapeTypes["WIRE"]       = TopAbs_WIRE;
324     aShapeTypes["WIRES"]      = TopAbs_WIRE;
325     aShapeTypes["EDGE"]       = TopAbs_EDGE;
326     aShapeTypes["EDGES"]      = TopAbs_EDGE;
327     aShapeTypes["VERTEX"]     = TopAbs_VERTEX;
328     aShapeTypes["VERTICES"]   = TopAbs_VERTEX;
329   }
330   if (aShapeTypes.find(theType) != aShapeTypes.end())
331     return aShapeTypes[theType];
332   Events_InfoMessage("Model_SelectionNaming", "Shape type defined in XML is not implemented!").send();
333   return TopAbs_SHAPE;
334 }
335
336 const TopoDS_Shape getShapeFromNS(
337   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
338 {
339   TopoDS_Shape aSelection;
340   std::string::size_type n = theSubShapeName.rfind('/');                        
341   if (n == std::string::npos) n = -1;
342   std::string aSubString = theSubShapeName.substr(n + 1);
343   n = aSubString.rfind('_');
344   int indx = 1;
345   if (n != std::string::npos) {// for primitives this is a first 
346     // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
347     Handle(TDataStd_Name) aName;
348     if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
349         aName->Get() != theSubShapeName.c_str()) {
350       aSubString = aSubString.substr(n+1);
351       indx = atoi(aSubString.c_str());
352     }
353   }
354
355   TNaming_Iterator anItL(theNS);
356   for(int i = 1; anItL.More(); anItL.Next(), i++) {
357     if (i == indx) {
358       return anItL.NewShape();
359     }
360   }
361   return aSelection;    
362 }
363
364 const TopoDS_Shape findFaceByName(
365   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
366 {
367   TopoDS_Shape aFace;
368   //std::string::size_type n, nb = theSubShapeName.rfind('/');                  
369   //if (nb == std::string::npos) nb = 0;
370   //std::string aSubString = theSubShapeName.substr(nb + 1);
371   std::string aSubString = theSubShapeName;
372
373   TDF_Label aLabel = theDoc->findNamingName(aSubString);
374   if (aLabel.IsNull()) { // try to remove additional artificial suffix
375     std::string::size_type n = aSubString.rfind('_');
376     if (n != std::string::npos) {
377       aSubString = aSubString.substr(0, n);
378        aLabel = theDoc->findNamingName(aSubString);
379     }
380   }
381   if(aLabel.IsNull()) return aFace;
382   Handle(TNaming_NamedShape) aNS;
383   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
384     aFace = getShapeFromNS(theSubShapeName, aNS);
385   }
386   return aFace;
387 }
388
389 size_t ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
390 {
391   std::string aName = theSubShapeName;
392   std::string aLastName;
393   size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
394   while ((n2 = aName.find('&', n1)) != std::string::npos) {
395     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
396     theList.push_back(aName1);  
397     n1 = n2 + 1;
398     aLastName = aName.substr(n1);
399   }
400   if(!aLastName.empty())
401     theList.push_back(aLastName);
402   return theList.size();
403 }
404
405 const TopoDS_Shape findCommonShape(
406   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
407 {
408   TopoDS_Shape aShape;
409   std::vector<TopTools_MapOfShape> aVec;
410   TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
411   if(theList.Extent() > 1) {
412     aVec.push_back(aMap1);
413     aVec.push_back(aMap2);
414   }
415   if(theList.Extent() > 2)
416     aVec.push_back(aMap3);
417   if(theList.Extent() == 4)
418     aVec.push_back(aMap4);
419
420   //fill maps
421   TopTools_ListIteratorOfListOfShape it(theList);
422   for(int i = 0;it.More();it.Next(),i++) {
423     const TopoDS_Shape& aFace = it.Value();             
424     if(i < 2) {
425       TopExp_Explorer anExp (aFace, theType);
426       for(;anExp.More();anExp.Next()) {
427         const TopoDS_Shape& anEdge = anExp.Current();
428         if (!anEdge.IsNull())
429           aVec[i].Add(anExp.Current());
430       }
431     } else {
432       TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
433       for(;anExp.More();anExp.Next()) {
434         const TopoDS_Shape& aVertex = anExp.Current();
435         if (!aVertex.IsNull())
436           aVec[i].Add(anExp.Current());
437       }
438     }
439   }
440   //trivial case: 2 faces
441   TopTools_ListOfShape aList;
442   TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
443   for(;it2.More();it2.Next()) {
444     if(aVec[1].Contains(it2.Key())) {
445       aShape = it2.Key();
446       if(theList.Extent() == 2)
447         break;
448       else 
449         aList.Append(it2.Key());
450     }
451   }
452   if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors 
453     if(aVec[2].Extent() && aVec[3].Extent()) {
454       TopTools_ListIteratorOfListOfShape it(aList);
455       for(;it.More();it.Next()) {
456         const TopoDS_Shape& aCand = it.Value();
457         // not yet completelly implemented, to be rechecked
458         TopoDS_Vertex aV1, aV2;
459         TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
460         int aNum(0);
461         if(aVec[2].Contains(aV1)) aNum++;
462         else if(aVec[2].Contains(aV2)) aNum++;
463         if(aVec[3].Contains(aV1)) aNum++;
464         else if(aVec[3].Contains(aV2)) aNum++;
465         if(aNum == 2) {
466           aShape = aCand;
467           break;
468         }
469       }
470     }
471   }
472
473   if(aList.Extent() && aVec.size() == 3) {
474
475     TopTools_ListIteratorOfListOfShape it(aList);
476     for(;it.More();it.Next()) {
477       const TopoDS_Shape& aCand = it.Value();
478       if(aVec[2].Contains(aCand)) {
479         aShape = aCand;
480         break;
481       }
482     }
483   }
484   return aShape;
485 }
486
487 std::string getContextName(const std::string& theSubShapeName)
488 {
489   std::string aName;
490   std::string::size_type n = theSubShapeName.find('/');                 
491   if (n == std::string::npos) return theSubShapeName;
492   aName = theSubShapeName.substr(0, n);
493   return aName;
494 }
495
496 /// Parses naming name of sketch sub-elements: takes indices and orientation 
497 /// (if theOriented = true) from this name. Map theIDs constains indices -> 
498 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
499 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
500   const std::string& theName, const char* theShapeType, 
501   std::map<int, int>& theIDs, const bool theOriented = false)
502 {
503   // collect all IDs in the name
504   std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
505   const int aSubNum = theComp->numberOfSubs();
506   for(int a = 0; a < aSubNum; a++) {
507     FeaturePtr aSub = theComp->subFeature(a);
508     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
509     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
510     // there may be many shapes (circle and center)
511     for(; aRes != aResults.cend(); aRes++) {
512       ResultConstructionPtr aConstr = 
513         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
514       if (aConstr.get()) {
515         aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
516       }
517     }
518   }
519
520   size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
521   bool isShape = false; // anyway the first world must be 'Vertex'
522   do {
523     aLastNamePos = theName.find('-', aPrevPos);
524     std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
525     if (!isShape) {
526       if (anID != theShapeType)
527         return false;
528       isShape = true;
529     } else {
530       int anOrientation = 1; // default
531       if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
532         std::string::iterator aSymbol = anID.end() - 1;
533         if (*aSymbol == 'r') anOrientation = -1;
534         anID.erase(aSymbol); // remove last symbol
535       }
536       // check start/end symbols
537       std::string::iterator aBack = anID.end() - 1;
538       if (*aBack == 's') {
539         anOrientation *= 2;
540         anID.erase(aBack); // remove last symbol
541       } else if (*aBack == 'e') {
542         anOrientation *= 3;
543         anID.erase(aBack); // remove last symbol
544       }
545
546       if (aNames.find(anID) != aNames.end()) {
547         theIDs[aNames[anID]] = anOrientation;
548       }
549     }
550     aPrevPos = aLastNamePos + 1;
551   } while (aLastNamePos != std::string::npos);
552   return true;
553 }
554
555 /// produces theEdge orientation relatively to theContext face
556 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
557 {
558   if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
559     return 0;
560   if (theEdge.Orientation() == TopAbs_FORWARD) 
561     return 1;
562   if (theEdge.Orientation() == TopAbs_REVERSED) 
563     return -1;
564   return 0; // unknown
565 }
566
567 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
568   std::shared_ptr<ModelAPI_Result>& theConstr, 
569   NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
570 {
571   int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
572   int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
573   std::shared_ptr<GeomAPI_Shape> aResult;
574   ResultConstructionPtr aConstructionContext = 
575       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
576   if (!aConstructionContext.get())
577     return aResult;
578   for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
579     int aFound = 0, aNotFound = 0, aSameOrientation = 0;
580     TopoDS_Face aFace = 
581       TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
582     std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
583     if (theIsWire) {
584       for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
585         aFacesWires.push_back(aWires.Current());
586       }
587     } else {
588       aFacesWires.push_back(aFace);
589     }
590     std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
591     for(; aFW != aFacesWires.end(); aFW++) {
592       TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
593       TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
594       for(; anEdgesExp.More(); anEdgesExp.Next()) {
595         TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
596         if (!anEdge.IsNull()) {
597           Standard_Real aFirst, aLast;
598           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
599           if (alreadyProcessed.Contains(aCurve))
600             continue;
601           alreadyProcessed.Add(aCurve);
602           if (theCurves.IsBound(aCurve)) {
603             aFound++;
604             int anOrient = theCurves.Find(aCurve);
605             if (anOrient != 0) {  // extra comparision score is orientation
606               if (edgeOrientation(aFace, anEdge) == anOrient)
607                 aSameOrientation++;
608             }
609           } else {
610             aNotFound++;
611           }
612         }
613       }
614       if (aFound + aNotFound != 0) {
615         if (aFound > aBestFound || 
616           (aFound == aBestFound && aSameOrientation > aBestOrient)) {
617             aBestFound = aFound;
618             aBestOrient = aSameOrientation;
619             if (theIsWire) {
620               std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
621               aWire->setImpl(new TopoDS_Shape(*aFW));
622               aResult = aWire;
623             } else {
624               aResult = aConstructionContext->face(aFaceIndex);
625             }
626         }
627       }
628     }
629   }
630   return aResult;
631 }
632
633 std::string Model_SelectionNaming::shortName(
634   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
635 {
636   std::string aName = theConstr->data()->name();
637   // remove "-", "/" and "&" command-symbols
638   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
639   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
640   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
641   // remove the last 's', 'e', 'f' and 'r' symbols: they are used as markers of start/end/forward/rewersed indicators
642   static const std::string aSyms("sefr");
643   std::string::iterator aSuffix = aName.end() - 1;
644   while(aSyms.find(*aSuffix) != std::string::npos) {
645     --aSuffix;
646   }
647   aName.erase(aSuffix + 1, aName.end());
648
649   if (theEdgeVertexPos == 1) {
650     aName += "s"; // start
651   } else if (theEdgeVertexPos == 2) {
652     aName += "e"; // end
653   }
654   return aName;
655 }
656
657 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
658 bool Model_SelectionNaming::selectSubShape(const std::string& theType, 
659   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
660   std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
661 {
662   if(theSubShapeName.empty() || theType.empty()) return false;
663   TopAbs_ShapeEnum aType = translateType(theType);
664
665   // check that it was selected in another document
666   size_t aSlash = theSubShapeName.find("/");
667   std::string aSubShapeName = theSubShapeName;
668   std::shared_ptr<Model_Document> aDoc = theDoc;
669   if (aSlash != std::string::npos) {
670     std::string aDocName = theSubShapeName.substr(0, aSlash);
671     ResultPartPtr aFoundPart;
672     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
673     if (aDocName == aRootDoc->kind()) {
674       aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
675     } else {
676       for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
677         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
678             aRootDoc->object(ModelAPI_ResultPart::group(), a));
679         if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
680           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
681           aFoundPart = aPart;
682           break;
683         }
684       }
685     }
686     if (aDoc != theDoc) { // so, the first word is the document name => reduce the string for the next manips
687       aSubShapeName = theSubShapeName.substr(aSlash + 1);
688       if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
689         theCont = aFoundPart;
690         return true;
691       }
692     }
693   }
694
695   std::string aContName = getContextName(aSubShapeName);
696   if(aContName.empty()) return false;
697   ResultPtr aCont = aDoc->findByName(aContName);
698    // possible this is body where postfix is added to distinguish several shapes on the same label
699   int aSubShapeId = -1; // -1 means sub shape not found
700   // for result body the name wihtout "_" has higher priority than with it: it is always added
701   if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) && 
702        aContName == aSubShapeName) {
703     size_t aPostIndex = aContName.rfind('_');
704     if (aPostIndex != std::string::npos) {
705       std::string aSubContName = aContName.substr(0, aPostIndex);
706       ResultPtr aSubCont = aDoc->findByName(aSubContName);
707       if (aSubCont.get()) {
708         try {
709           std::string aNum = aContName.substr(aPostIndex + 1);
710           aSubShapeId = std::stoi(aNum);
711         } catch (std::invalid_argument&) {
712           aSubShapeId = -1;
713         }
714         if (aSubShapeId > 0) {
715           aContName = aSubContName;
716           aCont = aSubCont;
717         }
718       }
719     }
720   }
721
722
723   TopoDS_Shape aSelection;
724   switch (aType) 
725   {
726   case TopAbs_FACE:
727   case TopAbs_WIRE:
728     {
729       aSelection = findFaceByName(aSubShapeName, aDoc);
730     }
731     break;
732   case TopAbs_EDGE:
733     {  
734       const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
735       if(!aLabel.IsNull()) {
736         Handle(TNaming_NamedShape) aNS;
737         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
738           aSelection = getShapeFromNS(aSubShapeName, aNS);
739         }
740       }
741     }
742     break;
743   case TopAbs_VERTEX:
744     {
745       const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
746       if(!aLabel.IsNull()) {
747         Handle(TNaming_NamedShape) aNS;
748         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
749           aSelection = getShapeFromNS(aSubShapeName, aNS);
750         }
751       }
752     }
753     break;
754   case TopAbs_COMPOUND:
755   case TopAbs_COMPSOLID:
756   case TopAbs_SOLID:
757   case TopAbs_SHELL:
758   default: {//TopAbs_SHAPE
759     /// case when the whole sketch is selected, so, selection type is compound, but there is no value
760     if (aCont.get() && aCont->shape().get()) {
761       if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
762         theCont = aCont;
763         return true;
764       } else if (aSubShapeId > 0) { // try to find sub-shape by the index
765         TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
766         for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
767           anExp.Next();
768         }
769         if (anExp.More()) {
770           std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
771           aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
772           theShapeToBeSelected = aShapeToBeSelected;
773           theCont = aCont;
774           return true;
775         }
776       }
777     }
778     return false;
779     }
780   }
781   // another try to find edge or vertex by faces
782   std::list<std::string> aListofNames;
783   size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
784   if (aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) {
785     if(aN > 1 && (aN < 4 || (aType == TopAbs_EDGE && aN < 5))) { // 2 || 3 or 4 for EDGE
786       TopTools_ListOfShape aList;
787       std::list<std::string>::iterator it = aListofNames.begin();
788       for(; it != aListofNames.end(); it++){
789         const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
790         if(!aFace.IsNull())
791           aList.Append(aFace);          
792       }
793       aSelection = findCommonShape(aType, aList);
794     }
795   }
796   // in case of construction, there is no registered names for all sub-elements,
797   // even for the main element; so, trying to find them by name (without "&" intersections)
798   if (aN == 0) {
799     size_t aConstrNamePos = aSubShapeName.find("/");
800     bool isFullName = aConstrNamePos == std::string::npos;
801     std::string aContrName = aContName;
802     ResultPtr aConstr = aDoc->findByName(aContrName);
803     if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
804       theCont = aConstr;
805       if (isFullName) {
806         // For the full construction selection shape must be empty.
807         //theShapeToBeSelected = aConstr->shape();
808         return true;
809       }
810       // for sketch sub-elements selected
811       CompositeFeaturePtr aComposite = 
812         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
813       if (aComposite.get()) {
814         if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
815           // collect all IDs in the name
816           std::map<int, int> anIDs;
817           if (!parseSubIndices(aComposite, aSubShapeName, 
818               aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs))
819             return false;
820
821           const int aSubNum = aComposite->numberOfSubs();
822           for(int a = 0; a < aSubNum; a++) {
823             int aCompID = aComposite->subFeatureId(a);
824             if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
825               FeaturePtr aSub = aComposite->subFeature(a);
826               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
827               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
828               // there may be many shapes (circle and center)
829               for(; aRIt != aResults.cend(); aRIt++) {
830                 ResultConstructionPtr aRes = 
831                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
832                 if (aRes) {
833                   int anOrientation = abs(anIDs[aCompID]);
834                   TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
835                   if (anOrientation == 1) {
836                     if (aType == aShape.ShapeType()) {
837                       theShapeToBeSelected = aRes->shape();
838                       return true;
839                     }
840                   } else { // take first or second vertex of the edge
841                     TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
842                     TopExp_Explorer anExp(aShape, aType);
843                     for(; anExp.More() && anOrientation != 2; anOrientation--)
844                       anExp.Next();
845                     if (anExp.More()) {
846                       std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
847                       aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
848                       theShapeToBeSelected = aShapeToBeSelected;
849                       return true;
850                     }
851                   }
852                 }
853               }
854             }
855           }
856           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
857         } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
858           std::map<int, int> anIDs;
859           if (!parseSubIndices(aComposite, aSubShapeName, 
860               aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
861             return false;
862
863           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
864           const int aSubNum = aComposite->numberOfSubs();
865           for(int a = 0; a < aSubNum; a++) {
866             int aSubID = aComposite->subFeatureId(a);
867             if (anIDs.find(aSubID) != anIDs.end()) {
868               FeaturePtr aSub = aComposite->subFeature(a);
869               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
870               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
871               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
872                 ResultConstructionPtr aConstr = 
873                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
874                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
875                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
876                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
877                   if (!anEdge.IsNull()) {
878                     Standard_Real aFirst, aLast;
879                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
880                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
881                   }
882                 }
883               }
884             }
885           }
886           std::shared_ptr<GeomAPI_Shape> aFoundFW =
887             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
888           if (aFoundFW.get()) {
889             theShapeToBeSelected = aFoundFW;
890             return true;
891           }
892         } else if (aType == TopAbs_WIRE) { // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
893           std::map<int, int> anIDs;
894           if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
895             return false;
896
897           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
898           const int aSubNum = aComposite->numberOfSubs();
899           for(int a = 0; a < aSubNum; a++) {
900             int aSubID = aComposite->subFeatureId(a);
901             if (anIDs.find(aSubID) != anIDs.end()) {
902               FeaturePtr aSub = aComposite->subFeature(a);
903               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
904               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
905               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
906                 ResultConstructionPtr aConstr = 
907                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
908                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
909                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
910                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
911                   if (!anEdge.IsNull()) {
912                     Standard_Real aFirst, aLast;
913                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
914                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
915                   }
916                 }
917               }
918             }
919           }
920           std::shared_ptr<GeomAPI_Shape> aFoundFW = 
921             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
922           if (aFoundFW.get()) {
923             theShapeToBeSelected = aFoundFW;
924             return true;
925           }
926         }
927       }
928     }
929   }
930   if (!aSelection.IsNull()) {// Select it (must be after N=0 checking, since for simple constructions the shape must be null)
931     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
932     aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
933     theShapeToBeSelected = aShapeToBeSelected;
934     theCont = aCont;
935     return true;
936   }
937
938   return false;
939 }