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