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