Salome HOME
Update copyrights
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ImportFeature.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_ImportFeature.h>
21
22 #include <algorithm>
23 #include <string>
24
25 #include <Config_Common.h>
26 #include <Config_PropManager.h>
27
28 #include <GeomAlgoAPI_BREPImport.h>
29 #include <GeomAlgoAPI_IGESImport.h>
30 #include <GeomAlgoAPI_STEPImport.h>
31 #include <GeomAlgoAPI_Tools.h>
32 #include <GeomAlgoAPI_XAOImport.h>
33
34 #include <GeomAPI_Shape.h>
35 #include <GeomAPI_ShapeExplorer.h>
36
37 #include <ModelAPI_AttributeRefList.h>
38 #include <ModelAPI_AttributeSelectionList.h>
39 #include <ModelAPI_AttributeString.h>
40 #include <ModelAPI_AttributeStringArray.h>
41 #include <ModelAPI_AttributeIntArray.h>
42 #include <ModelAPI_AttributeTables.h>
43 #include <ModelAPI_BodyBuilder.h>
44 #include <ModelAPI_Data.h>
45 #include <ModelAPI_Document.h>
46 #include <ModelAPI_Events.h>
47 #include <ModelAPI_Object.h>
48 #include <ModelAPI_ResultBody.h>
49 #include <ModelAPI_ResultGroup.h>
50 #include <ModelAPI_Session.h>
51 #include <ModelAPI_Validator.h>
52
53 #include <XAO_Xao.hxx>
54 #include <XAO_Group.hxx>
55 #include <XAO_Field.hxx>
56 #include <XAO_Step.hxx>
57
58 #include <ExchangePlugin_Tools.h>
59
60 ExchangePlugin_ImportFeature::ExchangePlugin_ImportFeature()
61 {
62 }
63
64 ExchangePlugin_ImportFeature::~ExchangePlugin_ImportFeature()
65 {
66   // TODO Auto-generated destructor stub
67 }
68
69 /*
70  * Request for initialization of data model of the feature: adding all attributes
71  */
72 void ExchangePlugin_ImportFeature::initAttributes()
73 {
74   data()->addAttribute(ExchangePlugin_ImportFeature::FILE_PATH_ID(),
75                        ModelAPI_AttributeString::typeId());
76   AttributePtr aFeaturesAttribute =
77     data()->addAttribute(ExchangePlugin_ImportFeature::FEATURES_ID(),
78                          ModelAPI_AttributeRefList::typeId());
79   aFeaturesAttribute->setIsArgument(false);
80
81   ModelAPI_Session::get()->validators()->registerNotObligatory(
82       getKind(), ExchangePlugin_ImportFeature::FEATURES_ID());
83 }
84
85 /*
86  * Computes or recomputes the results
87  */
88 void ExchangePlugin_ImportFeature::execute()
89 {
90   AttributeStringPtr aFilePathAttr = string(ExchangePlugin_ImportFeature::FILE_PATH_ID());
91   std::string aFilePath = aFilePathAttr->value();
92   if (aFilePath.empty()) {
93     setError("File path is empty.");
94     return;
95   }
96
97   importFile(aFilePath);
98 }
99
100 std::shared_ptr<ModelAPI_ResultBody> ExchangePlugin_ImportFeature::createResultBody(
101     std::shared_ptr<GeomAPI_Shape> aGeomShape)
102 {
103   std::shared_ptr<ModelAPI_ResultBody> aResultBody = document()->createBody(data());
104   //LoadNamingDS of the imported shape
105   loadNamingDS(aGeomShape, aResultBody);
106   return aResultBody;
107 }
108
109 void ExchangePlugin_ImportFeature::importFile(const std::string& theFileName)
110 {
111   // "*.brep" -> "BREP"
112   std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(theFileName);
113
114   if (anExtension == "XAO") {
115     importXAO(theFileName);
116     return;
117   }
118
119   // Perform the import
120   std::string anError;
121   std::shared_ptr<GeomAPI_Shape> aGeomShape;
122   if (anExtension == "BREP" || anExtension == "BRP") {
123     aGeomShape = BREPImport(theFileName, anExtension, anError);
124   } else if (anExtension == "STEP" || anExtension == "STP") {
125     aGeomShape = STEPImport(theFileName, anExtension, anError);
126   } else if (anExtension == "IGES" || anExtension == "IGS") {
127     aGeomShape = IGESImport(theFileName, anExtension, anError);
128   } else {
129     anError = "Unsupported format: " + anExtension;
130   }
131
132   // Check if shape is valid
133   if (!anError.empty()) {
134     setError("An error occurred while importing " + theFileName + ": " + anError);
135     return;
136   }
137
138   // Pass the results into the model
139   std::string anObjectName = GeomAlgoAPI_Tools::File_Tools::name(theFileName);
140   data()->setName(anObjectName);
141
142   setResult(createResultBody(aGeomShape));
143 }
144
145 void ExchangePlugin_ImportFeature::importXAO(const std::string& theFileName)
146 {
147   try {
148   std::string anError;
149
150   XAO::Xao aXao;
151   std::shared_ptr<GeomAPI_Shape> aGeomShape = XAOImport(theFileName, anError, &aXao);
152
153   if (!anError.empty()) {
154     setError("An error occurred while importing " + theFileName + ": " + anError);
155     return;
156   }
157
158   XAO::Geometry* aXaoGeometry = aXao.getGeometry();
159
160   // use the geometry name or the file name for the feature
161   std::string aBodyName = aXaoGeometry->getName();
162   if (aBodyName.empty())
163     aBodyName = GeomAlgoAPI_Tools::File_Tools::name(theFileName);
164   data()->setName(aBodyName);
165
166   ResultBodyPtr aResultBody = createResultBody(aGeomShape);
167   setResult(aResultBody);
168
169   // Process groups/fields
170   std::shared_ptr<ModelAPI_AttributeRefList> aRefListOfGroups =
171       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(data()->attribute(FEATURES_ID()));
172
173   // Remove previous groups/fields stored in RefList
174   std::list<ObjectPtr> anGroupList = aRefListOfGroups->list();
175   std::list<ObjectPtr>::iterator anGroupIt = anGroupList.begin();
176   for (; anGroupIt != anGroupList.end(); ++anGroupIt) {
177     std::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_Feature::feature(*anGroupIt);
178     if (aFeature)
179       document()->removeFeature(aFeature);
180   }
181
182   // Create new groups
183   for (int aGroupIndex = 0; aGroupIndex < aXao.countGroups(); ++aGroupIndex) {
184     XAO::Group* aXaoGroup = aXao.getGroup(aGroupIndex);
185
186     std::shared_ptr<ModelAPI_Feature> aGroupFeature = addFeature("Group");
187
188     // group name
189     if (!aXaoGroup->getName().empty())
190       aGroupFeature->data()->setName(aXaoGroup->getName());
191
192     // fill selection
193     AttributeSelectionListPtr aSelectionList = aGroupFeature->selectionList("group_list");
194
195     // conversion of dimension
196     std::string aDimensionString = XAO::XaoUtils::dimensionToString(aXaoGroup->getDimension());
197     std::string aSelectionType =
198       ExchangePlugin_Tools::xaoDimension2selectionType(aDimensionString);
199
200     aSelectionList->setSelectionType(aSelectionType);
201     for (int anElementIndex = 0; anElementIndex < aXaoGroup->count(); ++anElementIndex) {
202       aSelectionList->append(aResultBody, GeomShapePtr());
203       // complex conversion of element index to reference id
204       int anElementID = aXaoGroup->get(anElementIndex);
205       std::string aReferenceString =
206         aXaoGeometry->getElementReference(aXaoGroup->getDimension(), anElementID);
207       int aReferenceID = XAO::XaoUtils::stringToInt(aReferenceString);
208
209       aSelectionList->value(anElementIndex)->setId(aReferenceID);
210     }
211   }
212   // Create new fields
213   for (int aFieldIndex = 0; aFieldIndex < aXao.countFields(); ++aFieldIndex) {
214     XAO::Field* aXaoField = aXao.getField(aFieldIndex);
215
216     std::shared_ptr<ModelAPI_Feature> aFieldFeature = addFeature("Field");
217
218     // group name
219     if (!aXaoField->getName().empty())
220       aFieldFeature->data()->setName(aXaoField->getName());
221
222     // fill selection
223     AttributeSelectionListPtr aSelectionList = aFieldFeature->selectionList("selected");
224
225     // conversion of dimension
226     std::string aDimensionString = XAO::XaoUtils::dimensionToString(aXaoField->getDimension());
227     std::string aSelectionType =
228       ExchangePlugin_Tools::xaoDimension2selectionType(aDimensionString);
229     aSelectionList->setSelectionType(aSelectionType);
230     // limitation: now in XAO fields are related to everything, so, iterate all sub-shapes to fill
231     int aCountSelected = aXaoField->countElements();
232     std::list<ResultPtr>::const_iterator aResIter = results().begin();
233     for(; aResIter != results().end() && aCountSelected; aResIter++) {
234       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
235       if (!aBody.get())
236         continue;
237       // check that only results that were created before this field are used
238       FeaturePtr aResultFeature = document()->feature(aBody);
239       if (!aResultFeature.get())
240         continue;
241       GeomShapePtr aShape = aBody->shape();
242       if (!aShape.get() || aShape->isNull())
243         continue;
244       GeomAPI_ShapeExplorer anExp(aShape, GeomAPI_Shape::shapeTypeByStr(aSelectionType));
245       for(; anExp.more(); anExp.next()) {
246         aSelectionList->append(aBody, anExp.current());
247         aCountSelected--;
248         if (aCountSelected == 0)
249           break;
250       }
251     }
252
253     // conversion of type
254     XAO::Type aFieldType = aXaoField->getType();
255     std::string aTypeString = XAO::XaoUtils::fieldTypeToString(aFieldType);
256     ModelAPI_AttributeTables::ValueType aType =
257       ExchangePlugin_Tools::xaoType2valuesType(aTypeString);
258     // set components names
259     AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
260     aComponents->setSize(aXaoField->countComponents());
261     for(int aComp = 0; aComp < aXaoField->countComponents(); aComp++) {
262       aComponents->setValue(aComp, aXaoField->getComponentName(aComp));
263     }
264
265     AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
266     aStamps->setSize(aXaoField->countSteps());
267     std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
268     aTables->setSize(
269       aXaoField->countElements() + 1, aXaoField->countComponents(), aXaoField->countSteps());
270     aTables->setType(aType);
271     // iterate steps
272     XAO::stepIterator aStepIter = aXaoField->begin();
273     for(int aStepIndex = 0; aStepIter != aXaoField->end(); aStepIter++, aStepIndex++) {
274       aStamps->setValue(aStepIndex, (*aStepIter)->getStamp());
275       for(int aRow = 1; aRow <= aXaoField->countElements(); aRow++) {
276         for(int aCol = 0; aCol < aXaoField->countComponents(); aCol++) {
277           ModelAPI_AttributeTables::Value aVal;
278           std::string aValStr = (*aStepIter)->getStringValue(aRow - 1, aCol);
279           switch(aType) {
280           case ModelAPI_AttributeTables::BOOLEAN:
281             aVal.myBool = aValStr == "true";
282             break;
283           case ModelAPI_AttributeTables::INTEGER:
284             aVal.myInt = atoi(aValStr.c_str());
285             break;
286           case ModelAPI_AttributeTables::DOUBLE:
287             aVal.myDouble = atof(aValStr.c_str());
288             break;
289           case ModelAPI_AttributeTables::STRING:
290             aVal.myStr = aValStr;
291             break;
292           }
293           aTables->setValue(aVal, aRow, aCol, aStepIndex);
294         }
295       }
296     }
297     // remove everything with zero-values: zeroes are treated as defaults
298     std::set<int> aRowsToRemove;
299     for(int aRow = 1; aRow < aTables->rows(); aRow++) {
300       bool isZero = true;
301       for(int aCol = 0; aCol < aTables->columns() && isZero; aCol++) {
302         for(int aStepIndex = 0; aStepIndex != aTables->tables() && isZero; aStepIndex++) {
303           if (aTables->valueStr(aRow, aCol, aStepIndex) != aTables->valueStr(0, aCol, aStepIndex))
304             isZero = false;
305         }
306       }
307       if (isZero)
308         aRowsToRemove.insert(aRow - 1); // -1 to make prepared for remove from SelectionList
309     }
310     if (!aRowsToRemove.empty()) { // move usefull rows on bottom to the up of the tables
311       // number of rows passed during going through: the current rows will
312       // be moved up for this value
313       int aRemovedPassed = 0;
314       for(int aRow = 1; aRow < aTables->rows(); aRow++) {
315         if (aRowsToRemove.find(aRow - 1) != aRowsToRemove.end()) {
316           aRemovedPassed++;
317         } else if (aRemovedPassed != 0) { // copy the line up
318           for(int aCol = 0; aCol < aTables->columns(); aCol++) {
319             for(int aTable = 0; aTable != aTables->tables(); aTable++) {
320               aTables->setValue(
321                 aTables->value(aRow, aCol, aTable), aRow - aRemovedPassed, aCol, aTable);
322             }
323           }
324         }
325       }
326       aTables->setSize(aTables->rows() - aRemovedPassed, aTables->columns(), aTables->tables());
327       aSelectionList->remove(aRowsToRemove); // remove also selected elements
328     }
329   }
330   // Top avoid problems in Object Browser update: issue #1647.
331   ModelAPI_EventCreator::get()->sendReordered(
332     std::dynamic_pointer_cast<ModelAPI_Feature>(aRefListOfGroups->owner()));
333
334 // LCOV_EXCL_START
335   } catch (XAO::XAO_Exception& e) {
336     std::string anError = e.what();
337     setError("An error occurred while importing " + theFileName + ": " + anError);
338     return;
339   }
340 // LCOV_EXCL_STOP
341 }
342
343 //============================================================================
344 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::addFeature(
345     std::string theID)
346 {
347   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
348   if (aNew)
349     data()->reflist(FEATURES_ID())->append(aNew);
350   // set as current also after it becomes sub to set correctly enabled for other subs
351   //document()->setCurrentFeature(aNew, false);
352   return aNew;
353 }
354
355 // LCOV_EXCL_START
356 void ExchangePlugin_ImportFeature::removeFeature(
357     std::shared_ptr<ModelAPI_Feature> theFeature)
358 {
359   if (!data()->isValid())
360     return;
361   AttributeRefListPtr aList = reflist(FEATURES_ID());
362   aList->remove(theFeature);
363 }
364 // LCOV_EXCL_STOP
365
366 int ExchangePlugin_ImportFeature::numberOfSubs(bool forTree) const
367 {
368   return data()->reflist(FEATURES_ID())->size(true);
369 }
370
371 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::subFeature(
372     const int theIndex, bool forTree)
373 {
374   ObjectPtr anObj = data()->reflist(FEATURES_ID())->object(theIndex, false);
375   FeaturePtr aRes = std::dynamic_pointer_cast<ModelAPI_Feature>(anObj);
376   return aRes;
377 }
378
379 // LCOV_EXCL_START
380 int ExchangePlugin_ImportFeature::subFeatureId(const int theIndex) const
381 {
382   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
383       ModelAPI_AttributeRefList>(data()->attribute(FEATURES_ID()));
384   std::list<ObjectPtr> aFeatures = aRefList->list();
385   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin();
386   int aResultIndex = 1; // number of the counted (created) features, started from 1
387   int aFeatureIndex = -1; // number of the not-empty features in the list
388   for (; anIt != aFeatures.end(); anIt++) {
389     if (anIt->get())
390       aFeatureIndex++;
391     if (aFeatureIndex == theIndex)
392       break;
393     aResultIndex++;
394   }
395   return aResultIndex;
396 }
397 // LCOV_EXCL_STOP
398
399 bool ExchangePlugin_ImportFeature::isSub(ObjectPtr theObject) const
400 {
401   // check is this feature of result
402   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
403   if (aFeature)
404     return data()->reflist(FEATURES_ID())->isInList(aFeature);
405   return false;
406 }
407
408 //============================================================================
409 void ExchangePlugin_ImportFeature::loadNamingDS(
410     std::shared_ptr<GeomAPI_Shape> theGeomShape,
411     std::shared_ptr<ModelAPI_ResultBody> theResultBody)
412 {
413   //load result
414   theResultBody->store(theGeomShape);
415
416   int aTag(1);
417   std::string aNameMS = "Shape";
418   theResultBody->loadFirstLevel(theGeomShape, aNameMS);
419 }