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