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