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