Salome HOME
Bug #1038: Wrong result given by "revolution-fuse"
[modules/shaper.git] / src / FeaturesPlugin / FeaturesPlugin_CompositeBoolean.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        FeaturesPlugin_CompositeBoolean.cpp
4 // Created:     11 June 2015
5 // Author:      Dmitry Bobylev
6
7 #include <FeaturesPlugin_CompositeBoolean.h>
8
9 #include <ModelAPI_AttributeSelectionList.h>
10 #include <ModelAPI_AttributeReference.h>
11 #include <ModelAPI_BodyBuilder.h>
12 #include <ModelAPI_ResultBody.h>
13 #include <ModelAPI_ResultConstruction.h>
14 #include <ModelAPI_Session.h>
15 #include <ModelAPI_Tools.h>
16 #include <ModelAPI_Validator.h>
17
18 #include <GeomAlgoAPI_CompoundBuilder.h>
19 #include <GeomAlgoAPI_MakeShapeList.h>
20 #include <GeomAlgoAPI_PaveFiller.h>
21 #include <GeomAlgoAPI_Prism.h>
22 #include <GeomAlgoAPI_Revolution.h>
23 #include <GeomAlgoAPI_ShapeTools.h>
24 #include <GeomAPI_ShapeExplorer.h>
25
26 //=================================================================================================
27 void FeaturesPlugin_CompositeBoolean::initAttributes()
28 {
29   data()->addAttribute(SKETCH_OBJECT_ID(), ModelAPI_AttributeReference::typeId());
30
31   // Boolean works with solids always.
32   data()->addAttribute(BOOLEAN_OBJECTS_ID(), ModelAPI_AttributeSelectionList::typeId());
33   AttributeSelectionListPtr aSelection = data()->selectionList(BOOLEAN_OBJECTS_ID());
34   aSelection->setSelectionType("SOLID");
35
36   initMakeSolidsAttributes();
37
38   data()->addAttribute(SKETCH_SELECTION_ID(), ModelAPI_AttributeSelection::typeId());
39   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), SKETCH_SELECTION_ID());
40 }
41
42 //=================================================================================================
43 std::shared_ptr<ModelAPI_Feature> FeaturesPlugin_CompositeBoolean::addFeature(std::string theID)
44 {
45   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
46   if (aNew) {
47     data()->reference(SKETCH_OBJECT_ID())->setValue(aNew);
48   }
49   // set as current also after it becomes sub to set correctly enabled for other sketch subs
50   document()->setCurrentFeature(aNew, false);
51   return aNew;
52 }
53
54 //=================================================================================================
55 int FeaturesPlugin_CompositeBoolean::numberOfSubs(bool forTree) const
56 {
57   ObjectPtr aObj = data()->reference(SKETCH_OBJECT_ID())->value();
58   return aObj.get()? 1 : 0;
59 }
60
61 //=================================================================================================
62 std::shared_ptr<ModelAPI_Feature> FeaturesPlugin_CompositeBoolean::subFeature(const int theIndex, bool forTree)
63 {
64   if (theIndex == 0)
65     return std::dynamic_pointer_cast<ModelAPI_Feature>(data()->reference(SKETCH_OBJECT_ID())->value());
66   return std::shared_ptr<ModelAPI_Feature>();
67 }
68
69 //=================================================================================================
70 int FeaturesPlugin_CompositeBoolean::subFeatureId(const int theIndex) const
71 {
72   if (theIndex == 0) {
73     FeaturePtr aFeature = 
74       std::dynamic_pointer_cast<ModelAPI_Feature>(data()->reference(SKETCH_OBJECT_ID())->value());
75     if (aFeature.get())
76       return aFeature->data()->featureId();
77   }
78   return -1;
79 }
80
81 //=================================================================================================
82 bool FeaturesPlugin_CompositeBoolean::isSub(ObjectPtr theObject) const
83 {
84   // check is this feature of result
85   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
86   if (!aFeature)
87     return false;
88  
89   ObjectPtr aSub = data()->reference(SKETCH_OBJECT_ID())->value();
90   return aSub == theObject;
91 }
92
93 //=================================================================================================
94 void FeaturesPlugin_CompositeBoolean::removeFeature(std::shared_ptr<ModelAPI_Feature> theFeature)
95 {
96 }
97
98 //=================================================================================================
99 void FeaturesPlugin_CompositeBoolean::erase()
100 {
101   if (data().get() && data()->isValid()) { // on abort of sketch of this composite it may be invalid
102     FeaturePtr aSketch =
103       std::dynamic_pointer_cast<ModelAPI_Feature>(data()->reference(SKETCH_OBJECT_ID())->value());
104     if (aSketch.get() && aSketch->data()->isValid()) {
105       document()->removeFeature(aSketch);
106     }
107   }
108   ModelAPI_CompositeFeature::erase();
109 }
110
111
112 //=================================================================================================
113 void FeaturesPlugin_CompositeBoolean::execute()
114 {
115   // Getting faces to create solids.
116   std::shared_ptr<ModelAPI_Feature> aSketchFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
117                                                      reference(SKETCH_OBJECT_ID())->value());
118   if(!aSketchFeature || aSketchFeature->results().empty()) {
119     return;
120   }
121   ResultPtr aSketchRes = aSketchFeature->results().front();
122   ResultConstructionPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aSketchRes);
123   if(!aConstruction.get()) {
124     return;
125   }
126   selection(SKETCH_SELECTION_ID())->setValue(aSketchRes, std::shared_ptr<GeomAPI_Shape>());
127   int aSketchFacesNum = aConstruction->facesNum();
128   if(aSketchFacesNum == 0) {
129     return;
130   }
131   ListOfShape aFacesList;
132   for(int aFaceIndex = 0; aFaceIndex < aSketchFacesNum; aFaceIndex++) {
133     std::shared_ptr<GeomAPI_Shape> aFace = std::dynamic_pointer_cast<GeomAPI_Shape>(aConstruction->face(aFaceIndex));
134     aFacesList.push_back(aFace);
135   }
136
137   // Searching faces with common edges.
138   ListOfShape aShells;
139   ListOfShape aFreeFaces;
140   std::shared_ptr<GeomAPI_Shape> aFacesCompound = GeomAlgoAPI_CompoundBuilder::compound(aFacesList);
141   GeomAlgoAPI_ShapeTools::combineShapes(aFacesCompound, GeomAPI_Shape::SHELL, aShells, aFreeFaces);
142   aShells.insert(aShells.end(), aFreeFaces.begin(), aFreeFaces.end());
143
144   // Pass shells/faces to solids creation function.
145   ListOfShape aTools;
146   std::list<std::shared_ptr<GeomAPI_Interface>> aSolidsAlgos;
147   makeSolids(aShells, aTools, aSolidsAlgos);
148   if(aTools.empty()) {
149     return;
150   }
151
152   // Getting objects for boolean operation.
153   ListOfShape anObjects;
154   std::map<std::shared_ptr<GeomAPI_Shape>, ListOfShape> aCompSolidsObjects;
155   AttributeSelectionListPtr anObjectsSelList = selectionList(BOOLEAN_OBJECTS_ID());
156   if(anObjectsSelList->size() == 0) {
157     return;
158   }
159   for(int anObjectsIndex = 0; anObjectsIndex < anObjectsSelList->size(); anObjectsIndex++) {
160     AttributeSelectionPtr anObjectAttr = anObjectsSelList->value(anObjectsIndex);
161     std::shared_ptr<GeomAPI_Shape> anObject = anObjectAttr->value();
162     if(!anObject.get()) {
163       return;
164     }
165     ResultPtr aContext = anObjectAttr->context();
166     ResultCompSolidPtr aResCompSolidPtr = ModelAPI_Tools::compSolidOwner(aContext);
167     if(aResCompSolidPtr.get()) {
168       std::shared_ptr<GeomAPI_Shape> aContextShape = aResCompSolidPtr->shape();
169       std::map<std::shared_ptr<GeomAPI_Shape>, ListOfShape>::iterator anIt = aCompSolidsObjects.begin();
170       for(; anIt != aCompSolidsObjects.end(); anIt++) {
171         if(anIt->first->isEqual(aContextShape)) {
172           aCompSolidsObjects[anIt->first].push_back(anObject);
173           break;
174         }
175       }
176       if(anIt == aCompSolidsObjects.end()) {
177         aCompSolidsObjects[aContextShape].push_back(anObject);
178       }
179     } else {
180       anObjects.push_back(anObject);
181     }
182   }
183
184   // Cut from each object solids.
185   int aResultIndex = 0;
186
187   switch(myBooleanOperationType) {
188     case GeomAlgoAPI_Boolean::BOOL_CUT:
189     case GeomAlgoAPI_Boolean::BOOL_COMMON:{
190       // Cut each object with all tools
191       for(ListOfShape::iterator anObjectsIt = anObjects.begin(); anObjectsIt != anObjects.end(); anObjectsIt++) {
192         std::shared_ptr<GeomAPI_Shape> anObject = *anObjectsIt;
193         ListOfShape aListWithObject;
194         aListWithObject.push_back(anObject);
195         GeomAlgoAPI_Boolean aBoolAlgo(aListWithObject, aTools, myBooleanOperationType);
196
197         // Checking that the algorithm worked properly.
198         if(!aBoolAlgo.isDone() || aBoolAlgo.shape()->isNull() || !aBoolAlgo.isValid()) {
199           setError("Boolean algorithm failed");
200           return;
201         }
202
203         if(GeomAlgoAPI_ShapeTools::volume(aBoolAlgo.shape()) > 1.e-7) {
204           std::shared_ptr<ModelAPI_ResultBody> aResultBody = document()->createBody(data(), aResultIndex);
205           loadNamingDS(aResultBody, aShells, aSolidsAlgos, anObject, aTools, aBoolAlgo.shape(),
206                        *aBoolAlgo.makeShape(), *aBoolAlgo.mapOfShapes());
207           setResult(aResultBody, aResultIndex);
208           aResultIndex++;
209         }
210       }
211
212       // Compsolids handling
213       for(std::map<std::shared_ptr<GeomAPI_Shape>, ListOfShape>::iterator anIt = aCompSolidsObjects.begin();
214         anIt != aCompSolidsObjects.end(); anIt++) {
215         std::shared_ptr<GeomAPI_Shape> aCompSolid = anIt->first;
216         ListOfShape& aUsedInOperationSolids = anIt->second;
217
218         // Collecting solids from compsolids which will not be modified in boolean operation.
219         ListOfShape aNotUsedSolids;
220         for(GeomAPI_ShapeExplorer anExp(aCompSolid, GeomAPI_Shape::SOLID); anExp.more(); anExp.next()) {
221           std::shared_ptr<GeomAPI_Shape> aSolidInCompSolid = anExp.current();
222           ListOfShape::iterator anIt = aUsedInOperationSolids.begin();
223           for(; anIt != aUsedInOperationSolids.end(); anIt++) {
224             if(aSolidInCompSolid->isEqual(*anIt)) {
225               break;
226             }
227           }
228           if(anIt == aUsedInOperationSolids.end()) {
229             aNotUsedSolids.push_back(aSolidInCompSolid);
230           }
231         }
232
233         GeomAlgoAPI_Boolean aBoolAlgo(aUsedInOperationSolids, aTools, myBooleanOperationType);
234
235         // Checking that the algorithm worked properly.
236         if(!aBoolAlgo.isDone() || aBoolAlgo.shape()->isNull() || !aBoolAlgo.isValid()) {
237           setError("Boolean algorithm failed");
238           return;
239         }
240
241         GeomAlgoAPI_MakeShapeList aMakeShapeList;
242         aMakeShapeList.append(aBoolAlgo.makeShape());
243         GeomAPI_DataMapOfShapeShape aMapOfShapes;
244         aMapOfShapes.merge(aBoolAlgo.mapOfShapes());
245
246         // Add result to not used solids from compsolid.
247         ListOfShape aShapesToAdd = aNotUsedSolids;
248         aShapesToAdd.push_back(aBoolAlgo.shape());
249         GeomAlgoAPI_PaveFiller aFillerAlgo(aShapesToAdd, true);
250         if(!aFillerAlgo.isDone()) {
251           std::string aFeatureError = "PaveFiller algorithm failed";
252           setError(aFeatureError);
253           return;
254         }
255
256         aMakeShapeList.append(aFillerAlgo.makeShape());
257         aMapOfShapes.merge(aFillerAlgo.mapOfShapes());
258
259         if(GeomAlgoAPI_ShapeTools::volume(aFillerAlgo.shape()) > 1.e-7) {
260           std::shared_ptr<ModelAPI_ResultBody> aResultBody = document()->createBody(data(), aResultIndex);
261           loadNamingDS(aResultBody, aShells, aSolidsAlgos, aCompSolid, aTools, aFillerAlgo.shape(), aMakeShapeList, aMapOfShapes);
262           setResult(aResultBody, aResultIndex);
263           aResultIndex++;
264         }
265       }
266       break;
267     }
268     case GeomAlgoAPI_Boolean::BOOL_FUSE: {
269       // Collecting all solids which will be fused.
270       ListOfShape aSolidsToFuse;
271       aSolidsToFuse.insert(aSolidsToFuse.end(), anObjects.begin(), anObjects.end());
272       aSolidsToFuse.insert(aSolidsToFuse.end(), aTools.begin(), aTools.end());
273
274       // Collecting solids from compsolids which will not be modified in boolean operation.
275       ListOfShape aNotUsedSolids;
276       for(std::map<std::shared_ptr<GeomAPI_Shape>, ListOfShape>::iterator anIt = aCompSolidsObjects.begin();
277         anIt != aCompSolidsObjects.end(); anIt++) {
278         std::shared_ptr<GeomAPI_Shape> aCompSolid = anIt->first;
279         ListOfShape& aUsedInOperationSolids = anIt->second;
280         aSolidsToFuse.insert(aSolidsToFuse.end(), aUsedInOperationSolids.begin(), aUsedInOperationSolids.end());
281
282         // Collect solids from compsolid which will not be modified in boolean operation.
283         for(GeomAPI_ShapeExplorer anExp(aCompSolid, GeomAPI_Shape::SOLID); anExp.more(); anExp.next()) {
284           std::shared_ptr<GeomAPI_Shape> aSolidInCompSolid = anExp.current();
285           ListOfShape::iterator anIt = aUsedInOperationSolids.begin();
286           for(; anIt != aUsedInOperationSolids.end(); anIt++) {
287             if(aSolidInCompSolid->isEqual(*anIt)) {
288               break;
289             }
290           }
291           if(anIt == aUsedInOperationSolids.end()) {
292             aNotUsedSolids.push_back(aSolidInCompSolid);
293           }
294         }
295       }
296
297       ListOfShape anOriginalSolids = aSolidsToFuse;
298       anOriginalSolids.insert(anOriginalSolids.end(), aNotUsedSolids.begin(), aNotUsedSolids.end());
299       GeomAlgoAPI_MakeShapeList aMakeShapeList;
300       GeomAPI_DataMapOfShapeShape aMapOfShapes;
301
302       // If we have compsolids then cut with not used solids all others.
303       if(!aNotUsedSolids.empty()) {
304         aSolidsToFuse.clear();
305         for(ListOfShape::iterator anIt = anOriginalSolids.begin(); anIt != anOriginalSolids.end(); anIt++) {
306           ListOfShape aOneObjectList;
307           aOneObjectList.push_back(*anIt);
308           GeomAlgoAPI_Boolean aCutAlgo(aOneObjectList, aNotUsedSolids, GeomAlgoAPI_Boolean::BOOL_CUT);
309
310           if(GeomAlgoAPI_ShapeTools::volume(aCutAlgo.shape()) > 1.e-7) {
311             aSolidsToFuse.push_back(aCutAlgo.shape());
312             aMakeShapeList.append(aCutAlgo.makeShape());
313             aMapOfShapes.merge(aCutAlgo.mapOfShapes());
314           }
315         }
316       }
317
318       anObjects.clear();
319       anObjects.push_back(aSolidsToFuse.back());
320       aSolidsToFuse.pop_back();
321       aTools = aSolidsToFuse;
322
323       // Fuse all objects and all tools.
324       GeomAlgoAPI_Boolean aFuseAlgo(anObjects, aTools, myBooleanOperationType);
325
326       // Checking that the algorithm worked properly.
327       if(!aFuseAlgo.isDone() || aFuseAlgo.shape()->isNull() || !aFuseAlgo.isValid()) {
328         static const std::string aFeatureError = "Boolean algorithm failed";
329         setError(aFeatureError);
330         return;
331       }
332
333       std::shared_ptr<GeomAPI_Shape> aShape = aFuseAlgo.shape();
334       aMakeShapeList.append(aFuseAlgo.makeShape());
335       aMapOfShapes.merge(aFuseAlgo.mapOfShapes());
336
337       // Add result to not used solids from compsolid (if we have any).
338       if(!aNotUsedSolids.empty()) {
339         aNotUsedSolids.push_back(aShape);
340         GeomAlgoAPI_PaveFiller aFillerAlgo(aNotUsedSolids, true);
341         if(!aFillerAlgo.isDone()) {
342           std::string aFeatureError = "PaveFiller algorithm failed";
343           setError(aFeatureError);
344           return;
345         }
346         if(aFillerAlgo.shape()->isNull()) {
347           static const std::string aShapeError = "Resulting shape is Null";
348           setError(aShapeError);
349           return;
350         }
351         if(!aFillerAlgo.isValid()) {
352           std::string aFeatureError = "Warning: resulting shape is not valid";
353           setError(aFeatureError);
354           return;
355         }
356
357         aShape = aFillerAlgo.shape();
358         aMakeShapeList.append(aFillerAlgo.makeShape());
359         aMapOfShapes.merge(aFillerAlgo.mapOfShapes());
360       }
361
362       std::shared_ptr<ModelAPI_ResultBody> aResultBody = document()->createBody(data(), aResultIndex);
363       loadNamingDS(aResultBody, aShells, aSolidsAlgos, anOriginalSolids.front(), anOriginalSolids, aShape, aMakeShapeList, aMapOfShapes);
364       setResult(aResultBody, aResultIndex);
365       aResultIndex++;
366       break;
367     }
368     default: {
369       setError("Error: wrong type of boolean operation");
370       return;
371     }
372   }
373
374   // Remove the rest results if there were produced in the previous pass.
375   removeResults(aResultIndex);
376 }
377
378 //=================================================================================================
379 void FeaturesPlugin_CompositeBoolean::loadNamingDS(std::shared_ptr<ModelAPI_ResultBody> theResultBody,
380                                                    const ListOfShape& theShells,
381                                                    const std::list<std::shared_ptr<GeomAPI_Interface>>& theSolidsAlgos,
382                                                    const std::shared_ptr<GeomAPI_Shape> theBaseShape,
383                                                    const ListOfShape& theTools,
384                                                    const std::shared_ptr<GeomAPI_Shape> theResultShape,
385                                                    GeomAlgoAPI_MakeShape& theMakeShape,
386                                                    GeomAPI_DataMapOfShapeShape& theMapOfShapes)
387 {
388   //load result
389   if(theBaseShape->isEqual(theResultShape)) {
390     theResultBody->store(theResultShape);
391   } else {
392     const int aGenTag = 1;
393     const int aModTag = 2;
394     const int aDelTag = 3;
395     const int aSubsolidsTag=4; /// sub solids will be placed at labels 6, 7, etc. if result is compound of solids
396     int aToTag = 5; // may be many labels, starting from this index
397     int aFromTag = 10000; // may be many labels, starting from this index or last aToTag index
398     const std::string aGenName = "Generated";
399     const std::string aModName = "Modified";
400     const std::string aLatName = "LateralFace";
401     const std::string aFromName = "FromFace";
402     const std::string aToName = "ToFace";
403
404     theResultBody->storeModified(theBaseShape, theResultShape, aSubsolidsTag);
405
406     ListOfShape::const_iterator aShellsIter = theShells.begin();
407     std::list<std::shared_ptr<GeomAPI_Interface>>::const_iterator aSolidsAlgosIter = theSolidsAlgos.begin();
408     for(; aShellsIter != theShells.end() && aSolidsAlgosIter != theSolidsAlgos.end(); aShellsIter++, aSolidsAlgosIter++) {
409       ListOfShape aFromFaces;
410       ListOfShape aToFaces;
411       std::shared_ptr<GeomAPI_DataMapOfShapeShape> aSubShapes;
412
413       //Insert lateral face : Face from Edge
414       if(std::dynamic_pointer_cast<GeomAlgoAPI_Prism>(*aSolidsAlgosIter)) {
415         std::shared_ptr<GeomAlgoAPI_Prism> aPrismAlgo = std::dynamic_pointer_cast<GeomAlgoAPI_Prism>(*aSolidsAlgosIter);
416         aSubShapes = aPrismAlgo->mapOfShapes();
417         theResultBody->loadAndOrientGeneratedShapes(aPrismAlgo->makeShape().get(), *aShellsIter, GeomAPI_Shape::EDGE, aGenTag,
418                                                     aLatName, *aSubShapes.get());
419
420         aFromFaces = aPrismAlgo->fromFaces();
421         aToFaces = aPrismAlgo->toFaces();
422       } else if(std::dynamic_pointer_cast<GeomAlgoAPI_Revolution>(*aSolidsAlgosIter)) {
423         std::shared_ptr<GeomAlgoAPI_Revolution> aRevolAlgo = std::dynamic_pointer_cast<GeomAlgoAPI_Revolution>(*aSolidsAlgosIter);
424         aSubShapes = aRevolAlgo->mapOfShapes();
425         theResultBody->loadAndOrientGeneratedShapes(aRevolAlgo->makeShape().get(), *aShellsIter, GeomAPI_Shape::EDGE, aGenTag,
426                                                     aLatName, *aSubShapes.get());
427         aFromFaces = aRevolAlgo->fromFaces();
428         aToFaces = aRevolAlgo->toFaces();
429       }
430
431       //Insert to faces
432       for(ListOfShape::const_iterator anIt = aToFaces.cbegin(); anIt != aToFaces.cend(); anIt++) {
433         std::shared_ptr<GeomAPI_Shape> aToFace = *anIt;
434         if(aSubShapes->isBound(aToFace)) {
435           aToFace = aSubShapes->find(aToFace);
436         }
437         theResultBody->generated(aToFace, aToName, aToTag++);
438       }
439
440       //Insert from faces
441       if (aFromTag < aToTag) aFromTag = aToTag;
442       for(ListOfShape::const_iterator anIt = aFromFaces.cbegin(); anIt != aFromFaces.cend(); anIt++) {
443         std::shared_ptr<GeomAPI_Shape> aFromFace = *anIt;
444         if(aSubShapes->isBound(aFromFace)) {
445           aFromFace = aSubShapes->find(aFromFace);
446         }
447         theResultBody->generated(aFromFace, aFromName, aFromTag++);
448       }
449     }
450
451     theResultBody->loadAndOrientModifiedShapes(&theMakeShape, theBaseShape, GeomAPI_Shape::FACE,
452                                                aModTag, aModName, theMapOfShapes);
453     theResultBody->loadDeletedShapes(&theMakeShape, theBaseShape, GeomAPI_Shape::FACE, aDelTag);
454
455     for(ListOfShape::const_iterator anIter = theTools.begin(); anIter != theTools.end(); anIter++) {
456       theResultBody->loadAndOrientModifiedShapes(&theMakeShape, *anIter, GeomAPI_Shape::FACE,
457                                                  aModTag, aModName, theMapOfShapes);
458       theResultBody->loadDeletedShapes(&theMakeShape, *anIter, GeomAPI_Shape::FACE, aDelTag);
459     }
460   }
461 }