Salome HOME
support fuzzy parameter in all boolean operations
[modules/shaper.git] / src / FeaturesPlugin / FeaturesPlugin_BooleanFuse.cpp
1 // Copyright (C) 2014-2022  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 "FeaturesPlugin_BooleanFuse.h"
21
22 #include <ModelAPI_ResultBody.h>
23 #include <ModelAPI_AttributeBoolean.h>
24 #include <ModelAPI_AttributeDouble.h>
25 #include <ModelAPI_AttributeInteger.h>
26 #include <ModelAPI_AttributeSelectionList.h>
27 #include <ModelAPI_AttributeString.h>
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_Tools.h>
30 #include <ModelAPI_Validator.h>
31
32 #include <GeomAlgoAPI_Boolean.h>
33 #include <GeomAlgoAPI_MakeShapeList.h>
34 #include <GeomAlgoAPI_PaveFiller.h>
35 #include <GeomAlgoAPI_ShapeBuilder.h>
36 #include <GeomAlgoAPI_ShapeTools.h>
37 #include <GeomAlgoAPI_Tools.h>
38 #include <GeomAlgoAPI_UnifySameDomain.h>
39
40 #include <GeomAPI_ShapeExplorer.h>
41 #include <GeomAPI_ShapeIterator.h>
42
43
44 //==================================================================================================
45 static void explodeCompound(const GeomShapePtr& theShape, ListOfShape& theResult)
46 {
47   if (theShape->shapeType() == GeomAPI_Shape::COMPOUND) {
48     GeomAPI_ShapeIterator it(theShape);
49     for (; it.more(); it.next())
50       theResult.push_back(it.current());
51   } else
52     theResult.push_back(theShape);
53 }
54
55 static void collectSolids(const ListOfShape& theShapes, ListOfShape& theResult)
56 {
57   for (ListOfShape::const_iterator it = theShapes.begin(); it != theShapes.end(); ++it)
58     explodeCompound(*it, theResult);
59 }
60
61 //==================================================================================================
62 FeaturesPlugin_BooleanFuse::FeaturesPlugin_BooleanFuse()
63 : FeaturesPlugin_Boolean(FeaturesPlugin_Boolean::BOOL_FUSE)
64 {
65 }
66
67 //==================================================================================================
68 void FeaturesPlugin_BooleanFuse::initAttributes()
69 {
70   data()->addAttribute(CREATION_METHOD(), ModelAPI_AttributeString::typeId());
71
72   data()->addAttribute(OBJECT_LIST_ID(), ModelAPI_AttributeSelectionList::typeId());
73   data()->addAttribute(TOOL_LIST_ID(), ModelAPI_AttributeSelectionList::typeId());
74
75   data()->addAttribute(FUZZY_PARAM_ID(), ModelAPI_AttributeDouble::typeId());
76   // Initialize the fuzzy parameter with a value below Precision::Confusion() to indicate,
77   // that the internal algorithms should use their default fuzzy value, if none was specified
78   // by the user.
79   real(FUZZY_PARAM_ID())->setValue(1.e-8);
80
81   data()->addAttribute(REMOVE_INTERSECTION_EDGES_ID(), ModelAPI_AttributeBoolean::typeId());
82
83   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), OBJECT_LIST_ID());
84   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), TOOL_LIST_ID());
85
86   initVersion(BOP_VERSION_9_4(), selectionList(OBJECT_LIST_ID()), selectionList(TOOL_LIST_ID()));
87 }
88
89 //==================================================================================================
90 void FeaturesPlugin_BooleanFuse::execute()
91 {
92   std::string anError;
93   GeomAPI_ShapeHierarchy anObjectsHierarchy, aToolsHierarchy;
94   ListOfShape aPlanes;
95
96   bool isSimpleCreation = false;
97
98   AttributeStringPtr aCreationMethodAttr = string(CREATION_METHOD());
99   if (aCreationMethodAttr.get()
100       && aCreationMethodAttr->value() == CREATION_METHOD_SIMPLE())
101   {
102     isSimpleCreation = true;
103   }
104
105   // Getting objects.
106   if (!processAttribute(OBJECT_LIST_ID(), anObjectsHierarchy, aPlanes))
107     return;
108
109   // Getting tools.
110   if (!isSimpleCreation &&
111       !processAttribute(TOOL_LIST_ID(), aToolsHierarchy, aPlanes))
112     return;
113
114   ListOfShape anObjects, aTools, anEdgesAndFaces;
115   // all objects except edges and faces
116   anObjectsHierarchy.objectsByType(anEdgesAndFaces, anObjects,
117                                    GeomAPI_Shape::FACE, GeomAPI_Shape::EDGE);
118   aToolsHierarchy.objectsByType(anEdgesAndFaces, aTools,
119                                 GeomAPI_Shape::FACE, GeomAPI_Shape::EDGE);
120
121   if ((anObjects.size() + aTools.size() + anEdgesAndFaces.size()) < 2) {
122     std::string aFeatureError = "Error: Not enough objects for boolean operation.";
123     setError(aFeatureError);
124     return;
125   }
126
127   // Getting fuzzy parameter.
128   // Used as additional tolerance to eliminate tiny results.
129   double aFuzzy = real(FUZZY_PARAM_ID())->value();
130
131   // version of FUSE feature
132   const std::string aFuseVersion = data()->version();
133
134   // Collecting all solids which will be fused.
135   // We explode the top-level compounds here because of issue #19931. It performs Fuse operation
136   // on a set of compounds, one of which is treated as self-intersected.
137   // But this problem is eliminated after the exploding, because in this case,
138   // the shapes are intersected, but not self-intersected.
139   ListOfShape aSolidsToFuse;
140   collectSolids(anObjects, aSolidsToFuse);
141   collectSolids(aTools, aSolidsToFuse);
142
143   // Collecting solids from compsolids which will not be modified
144   // in boolean operation and will be added to result.
145   bool isProcessCompsolid = !isSimpleCreation || !aFuseVersion.empty();
146   ListOfShape aShapesToAdd;
147   int aNbCompsolids = 0; // number of compsolids, which subs is taken into operation
148   bool hasSeparateSolids = false; // are solids or full results exist
149   for (GeomAPI_ShapeHierarchy::iterator anObjectsIt = anObjectsHierarchy.begin();
150        isProcessCompsolid && anObjectsIt != anObjectsHierarchy.end();
151        ++anObjectsIt) {
152     GeomShapePtr anObject = *anObjectsIt;
153     GeomShapePtr aParent = anObjectsHierarchy.parent(anObject, false);
154
155     if (aParent && aParent->shapeType() == GeomAPI_Shape::COMPSOLID) {
156       ++aNbCompsolids;
157       // mark all subs of this parent as precessed to avoid handling twice
158       aParent = anObjectsHierarchy.parent(anObject);
159
160       ListOfShape aUsed, aNotUsed;
161       anObjectsHierarchy.splitCompound(aParent, aUsed, aNotUsed);
162       aShapesToAdd.insert(aShapesToAdd.end(), aNotUsed.begin(), aNotUsed.end());
163     }
164     else
165       hasSeparateSolids = true;
166   }
167   bool isSingleCompsolid = aNbCompsolids == 1 && !hasSeparateSolids;
168
169   ListOfShape anOriginalShapes = aSolidsToFuse;
170   anOriginalShapes.insert(anOriginalShapes.end(), aShapesToAdd.begin(), aShapesToAdd.end());
171
172   // Cut edges and faces(if we have any) with solids.
173   std::shared_ptr<GeomAlgoAPI_MakeShapeList> aMakeShapeList(new GeomAlgoAPI_MakeShapeList());
174   GeomShapePtr aCuttedEdgesAndFaces;
175   if (!anEdgesAndFaces.empty()) {
176     std::shared_ptr<GeomAlgoAPI_Boolean> aCutAlgo(new GeomAlgoAPI_Boolean(anEdgesAndFaces,
177       anOriginalShapes, GeomAlgoAPI_Tools::BOOL_CUT, aFuzzy));
178     if (aCutAlgo->isDone()) {
179       aCuttedEdgesAndFaces = aCutAlgo->shape();
180       aMakeShapeList->appendAlgo(aCutAlgo);
181     }
182   }
183
184   if (aShapesToAdd.empty() || !aCuttedEdgesAndFaces) {
185     anOriginalShapes.insert(anOriginalShapes.end(), anEdgesAndFaces.begin(),
186                             anEdgesAndFaces.end());
187   }
188
189   // If we have compsolids then cut with not used solids all others.
190   if (!aShapesToAdd.empty() && !isSingleCompsolid) {
191     aSolidsToFuse.clear();
192     for (ListOfShape::iterator
193          anIt = anOriginalShapes.begin(); anIt != anOriginalShapes.end(); anIt++) {
194       ListOfShape aOneObjectList;
195       aOneObjectList.push_back(*anIt);
196       std::shared_ptr<GeomAlgoAPI_Boolean> aCutAlgo(
197         new GeomAlgoAPI_Boolean(aOneObjectList, aShapesToAdd, GeomAlgoAPI_Tools::BOOL_CUT, aFuzzy));
198
199       if (GeomAlgoAPI_ShapeTools::area(aCutAlgo->shape()) > 1.e-27) {
200         aSolidsToFuse.push_back(aCutAlgo->shape());
201         aMakeShapeList->appendAlgo(aCutAlgo);
202       }
203     }
204   }
205
206   if (!aSolidsToFuse.empty()) {
207     anObjects.clear();
208     anObjects.push_back(aSolidsToFuse.back());
209     aSolidsToFuse.pop_back();
210     aTools = aSolidsToFuse;
211   }
212
213   // Fuse all objects and all tools.
214   GeomShapePtr aShape;
215   if (anObjects.size() == 1 && aTools.empty()) {
216     aShape = anObjects.front();
217   } else if (anObjects.empty() && aTools.size() == 1) {
218     aShape = aTools.front();
219   } else if ((anObjects.size() + aTools.size()) > 1) {
220     std::shared_ptr<GeomAlgoAPI_Boolean> aFuseAlgo(new GeomAlgoAPI_Boolean(anObjects,
221       aTools,
222       GeomAlgoAPI_Tools::BOOL_FUSE,
223       aFuzzy));
224
225     // Checking that the algorithm worked properly.
226     if (GeomAlgoAPI_Tools::AlgoError::isAlgorithmFailed(aFuseAlgo, getKind(), anError)) {
227       setError(anError);
228       return;
229     }
230
231     aShape = aFuseAlgo->shape();
232     aMakeShapeList->appendAlgo(aFuseAlgo);
233   }
234
235   // Combine result with not used solids from compsolid and edges and faces (if we have any).
236   if (aCuttedEdgesAndFaces.get() && !aCuttedEdgesAndFaces->isNull()) {
237     aShapesToAdd.push_back(aCuttedEdgesAndFaces);
238   } else {
239     aShapesToAdd.insert(aShapesToAdd.end(), anEdgesAndFaces.begin(), anEdgesAndFaces.end());
240   }
241   if (!aShapesToAdd.empty()) {
242     if (aShape.get()) {
243       aShapesToAdd.push_back(aShape);
244     }
245     std::shared_ptr<GeomAlgoAPI_PaveFiller> aFillerAlgo(
246       new GeomAlgoAPI_PaveFiller(aShapesToAdd, true, aFuzzy));
247     if (GeomAlgoAPI_Tools::AlgoError::isAlgorithmFailed(aFillerAlgo, getKind(), anError)) {
248       setError(anError);
249       return;
250     }
251
252     aShape = aFillerAlgo->shape();
253     aMakeShapeList->appendAlgo(aFillerAlgo);
254   }
255
256   bool isRemoveEdges = false;
257   AttributeBooleanPtr removeEdgesAttr = boolean(REMOVE_INTERSECTION_EDGES_ID());
258   if (removeEdgesAttr.get()) {
259     isRemoveEdges = removeEdgesAttr->value();
260   }
261
262   if (isRemoveEdges) {
263     std::shared_ptr<GeomAlgoAPI_UnifySameDomain> aUnifyAlgo(
264       new GeomAlgoAPI_UnifySameDomain(aShape));
265
266     if (GeomAlgoAPI_Tools::AlgoError::isAlgorithmFailed(aUnifyAlgo, getKind(), anError)) {
267       setError(anError);
268       return;
269     }
270
271     aShape = aUnifyAlgo->shape();
272     aMakeShapeList->appendAlgo(aUnifyAlgo);
273   }
274
275   if (aFuseVersion == BOP_VERSION_9_4()) {
276     // merge hierarchies of compounds containing objects and tools
277     // and append the result of the FUSE operation
278     aShape = keepUnusedSubsOfCompound(aShape, anObjectsHierarchy, aToolsHierarchy, aMakeShapeList);
279   }
280
281   int aResultIndex = 0;
282
283   ResultBodyPtr aResultBody = document()->createBody(data(), aResultIndex);
284
285   ListOfShape anEmptyTools;
286   ModelAPI_Tools::loadModifiedShapes(aResultBody,
287                                      anOriginalShapes,
288                                      anEmptyTools,
289                                      aMakeShapeList,
290                                      aShape);
291   setResult(aResultBody, aResultIndex);
292   aResultIndex++;
293
294   ModelAPI_Tools::loadDeletedShapes(aResultBody,
295                                     GeomShapePtr(),
296                                     anOriginalShapes,
297                                     aMakeShapeList,
298                                     aShape);
299
300   // remove the rest results if there were produced in the previous pass
301   removeResults(aResultIndex);
302 }