Salome HOME
a8ecc73c1a408fa6d9147f99426bac3c47171953
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ExportFeature.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 <ExchangePlugin_ExportFeature.h>
21
22 #include <algorithm>
23 #include <iterator>
24 #include <string>
25 #ifdef _DEBUG
26 #include <iostream>
27 #include <ostream>
28 #endif
29
30 #include <Config_Common.h>
31 #include <Config_PropManager.h>
32
33 #include <GeomAlgoAPI_BREPExport.h>
34 #include <GeomAlgoAPI_CompoundBuilder.h>
35 #include <GeomAlgoAPI_IGESExport.h>
36 #include <GeomAlgoAPI_STEPExport.h>
37 #include <GeomAlgoAPI_Tools.h>
38 #include <GeomAlgoAPI_XAOExport.h>
39
40 #include <GeomAPI_Shape.h>
41
42 #include <ModelAPI_AttributeSelectionList.h>
43 #include <ModelAPI_AttributeString.h>
44 #include <ModelAPI_AttributeStringArray.h>
45 #include <ModelAPI_AttributeIntArray.h>
46 #include <ModelAPI_AttributeTables.h>
47 #include <ModelAPI_Data.h>
48 #include <ModelAPI_Document.h>
49 #include <ModelAPI_Object.h>
50 #include <ModelAPI_ResultBody.h>
51 #include <ModelAPI_ResultGroup.h>
52 #include <ModelAPI_ResultField.h>
53 #include <ModelAPI_Session.h>
54 #include <ModelAPI_Validator.h>
55 #include <ModelAPI_Tools.h>
56
57 #include <Events_InfoMessage.h>
58
59 #include <XAO_Group.hxx>
60 #include <XAO_Field.hxx>
61 #include <XAO_Xao.hxx>
62 #include <XAO_Geometry.hxx>
63
64 #include <ExchangePlugin_Tools.h>
65
66 ExchangePlugin_ExportFeature::ExchangePlugin_ExportFeature()
67 {
68 }
69
70 ExchangePlugin_ExportFeature::~ExchangePlugin_ExportFeature()
71 {
72   // TODO Auto-generated destructor stub
73 }
74
75 /*
76  * Request for initialization of data model of the feature: adding all attributes
77  */
78 void ExchangePlugin_ExportFeature::initAttributes()
79 {
80   data()->addAttribute(ExchangePlugin_ExportFeature::EXPORT_TYPE_ID(),
81     ModelAPI_AttributeString::typeId());
82   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_PATH_ID(),
83     ModelAPI_AttributeString::typeId());
84   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID(),
85     ModelAPI_AttributeString::typeId());
86   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_FORMAT_ID(),
87     ModelAPI_AttributeString::typeId());
88   data()->addAttribute(ExchangePlugin_ExportFeature::SELECTION_LIST_ID(),
89     ModelAPI_AttributeSelectionList::typeId());
90   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID(),
91     ModelAPI_AttributeString::typeId());
92   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID(),
93     ModelAPI_AttributeString::typeId());
94
95   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
96     ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID());
97   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
98     ExchangePlugin_ExportFeature::XAO_AUTHOR_ID());
99   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
100     ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID());
101 }
102
103 void ExchangePlugin_ExportFeature::attributeChanged(const std::string& theID)
104 {
105   if (theID == XAO_FILE_PATH_ID()) {
106     string(ExchangePlugin_ExportFeature::FILE_PATH_ID())->setValue(
107       string(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID())->value());
108   }
109 }
110
111 /*
112  * Computes or recomputes the results
113  */
114 void ExchangePlugin_ExportFeature::execute()
115 {
116   AttributeStringPtr aFormatAttr =
117       this->string(ExchangePlugin_ExportFeature::FILE_FORMAT_ID());
118   std::string aFormat = aFormatAttr->value();
119
120   AttributeStringPtr aFilePathAttr =
121       this->string(ExchangePlugin_ExportFeature::FILE_PATH_ID());
122   std::string aFilePath = aFilePathAttr->value();
123   if (aFilePath.empty())
124     return;
125
126   exportFile(aFilePath, aFormat);
127 }
128
129 void ExchangePlugin_ExportFeature::exportFile(const std::string& theFileName,
130                                               const std::string& theFormat)
131 {
132   std::string aFormatName = theFormat;
133
134   if (aFormatName.empty()) { // get default format for the extension
135     // ".brep" -> "BREP"
136     std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(theFileName);
137     if (anExtension == "BREP" || anExtension == "BRP") {
138       aFormatName = "BREP";
139     } else if (anExtension == "STEP" || anExtension == "STP") {
140       aFormatName = "STEP";
141     } else if (anExtension == "IGES" || anExtension == "IGS") {
142       aFormatName = "IGES-5.1";
143     } else if (anExtension == "XAO") {
144       aFormatName = "XAO";
145     } else {
146       aFormatName = anExtension;
147     }
148   }
149
150   if (aFormatName == "XAO") {
151     exportXAO(theFileName);
152     return;
153   }
154
155   // make shape for export from selected shapes
156   AttributeSelectionListPtr aSelectionListAttr =
157       this->selectionList(ExchangePlugin_ExportFeature::SELECTION_LIST_ID());
158   std::list<GeomShapePtr> aShapes;
159   for (int i = 0, aSize = aSelectionListAttr->size(); i < aSize; ++i) {
160     AttributeSelectionPtr anAttrSelection = aSelectionListAttr->value(i);
161     std::shared_ptr<GeomAPI_Shape> aCurShape = anAttrSelection->value();
162     if (aCurShape.get() == NULL)
163       aCurShape = anAttrSelection->context()->shape();
164     if (aCurShape.get() != NULL)
165       aShapes.push_back(aCurShape);
166   }
167
168   // Store compound if we have more than one shape.
169   std::shared_ptr<GeomAPI_Shape> aShape;
170   if(aShapes.size() == 1) {
171     aShape = aShapes.front();
172   } else {
173     aShape = GeomAlgoAPI_CompoundBuilder::compound(aShapes);
174   }
175
176   // Perform the export
177   std::string anError;
178   bool aResult = false;
179   if (aFormatName == "BREP") {
180     aResult = BREPExport(theFileName, aFormatName, aShape, anError);
181   } else if (aFormatName == "STEP") {
182     aResult = STEPExport(theFileName, aFormatName, aShape, anError);
183   } else if (aFormatName.substr(0, 4) == "IGES") {
184     aResult = IGESExport(theFileName, aFormatName, aShape, anError);
185   } else {
186     anError = "Unsupported format: " + aFormatName;
187   }
188
189   if (!anError.empty()) {
190     setError("An error occurred while exporting " + theFileName + ": " + anError);
191     return;
192   }
193 }
194
195 /// Returns XAO string by the value from the table
196 static std::string valToString(const ModelAPI_AttributeTables::Value& theVal,
197   const ModelAPI_AttributeTables::ValueType& theType) {
198   std::ostringstream aStr; // the resulting string value
199   switch(theType) {
200   case ModelAPI_AttributeTables::BOOLEAN:
201     aStr<<(theVal.myBool ? "true" : "false");
202     break;
203   case ModelAPI_AttributeTables::INTEGER:
204     aStr<<theVal.myInt;
205     break;
206   case ModelAPI_AttributeTables::DOUBLE:
207     aStr<<theVal.myDouble;
208     break;
209   case ModelAPI_AttributeTables::STRING:
210     aStr<<theVal.myStr;
211     break;
212   }
213   return aStr.str();
214 }
215
216 /// Returns true if something in selection is presented in the results list
217 static bool isInResults(AttributeSelectionListPtr theSelection,
218                         const std::list<ResultBodyPtr>& theResults,
219                         std::set<ResultBodyPtr>& theCashedResults)
220 {
221   // collect all results into a cashed set
222   if (theCashedResults.empty()) {
223     std::list<ResultPtr> aResults;
224     std::list<ResultBodyPtr>::const_iterator aRes = theResults.cbegin();
225     for(; aRes != theResults.cend(); aRes++) {
226       if (theCashedResults.count(*aRes))
227         continue;
228       else
229         theCashedResults.insert(*aRes);
230       std::list<ResultPtr> aResults;
231       ModelAPI_Tools::allSubs(*aRes, aResults, false);
232       for(std::list<ResultPtr>::iterator aR = aResults.begin(); aR != aResults.end(); aR++) {
233         theCashedResults.insert(std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aR));
234       }
235     }
236   }
237   // if context is in results, return true
238   for(int a = 0; a < theSelection->size(); a++) {
239     AttributeSelectionPtr anAttr = theSelection->value(a);
240     ResultBodyPtr aSelected= std::dynamic_pointer_cast<ModelAPI_ResultBody>(anAttr->context());
241     if (aSelected.get() && theCashedResults.count(aSelected))
242       return true;
243   }
244   return false;
245 }
246
247 void ExchangePlugin_ExportFeature::exportXAO(const std::string& theFileName)
248 {
249   try {
250
251   std::string anError;
252   XAO::Xao aXao;
253
254   // author
255
256   std::string anAuthor = string(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID())->value();
257   aXao.setAuthor(anAuthor);
258
259   // make shape for export from all results
260   std::list<GeomShapePtr> aShapes;
261   std::list<ResultBodyPtr> aResults;
262
263   AttributeSelectionListPtr aSelection = selectionList(SELECTION_LIST_ID());
264   bool aIsSelection = aSelection->isInitialized() && aSelection->size() > 0;
265   if (aIsSelection) { // a mode for export to geom result by result
266     for(int a = 0; a < aSelection->size(); a++) {
267       AttributeSelectionPtr anAttr = aSelection->value(a);
268       ResultBodyPtr aBodyContext = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anAttr->context());
269       if (aBodyContext.get() && !aBodyContext->isDisabled() && aBodyContext->shape().get()) {
270         aResults.push_back(aBodyContext);
271         GeomShapePtr aShape = anAttr->value();
272         if (!aShape.get())
273           aShape = aBodyContext->shape();
274         aShapes.push_back(aShape);
275       }
276     }
277   } else {
278     int aBodyCount = document()->size(ModelAPI_ResultBody::group());
279     for (int aBodyIndex = 0; aBodyIndex < aBodyCount; ++aBodyIndex) {
280       ResultBodyPtr aResultBody =
281           std::dynamic_pointer_cast<ModelAPI_ResultBody>(
282               document()->object(ModelAPI_ResultBody::group(), aBodyIndex));
283       if (!aResultBody.get())
284         continue;
285       aShapes.push_back(aResultBody->shape());
286       aResults.push_back(aResultBody);
287     }
288   }
289   if (aShapes.empty()) {
290     setError("No shapes to export");
291     return;
292   }
293
294
295   GeomShapePtr aShape = (aShapes.size() == 1)
296       ? *aShapes.begin()
297       : GeomAlgoAPI_CompoundBuilder::compound(aShapes);
298
299   SetShapeToXAO(aShape, &aXao, anError);
300
301   if (!anError.empty()) {
302     setError("An error occurred while exporting " + theFileName + ": " + anError);
303     return;
304   }
305
306   // geometry name
307   std::string aGeometryName = string(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID())->value();
308   if (aGeometryName.empty() && aResults.size() == 1) {
309     // get the name from the first result
310     ResultBodyPtr aResultBody = *aResults.begin();
311     aGeometryName = aResultBody->data()->name();
312   }
313
314   aXao.getGeometry()->setName(aGeometryName);
315
316   std::set<ResultBodyPtr> allResultsCashed; // cash to speed up searching in all results selected
317
318   // groups
319   int aGroupCount = document()->size(ModelAPI_ResultGroup::group());
320   for (int aGroupIndex = 0; aGroupIndex < aGroupCount; ++aGroupIndex) {
321     ResultGroupPtr aResultGroup =
322         std::dynamic_pointer_cast<ModelAPI_ResultGroup>(
323             document()->object(ModelAPI_ResultGroup::group(), aGroupIndex));
324
325     FeaturePtr aGroupFeature = document()->feature(aResultGroup);
326
327     AttributeSelectionListPtr aSelectionList =
328         aGroupFeature->selectionList("group_list");
329
330     if (!isInResults(aSelectionList, aResults, allResultsCashed))// skip group not used in results
331       continue;
332
333     // conversion of dimension
334     std::string aSelectionType = aSelectionList->selectionType();
335     std::string aDimensionString =
336       ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
337     XAO::Dimension aGroupDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
338
339     XAO::Group* aXaoGroup = aXao.addGroup(aGroupDimension,
340                                           aResultGroup->data()->name());
341
342     try {
343       for (int aSelectionIndex = 0; aSelectionIndex < aSelectionList->size(); ++aSelectionIndex) {
344         AttributeSelectionPtr aSelection = aSelectionList->value(aSelectionIndex);
345
346         // complex conversion of reference id to element index
347         // gives bad id in case the selection is done from python script
348         // => using GeomAlgoAPI_CompoundBuilder::id instead
349         // int aReferenceID_old = aSelection->Id();
350
351         int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aSelection->value());
352
353         if (aReferenceID == 0) // selected value does not found in the exported shape
354           continue;
355
356         std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
357         int anElementID =
358           aXao.getGeometry()->getElementIndexByReference(aGroupDimension, aReferenceString);
359
360         aXaoGroup->add(anElementID);
361       }
362     } catch (XAO::XAO_Exception& e) {
363       std::string msg = "An error occurred while exporting group " + aResultGroup->data()->name();
364       msg += ".\n";
365       msg += e.what();
366       msg += "\n";
367       msg += "=> skipping this group from XAO export.";
368       Events_InfoMessage("ExportFeature", msg, this).send();
369       aXao.removeGroup(aXaoGroup);
370     }
371   }
372
373   // fields
374   int aFieldCount = document()->size(ModelAPI_ResultField::group());
375   for (int aFieldIndex = 0; aFieldIndex < aFieldCount; ++aFieldIndex) {
376     ResultFieldPtr aResultField =
377         std::dynamic_pointer_cast<ModelAPI_ResultField>(
378             document()->object(ModelAPI_ResultField::group(), aFieldIndex));
379
380     FeaturePtr aFieldFeature = document()->feature(aResultField);
381
382     AttributeSelectionListPtr aSelectionList =
383         aFieldFeature->selectionList("selected");
384     std::string aSelectionType = aSelectionList->selectionType();
385     bool isWholePart = aSelectionType == "part";
386
387     if (!isWholePart &&
388         !isInResults(aSelectionList, aResults, allResultsCashed))// skip field not used in results
389       continue;
390
391     // conversion of dimension
392     std::string aDimensionString =
393       ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
394     XAO::Dimension aFieldDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
395     // get tables and their type
396     std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
397     std::string aTypeString = ExchangePlugin_Tools::valuesType2xaoType(aTables->type());
398     XAO::Type aFieldType = XAO::XaoUtils::stringToFieldType(aTypeString);
399
400     XAO::Field* aXaoField = aXao.addField(aFieldType, aFieldDimension, aTables->columns(),
401                                           aResultField->data()->name());
402
403
404     try {
405       // set components names
406       AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
407       for(int aComp = 0; aComp < aComponents->size(); aComp++) {
408         std::string aName = aComponents->value(aComp);
409         aXaoField->setComponentName(aComp, aName);
410       }
411
412       AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
413       for (int aStepIndex = 0; aStepIndex < aTables->tables(); aStepIndex++) {
414         XAO::Step* aStep = aXaoField->addNewStep(aStepIndex);
415         aStep->setStep(aStepIndex);
416         int aStampIndex = aStamps->value(aStepIndex);
417         aStep->setStamp(aStampIndex);
418         int aNumElements = isWholePart ? aXaoField->countElements() : aTables->rows();
419         int aNumComps = aTables->columns();
420         std::set<int> aFilledIDs; // to fill the rest by defaults
421         // omit default values first row
422         for(int aRow = isWholePart ? 0 : 1; aRow < aNumElements; aRow++) {
423           for(int aCol = 0; aCol < aNumComps; aCol++) {
424             int anElementID = 0;
425             if (!isWholePart) {
426               // element index actually is the ID of the selection
427               AttributeSelectionPtr aSelection = aSelectionList->value(aRow - 1);
428               int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aSelection->value());
429               if (aReferenceID == 0) // selected value does not found in the exported shape
430                 continue;
431
432               std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
433               anElementID =
434                 aXao.getGeometry()->getElementIndexByReference(aFieldDimension, aReferenceString);
435             }
436
437             ModelAPI_AttributeTables::Value aVal = aTables->value(
438               isWholePart ? 0 : aRow, aCol, aStepIndex);
439             std::string aStrVal = valToString(aVal, aTables->type());
440             aStep->setStringValue(isWholePart ? aRow : anElementID, aCol, aStrVal);
441             aFilledIDs.insert(anElementID);
442           }
443         }
444         if (!isWholePart) { // fill the rest values by default ones
445           XAO::GeometricElementList::iterator allElem = aXao.getGeometry()->begin(aFieldDimension);
446           for(; allElem != aXao.getGeometry()->end(aFieldDimension); allElem++) {
447             if (aFilledIDs.find(allElem->first) != aFilledIDs.end())
448               continue;
449             for(int aCol = 0; aCol < aNumComps; aCol++) {
450               ModelAPI_AttributeTables::Value aVal = aTables->value(0, aCol, aStepIndex); // default
451               std::string aStrVal = valToString(aVal, aTables->type());
452               aStep->setStringValue(allElem->first, aCol, aStrVal);
453             }
454           }
455         }
456       }
457     } catch (XAO::XAO_Exception& e) {
458       std::string msg = "An error occurred while exporting field " + aResultField->data()->name();
459       msg += ".\n";
460       msg += e.what();
461       msg += "\n";
462       msg += "=> skipping this field from XAO export.";
463       Events_InfoMessage("ExportFeature", msg, this).send();
464       aXao.removeField(aXaoField);
465     }
466   }
467
468   // exporting
469   XAOExport(theFileName, &aXao, anError);
470
471   if (!anError.empty()) {
472     setError("An error occurred while exporting " + theFileName + ": " + anError);
473     return;
474   }
475
476 // LCOV_EXCL_START
477   } catch (XAO::XAO_Exception& e) {
478     std::string anError = e.what();
479     setError("An error occurred while exporting " + theFileName + ": " + anError);
480     return;
481   }
482 // LCOV_EXCL_STOP
483 }