]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_ResultConstruction.cpp
Salome HOME
Fix for the big models (like flange) naming correctness. Make sketch sub-elements...
[modules/shaper.git] / src / Model / Model_ResultConstruction.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_ResultConstruction.h>
22
23 #include <Model_Data.h>
24 #include <ModelAPI_CompositeFeature.h>
25 #include <Model_SelectionNaming.h>
26 #include <ModelAPI_Events.h>
27 #include <Config_PropManager.h>
28 #include <GeomAPI_PlanarEdges.h>
29 #include <GeomAPI_Shape.h>
30 #include <GeomAlgoAPI_SketchBuilder.h>
31 #include <Events_Loop.h>
32
33 #include <TDF_Reference.hxx>
34 #include <TDF_ChildIterator.hxx>
35 #include <TNaming_NamedShape.hxx>
36 #include <TNaming_Builder.hxx>
37 #include <TDataStd_Integer.hxx>
38 #include <TDataStd_IntPackedMap.hxx>
39 #include <TDataStd_Name.hxx>
40 #include <TDataStd_UAttribute.hxx>
41 #include <TColStd_MapOfTransient.hxx>
42 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
43 #include <BRep_Tool.hxx>
44 #include <BRep_Builder.hxx>
45 #include <TopoDS.hxx>
46 #include <TopoDS_Shape.hxx>
47 #include <TopoDS_Edge.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopExp_Explorer.hxx>
50 #include <TNaming_Tool.hxx>
51 #include <Precision.hxx>
52
53 // identifier that it is full result selected, but in external document (for internal index is 0)
54 Standard_GUID kFULL_RESULT_ID("ee87e529-da6f-46af-be25-5e0fefde52f7");
55
56
57 void Model_ResultConstruction::colorConfigInfo(std::string& theSection, std::string& theName,
58                                        std::string& theDefault)
59 {
60   theSection = "Visualization";
61   theName = "result_construction_color";
62   theDefault = DEFAULT_COLOR();
63 }
64
65 void Model_ResultConstruction::setShape(std::shared_ptr<GeomAPI_Shape> theShape)
66 {
67   if (myShape != theShape) {
68     if (!theShape.get() || !theShape->isEqual(myShape)) {
69         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
70         ModelAPI_EventCreator::get()->sendUpdated(data()->owner(), anEvent);
71         if (theShape.get()) {
72           myFacesUpToDate = false;
73           myFaces.clear();
74         }
75     }
76     myShape = theShape;
77   }
78 }
79
80 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape()
81 {
82   return myShape;
83 }
84
85 Model_ResultConstruction::Model_ResultConstruction()
86 {
87   myIsInHistory = true;
88   myIsInfinite = false;
89   myFacesUpToDate = false;
90 }
91
92 void Model_ResultConstruction::setIsInHistory(const bool isInHistory)
93 {
94   myIsInHistory = isInHistory;
95 }
96
97 int Model_ResultConstruction::facesNum(const bool theUpdateNaming)
98 {
99   if (!myFacesUpToDate) {
100     std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
101       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(myShape);
102     if (aWirePtr.get()) {
103       std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
104       GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
105         aWirePtr->norm(), aWirePtr, aFaces);
106       std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFIter = aFaces.begin();
107       for(; aFIter != aFaces.end(); aFIter++) {
108         std::shared_ptr<GeomAPI_Face> aFace(new GeomAPI_Face(*aFIter));
109         if (aFace.get() && !aFace->isNull())
110           myFaces.push_back(aFace);
111       }
112     }
113     myFacesUpToDate = true;
114
115     // update all the faces and sub-elements in the naming structure
116     if (theUpdateNaming) {
117       DocumentPtr anEmptyExt;
118       bool aNotExt = false;
119       TDF_Label aDataLab = startLabel(anEmptyExt, aNotExt);
120       TDF_ChildIterator aSubsIter(aDataLab, Standard_False);
121       for(; aSubsIter.More(); aSubsIter.Next()) {
122         const TDF_Label aLab = aSubsIter.Value();
123         if (aLab.Tag() == 1) // skip the root shape label
124           continue;
125         Handle(TNaming_NamedShape) aNS;
126         if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
127           update(aLab.Tag() - 1, anEmptyExt, aNotExt);
128         }
129       }
130     }
131   }
132   return int(myFaces.size());
133 }
134
135 std::shared_ptr<GeomAPI_Face> Model_ResultConstruction::face(const int theIndex)
136 {
137   return myFaces[theIndex];
138 }
139
140 bool Model_ResultConstruction::isInfinite()
141 {
142   return myIsInfinite;
143 }
144
145 void Model_ResultConstruction::setInfinite(const bool theInfinite)
146 {
147   myIsInfinite = theInfinite;
148 }
149
150 void Model_ResultConstruction::setIsConcealed(const bool theValue)
151 {
152   // do nothing: the construction element is never concealed
153 }
154
155 static const int kSTART_VERTEX_DELTA = 1000000;
156
157 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape, std::string theFullName,
158   const int theID, std::shared_ptr<Model_Document> theDoc,
159   bool theSelectionMode)
160 {
161   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
162   TNaming_Builder aBuilder(aLab);
163   // wire never happens as sub, it must be generated to be found
164   // by SelectionNaming TNaming_Tool::NamedShape
165   if (theSelectionMode && theShape.ShapeType() != TopAbs_WIRE)
166     aBuilder.Select(theShape, theShape);
167   else
168     aBuilder.Generated(theShape);
169
170   theDoc->addNamingName(aLab, theFullName);
171   TDataStd_Name::Set(aLab, theFullName.c_str());
172 }
173
174 // generates a full-name for sub-element of the composite feature (sketch)
175 std::string fullName(CompositeFeaturePtr theComposite, const TopoDS_Shape& theSubShape,
176   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
177 {
178   TopAbs_ShapeEnum aShapeType = theSubShape.ShapeType();
179   gp_Pnt aVertexPos;
180   NCollection_Map<TopoDS_Edge> allExactEdges;
181   NCollection_Map<TopoDS_Edge, Model_EdgesHasher> allEdges;
182   NCollection_Map<Handle(Geom_Curve), Model_CurvesHasher> allCurves;
183   if (aShapeType == TopAbs_VERTEX) { // compare positions
184     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(theSubShape));
185   } else {
186     for(TopExp_Explorer anEdgeExp(theSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
187       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
188       allExactEdges.Add(anEdge);
189       allEdges.Add(anEdge);
190       Standard_Real aFirst, aLast;
191       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
192       allCurves.Add(aCurve);
193     }
194   }
195   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
196   std::map<int, std::string> aSubNames; //map from edges IDs to names of edges
197   TColStd_PackedMapOfInteger aRefs; // indixes of sub-elements in composite
198
199   const int aSubNum = theComposite->numberOfSubs();
200   // reduce equality criteria from strong to weak
201   for(int aTypeOfIdentification = 0; aTypeOfIdentification < 3; aTypeOfIdentification++) {
202     for(int a = 0; a < aSubNum; a++) {
203       FeaturePtr aSub = theComposite->subFeature(a);
204       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
205       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
206       // there may be many shapes (circle and center): register if at least one is in selection
207       for(; aRes != aResults.cend(); aRes++) {
208         ResultConstructionPtr aConstr =
209           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
210         if (!aConstr->shape()) {
211           continue;
212         }
213         if (aShapeType == TopAbs_VERTEX) {
214           if (aConstr->shape()->isVertex()) { // compare vertices positions
215             const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
216             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
217             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
218               aRefs.Add(theComposite->subFeatureId(a));
219               aSubNames[theComposite->subFeatureId(a)] = Model_SelectionNaming::shortName(aConstr);
220             }
221           } else { // get first or last vertex of the edge: last is stored with additional delta
222             const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
223             int aDelta = kSTART_VERTEX_DELTA;
224             for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
225               gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
226               if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
227                 aRefs.Add(aDelta + theComposite->subFeatureId(a));
228                 aSubNames[aDelta + theComposite->subFeatureId(a)] =
229                   Model_SelectionNaming::shortName(aConstr, aDelta / kSTART_VERTEX_DELTA);
230                 break;
231               }
232               aDelta += kSTART_VERTEX_DELTA;
233             }
234           }
235         } else {
236           if (aConstr->shape()->isEdge()) {
237             const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
238             TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
239             if (anEdge.IsNull())
240               continue;
241             bool aIsEqual = false;
242             if (aTypeOfIdentification == 0) { // check equality of curves
243               aIsEqual = allExactEdges.Contains(anEdge);
244             } else if (aTypeOfIdentification == 1) { // check EdgesHash equality of edges
245               aIsEqual = allEdges.Contains(anEdge);
246             } else { // check CurvesHash equality of curves
247               Standard_Real aFirst, aLast;
248               Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
249               aIsEqual = allCurves.Contains(aCurve);
250             }
251             if (aIsEqual) {
252               int anID = theComposite->subFeatureId(a);
253               aRefs.Add(anID);
254               aSubNames[anID] = Model_SelectionNaming::shortName(aConstr);
255               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
256                 // add edges to sub-label to support naming for edges selection
257                 TopExp_Explorer anEdgeExp(theSubShape, TopAbs_EDGE);
258                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
259                   TopoDS_Edge aFaceEdge = TopoDS::Edge(anEdgeExp.Current());
260                   bool aIsEqual = false;
261                   if (aTypeOfIdentification == 0) { // check equality of curves
262                     aIsEqual = anEdge.IsSame(aFaceEdge);
263                   } else if (aTypeOfIdentification == 1) { // check EdgesHash equality of edges
264                     aIsEqual = Model_EdgesHasher::IsEqual(aFaceEdge, anEdge);
265                   } else { // check CurvesHash equality of curves
266                     Standard_Real aFirst, aLast;
267                     Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(aFaceEdge, aFirst, aLast);
268                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
269                     aIsEqual = Model_CurvesHasher::IsEqual(aFaceCurve, aCurve);
270                   }
271                   if (aIsEqual) {
272                     int anOrient = Model_SelectionNaming::edgeOrientation(theSubShape, aFaceEdge);
273                     anOrientations[anID] = anOrient;
274                   }
275                 }
276               }
277             }
278           }
279         }
280       }
281     }
282     if (!aRefs.IsEmpty() || aShapeType == TopAbs_VERTEX)
283       break;
284   }
285   std::stringstream aName;
286   // #1839 : do not store name of the feature in the tree, since this name could be changed
287   if (theSubShape.ShapeType() != TopAbs_COMPOUND) { // compound means the whole construction result
288     if (theSubShape.ShapeType() == TopAbs_FACE) aName<<"Face";
289     else if (theSubShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
290     else if (theSubShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
291     else if (theSubShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
292
293     // make a composite name from all sub-elements indexes: "1_2_3_4"
294     TColStd_MapIteratorOfPackedMapOfInteger aRef(aRefs);
295     for(; aRef.More(); aRef.Next()) {
296       aName<<"-"<<aSubNames[aRef.Key()];
297       if (anOrientations.find(aRef.Key()) != anOrientations.end()) {
298         if (anOrientations[aRef.Key()] == 1)
299           aName<<"f";
300         else if (anOrientations[aRef.Key()] == -1)
301           aName<<"r";
302       }
303     }
304   }
305   if (!theRefs.IsNull()) {
306     Handle(TColStd_HPackedMapOfInteger) aMap = new TColStd_HPackedMapOfInteger(aRefs);
307     theRefs->ChangeMap(aMap);
308   }
309   return aName.str();
310 }
311
312 // stores shape and name on sub-label of the main stored shape
313 static void saveSubName(CompositeFeaturePtr theComposite,
314   TDF_Label& theLab, const bool isSelectionMode, TopoDS_Shape aSub,
315   std::shared_ptr<Model_Document> theDoc, std::string theFullName)
316 {
317   // trying to store the edge of composite result, not sketch sub as it is
318   if (aSub.ShapeType() == TopAbs_EDGE) {
319     ResultPtr aRes = theComposite->firstResult();
320     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aRes);
321     if (aConstr.get()) {
322       Standard_Real aSubFirst, aSubLast;
323       TopoDS_Edge aSubEdge = TopoDS::Edge(aSub);
324       Handle(Geom_Curve) aSubCurve = BRep_Tool::Curve(aSubEdge, aSubFirst, aSubLast);
325       for(int aFaceIndex = 0; aFaceIndex < aConstr->facesNum(); aFaceIndex++) {
326         GeomShapePtr aGFace = aConstr->face(aFaceIndex);
327         TopoDS_Shape aFace = aGFace->impl<TopoDS_Shape>();
328         for(TopExp_Explorer anExp(aFace, TopAbs_EDGE); anExp.More(); anExp.Next()) {
329           TopoDS_Edge anEdge = TopoDS::Edge(anExp.Current());
330           Standard_Real aFirst, aLast;
331           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
332           if (Model_CurvesHasher::IsEqual(aCurve, aSubCurve) &&
333               ((fabs(aFirst - aSubFirst) < 1.e-9 &&  fabs(aLast - aSubLast) < 1.e-9)) ||
334               (fabs(aFirst - aSubLast) < 1.e-9 &&  fabs(aLast - aSubFirst) < 1.e-9)) {
335             aSub = anEdge;
336             break;
337           }
338         }
339       }
340     }
341   }
342
343   TNaming_Builder aBuilder(theLab);
344   if (isSelectionMode)
345     aBuilder.Select(aSub, aSub);
346   else
347     aBuilder.Generated(aSub);
348   theDoc->addNamingName(theLab, theFullName.c_str());
349   TDataStd_Name::Set(theLab, theFullName.c_str());
350 }
351
352
353 TDF_Label Model_ResultConstruction::startLabel(
354   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theExternal)
355 {
356   theExternal = theExtDoc.get() && theExtDoc != document();
357   if (theExternal) { // external document is used
358     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theExtDoc);
359     return aDoc->extConstructionsLabel();
360   }
361   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
362   return aData->label();
363 }
364
365 int Model_ResultConstruction::select(const std::shared_ptr<GeomAPI_Shape>& theSubShape,
366   const std::shared_ptr<ModelAPI_Document> theExtDoc, const int theIndex)
367 {
368   int anIndex; // resulting index of the sub-label
369   TopoDS_Shape aSubShape;
370   if (theSubShape.get()) {
371     aSubShape = theSubShape->impl<TopoDS_Shape>();
372   } else if (shape().get()) {
373     aSubShape = shape()->impl<TopoDS_Shape>();
374   }
375   // if external document requires this selection, put the naming structures to this doc
376   // to support the naming mechanism in this document correctly
377   bool anExternal;
378   TDF_Label aDataLab = startLabel(theExtDoc, anExternal);
379   if (theIndex == -1) {
380     anIndex = anExternal ? 2 : 1; // for the external doc don't mind about the main shape
381
382     if (theSubShape.get() || anExternal) { // searching for already selected sub (or whole for ext)
383       // iterate all the already presented shapes to see the same
384       TDF_ChildIterator aSubsIter(aDataLab, Standard_False);
385       for(; aSubsIter.More(); aSubsIter.Next()) {
386         const TDF_Label aLab = aSubsIter.Value();
387         if (aLab.Tag() == 1) // skip the root shape label
388           continue;
389         Handle(TNaming_NamedShape) aNS;
390         if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
391           if (aNS->Get().IsSame(aSubShape)) {
392             return aLab.Tag() - 1; // found exactly the needed shape, nothing else to do
393           }
394         }
395         anIndex = aLab.Tag(); // searching for the latest index
396       }
397       anIndex = (anIndex == 1) ? 2 : (anIndex + 1); // next after 1-root, or next after all
398     }
399   } else {
400     anIndex = theIndex + 1;
401   }
402
403   // set the naming structure at index
404   TDF_Label aLab = aDataLab.FindChild(anIndex, Standard_True);
405
406   // if the subshape is part of a result face, select the whole face (#1997)
407   bool isSelectionMode = false; // and other don't set shapes - all the naming is in face label
408   if (!aSubShape.IsNull() && aSubShape.ShapeType() > TopAbs_FACE) {
409     // but before check that sub-vertex correctly detected as intersection of sketch edges (#2389)
410     int anEdgesNum = 2;
411     if (aSubShape.ShapeType() == TopAbs_VERTEX) {
412       anEdgesNum = 0;
413       ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
414       FeaturePtr aThisFeature = document()->feature(aThisPtr);
415       CompositeFeaturePtr aComposite =
416         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
417       if (aComposite.get()) {
418         const int aSubNum = aComposite->numberOfSubs();
419         for(int a = 0; a < aSubNum; a++) {
420           int aSubID = aComposite->subFeatureId(a);
421           FeaturePtr aSub = aComposite->subFeature(a);
422           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
423           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
424           for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
425             ResultConstructionPtr aConstr =
426               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
427             if (aConstr->shape() && aConstr->shape()->isEdge()) {
428               TopoDS_Shape aResShape = aConstr->shape()->impl<TopoDS_Shape>();
429               for(TopExp_Explorer anExp(aResShape, TopAbs_VERTEX); anExp.More(); anExp.Next()) {
430                 if (aSubShape.IsSame(anExp.Current())) {
431                   anEdgesNum++;
432                   break;
433                 }
434               }
435             }
436           }
437         }
438       }
439     }
440     if (anEdgesNum > 1) {
441       for(int aFaceIndex = 0; aFaceIndex < facesNum(); aFaceIndex++) {
442         TopExp_Explorer anExp(face(aFaceIndex)->impl<TopoDS_Shape>(), aSubShape.ShapeType());
443         for(; anExp.More(); anExp.Next()) {
444           if (aSubShape.IsSame(anExp.Current())) { // this is the case: select the whole face
445             // here just store the face index (to update face if update of edge is needed)
446             TNaming_Builder aBuilder(aLab);
447             aBuilder.Select(aSubShape, aSubShape);
448             int aFaceSelID = select(face(aFaceIndex), theExtDoc, -1);
449             TDF_Reference::Set(aLab, aLab.Father().FindChild(aFaceSelID));
450             isSelectionMode = true;
451             break;
452           }
453         }
454       }
455     }
456   }
457
458   // external full result is not identified by index == 0, so, add here the ID
459   if (!theSubShape.get()) {
460     TDataStd_UAttribute::Set(aLab, kFULL_RESULT_ID);
461     // empty NS
462     TNaming_Builder aBuilder(aLab);
463     // store all sub-faces naming since faces may be used for extrusion, where all edges are needed
464     Handle(TDataStd_IntPackedMap) anIndices = TDataStd_IntPackedMap::Set(aLab);
465     std::list<int> aFacesIndexes;
466     for(int a = 0; a < facesNum(); a++) {
467       anIndices->Add(select(face(a), theExtDoc, -1));
468     }
469     return anIndex - 1;
470   }
471
472   { // this to have erased Builder after the shape was generated (NS on this label may be changed)
473     TNaming_Builder aBuilder(aLab);
474     if (aSubShape.IsNull()) {
475       return anIndex - 1; // just keep empty named shape
476     }
477     // wire never happens as sub, it must be generated to be found
478     // by SelectionNaming TNaming_Tool::NamedShape
479     if (isSelectionMode && aSubShape.ShapeType() != TopAbs_WIRE) {
480       aBuilder.Select(aSubShape, aSubShape);
481     } else {
482       aBuilder.Generated(aSubShape);
483     }
484   }
485
486   if (anIndex == 1 && isInfinite()) { // infinitive results has no sub-selection
487     return anIndex - 1;
488   }
489   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
490   FeaturePtr aThisFeature = document()->feature(aThisPtr);
491   CompositeFeaturePtr aComposite =
492     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
493   if (!aComposite || aComposite->numberOfSubs() == 0) {
494     // saving of context is enough: result construction contains exactly the needed shape
495     return anIndex - 1;
496   }
497
498   // identify the results of sub-object of the composite by edges
499   // save type of the selected shape in integer attribute
500   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
501   TDataStd_Integer::Set(aLab, (int)aShapeType);
502   gp_Pnt aVertexPos;
503   TColStd_MapOfTransient allCurves; // curves of the sketc hsub-elements are used, so, edges are not equal
504   if (aShapeType == TopAbs_VERTEX) { // compare positions
505     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
506   } else {
507     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
508       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
509       Standard_Real aFirst, aLast;
510       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
511       allCurves.Add(aCurve);
512     }
513   }
514   std::shared_ptr<Model_Document> aMyDoc =
515     std::dynamic_pointer_cast<Model_Document>(document());
516   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
517   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
518   const int aSubNum = aComposite->numberOfSubs();
519   // subs are placed on unique labels because of #2248: sketch curve may produce several edges,
520   // but #2401 - on stable labels
521   NCollection_Map<int> aUsedIDMap; // already used lab tags for placement of shapes
522
523   for(int a = 0; a < aSubNum; a++) {
524     FeaturePtr aSub = aComposite->subFeature(a);
525     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
526     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
527     // there may be many shapes (circle and center): register if at least one is in selection
528     for(; aRes != aResults.cend(); aRes++) {
529       ResultConstructionPtr aConstr =
530         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
531       if (!aConstr->shape()) {
532         continue;
533       }
534       if (aShapeType != TopAbs_VERTEX) {
535         if (aConstr->shape()->isEdge()) {
536           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
537           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
538           if (!anEdge.IsNull()) {
539             Standard_Real aFirst, aLast;
540             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
541             if (allCurves.Contains(aCurve)) {
542               int anID = aComposite->subFeatureId(a);
543               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
544                 // add edges to sub-label to support naming for edges selection
545                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
546                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
547                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
548                   Standard_Real aFirst, aLast;
549                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
550                   if (Model_CurvesHasher::IsEqual(aFaceCurve, aCurve)) {
551                     while(aUsedIDMap.Contains(anID))
552                       anID += 100000;
553                     aUsedIDMap.Add(anID);
554                     TDF_Label aSubLab = aLab.FindChild(anID);
555                     std::string aFullNameSub = fullName(aComposite, anEdge);
556                     saveSubName(aComposite, aSubLab, isSelectionMode, anEdge, aMyDoc, aFullNameSub);
557
558                     int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
559                     if (anOrient != 0) {
560                       // store the orientation of edge relatively to face if needed
561                       TDataStd_Integer::Set(aSubLab, anOrient);
562                     }
563                   }
564                 }
565               } else { // put vertices of the selected edge to sub-labels
566                 // add edges to sub-label to support naming for edges selection
567                 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
568                       anEdgeExp.More(); anEdgeExp.Next()) {
569                     TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
570                     while(aUsedIDMap.Contains(anID))
571                       anID += 100000;
572                     aUsedIDMap.Add(anID);
573                     TDF_Label aSubLab = aLab.FindChild(anID);
574                     std::string aFullNameSub = fullName(aComposite, aV);
575                     saveSubName(aComposite, aSubLab, isSelectionMode, aV, aMyDoc, aFullNameSub);
576                 }
577               }
578             }
579           }
580         }
581       }
582     }
583   }
584   std::string aFullName = fullName(aComposite, aSubShape, aRefs);
585   // store the selected as primitive
586   registerSubShape(aLab, aSubShape, aFullName, 0, aMyDoc, isSelectionMode);
587   return anIndex - 1;
588 }
589
590 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape(const int theIndex,
591   const std::shared_ptr<ModelAPI_Document> theExtDoc)
592 {
593   std::shared_ptr<GeomAPI_Shape> aResult;
594   if (theIndex == 0)
595     return aResult; // the whole shape, so, NULL
596
597   bool isExt;
598   TDF_Label aLab = startLabel(theExtDoc, isExt).FindChild(theIndex + 1);
599   if (!aLab.IsNull()) { // index is not bad
600     Handle(TNaming_NamedShape) aSelection;
601     if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
602       TopoDS_Shape aSelShape = aSelection->Get();
603       if (aSelShape.IsNull())
604         return aResult; // shape equal to context => null
605       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
606       aResult->setImpl(new TopoDS_Shape(aSelShape));
607     }
608   }
609
610   return aResult;
611 }
612
613 bool Model_ResultConstruction::update(const int theIndex,
614   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theModified)
615 {
616   theModified = false;
617   bool anExt;
618   TDF_Label aLab = startLabel(theExtDoc, anExt).FindChild(theIndex + 1, Standard_True);
619   if (theIndex == 0 || aLab.IsAttribute(kFULL_RESULT_ID)) { // full for external same as index == 0
620     // it is just reference to construction, not sub-shape
621     // if there is a sketch, the sketch-naming must be updated
622     if (!isInfinite()) {
623       // update all faces named by the whole result
624       bool aRes = true;
625       Handle(TDataStd_IntPackedMap) anIndices;
626       if (aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), anIndices)) {
627         NCollection_Map<TopoDS_Shape> aFaces; // collect faces, updated in the tree
628         TColStd_MapIteratorOfPackedMapOfInteger anIndexIter(anIndices->GetMap());
629         Handle(TColStd_HPackedMapOfInteger) aNewPackedMap =
630           new TColStd_HPackedMapOfInteger; // with only faces that are ok
631         // iterate to find existing faces, updated
632         for(; anIndexIter.More(); anIndexIter.Next()) {
633           if (update(anIndexIter.Key(), theExtDoc, theModified)) {
634             GeomShapePtr aFace = shape(anIndexIter.Key(), theExtDoc);
635             if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
636               aNewPackedMap->ChangeMap().Add(anIndexIter.Key());
637               aFaces.Add(aFace->impl<TopoDS_Shape>());
638             }
639           }
640         }
641         // then iterate all existing faces to find new faces
642         int aCurrentFacesNum = facesNum();
643         for(int a = 0; a < aCurrentFacesNum; a++) {
644           GeomShapePtr aFace = face(a);
645           if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
646             // add this one
647             int aNewFaceIndex = select(aFace, theExtDoc, -1);
648             if (aNewFaceIndex > 0) {
649               aNewPackedMap->ChangeMap().Add(aNewFaceIndex);
650             }
651           }
652         }
653         anIndices->ChangeMap(aNewPackedMap);
654       }
655       return aRes;
656     } else {
657       // check is this modified or not
658       std::shared_ptr<GeomAPI_Shape> aNewShape = shape();
659       TopoDS_Shape anOldSh;
660       Handle(TNaming_NamedShape) aNS;
661       if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
662         anOldSh = aNS->Get();
663       }
664       if (aNewShape.get()) {
665         if (anOldSh.IsNull())
666           theModified = true;
667         else {
668           std::shared_ptr<GeomAPI_Shape> anOldShape(new GeomAPI_Shape);
669           anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOldSh));
670           theModified = !anOldShape->isEqual(aNewShape);
671         }
672       }
673       else if (!anOldSh.IsNull()) {
674         theModified = true;
675       }
676
677       // For correct naming selection, put the shape into the naming structure.
678       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
679       TNaming_Builder aBuilder(aLab);
680       aBuilder.Generated(aNewShape->impl<TopoDS_Shape>());
681     }
682     return shape() && !shape()->isNull();
683   }
684   // construction: identification by the results indexes, recompute faces and
685   // take the face that more close by the indexes
686   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
687   FeaturePtr aContextFeature = document()->feature(aThisPtr);
688
689   // sketch sub-element
690   if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
691   {
692     // update the referenced object if it is sub
693     Handle(TDF_Reference) aRef;
694     if (aLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
695       int aFaceIndex = aRef->Get().Tag();
696       // don't check selection since face may disappear, but the shape stays correct
697       Model_ResultConstruction::update(aFaceIndex, theExtDoc, theModified);
698     }
699     // getting a type of selected shape
700     Handle(TDataStd_Integer) aTypeAttr;
701     if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
702       return false;
703     }
704     TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
705     // selected indexes will be needed in each "if"
706     Handle(TDataStd_IntPackedMap) aSubIds;
707     std::shared_ptr<GeomAPI_Shape> aNewSelected;
708     bool aNoIndexes =
709       !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
710     // for now working only with composite features
711     CompositeFeaturePtr aComposite =
712       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
713     if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
714       return false;
715     }
716
717     if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) {
718       // compound is for the whole sketch selection
719       // If this is a wire with plane defined then it is a sketch-like object
720       if (!facesNum()) // no faces, update can not work correctly
721         return false;
722       // if there is no edges indexes, any face can be used: take the first
723       std::shared_ptr<GeomAPI_Shape> aNewSelected;
724       if (aNoIndexes) {
725         aNewSelected = face(0);
726       } else { // searching for most looks-like initial face by the indexes
727         // prepare edges of the current result for the fast searching
728         // curves and orientations of edges
729         NCollection_DataMap<Handle(Geom_Curve), int, Model_CurvesHasher> allCurves;
730         const int aSubNum = aComposite->numberOfSubs();
731         for(int a = 0; a < aSubNum; a++) {
732           int aSubID = aComposite->subFeatureId(a);
733           if (aSubIds->Contains(aSubID)) {
734             FeaturePtr aSub = aComposite->subFeature(a);
735             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
736             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
737             for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
738               ResultConstructionPtr aConstr =
739                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
740               if (aConstr->shape() && aConstr->shape()->isEdge()) {
741                 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
742                 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
743                 if (!anEdge.IsNull()) {
744                   Standard_Real aFirst, aLast;
745                   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
746                   // searching for orientation information
747                   int anOrient = 0;
748                   Handle(TDataStd_Integer) anInt;
749                   if (aLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)) {
750                     anOrient = anInt->Get();
751                   }
752                   allCurves.Bind(aCurve, anOrient);
753                 }
754               }
755             }
756           }
757         }
758         aNewSelected = Model_SelectionNaming::findAppropriateFace(
759           aThisPtr, allCurves, aShapeType == TopAbs_WIRE);
760       }
761       if (aNewSelected) { // store this new selection
762         select(aNewSelected, theExtDoc, theIndex);
763         theModified = true;
764         return true;
765       } else {
766         // if the selection is not found, put the empty shape:
767         // it's better to have disappeared shape, than the old, the lost one
768         TNaming_Builder anEmptyBuilder(aLab);
769         return false;
770       }
771     } else if (aShapeType == TopAbs_EDGE) {
772       // just reselect the edge by the id
773       const int aSubNum = aComposite->numberOfSubs();
774       for(int a = 0; a < aSubNum; a++) {
775         // if aSubIds take any, the first appropriate
776         if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
777           // found the appropriate feature
778           FeaturePtr aFeature = aComposite->subFeature(a);
779           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
780             aFeature->results().cbegin();
781           for(;aResIter != aFeature->results().cend(); aResIter++) {
782             ResultConstructionPtr aRes =
783               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
784             if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
785               select(aRes->shape(), theExtDoc, theIndex);
786               theModified = true;
787               return true;
788             }
789           }
790         }
791       }
792     } else if (aShapeType == TopAbs_VERTEX) {
793       // just reselect the vertex by the id of edge
794       const int aSubNum = aComposite->numberOfSubs();
795       for(int a = 0; a < aSubNum; a++) {
796         // if aSubIds take any, the first appropriate
797         int aFeatureID = aComposite->subFeatureId(a);
798         if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
799           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
800           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
801             // searching for deltas
802             int aVertexNum = 0;
803             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
804             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
805             // found the feature with appropriate edge
806             FeaturePtr aFeature = aComposite->subFeature(a);
807             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
808               aFeature->results().cbegin();
809             for(;aResIter != aFeature->results().cend(); aResIter++) {
810               ResultConstructionPtr aRes =
811                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
812               if (aRes && aRes->shape()) {
813                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
814                   select(aRes->shape(), theExtDoc, theIndex);
815                   theModified = true;
816                   return true;
817                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
818                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
819                   int aVIndex = 1;
820                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
821                     if (aVIndex == aVertexNum) { // found!
822                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
823                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
824                       select(aVertex, theExtDoc, theIndex);
825                       theModified = true;
826                       return true;
827                     }
828                     aVIndex++;
829                   }
830                 }
831               }
832             }
833         }
834       }
835     }
836   } else { // simple construction element: the selected is that needed
837     select(shape(), theExtDoc, theIndex);
838     theModified = true;
839     return true;
840   }
841   return false; // unknown case
842 }