Salome HOME
041e8f226d34a769e6e4ccf23110d04d99a55ace
[modules/shaper.git] / src / Model / Model_ResultConstruction.cpp
1 // Copyright (C) 2014-2019  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_ResultConstruction.h>
21
22 #include <Model_Data.h>
23 #include <ModelAPI_CompositeFeature.h>
24 #include <GeomAlgoAPI_SketchBuilder.h>
25 #include <GeomAPI_Tools.h>
26 #include <ModelAPI_Events.h>
27 #include <Model_Document.h>
28 #include <GeomAPI_PlanarEdges.h>
29 #include <GeomAPI_Shape.h>
30 #include <Events_Loop.h>
31 #include <GeomDataAPI_Point.h>
32 #include <GeomDataAPI_Dir.h>
33
34 #include <TDF_ChildIDIterator.hxx>
35 #include <TNaming_NamedShape.hxx>
36 #include <TNaming_Builder.hxx>
37 #include <TDataStd_IntPackedMap.hxx>
38 #include <TDataStd_Name.hxx>
39 #include <TDataStd_UAttribute.hxx>
40 #include <BRep_Builder.hxx>
41 #include <TopoDS.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Vertex.hxx>
44 #include <TopoDS_ListOfShape.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopTools_MapOfShape.hxx>
47 #include <NCollection_IndexedDataMap.hxx>
48
49 #include <algorithm>
50
51
52 // identifier of the infinite result
53 Standard_GUID kIS_INFINITE("dea8cc5a-53f2-49c1-94e8-a947bed20a9f");
54 // identifier of the result not in history
55 Standard_GUID kIS_IN_HISTORY("a9aec01c-805e-44d1-b5d2-a63f06522f8a");
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     storeShape(theShape);
69     if (!theShape.get() || !theShape->isEqual(myShape)) {
70       static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
71       ModelAPI_EventCreator::get()->sendUpdated(data()->owner(), anEvent);
72     }
73     myShape = theShape;
74   }
75 }
76
77 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape()
78 {
79   return myShape;
80 }
81
82 static std::string shortName(
83   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr)
84 {
85   std::string aName = theConstr->data()->name();
86   // remove "-", "/" and "&" command-symbols
87   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
88   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
89   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
90   // remove the last 's', 'e', 'f' and 'r' symbols:
91   // they are used as markers of start/end/forward/reversed indicators
92   static const std::string aSyms("sefr");
93   std::string::iterator aSuffix = aName.end() - 1;
94   while(aSyms.find(*aSuffix) != std::string::npos) {
95     --aSuffix;
96   }
97   aName.erase(aSuffix + 1, aName.end());
98   return aName;
99 }
100
101 bool Model_ResultConstruction::updateShape()
102 {
103   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
104   if (aData && aData->isValid()) {
105     TDF_Label aShapeLab = aData->shapeLab();
106     Handle(TNaming_NamedShape) aNS;
107     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
108       TopoDS_Shape aShape = aNS->Get();
109       if (!aShape.IsNull()) {
110         if (aShape.ShapeType() == TopAbs_COMPOUND) {
111           // restore the sketch planar edges object
112           std::shared_ptr<GeomAPI_PlanarEdges> aBigWire(new GeomAPI_PlanarEdges);
113           aBigWire->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
114           FeaturePtr aSketch =
115             document()->feature(std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner()));
116           std::shared_ptr<GeomDataAPI_Point> anOrigin =
117             std::dynamic_pointer_cast<GeomDataAPI_Point>(aSketch->data()->attribute("Origin"));
118           std::shared_ptr<GeomDataAPI_Dir> aDirX =
119             std::dynamic_pointer_cast<GeomDataAPI_Dir>(aSketch->data()->attribute("DirX"));
120           std::shared_ptr<GeomDataAPI_Dir> aNorm =
121             std::dynamic_pointer_cast<GeomDataAPI_Dir>(aSketch->data()->attribute("Norm"));
122           if (anOrigin.get() && aDirX.get() && aNorm.get()) {
123             aBigWire->setPlane(anOrigin->pnt(), aDirX->dir(), aNorm->dir());
124             myShape = aBigWire;
125             return true;
126           }
127         }
128         // just restore shape
129         GeomShapePtr aGShape(new GeomAPI_Shape);
130         aGShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
131         myShape = GeomAPI_Tools::getTypedShape(aGShape); // restore the sketch sub-components
132         return true;
133       }
134     }
135   }
136   return false;
137 }
138
139 Model_ResultConstruction::Model_ResultConstruction()
140 {
141 }
142
143 bool Model_ResultConstruction::isInHistory()
144 {
145   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
146   if (aData.get() && aData->isValid()) {
147     return !aData->label().IsAttribute(kIS_IN_HISTORY); // by default no attribute, but in history
148   }
149   return true;  // unknown case
150 }
151
152 void Model_ResultConstruction::setIsInHistory(const bool isInHistory)
153 {
154   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
155   if (aData.get() && aData->isValid()) {
156     if (!isInHistory)
157       TDataStd_UAttribute::Set(aData->label(), kIS_IN_HISTORY);
158     else
159       aData->label().ForgetAttribute(kIS_IN_HISTORY);
160   }
161 }
162
163 bool Model_ResultConstruction::isInfinite()
164 {
165   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
166   if (aData.get() && aData->isValid()) {
167     return aData->label().IsAttribute(kIS_INFINITE);
168   }
169   return false;  // unknown case
170 }
171
172 void Model_ResultConstruction::setInfinite(const bool theInfinite)
173 {
174   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
175   if (aData.get() && aData->isValid()) {
176     if (theInfinite)
177       TDataStd_UAttribute::Set(aData->label(), kIS_INFINITE);
178     else
179       aData->label().ForgetAttribute(kIS_INFINITE);
180   }
181 }
182
183 int Model_ResultConstruction::facesNum(const bool theUpdateNaming)
184 {
185   int aResult = 0;
186   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
187   if (aData.get() && aData->isValid()) {
188     TDF_Label aShapeLab = aData->shapeLab();
189     TDF_ChildIDIterator anOldIter(aShapeLab, TDataStd_IntPackedMap::GetID());
190     for (; anOldIter.More(); anOldIter.Next()) {
191       aResult++;
192     }
193   }
194   return aResult;
195 }
196
197 std::shared_ptr<GeomAPI_Face> Model_ResultConstruction::face(const int theIndex)
198 {
199   std::shared_ptr<GeomAPI_Face> aResult;
200   int anIndex = 0;
201   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
202   if (aData.get() && aData->isValid()) {
203     TDF_Label aShapeLab = aData->shapeLab();
204     TDF_ChildIDIterator anOldIter(aShapeLab, TDataStd_IntPackedMap::GetID());
205     for (; anOldIter.More(); anOldIter.Next()) {
206       if (anIndex == theIndex) {
207         Handle(TNaming_NamedShape) aNS;
208         anOldIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS);
209         aResult.reset(new GeomAPI_Face);
210         aResult->setImpl(new TopoDS_Shape(aNS->Get()));
211         break;
212       }
213       anIndex++;
214     }
215   }
216   return aResult;
217 }
218
219 void Model_ResultConstruction::setIsConcealed(const bool theValue)
220 {
221   // do nothing: the construction element is never concealed
222 }
223
224 void Model_ResultConstruction::storeShape(std::shared_ptr<GeomAPI_Shape> theShape)
225 {
226   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
227   if (aData && aData->isValid()) {
228     std::string aMyName = data()->name();
229     TDF_Label aShapeLab = aData->shapeLab();
230     if (!theShape.get() || theShape->isNull()) {
231       aShapeLab.ForgetAllAttributes();
232       TDataStd_Name::Set(aShapeLab, aMyName.c_str()); // restore name forgotten
233       return;
234     }
235     std::shared_ptr<Model_Document> aMyDoc =
236       std::dynamic_pointer_cast<Model_Document>(document());
237     const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
238     if (isInfinite() || aShape.ShapeType() == TopAbs_VERTEX) {
239       aShapeLab.ForgetAllAttributes(); // clear all previously stored
240       TNaming_Builder aBuilder(aShapeLab);
241       aBuilder.Generated(aShape);
242       TDataStd_Name::Set(aShapeLab, aMyName.c_str());
243       aMyDoc->addNamingName(aShapeLab, aMyName);
244     } else if (aShape.ShapeType() == TopAbs_EDGE) { // store sub-vertices on sub-labels
245       aShapeLab.ForgetAllAttributes(); // clear all previously stored
246       TNaming_Builder aBuilder(aShapeLab);
247       aBuilder.Generated(aShape);
248
249       TopExp_Explorer anExp(aShape, TopAbs_VERTEX);
250       for(int anIndex = 1; anExp.More(); anExp.Next(), anIndex++) {
251         TDF_Label aSubLab = aShapeLab.FindChild(anIndex);
252         TNaming_Builder aBuilder(aSubLab);
253         aBuilder.Generated(anExp.Current());
254         std::string aVertexName = aMyName + "_" + (anIndex == 1 ? "StartVertex" : "EndVertex");
255         TDataStd_Name::Set(aSubLab, aVertexName.c_str());
256         aMyDoc->addNamingName(aSubLab, aVertexName);
257       }
258       TDataStd_Name::Set(aShapeLab, aMyName.c_str());
259       aMyDoc->addNamingName(aShapeLab, aMyName);
260     } else { // this is probably sketch, so, work with it as with composite
261       std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
262         std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(theShape);
263       if (!aWirePtr.get())
264         return; // unknown case
265       ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
266       FeaturePtr aThisFeature = aMyDoc->feature(aThisPtr);
267       CompositeFeaturePtr aComposite =
268         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
269       if (!aComposite || aComposite->numberOfSubs() == 0)
270         return; // unknown case
271       // collect indices of curves of current composite
272       NCollection_DataMap<Handle(Geom_Curve), int> aCurvesIndices;
273       NCollection_DataMap<int, TopoDS_Edge> anEdgeIndices;
274       std::map<int, std::string> aComponentsNames; // names of components that lay on index
275       const int aSubNum = aComposite->numberOfSubs();
276       for (int a = 0; a < aSubNum; a++) {
277         FeaturePtr aSub = aComposite->subFeature(a);
278         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
279         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
280         for (; aRes != aResults.cend(); aRes++) {
281           ResultConstructionPtr aConstr =
282             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
283           if (aConstr->shape() && aConstr->shape()->isEdge()) {
284             TopoDS_Edge anEdge = TopoDS::Edge(aConstr->shape()->impl<TopoDS_Shape>());
285             Standard_Real aFirst, aLast;
286             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
287             aCurvesIndices.Bind(aCurve, a);
288             anEdgeIndices.Bind(a, anEdge);
289             aComponentsNames[a] = shortName(aConstr);
290           }
291         }
292       }
293
294       GeomAlgoAPI_SketchBuilder aSketchBuilder(aWirePtr->origin(), aWirePtr->dirX(),
295                                                aWirePtr->norm(), aWirePtr);
296       const ListOfShape& aFaces = aSketchBuilder.faces();
297       // order is important to store faces in the same order if sketch is created from scratch
298       NCollection_IndexedDataMap<TopoDS_Face, TColStd_ListOfInteger> aNewIndices; // edges indices
299       std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator aFIter = aFaces.begin();
300       for (; aFIter != aFaces.end(); aFIter++) {
301         std::shared_ptr<GeomAPI_Face> aFace(new GeomAPI_Face(*aFIter));
302         // put them to a label, trying to keep the same faces on the same labels
303         if (aFace.get() && !aFace->isNull()) {
304           TopoDS_Face aTopoFace = TopoDS::Face(aFace->impl<TopoDS_Shape>());
305           aNewIndices.Add(aTopoFace, TColStd_ListOfInteger());
306           // keep new indices of sub-elements used in this face
307           for (TopExp_Explorer anEdges(aTopoFace, TopAbs_EDGE); anEdges.More(); anEdges.Next()) {
308             TopoDS_Edge anEdge = TopoDS::Edge(anEdges.Current());
309             Standard_Real aFirst, aLast;
310             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
311             if (aCurvesIndices.IsBound(aCurve)) {
312               int anIndex = aCurvesIndices.Find(aCurve);
313               if ((aFirst > aLast) != (anEdge.Orientation() == TopAbs_REVERSED))
314                 anIndex = -anIndex;
315               aNewIndices.ChangeFromKey(aTopoFace).Append(anIndex);
316             }
317           }
318         }
319       }
320       NCollection_DataMap<int, TopoDS_Face> aFacesOrder; // faces -> tag where they must be set
321       NCollection_List<TopoDS_Face> anUnorderedFaces; // faces that may be located at any index
322       // searching for the best new candidate to old location
323       NCollection_IndexedDataMap<TopoDS_Face, TColStd_ListOfInteger>::Iterator
324         aNewIter(aNewIndices);
325       for (; aNewIter.More(); aNewIter.Next()) {
326         double aBestFound = 0, aBestNotFound = 1.e+100;
327         int aBestTag = 0;
328         const TColStd_ListOfInteger& aNewInd = aNewIter.Value();
329         // old faces indices where they where located
330         TDF_ChildIDIterator anOldIter(aShapeLab, TDataStd_IntPackedMap::GetID());
331         for (; anOldIter.More(); anOldIter.Next()) {
332           int aTag = anOldIter.Value()->Label().Tag();
333           if (aFacesOrder.IsBound(aTag))
334             continue; // already found a best candidate
335           Handle(TDataStd_IntPackedMap) anOldIndices =
336             Handle(TDataStd_IntPackedMap)::DownCast(anOldIter.Value());
337           double aFound = 0, aNotFound = 0;
338           TColStd_ListOfInteger::Iterator aNewIndIter(aNewInd);
339           for (; aNewIndIter.More(); aNewIndIter.Next()) {
340             if (anOldIndices->Contains(aNewIndIter.Value())) {
341               aFound += 1.;
342             }
343             else if (anOldIndices->Contains(-aNewIndIter.Value())) { // different orientation
344               aFound += 0.001;
345             }
346             else {
347               aNotFound += 1.;
348             }
349           }
350           if (aNotFound <= aBestNotFound) { // less and equal to find better "found": #2859
351             if (aFound > aBestFound) {
352               aBestNotFound = aNotFound;
353               aBestFound = aFound;
354               aBestTag = aTag;
355             }
356           }
357         }
358         if (aBestTag != 0) { // found an appropriate face
359           aFacesOrder.Bind(aBestTag, aNewIter.Key());
360         } else {
361           anUnorderedFaces.Append(aNewIter.Key());
362         }
363       }
364       aShapeLab.ForgetAllAttributes(); // clear all previously stored
365       TDataStd_Name::Set(aShapeLab, aMyName.c_str()); // restore name forgotten
366       TNaming_Builder aBuilder(aShapeLab); // store the compound to get it ready on open of document
367       aBuilder.Generated(aShape);
368       aMyDoc->addNamingName(aShapeLab, aMyName);
369       // set new faces to the labels
370       int aCurrentTag = 1;
371       NCollection_List<TopoDS_Face>::Iterator anUnordered(anUnorderedFaces);
372       for(int aCurrentTag = 1; !aFacesOrder.IsEmpty() || anUnordered.More(); aCurrentTag++) {
373         TopoDS_Face aFaceToPut;
374         if (aFacesOrder.IsBound(aCurrentTag)) {
375           aFaceToPut = aFacesOrder.Find(aCurrentTag);
376           aFacesOrder.UnBind(aCurrentTag);
377         } else if (anUnordered.More()){
378           aFaceToPut = anUnordered.Value();
379           anUnordered.Next();
380         }
381
382         if (!aFaceToPut.IsNull()) {
383           TopTools_MapOfShape aFaceEdges;
384           for(TopExp_Explorer anEdges(aFaceToPut, TopAbs_EDGE); anEdges.More(); anEdges.Next()) {
385             aFaceEdges.Add(anEdges.Current());
386           }
387
388           TDF_Label aLab = aShapeLab.FindChild(aCurrentTag);
389           TNaming_Builder aFaceBuilder(aLab);
390           aFaceBuilder.Generated(aFaceToPut);
391           // store also indices of the new face edges
392           Handle(TDataStd_IntPackedMap) aNewMap = TDataStd_IntPackedMap::Set(aLab);
393           const TColStd_ListOfInteger& aNewInd = aNewIndices.FindFromKey(aFaceToPut);
394           std::stringstream aName;
395           aName<<"Face";
396           TopExp_Explorer aPutEdges(aFaceToPut, TopAbs_EDGE);
397           TNaming_Builder *anEdgesBuilder = 0, *aVerticesBuilder = 0;
398           for(TColStd_ListOfInteger::Iterator anIter(aNewInd); anIter.More(); anIter.Next()) {
399             int anIndex = anIter.Value();
400             int aModIndex = anIndex > 0 ? anIndex : -anIndex;
401             aNewMap->Add(anIndex);
402             aName<<"-"<<aComponentsNames[aModIndex];
403             if (anIter.Value() > 0)
404               aName<<"f";
405             else
406               aName<<"r";
407             // collect all edges of the face which are modified in sub-label of the face
408             if (anEdgeIndices.IsBound(aModIndex) &&
409                 !aFaceEdges.Contains(anEdgeIndices.Find(aModIndex))) {
410               if (!anEdgesBuilder) {
411                 TDF_Label anEdgesLabel = aLab.FindChild(1);
412                 anEdgesBuilder = new TNaming_Builder(anEdgesLabel);
413                 std::ostringstream aSubName;
414                 // tag is needed for Test1922 to distinguish sub-edges of different faces
415                 aSubName<<"SubEdge_"<<aCurrentTag;
416                 TDataStd_Name::Set(anEdgesLabel, aSubName.str().c_str());
417               }
418               anEdgesBuilder->Modify(anEdgeIndices.Find(aModIndex), aPutEdges.Current());
419             }
420             // put also modified vertices, otherwise vertex of original edge has no history
421             if (anEdgeIndices.IsBound(aModIndex)) {
422               TopExp_Explorer aVExpOld(anEdgeIndices.Find(aModIndex), TopAbs_VERTEX);
423               TopExp_Explorer aVExpNew(aPutEdges.Current(), TopAbs_VERTEX);
424               for(; aVExpNew.More() && aVExpOld.More(); aVExpNew.Next(), aVExpOld.Next()) {
425                 if (!aVExpOld.Current().IsSame(aVExpNew.Current())) {
426                   if (!aVerticesBuilder) {
427                     TDF_Label aVertLabel = aLab.FindChild(2);
428                     aVerticesBuilder = new TNaming_Builder(aVertLabel);
429                     std::ostringstream aSubName;
430                     // tag is needed for Test1922 to distinguish sub-edges of different faces
431                     aSubName<<"SubVertex_"<<aCurrentTag;
432                     TDataStd_Name::Set(aVertLabel, aSubName.str().c_str());
433                   }
434                   aVerticesBuilder->Modify(aVExpOld.Current(), aVExpNew.Current());
435
436                 }
437               }
438             }
439             aPutEdges.Next();
440           }
441           if (anEdgesBuilder)
442             delete anEdgesBuilder;
443           if (aVerticesBuilder)
444             delete aVerticesBuilder;
445           TDataStd_Name::Set(aLab, TCollection_ExtendedString(aName.str().c_str()));
446           aMyDoc->addNamingName(aLab, aName.str());
447           // put also wires to sub-labels to correctly select them instead of collection by edges
448           int aWireTag = 3; // first tag is for SubEdge-s, second - for vertices
449           for(TopExp_Explorer aWires(aFaceToPut, TopAbs_WIRE); aWires.More(); aWires.Next()) {
450             TDF_Label aWireLab = aLab.FindChild(aWireTag);
451             TNaming_Builder aWireBuilder(aWireLab);
452             aWireBuilder.Generated(aWires.Current());
453             std::ostringstream aWireName;
454             aWireName<<aName.str()<<"_wire";
455             if (aWireTag > 3)
456               aWireName<<"_"<<aWireTag - 2;
457             TDataStd_Name::Set(aWireLab, aWireName.str().c_str());
458             aMyDoc->addNamingName(aWireLab, aWireName.str());
459             aWireTag++;
460           }
461         }
462       }
463     }
464   }
465 }