Salome HOME
Boost has been removed from code
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // File:        Model_AttributeSelection.h
2 // Created:     2 Oct 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include "Model_AttributeSelection.h"
6 #include "Model_Application.h"
7 #include "Model_Events.h"
8 #include "Model_Data.h"
9 #include <ModelAPI_Feature.h>
10 #include <ModelAPI_ResultBody.h>
11 #include <ModelAPI_ResultConstruction.h>
12 #include <ModelAPI_CompositeFeature.h>
13 #include <GeomAPI_Shape.h>
14 #include <GeomAPI_PlanarEdges.h>
15 #include <GeomAlgoAPI_SketchBuilder.h>
16 #include <Events_Error.h>
17
18 #include <TNaming_Selector.hxx>
19 #include <TNaming_NamedShape.hxx>
20 #include <TNaming_Tool.hxx>
21 #include <TNaming_Builder.hxx>
22 #include <TopoDS_Shape.hxx>
23 #include <TDataStd_IntPackedMap.hxx>
24 #include <TDataStd_Integer.hxx>
25 #include <TopTools_MapOfShape.hxx>
26 #include <TopExp_Explorer.hxx>
27 #include <TDF_LabelMap.hxx>
28 #include <BRep_Tool.hxx>
29 #include <TopoDS_Edge.hxx>
30 #include <TopoDS.hxx>
31 #include <TColStd_MapOfTransient.hxx>
32 #include <gp_Pnt.hxx>
33 #include <Precision.hxx>
34
35 using namespace std;
36 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
37 /// (multiplied by the index of the edge)
38 static const int kSTART_VERTEX_DELTA = 1000000;
39
40 // on this label is stored:
41 // TNaming_NamedShape - selected shape
42 // TNaming_Naming - topological selection information (for the body)
43 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
44 // TDataStd_Integer - type of the selected shape (for construction)
45 // TDF_Reference - from ReferenceAttribute, the context
46
47 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
48   const std::shared_ptr<GeomAPI_Shape>& theSubShape)
49 {
50   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
51   bool isOldShape = 
52     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
53   if (isOldShape) return; // shape is the same, so context is also unchanged
54   // update the referenced object if needed
55   bool isOldContext = theContext == myRef.value();
56   if (!isOldContext)
57     myRef.setValue(theContext);
58
59   if (theContext->groupName() == ModelAPI_ResultBody::group())
60     selectBody(theContext, theSubShape);
61   else if (theContext->groupName() == ModelAPI_ResultConstruction::group())
62     selectConstruction(theContext, theSubShape);
63
64   myIsInitialized = true;
65   owner()->data()->sendAttributeUpdated(this);
66 }
67
68 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
69 {
70   std::shared_ptr<GeomAPI_Shape> aResult;
71   if (myIsInitialized) {
72     Handle(TNaming_NamedShape) aSelection;
73     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
74       TopoDS_Shape aSelShape = aSelection->Get();
75       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
76       aResult->setImpl(new TopoDS_Shape(aSelShape));
77     }
78   }
79   return aResult;
80 }
81
82 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
83   : myRef(theLabel)
84 {
85   myIsInitialized = myRef.isInitialized();
86 }
87
88 ResultPtr Model_AttributeSelection::context() {
89   return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
90 }
91
92
93 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
94 {
95   ModelAPI_AttributeSelection::setObject(theObject);
96   myRef.setObject(theObject);
97 }
98
99 bool Model_AttributeSelection::update()
100 {
101   ResultPtr aContext = context();
102   if (!aContext) return false;
103   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
104     // body: just a named shape, use selection mechanism from OCCT
105     TNaming_Selector aSelector(selectionLabel());
106     TDF_LabelMap aScope; // empty means the whole document
107     bool aResult = aSelector.Solve(aScope) == Standard_True;
108     owner()->data()->sendAttributeUpdated(this);
109     return aResult;
110   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
111     // construction: identification by the results indexes, recompute faces and
112     // take the face that more close by the indexes
113     std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr = 
114       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
115       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
116     if (aWirePtr && aWirePtr->hasPlane()) {
117       TDF_Label aLab = myRef.myRef->Label();
118       // getting a type of selected shape
119       Handle(TDataStd_Integer) aTypeAttr;
120       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
121         return false;
122       }
123       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
124       // selected indexes will be needed in each "if"
125       Handle(TDataStd_IntPackedMap) aSubIds;
126       std::shared_ptr<GeomAPI_Shape> aNewSelected;
127       bool aNoIndexes = 
128         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
129       // for now working only with composite features
130       FeaturePtr aContextFeature = owner()->document()->feature(aContext);
131       CompositeFeaturePtr aComposite = 
132         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
133       if (!aComposite || aComposite->numberOfSubs() == 0) {
134         return false;
135       }
136
137       if (aShapeType == TopAbs_FACE) {
138         // If this is a wire with plane defined thin it is a sketch-like object
139         std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
140         GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
141           aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
142         if (aFaces.empty()) // no faces, update can not work correctly
143           return false;
144         // if there is no edges indexes, any face can be used: take the first
145         std::shared_ptr<GeomAPI_Shape> aNewSelected;
146         if (aNoIndexes) {
147           aNewSelected = *(aFaces.begin());
148         } else { // searching for most looks-like initial face by the indexes
149           // prepare edges of the current resut for the fast searching
150           TColStd_MapOfTransient allCurves;
151           const int aSubNum = aComposite->numberOfSubs();
152           for(int a = 0; a < aSubNum; a++) {
153             if (aSubIds->Contains(aComposite->subFeatureId(a))) {
154               FeaturePtr aSub = aComposite->subFeature(a);
155               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
156               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
157               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
158                 ResultConstructionPtr aConstr = 
159                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
160                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
161                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
162                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
163                   if (!anEdge.IsNull()) {
164                     Standard_Real aFirst, aLast;
165                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
166                     allCurves.Add(aCurve);
167                   }
168                 }
169               }
170             }
171           }
172           // iterate new result faces and searching for these edges
173           std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
174           double aBestFound = 0; // best percentage of found edges
175           for(; aFacesIter != aFaces.end(); aFacesIter++) {
176             int aFound = 0, aNotFound = 0;
177             TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
178             for(; anEdgesExp.More(); anEdgesExp.Next()) {
179               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
180               if (!anEdge.IsNull()) {
181                 Standard_Real aFirst, aLast;
182                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
183                 if (allCurves.Contains(aCurve)) {
184                   aFound++;
185                 } else {
186                   aNotFound++;
187                 }
188               }
189             }
190             if (aFound + aNotFound != 0) {
191               double aPercentage = double(aFound) / double(aFound + aNotFound);
192               if (aPercentage > aBestFound) {
193                 aBestFound = aPercentage;
194                 aNewSelected = *aFacesIter;
195               }
196             }
197           }
198         }
199         if (aNewSelected) { // store this new selection
200           selectConstruction(aContext, aNewSelected);
201           owner()->data()->sendAttributeUpdated(this);
202           return true;
203         }
204       } else if (aShapeType == TopAbs_EDGE) {
205         // just reselect the edge by the id
206         const int aSubNum = aComposite->numberOfSubs();
207         for(int a = 0; a < aSubNum; a++) {
208           // if aSubIds take any, the first appropriate
209           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
210             // found the appropriate feature
211             FeaturePtr aFeature = aComposite->subFeature(a);
212             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
213               aFeature->results().cbegin();
214             for(;aResIter != aFeature->results().cend(); aResIter++) {
215               ResultConstructionPtr aRes = 
216                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
217               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
218                 selectConstruction(aContext, aRes->shape());
219                 owner()->data()->sendAttributeUpdated(this);
220                 return true;
221               }
222             }
223           }
224         }
225       } else if (aShapeType == TopAbs_VERTEX) {
226         // just reselect the vertex by the id of edge
227         const int aSubNum = aComposite->numberOfSubs();
228         for(int a = 0; a < aSubNum; a++) {
229           // if aSubIds take any, the first appropriate
230           int aFeatureID = aComposite->subFeatureId(a);
231           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID)) {
232             // searching for deltas
233             int aVertexNum = 0;
234             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
235             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 2;
236             // found the feature with appropriate edge
237             FeaturePtr aFeature = aComposite->subFeature(a);
238             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
239               aFeature->results().cbegin();
240             for(;aResIter != aFeature->results().cend(); aResIter++) {
241               ResultConstructionPtr aRes = 
242                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
243               if (aRes && aRes->shape()) {
244                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
245                   selectConstruction(aContext, aRes->shape());
246                   owner()->data()->sendAttributeUpdated(this);
247                   return true;
248                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
249                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
250                   int aVIndex = 1;
251                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
252                     if (aVIndex == aVertexNum) { // found!
253                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
254                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
255                       selectConstruction(aContext, aVertex);
256                       owner()->data()->sendAttributeUpdated(this);
257                       return true;
258                     }
259                     aVIndex++;
260                   }
261                 }
262               }
263             }
264           }
265         }
266       }
267     }
268   }
269   return false; // unknown case
270 }
271
272
273 void Model_AttributeSelection::selectBody(
274     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
275 {
276   // perform the selection
277   TNaming_Selector aSel(selectionLabel());
278   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
279   TopoDS_Shape aContext;
280
281   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
282   if (aBody)
283     aContext = aBody->shape()->impl<TopoDS_Shape>();
284   else {
285     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
286     if (aConstr) {
287       aContext = aConstr->shape()->impl<TopoDS_Shape>();
288     } else {
289       Events_Error::send("A result with shape is expected");
290       return;
291     }
292   }
293   aSel.Select(aNewShape, aContext);
294 }
295
296 void Model_AttributeSelection::selectConstruction(
297     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
298 {
299   FeaturePtr aContextFeature = owner()->document()->feature(theContext);
300   CompositeFeaturePtr aComposite = 
301     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
302   if (!aComposite || aComposite->numberOfSubs() == 0) {
303     return; // saving of context is enough: result construction contains exactly the needed shape
304   }
305   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
306   TDF_Label aLab = myRef.myRef->Label();
307   // identify the reuslts of sub-object of the composite by edges
308   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
309   // save type of the selected shape in integer attribute
310   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
311   TDataStd_Integer::Set(aLab, (int)aShapeType);
312   gp_Pnt aVertexPos;
313   TColStd_MapOfTransient allCurves;
314   if (aShapeType == TopAbs_VERTEX) { // compare positions
315     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
316   } else { 
317     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
318       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
319       Standard_Real aFirst, aLast;
320       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
321       allCurves.Add(aCurve);
322     }
323   }
324   // iterate and store the result ids of sub-elements
325   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
326   aRefs->Clear();
327   const int aSubNum = aComposite->numberOfSubs();
328   for(int a = 0; a < aSubNum; a++) {
329     FeaturePtr aSub = aComposite->subFeature(a);
330     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
331     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
332     // there may be many shapes (circle and center): register if at least one is in selection
333     for(; aRes != aResults.cend(); aRes++) {
334       ResultConstructionPtr aConstr = 
335         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
336       if (!aConstr->shape()) {
337         continue;
338       }
339       if (aShapeType == TopAbs_VERTEX) {
340         if (aConstr->shape()->isVertex()) { // compare vertices positions
341           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
342           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
343           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
344             aRefs->Add(aComposite->subFeatureId(a));
345           }
346         } else { // get first or last vertex of the edge: last is stored with negative sign
347           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
348           int aDelta = kSTART_VERTEX_DELTA;
349           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
350             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
351             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
352               aRefs->Add(aComposite->subFeatureId(a));
353               aRefs->Add(aDelta + aComposite->subFeatureId(a));
354               break;
355             }
356             aDelta += kSTART_VERTEX_DELTA;
357           }
358         }
359       } else {
360         if (aConstr->shape()->isEdge()) {
361           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
362           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
363           if (!anEdge.IsNull()) {
364             Standard_Real aFirst, aLast;
365             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
366             if (allCurves.Contains(aCurve)) {
367               int anID = aComposite->subFeatureId(a);
368               aRefs->Add(anID);
369               // add edges to sub-label to support naming for edges selection
370               for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
371                 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
372                 Standard_Real aFirst, aLast;
373                 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
374                 if (aFaceCurve == aCurve) {
375                   TNaming_Builder anEdgeBuilder(selectionLabel().FindChild(anID));
376                   anEdgeBuilder.Generated(anEdge);
377                 }
378               }
379             }
380           }
381         }
382       }
383     }
384   }
385   // store the selected as primitive
386   TNaming_Builder aBuilder(selectionLabel());
387   aBuilder.Generated(aSubShape);
388 }
389
390 TDF_Label Model_AttributeSelection::selectionLabel()
391 {
392   return myRef.myRef->Label().FindChild(1);
393 }