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