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