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