Salome HOME
6b19e7e5c6a006cb37769d84ffe943b73f162ddf
[modules/shaper.git] / src / FeaturesPlugin / FeaturesPlugin_BooleanFuse.cpp
1 // Copyright (C) 2014-2023  CEA, EDF
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 static const double DEFAULT_FUZZY = 1.e-5;
45
46
47 //==================================================================================================
48 static void explodeCompound(const GeomShapePtr& theShape, ListOfShape& theResult)
49 {
50   if (theShape->shapeType() == GeomAPI_Shape::COMPOUND) {
51     GeomAPI_ShapeIterator it(theShape);
52     for (; it.more(); it.next())
53       theResult.push_back(it.current());
54   } else
55     theResult.push_back(theShape);
56 }
57
58 static void collectSolids(const ListOfShape& theShapes, ListOfShape& theResult)
59 {
60   for (ListOfShape::const_iterator it = theShapes.begin(); it != theShapes.end(); ++it)
61     explodeCompound(*it, theResult);
62 }
63
64 //==================================================================================================
65 FeaturesPlugin_BooleanFuse::FeaturesPlugin_BooleanFuse()
66 : FeaturesPlugin_Boolean(FeaturesPlugin_Boolean::BOOL_FUSE)
67 {
68 }
69
70 //==================================================================================================
71 void FeaturesPlugin_BooleanFuse::initAttributes()
72 {
73   AttributeStringPtr aMethodAttr = std::dynamic_pointer_cast<ModelAPI_AttributeString>
74     (data()->addAttribute(CREATION_METHOD(), ModelAPI_AttributeString::typeId())); // #1
75
76   data()->addAttribute(OBJECT_LIST_ID(), ModelAPI_AttributeSelectionList::typeId()); // #2
77   data()->addAttribute(TOOL_LIST_ID(), ModelAPI_AttributeSelectionList::typeId()); // #3
78
79   data()->addAttribute(REMOVE_INTERSECTION_EDGES_ID(),
80                        ModelAPI_AttributeBoolean::typeId()); // #4 ???
81
82   AttributeBooleanPtr aUseFuzzyAttr; // #5 ???
83   AttributeDoublePtr aValFuzzyAttr; // #6 ???
84
85   bool badOrder = false;
86   if (aMethodAttr->isInitialized()) { // restoring data from saved study
87     // It is a fix for 37570 Tuleap issue.
88     // We could have studies with aValFuzzyAttr at the 5th position instead of expected 6th.
89
90     // Fuzzy value (check, is it present at 5th label)
91     aValFuzzyAttr = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>
92       (data()->addAttribute(FUZZY_PARAM_ID(),
93                             ModelAPI_AttributeDouble::typeId())); // #5
94     if (aValFuzzyAttr->isInitialized()) {
95       badOrder = true;
96       // bad order of attributes in saved study
97       // 4 - is fuzzy
98       // 5 - fuzzy value
99       // 6 - remove edges
100       aUseFuzzyAttr = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
101       (data()->addAttribute(FeaturesPlugin_Boolean::USE_FUZZY_ID(),
102                             ModelAPI_AttributeBoolean::typeId(),
103                             4)); // #4
104       data()->addAttribute(REMOVE_INTERSECTION_EDGES_ID(),
105                            ModelAPI_AttributeBoolean::typeId(),
106                            6); // #6
107     }
108   }
109
110   if (!badOrder) {
111     // good order of attributes
112     // 4 - remove edges
113     // 5 - is fuzzy
114     // 6 - fuzzy value
115
116     // Is fuzzy value
117     aUseFuzzyAttr = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
118       (data()->addAttribute(FeaturesPlugin_Boolean::USE_FUZZY_ID(),
119                             ModelAPI_AttributeBoolean::typeId(),
120                             5)); // #5
121     // Fuzzy value
122     aValFuzzyAttr = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>
123       (data()->addAttribute(FUZZY_PARAM_ID(),
124                             ModelAPI_AttributeDouble::typeId(),
125                             6)); // #6
126   }
127
128   if (!aUseFuzzyAttr->isInitialized())
129     aUseFuzzyAttr->setValue(false); // Do NOT use the fuzzy parameter by default.
130   if (!aValFuzzyAttr->isInitialized())
131     aValFuzzyAttr->setValue(DEFAULT_FUZZY);
132
133   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), OBJECT_LIST_ID());
134   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), TOOL_LIST_ID());
135
136   initVersion(BOP_VERSION_9_4(), selectionList(OBJECT_LIST_ID()), selectionList(TOOL_LIST_ID()));
137 }
138
139 //==================================================================================================
140 void FeaturesPlugin_BooleanFuse::execute()
141 {
142   std::string anError;
143   GeomAPI_ShapeHierarchy anObjectsHierarchy, aToolsHierarchy;
144   ListOfShape aPlanes;
145
146   bool isSimpleCreation = false;
147
148   AttributeStringPtr aCreationMethodAttr = string(CREATION_METHOD());
149   if (aCreationMethodAttr.get()
150       && aCreationMethodAttr->value() == CREATION_METHOD_SIMPLE())
151   {
152     isSimpleCreation = true;
153   }
154
155   // Getting objects.
156   if (!processAttribute(OBJECT_LIST_ID(), anObjectsHierarchy, aPlanes))
157     return;
158
159   // Getting tools.
160   if (!isSimpleCreation &&
161       !processAttribute(TOOL_LIST_ID(), aToolsHierarchy, aPlanes))
162     return;
163
164   ListOfShape anObjects, aTools, anEdgesAndFaces;
165   // all objects except edges and faces
166   anObjectsHierarchy.objectsByType(anEdgesAndFaces, anObjects,
167                                    GeomAPI_Shape::FACE, GeomAPI_Shape::EDGE);
168   aToolsHierarchy.objectsByType(anEdgesAndFaces, aTools,
169                                 GeomAPI_Shape::FACE, GeomAPI_Shape::EDGE);
170
171   if ((anObjects.size() + aTools.size() + anEdgesAndFaces.size()) < 2) {
172     std::string aFeatureError = "Error: Not enough objects for boolean operation.";
173     setError(aFeatureError);
174     return;
175   }
176
177   // Getting fuzzy parameter.
178   // Used as additional tolerance to eliminate tiny results.
179   // Using -1 as fuzzy value in the GeomAlgoAPI means to ignore it during the boolean operation!
180   bool aUseFuzzy = boolean(USE_FUZZY_ID())->value();
181   double aFuzzy = (aUseFuzzy ? real(FUZZY_PARAM_ID())->value() : -1);
182
183   // version of FUSE feature
184   const std::string aFuseVersion = data()->version();
185
186   // Collecting all solids which will be fused.
187   // We explode the top-level compounds here because of issue #19931. It performs Fuse operation
188   // on a set of compounds, one of which is treated as self-intersected.
189   // But this problem is eliminated after the exploding, because in this case,
190   // the shapes are intersected, but not self-intersected.
191   ListOfShape aSolidsToFuse;
192   collectSolids(anObjects, aSolidsToFuse);
193   collectSolids(aTools, aSolidsToFuse);
194
195   // Collecting solids from compsolids which will not be modified
196   // in boolean operation and will be added to result.
197   bool isProcessCompsolid = !isSimpleCreation || !aFuseVersion.empty();
198   ListOfShape aShapesToAdd;
199   int aNbCompsolids = 0; // number of compsolids, which subs is taken into operation
200   bool hasSeparateSolids = false; // are solids or full results exist
201   for (GeomAPI_ShapeHierarchy::iterator anObjectsIt = anObjectsHierarchy.begin();
202        isProcessCompsolid && anObjectsIt != anObjectsHierarchy.end();
203        ++anObjectsIt) {
204     GeomShapePtr anObject = *anObjectsIt;
205     GeomShapePtr aParent = anObjectsHierarchy.parent(anObject, false);
206
207     if (aParent && aParent->shapeType() == GeomAPI_Shape::COMPSOLID) {
208       ++aNbCompsolids;
209       // mark all subs of this parent as precessed to avoid handling twice
210       aParent = anObjectsHierarchy.parent(anObject);
211
212       ListOfShape aUsed, aNotUsed;
213       anObjectsHierarchy.splitCompound(aParent, aUsed, aNotUsed);
214       aShapesToAdd.insert(aShapesToAdd.end(), aNotUsed.begin(), aNotUsed.end());
215     }
216     else
217       hasSeparateSolids = true;
218   }
219   bool isSingleCompsolid = aNbCompsolids == 1 && !hasSeparateSolids;
220
221   ListOfShape anOriginalShapes = aSolidsToFuse;
222   anOriginalShapes.insert(anOriginalShapes.end(), aShapesToAdd.begin(), aShapesToAdd.end());
223
224   // Cut edges and faces(if we have any) with solids.
225   std::shared_ptr<GeomAlgoAPI_MakeShapeList> aMakeShapeList(new GeomAlgoAPI_MakeShapeList());
226   GeomShapePtr aCuttedEdgesAndFaces;
227   if (!anEdgesAndFaces.empty()) {
228     std::shared_ptr<GeomAlgoAPI_Boolean> aCutAlgo(new GeomAlgoAPI_Boolean(anEdgesAndFaces,
229       anOriginalShapes, GeomAlgoAPI_Tools::BOOL_CUT, aFuzzy));
230     if (aCutAlgo->isDone()) {
231       aCuttedEdgesAndFaces = aCutAlgo->shape();
232       aMakeShapeList->appendAlgo(aCutAlgo);
233     }
234   }
235
236   if (aShapesToAdd.empty() || !aCuttedEdgesAndFaces) {
237     anOriginalShapes.insert(anOriginalShapes.end(), anEdgesAndFaces.begin(),
238                             anEdgesAndFaces.end());
239   }
240
241   // If we have compsolids then cut with not used solids all others.
242   if (!aShapesToAdd.empty() && !isSingleCompsolid) {
243     aSolidsToFuse.clear();
244     for (ListOfShape::iterator
245          anIt = anOriginalShapes.begin(); anIt != anOriginalShapes.end(); anIt++) {
246       ListOfShape aOneObjectList;
247       aOneObjectList.push_back(*anIt);
248       std::shared_ptr<GeomAlgoAPI_Boolean> aCutAlgo(
249         new GeomAlgoAPI_Boolean(aOneObjectList, aShapesToAdd, GeomAlgoAPI_Tools::BOOL_CUT, aFuzzy));
250
251       if (GeomAlgoAPI_ShapeTools::area(aCutAlgo->shape()) > 1.e-27) {
252         aSolidsToFuse.push_back(aCutAlgo->shape());
253         aMakeShapeList->appendAlgo(aCutAlgo);
254       }
255     }
256   }
257
258   if (!aSolidsToFuse.empty()) {
259     anObjects.clear();
260     anObjects.push_back(aSolidsToFuse.back());
261     aSolidsToFuse.pop_back();
262     aTools = aSolidsToFuse;
263   }
264
265   // Fuse all objects and all tools.
266   GeomShapePtr aShape;
267   if (anObjects.size() == 1 && aTools.empty()) {
268     aShape = anObjects.front();
269   } else if (anObjects.empty() && aTools.size() == 1) {
270     aShape = aTools.front();
271   } else if ((anObjects.size() + aTools.size()) > 1) {
272     std::shared_ptr<GeomAlgoAPI_Boolean> aFuseAlgo(new GeomAlgoAPI_Boolean(anObjects,
273       aTools,
274       GeomAlgoAPI_Tools::BOOL_FUSE,
275       aFuzzy));
276
277     // Checking that the algorithm worked properly.
278     if (GeomAlgoAPI_Tools::AlgoError::isAlgorithmFailed(aFuseAlgo, getKind(), anError)) {
279       setError(anError);
280       return;
281     }
282
283     aShape = aFuseAlgo->shape();
284     aMakeShapeList->appendAlgo(aFuseAlgo);
285   }
286
287   // Combine result with not used solids from compsolid and edges and faces (if we have any).
288   if (aCuttedEdgesAndFaces.get() && !aCuttedEdgesAndFaces->isNull()) {
289     aShapesToAdd.push_back(aCuttedEdgesAndFaces);
290   } else {
291     aShapesToAdd.insert(aShapesToAdd.end(), anEdgesAndFaces.begin(), anEdgesAndFaces.end());
292   }
293   if (!aShapesToAdd.empty()) {
294     if (aShape.get()) {
295       aShapesToAdd.push_back(aShape);
296     }
297     std::shared_ptr<GeomAlgoAPI_PaveFiller> aFillerAlgo(
298       new GeomAlgoAPI_PaveFiller(aShapesToAdd, true, aFuzzy));
299     if (GeomAlgoAPI_Tools::AlgoError::isAlgorithmFailed(aFillerAlgo, getKind(), anError)) {
300       setError(anError);
301       return;
302     }
303
304     aShape = aFillerAlgo->shape();
305     aMakeShapeList->appendAlgo(aFillerAlgo);
306   }
307
308   bool isRemoveEdges = false;
309   AttributeBooleanPtr removeEdgesAttr = boolean(REMOVE_INTERSECTION_EDGES_ID());
310   if (removeEdgesAttr.get()) {
311     isRemoveEdges = removeEdgesAttr->value();
312   }
313
314   if (isRemoveEdges) {
315     std::shared_ptr<GeomAlgoAPI_UnifySameDomain> aUnifyAlgo(
316       new GeomAlgoAPI_UnifySameDomain(aShape));
317
318     if (GeomAlgoAPI_Tools::AlgoError::isAlgorithmFailed(aUnifyAlgo, getKind(), anError)) {
319       setError(anError);
320       return;
321     }
322
323     aShape = aUnifyAlgo->shape();
324     aMakeShapeList->appendAlgo(aUnifyAlgo);
325   }
326
327   if (aFuseVersion == BOP_VERSION_9_4()) {
328     // merge hierarchies of compounds containing objects and tools
329     // and append the result of the FUSE operation
330     aShape = keepUnusedSubsOfCompound(aShape, anObjectsHierarchy, aToolsHierarchy, aMakeShapeList);
331   }
332
333   int aResultIndex = 0;
334
335   ResultBodyPtr aResultBody = document()->createBody(data(), aResultIndex);
336
337   ListOfShape anEmptyTools;
338   ModelAPI_Tools::loadModifiedShapes(aResultBody,
339                                      anOriginalShapes,
340                                      anEmptyTools,
341                                      aMakeShapeList,
342                                      aShape);
343   setResult(aResultBody, aResultIndex);
344   aResultIndex++;
345
346   ModelAPI_Tools::loadDeletedShapes(aResultBody,
347                                     GeomShapePtr(),
348                                     anOriginalShapes,
349                                     aMakeShapeList,
350                                     aShape);
351
352   // remove the rest results if there were produced in the previous pass
353   removeResults(aResultIndex);
354 }