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