]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
767e86331386183fe001085890b1f41722e11874
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.cpp
4 // Created:     2 Oct 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <ModelAPI_Feature.h>
14 #include <ModelAPI_ResultBody.h>
15 #include <ModelAPI_ResultConstruction.h>
16 #include <ModelAPI_ResultPart.h>
17 #include <ModelAPI_CompositeFeature.h>
18 #include <GeomAPI_Shape.h>
19 #include <GeomAPI_PlanarEdges.h>
20 #include <Events_Error.h>
21
22 #include <TNaming_Selector.hxx>
23 #include <TNaming_NamedShape.hxx>
24 #include <TNaming_Tool.hxx>
25 #include <TNaming_Builder.hxx>
26 #include <TNaming_Localizer.hxx>
27 #include <TopoDS_Shape.hxx>
28 #include <TopoDS_Compound.hxx>
29 #include <TDataStd_IntPackedMap.hxx>
30 #include <TDataStd_Integer.hxx>
31 #include <TDataStd_UAttribute.hxx>
32 #include <TDataStd_Name.hxx>
33 #include <TopTools_MapOfShape.hxx>
34 #include <TopTools_IndexedMapOfShape.hxx>
35 #include <TopTools_MapIteratorOfMapOfShape.hxx>
36 #include <TopTools_ListOfShape.hxx>
37 #include <NCollection_DataMap.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TDF_LabelMap.hxx>
40 #include <BRep_Tool.hxx>
41 #include <BRep_Builder.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS.hxx>
44 #include <TopExp.hxx>
45 #include <TColStd_MapOfTransient.hxx>
46 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
48 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
49 #include <gp_Pnt.hxx>
50 #include <Precision.hxx>
51 #include <TDF_ChildIterator.hxx>
52 #include <TDF_ChildIDIterator.hxx>
53 #include <TDataStd_Name.hxx>
54 #include <TopAbs_ShapeEnum.hxx>
55 #include <TopoDS_Iterator.hxx>
56 #include <TNaming_Iterator.hxx>
57 using namespace std;
58 //#define DEB_NAMING 1
59 #ifdef DEB_NAMING
60 #include <BRepTools.hxx>
61 #endif
62 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
63 /// (multiplied by the index of the edge)
64 static const int kSTART_VERTEX_DELTA = 1000000;
65 // identifier that there is simple reference: selection equals to context
66 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
67 // simple reference in the construction
68 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
69 // reference to Part sub-object
70 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
71
72 // on this label is stored:
73 // TNaming_NamedShape - selected shape
74 // TNaming_Naming - topological selection information (for the body)
75 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
76 // TDataStd_Integer - type of the selected shape (for construction)
77 // TDF_Reference - from ReferenceAttribute, the context
78 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
79   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
80 {
81   if (theTemporarily) { // just keep the stored without DF update
82     myTmpContext = theContext;
83     myTmpSubShape = theSubShape;
84     owner()->data()->sendAttributeUpdated(this);
85     return;
86   } else {
87     myTmpContext.reset();
88     myTmpSubShape.reset();
89   }
90
91   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
92   bool isOldContext = theContext == myRef.value();
93   bool isOldShape = isOldContext &&
94     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
95   if (isOldShape) return; // shape is the same, so context is also unchanged
96   // update the referenced object if needed
97   if (!isOldContext)
98     myRef.setValue(theContext);
99
100   // do noth use naming if selected shape is result shape itself, but not sub-shape
101   TDF_Label aSelLab = selectionLabel();
102   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
103   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
104
105   bool isDegeneratedEdge = false;
106   // do not use the degenerated edge as a shape, a null context and shape is used in the case
107   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
108     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
109     if (aSubShape.ShapeType() == TopAbs_EDGE)
110       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
111   }
112   if (!theContext.get() || isDegeneratedEdge) {
113     // to keep the reference attribute label
114     TDF_Label aRefLab = myRef.myRef->Label();
115     aSelLab.ForgetAllAttributes(true);
116     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
117     return;
118   }
119   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
120     // do not select the whole shape for body:it is already must be in the data framework
121     // equal and null selected objects mean the same: object is equal to context,
122     // TODO: synchronize with GUI later that it must be null always
123     if (theContext->shape().get() && 
124         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
125       aSelLab.ForgetAllAttributes(true);
126       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
127     } else {
128       selectBody(theContext, theSubShape);
129     }
130   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
131     if (!theSubShape.get()) {
132       // to sub, so the whole result is selected
133       aSelLab.ForgetAllAttributes(true);
134       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
135     } else {
136       selectConstruction(theContext, theSubShape);
137     }
138   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
139     aSelLab.ForgetAllAttributes(true);
140     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
141     selectPart(theContext, theSubShape);
142   }
143   //the attribute initialized state should be changed by sendAttributeUpdated only
144   //myIsInitialized = true;
145
146   owner()->data()->sendAttributeUpdated(this);
147
148   std::string aSelName = namingName();
149   if(!aSelName.empty())
150     TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
151 }
152
153 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
154 {
155   if (myTmpContext.get() || myTmpSubShape.get()) {
156     return myTmpSubShape;
157   }
158
159   std::shared_ptr<GeomAPI_Shape> aResult;
160   if (myRef.isInitialized()) {
161     TDF_Label aSelLab = selectionLabel();
162     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
163       ResultPtr aContext = context();
164       if (!aContext.get()) 
165         return aResult; // empty result
166       return aContext->shape();
167     }
168     if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
169         return aResult; // empty result
170     }
171     if (aSelLab.IsAttribute(kPART_REF_ID)) {
172       /* TODO: implement used text here
173       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
174       if (!aPart.get() || !aPart->isActivated())
175         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
176       Handle(TDataStd_Integer) anIndex;
177       if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
178         return aPart->selectionValue(anIndex->Get());
179       }
180       Handle(TDataStd_Name) aName;
181       if (!selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
182         return std::shared_ptr<GeomAPI_Shape>(); // something is wrong
183       }
184       return aPart->shapeInPart(TCollection_AsciiString(aName).ToCString());
185       */
186     }
187
188     Handle(TNaming_NamedShape) aSelection;
189     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
190       TopoDS_Shape aSelShape = aSelection->Get();
191       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
192       aResult->setImpl(new TopoDS_Shape(aSelShape));
193     } else { // for simple construction element: just shape of this construction element
194       ResultConstructionPtr aConstr = 
195         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
196       if (aConstr) {
197         return aConstr->shape();
198       }
199     }
200   }
201   return aResult;
202 }
203
204 bool Model_AttributeSelection::isInitialized()
205 {
206   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checkings if it is initialized
207     std::shared_ptr<GeomAPI_Shape> aResult;
208     if (myRef.isInitialized()) {
209       TDF_Label aSelLab = selectionLabel();
210       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
211         ResultPtr aContext = context();
212         return aContext.get() != NULL;
213       }
214       if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
215           return true;
216       }
217
218       Handle(TNaming_NamedShape) aSelection;
219       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
220         return !aSelection->Get().IsNull();
221       } else { // for simple construction element: just shape of this construction element
222         ResultConstructionPtr aConstr = 
223           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
224         if (aConstr.get()) {
225           return aConstr->shape().get() != NULL;
226         }
227       }
228     }
229   }
230   return false;
231 }
232
233 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
234   : myRef(theLabel)
235 {
236   myIsInitialized = myRef.isInitialized();
237 }
238
239 void Model_AttributeSelection::setID(const std::string theID)
240 {
241   myRef.setID(theID);
242   ModelAPI_AttributeSelection::setID(theID);
243 }
244
245 ResultPtr Model_AttributeSelection::context() {
246   if (myTmpContext.get() || myTmpSubShape.get()) {
247     return myTmpContext;
248   }
249
250   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
251   // for parts there could be same-data result, so take the last enabled
252   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
253     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
254     for(int a = aSize - 1; a >= 0; a--) {
255       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
256       if (aPart.get() && aPart->data() == aResult->data()) {
257         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
258         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
259         // check that this result is not this-feature result (it is forbidden t oselect itself)
260         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
261           return aPartResult;
262         }
263       }
264     }
265   }
266   return aResult;
267 }
268
269
270 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
271 {
272   ModelAPI_AttributeSelection::setObject(theObject);
273   myRef.setObject(theObject);
274 }
275
276 TDF_LabelMap& Model_AttributeSelection::scope()
277 {
278   if (myScope.IsEmpty()) { // create a new scope if not yet done
279     // gets all featueres with named shapes that are bofore this feature label (before in history)
280     DocumentPtr aMyDoc = owner()->document();
281     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
282     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
283     for(; aFIter != allFeatures.end(); aFIter++) {
284       if (*aFIter == owner()) break; // the left features are created later
285       if (aFIter->get() && (*aFIter)->data()->isValid()) {
286         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
287           (*aFIter)->data())->label().Father();
288         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
289         for(; aNSIter.More(); aNSIter.Next()) {
290           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
291           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
292             myScope.Add(aNS->Label());
293           }
294         }
295       }
296     }
297   }
298   return myScope;
299 }
300
301 /// produces theEdge orientation relatively to theContext face
302 int edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
303 {
304   if (theContext.ShapeType() != TopAbs_FACE)
305     return 0;
306   TopoDS_Face aContext = TopoDS::Face(theContext);
307   if (theEdge.Orientation() == TopAbs_FORWARD) 
308     return 1;
309   if (theEdge.Orientation() == TopAbs_REVERSED) 
310     return -1;
311   return 0; // unknown
312 }
313
314 bool Model_AttributeSelection::update()
315 {
316   ResultPtr aContext = context();
317   if (!aContext.get()) return false;
318   TDF_Label aSelLab = selectionLabel();
319   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
320     return aContext->shape() && !aContext->shape()->isNull();
321   }
322   if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
323     return aContext->shape() && !aContext->shape()->isNull();
324   }
325
326   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
327     std::shared_ptr<GeomAPI_Shape> aNoSelection;
328     return selectPart(aContext, aNoSelection, true);
329   }
330
331   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
332     // body: just a named shape, use selection mechanism from OCCT
333     TNaming_Selector aSelector(aSelLab);
334     bool aResult = aSelector.Solve(scope()) == Standard_True;
335     owner()->data()->sendAttributeUpdated(this);
336     return aResult;
337   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
338     // construction: identification by the results indexes, recompute faces and
339     // take the face that more close by the indexes
340     ResultConstructionPtr aConstructionContext = 
341       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
342     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
343     // sketch sub-element
344     if (aConstructionContext && 
345         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
346     {
347       TDF_Label aLab = myRef.myRef->Label();
348       // getting a type of selected shape
349       Handle(TDataStd_Integer) aTypeAttr;
350       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
351         return false;
352       }
353       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
354       // selected indexes will be needed in each "if"
355       Handle(TDataStd_IntPackedMap) aSubIds;
356       std::shared_ptr<GeomAPI_Shape> aNewSelected;
357       bool aNoIndexes = 
358         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
359       // for now working only with composite features
360       CompositeFeaturePtr aComposite = 
361         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
362       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
363         return false;
364       }
365
366       if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
367         // If this is a wire with plane defined thin it is a sketch-like object
368         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
369           return false;
370         // if there is no edges indexes, any face can be used: take the first
371         std::shared_ptr<GeomAPI_Shape> aNewSelected;
372         if (aNoIndexes) {
373           aNewSelected = aConstructionContext->face(0);
374         } else { // searching for most looks-like initial face by the indexes
375           // prepare edges of the current resut for the fast searching
376           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
377           const int aSubNum = aComposite->numberOfSubs();
378           for(int a = 0; a < aSubNum; a++) {
379             int aSubID = aComposite->subFeatureId(a);
380             if (aSubIds->Contains(aSubID)) {
381               FeaturePtr aSub = aComposite->subFeature(a);
382               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
383               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
384               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
385                 ResultConstructionPtr aConstr = 
386                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
387                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
388                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
389                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
390                   if (!anEdge.IsNull()) {
391                     Standard_Real aFirst, aLast;
392                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
393                     // searching for orientation information
394                     int anOrient = 0;
395                     Handle(TDataStd_Integer) anInt;
396                     if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
397                       anOrient = anInt->Get();
398                     }
399                     allCurves.Bind(aCurve, anOrient);
400                   }
401                 }
402               }
403             }
404           }
405           double aBestFound = 0; // best percentage of found edges
406           int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
407           for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
408             int aFound = 0, aNotFound = 0, aSameOrientation = 0;
409             TopoDS_Face aFace = 
410               TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
411             TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
412             TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
413             for(; anEdgesExp.More(); anEdgesExp.Next()) {
414               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
415               if (!anEdge.IsNull()) {
416                 Standard_Real aFirst, aLast;
417                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
418                 if (alreadyProcessed.Contains(aCurve))
419                   continue;
420                 alreadyProcessed.Add(aCurve);
421                 if (allCurves.IsBound(aCurve)) {
422                   aFound++;
423                   int anOrient = allCurves.Find(aCurve);
424                   if (anOrient != 0) {  // extra comparision score is orientation
425                     if (edgeOrientation(aFace, anEdge) == anOrient)
426                       aSameOrientation++;
427                   }
428                 } else {
429                   aNotFound++;
430                 }
431               }
432             }
433             if (aFound + aNotFound != 0) {
434               double aSum = aFound + aNotFound;
435                // aSameOrientation: if edges are same, take where orientation is better
436               double aPercentage = double(aFound) / double(aFound + aNotFound);
437               if (aPercentage > aBestFound || 
438                   (aPercentage == aBestFound && aSameOrientation > aBestOrient)) {
439                 aBestFound = aPercentage;
440                 aBestOrient = aSameOrientation;
441                 aNewSelected = aConstructionContext->face(aFaceIndex);
442               }
443             }
444           }
445         }
446         if (aNewSelected) { // store this new selection
447           selectConstruction(aContext, aNewSelected);
448           owner()->data()->sendAttributeUpdated(this);
449           return true;
450         }
451       } else if (aShapeType == TopAbs_EDGE) {
452         // just reselect the edge by the id
453         const int aSubNum = aComposite->numberOfSubs();
454         for(int a = 0; a < aSubNum; a++) {
455           // if aSubIds take any, the first appropriate
456           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
457             // found the appropriate feature
458             FeaturePtr aFeature = aComposite->subFeature(a);
459             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
460               aFeature->results().cbegin();
461             for(;aResIter != aFeature->results().cend(); aResIter++) {
462               ResultConstructionPtr aRes = 
463                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
464               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
465                 selectConstruction(aContext, aRes->shape());
466                 owner()->data()->sendAttributeUpdated(this);
467                 return true;
468               }
469             }
470           }
471         }
472       } else if (aShapeType == TopAbs_VERTEX) {
473         // just reselect the vertex by the id of edge
474         const int aSubNum = aComposite->numberOfSubs();
475         for(int a = 0; a < aSubNum; a++) {
476           // if aSubIds take any, the first appropriate
477           int aFeatureID = aComposite->subFeatureId(a);
478           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
479             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
480             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
481               // searching for deltas
482               int aVertexNum = 0;
483               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
484               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
485               // found the feature with appropriate edge
486               FeaturePtr aFeature = aComposite->subFeature(a);
487               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
488                 aFeature->results().cbegin();
489               for(;aResIter != aFeature->results().cend(); aResIter++) {
490                 ResultConstructionPtr aRes = 
491                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
492                 if (aRes && aRes->shape()) {
493                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
494                     selectConstruction(aContext, aRes->shape());
495                     owner()->data()->sendAttributeUpdated(this);
496                     return true;
497                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
498                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
499                     int aVIndex = 1;
500                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
501                       if (aVIndex == aVertexNum) { // found!
502                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
503                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
504                         selectConstruction(aContext, aVertex);
505                         owner()->data()->sendAttributeUpdated(this);
506                         return true;
507                       }
508                       aVIndex++;
509                     }
510                   }
511                 }
512               }
513           }
514         }
515       }
516     } else { // simple construction element: the selected is that needed
517       selectConstruction(aContext, aContext->shape());
518       owner()->data()->sendAttributeUpdated(this);
519       return true;
520     }
521   }
522   return false; // unknown case
523 }
524
525
526 void Model_AttributeSelection::selectBody(
527   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
528 {
529   // perform the selection
530   TNaming_Selector aSel(selectionLabel());
531   TopoDS_Shape aContext;
532
533   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
534   if (aBody) {
535     aContext = aBody->shape()->impl<TopoDS_Shape>();
536   } else {
537     ResultPtr aResult = 
538       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
539     if (aResult) {
540       aContext = aResult->shape()->impl<TopoDS_Shape>();
541     } else {
542       Events_Error::send("A result with shape is expected");
543       return;
544     }
545   }
546   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
547   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
548   /*
549   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
550   if (aFeatureOwner.get())
551     aFeatureOwner->eraseResults();
552     */
553   if (!aContext.IsNull()) {
554     aSel.Select(aNewShape, aContext); 
555   }
556 }
557
558 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
559 /// if theID is zero, 
560 /// theOrientation is additional information about the positioning of edge relatively to face
561 ///    it is stored in the integer attribute of the edge sub-label: 
562 ///    -1 is out, 1 is in, 0 is not needed
563 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
564   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
565   std::string theAdditionalName, std::map<int, int>& theOrientations,
566   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
567   const int theOrientation = 0)
568 {
569   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
570   if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
571     TDataStd_Integer::Set(aLab, theOrientation);
572   }
573   TNaming_Builder aBuilder(aLab);
574   aBuilder.Generated(theShape);
575   std::stringstream aName;
576   aName<<theContextFeature->name()<<"/";
577   if (!theAdditionalName.empty())
578     aName<<theAdditionalName<<"/";
579   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
580   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
581   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
582
583   if (theRefs.IsNull()) {
584     aName<<theID;
585     if (theOrientation == 1)
586       aName<<"f";
587     else if (theOrientation == -1)
588       aName<<"r";
589   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
590     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
591     for(; aRef.More(); aRef.Next()) {
592       aName<<"-"<<aRef.Key();
593       if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
594         if (theOrientations[aRef.Key()] == 1)
595           aName<<"f";
596         else if (theOrientations[aRef.Key()] == -1)
597           aName<<"r";
598       }
599     }
600   }
601
602   theDoc->addNamingName(aLab, aName.str());
603   TDataStd_Name::Set(aLab, aName.str().c_str());
604 }
605
606 void Model_AttributeSelection::selectConstruction(
607   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
608 {
609   std::shared_ptr<Model_Document> aMyDoc = 
610     std::dynamic_pointer_cast<Model_Document>(owner()->document());
611   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
612   CompositeFeaturePtr aComposite = 
613     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
614   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
615   if (!aComposite || aComposite->numberOfSubs() == 0) {
616     // saving of context is enough: result construction contains exactly the needed shape
617     TNaming_Builder aBuilder(selectionLabel());
618     aBuilder.Generated(aSubShape);
619     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
620     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
621     return;
622   }
623   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
624   TDF_Label aLab = myRef.myRef->Label();
625   // identify the reuslts of sub-object of the composite by edges
626   // save type of the selected shape in integer attribute
627   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
628   TDataStd_Integer::Set(aLab, (int)aShapeType);
629   gp_Pnt aVertexPos;
630   TColStd_MapOfTransient allCurves;
631   if (aShapeType == TopAbs_VERTEX) { // compare positions
632     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
633   } else { 
634     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
635       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
636       Standard_Real aFirst, aLast;
637       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
638       allCurves.Add(aCurve);
639     }
640   }
641   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
642   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
643   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
644   aRefs->Clear();
645   const int aSubNum = aComposite->numberOfSubs();
646   for(int a = 0; a < aSubNum; a++) {
647     FeaturePtr aSub = aComposite->subFeature(a);
648     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
649     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
650     // there may be many shapes (circle and center): register if at least one is in selection
651     for(; aRes != aResults.cend(); aRes++) {
652       ResultConstructionPtr aConstr = 
653         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
654       if (!aConstr->shape()) {
655         continue;
656       }
657       if (aShapeType == TopAbs_VERTEX) {
658         if (aConstr->shape()->isVertex()) { // compare vertices positions
659           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
660           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
661           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
662             aRefs->Add(aComposite->subFeatureId(a));
663           }
664         } else { // get first or last vertex of the edge: last is stored with negative sign
665           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
666           int aDelta = kSTART_VERTEX_DELTA;
667           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
668             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
669             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
670               aRefs->Add(aDelta + aComposite->subFeatureId(a));
671               break;
672             }
673             aDelta += kSTART_VERTEX_DELTA;
674           }
675         }
676       } else {
677         if (aConstr->shape()->isEdge()) {
678           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
679           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
680           if (!anEdge.IsNull()) {
681             Standard_Real aFirst, aLast;
682             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
683             if (allCurves.Contains(aCurve)) {
684               int anID = aComposite->subFeatureId(a);
685               aRefs->Add(anID);
686               if (aShapeType != TopAbs_EDGE) { // face nneds the sub-edges on sub-labels
687                 // add edges to sub-label to support naming for edges selection
688                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
689                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
690                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
691                   Standard_Real aFirst, aLast;
692                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
693                   if (aFaceCurve == aCurve) {
694                     int anOrient = edgeOrientation(aSubShape, anEdge);
695                     anOrientations[anID] = anOrient;
696                     registerSubShape(
697                       selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
698                       Handle(TDataStd_IntPackedMap)(), anOrient);
699                   }
700                 }
701               } else { // put vertices of the selected edge to sub-labels
702                 // add edges to sub-label to support naming for edges selection
703                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
704                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
705                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
706                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
707
708                   std::stringstream anAdditionalName; 
709                   registerSubShape(
710                     selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
711                 }
712               }
713             }
714           }
715         }
716       }
717     }
718   }
719   // store the selected as primitive
720   TNaming_Builder aBuilder(selectionLabel());
721   aBuilder.Generated(aSubShape);
722     registerSubShape(
723       selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs); 
724 }
725
726 bool Model_AttributeSelection::selectPart(
727   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
728   const bool theUpdate)
729 {
730   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
731   if (!aPart.get() || !aPart->isActivated())
732     return true; // postponed naming
733   if (theUpdate) {
734     Handle(TDataStd_Integer) anIndex;
735     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
736       if (anIndex->Get() > 0) {
737         // update the selection by index
738         return aPart->updateInPart(anIndex->Get());
739       } else {
740         return true; // nothing to do, referencing just by name
741       }
742     }
743     return true; // nothing to do, referencing just by name
744   }
745   // store the shape (in case part is not loaded it should be usefull
746   TopoDS_Shape aShape;
747   std::string aName = theContext->data()->name();
748   if (theSubShape->isNull()) {// the whole part shape is selected
749     aShape = theContext->shape()->impl<TopoDS_Shape>();
750   } else {
751     aShape = theSubShape->impl<TopoDS_Shape>();
752     int anIndex;
753     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
754     TDataStd_Integer::Set(selectionLabel(), anIndex);
755   }
756   TNaming_Builder aBuilder(selectionLabel());
757   aBuilder.Select(aShape, aShape);
758   // identify by name in the part
759   TDataStd_Name::Set(selectionLabel(), aName.c_str());
760   return !aName.empty();
761 }
762
763 TDF_Label Model_AttributeSelection::selectionLabel()
764 {
765   return myRef.myRef->Label().FindChild(1);
766 }
767
768 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
769 {
770   std::string aName("");
771   if(!this->isInitialized())
772     return !theDefaultName.empty() ? theDefaultName : aName;
773   Handle(TDataStd_Name) anAtt;
774   if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
775     aName = TCollection_AsciiString(anAtt->Get()).ToCString();
776     return aName;
777   }
778
779   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
780   ResultPtr aCont = context();
781
782   Model_SelectionNaming aSelNaming(selectionLabel());
783   return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
784 }
785
786 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
787 void Model_AttributeSelection::selectSubShape(
788   const std::string& theType, const std::string& theSubShapeName)
789 {
790   if(theSubShapeName.empty() || theType.empty()) return;
791
792   Model_SelectionNaming aSelNaming(selectionLabel());
793   std::shared_ptr<Model_Document> aDoc = 
794     std::dynamic_pointer_cast<Model_Document>(owner()->document());
795   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
796   ResultPtr aCont;
797   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
798     setValue(aCont, aShapeToBeSelected);
799   }
800 }
801
802 int Model_AttributeSelection::Id()
803 {
804   std::shared_ptr<GeomAPI_Shape> aSelection = value();
805   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
806   const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
807   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
808   int anID = 0;
809   if (aSelection && !aSelection->isNull() &&
810     aContext   && !aContext->isNull())
811   {
812     TopTools_IndexedMapOfShape aSubShapesMap;
813     TopExp::MapShapes(aMainShape, aSubShapesMap);
814     anID = aSubShapesMap.FindIndex(aSubShape);
815   }
816   return anID;
817 }