Salome HOME
Fix issues related to Python dump.
[modules/shaper.git] / src / ModelHighAPI / ModelHighAPI_Dumper.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "ModelHighAPI_Dumper.h"
22
23 #include <Config_PropManager.h>
24
25 #include <GeomAPI_Pnt.h>
26 #include <GeomAPI_Dir.h>
27 #include <GeomAPI_ShapeExplorer.h>
28
29 #include <GeomDataAPI_Dir.h>
30 #include <GeomDataAPI_Point.h>
31 #include <GeomDataAPI_Point2D.h>
32
33 #include <ModelAPI_AttributeBoolean.h>
34 #include <ModelAPI_AttributeDouble.h>
35 #include <ModelAPI_AttributeIntArray.h>
36 #include <ModelAPI_AttributeInteger.h>
37 #include <ModelAPI_AttributeRefAttr.h>
38 #include <ModelAPI_AttributeRefAttrList.h>
39 #include <ModelAPI_AttributeReference.h>
40 #include <ModelAPI_AttributeRefList.h>
41 #include <ModelAPI_AttributeSelection.h>
42 #include <ModelAPI_AttributeSelectionList.h>
43 #include <ModelAPI_AttributeString.h>
44 #include <ModelAPI_AttributeStringArray.h>
45 #include <ModelAPI_CompositeFeature.h>
46 #include <ModelAPI_Document.h>
47 #include <ModelAPI_Entity.h>
48 #include <ModelAPI_Feature.h>
49 #include <ModelAPI_Folder.h>
50 #include <ModelAPI_Result.h>
51 #include <ModelAPI_ResultBody.h>
52 #include <ModelAPI_ResultCompSolid.h>
53 #include <ModelAPI_ResultConstruction.h>
54 #include <ModelAPI_ResultPart.h>
55 #include <ModelAPI_Tools.h>
56
57 #include <PartSetPlugin_Part.h>
58
59 #include <OSD_OpenFile.hxx>
60
61 #include <fstream>
62
63 static int gCompositeStackDepth = 0;
64
65 ModelHighAPI_Dumper* ModelHighAPI_Dumper::mySelf = 0;
66
67 ModelHighAPI_Dumper::ModelHighAPI_Dumper()
68 {
69   clear();
70 }
71
72 void ModelHighAPI_Dumper::setInstance(ModelHighAPI_Dumper* theDumper)
73 {
74   if (mySelf == 0)
75     mySelf = theDumper;
76 }
77
78 ModelHighAPI_Dumper* ModelHighAPI_Dumper::getInstance()
79 {
80   return mySelf;
81 }
82
83 void ModelHighAPI_Dumper::clear(bool bufferOnly)
84 {
85   myDumpBuffer.str("");
86   myDumpBuffer << std::setprecision(16);
87
88   clearNotDumped();
89
90   if (!bufferOnly) {
91     myFullDump.str("");
92     myFullDump << std::setprecision(16);
93
94     myNames.clear();
95     myModules.clear();
96     myFeatureCount.clear();
97     while (!myEntitiesStack.empty())
98       myEntitiesStack.pop();
99
100     myPostponed.clear();
101     myDumpPostponedInProgress = false;
102   }
103 }
104
105 void ModelHighAPI_Dumper::clearNotDumped()
106 {
107   myNotDumpedEntities.clear();
108 }
109
110 // Convert string to integer. If the string is not a number, return -1
111 static int toInt(const std::string& theString)
112 {
113   std::string::const_iterator aChar = theString.begin();
114   for (; aChar != theString.end(); ++aChar)
115     if (!std::isdigit(*aChar))
116       break;
117   if (aChar != theString.end())
118     return -1; // not a number
119   return std::stoi(theString);
120 }
121
122 const std::string& ModelHighAPI_Dumper::name(const EntityPtr& theEntity,
123                                              bool theSaveNotDumped,
124                                              bool theUseEntityName)
125 {
126   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
127   if (aFound != myNames.end())
128     return aFound->second.myCurrentName;
129
130   // entity is not found, store it
131   std::string aName, aKind;
132   bool isDefaultName = false;
133   bool isSaveNotDumped = theSaveNotDumped;
134   std::ostringstream aDefaultName;
135   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
136   if (aFeature) {
137     aName = aFeature->name();
138     aKind = aFeature->getKind();
139   } else {
140     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theEntity);
141     if (aFolder) {
142       aName = aFolder->data()->name();
143       aKind = ModelAPI_Folder::ID();
144       isSaveNotDumped = false;
145     }
146   }
147
148   ObjectPtr anObject = std::dynamic_pointer_cast<ModelAPI_Object>(theEntity);
149   if (anObject) {
150     DocumentPtr aDoc = anObject->document();
151     int& aNbFeatures = myFeatureCount[aDoc][aKind];
152     aNbFeatures += 1;
153
154     size_t anIndex = aName.find(aKind);
155     if (anIndex == 0 && aName[aKind.length()] == '_') { // name starts with "FeatureKind_"
156       std::string anIdStr = aName.substr(aKind.length() + 1);
157       int anId = toInt(anIdStr);
158
159       // Check number of already registered objects of such kind. Index of current object
160       // should be the same to identify feature's name as automatically generated.
161       if (aNbFeatures == anId) {
162         // name is not user-defined
163         isDefaultName = true;
164       }
165     }
166
167     // obtain default name for the feature
168     if (theUseEntityName)
169       aDefaultName << aName;
170     else {
171       int aFullIndex = 0;
172       NbFeaturesMap::const_iterator aFIt = myFeatureCount.begin();
173       for (; aFIt != myFeatureCount.end(); ++aFIt) {
174         std::map<std::string, int>::const_iterator aFound = aFIt->second.find(aKind);
175         if (aFound != aFIt->second.end())
176           aFullIndex += aFound->second;
177       }
178       aDefaultName << aKind << "_" << aFullIndex;
179     }
180   }
181
182   myNames[theEntity] = EntityName(aDefaultName.str(), aName, isDefaultName);
183   if (isSaveNotDumped)
184     myNotDumpedEntities.insert(theEntity);
185
186   // store names of results
187   if (aFeature)
188     saveResultNames(aFeature);
189
190   return myNames[theEntity].myCurrentName;
191 }
192
193 const std::string& ModelHighAPI_Dumper::parentName(const FeaturePtr& theEntity)
194 {
195   const std::set<AttributePtr>& aRefs = theEntity->data()->refsToMe();
196   std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
197   for (; aRefIt != aRefs.end(); ++aRefIt) {
198     CompositeFeaturePtr anOwner = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
199         ModelAPI_Feature::feature((*aRefIt)->owner()));
200     if (anOwner)
201       return name(anOwner);
202   }
203
204   static const std::string DUMMY;
205   return DUMMY;
206 }
207
208 void ModelHighAPI_Dumper::saveResultNames(const FeaturePtr& theFeature)
209 {
210   // Default name of the feature
211   bool isFeatureDefaultName = myNames[theFeature].myIsDefault;
212
213   // Save only names of results which is not correspond to default feature name
214   const std::list<ResultPtr>& aResults = theFeature->results();
215   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
216   for (int i = 0; aResIt != aResults.end(); ++aResIt, ++i) {
217     std::pair<std::string, bool> aName = ModelAPI_Tools::getDefaultName(*aResIt, i);
218     std::string aDefaultName = aName.first;
219     std::string aResName = (*aResIt)->data()->name();
220
221     bool isUserDefined = !(isFeatureDefaultName && aDefaultName == aResName);
222
223     myNames[*aResIt] = EntityName(aResName,
224         (isUserDefined ? aResName : std::string()), !isUserDefined);
225
226     // check names of sub-results for CompSolid
227     ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIt);
228     if (aCompSolid) {
229       int aNbSubs = aCompSolid->numberOfSubs();
230       for (int j = 0; j < aNbSubs; ++j) {
231         ResultPtr aSub = aCompSolid->subResult(j);
232         std::string aSubName = aSub->data()->name();
233         aName = ModelAPI_Tools::getDefaultName(aSub, j);
234         aDefaultName = aName.first;
235
236         bool isUserDefinedSubName = isUserDefined || aDefaultName != aSubName;
237         myNames[aSub] = EntityName(aSubName,
238             (isUserDefinedSubName ? aSubName : std::string()), !isUserDefinedSubName);
239       }
240     }
241   }
242 }
243
244 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc,
245                                   const std::string& theFileName)
246 {
247   // dump top level document feature
248   static const std::string aDocName("partSet");
249   myNames[theDoc] = EntityName(aDocName, std::string(), true);
250   *this << aDocName << " = model.moduleDocument()" << std::endl;
251
252   // dump subfeatures and store result to file
253   return process(theDoc) && exportTo(theFileName);
254 }
255
256 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc)
257 {
258   bool isOk = true;
259   std::list<ObjectPtr> anObjects = theDoc->allObjects();
260   std::list<ObjectPtr>::const_iterator anObjIt = anObjects.begin();
261   // firstly, dump all parameters
262   for (; anObjIt != anObjects.end(); ++ anObjIt) {
263     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
264     if (aFeature)
265       dumpParameter(aFeature);
266   }
267   // dump all other features
268   for (anObjIt = anObjects.begin(); anObjIt != anObjects.end(); ++anObjIt) {
269     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anObjIt);
270     if (aCompFeat) // iteratively process composite features
271       isOk = process(aCompFeat) && isOk;
272     else if (!isDumped(EntityPtr(*anObjIt))) {
273       // dump folder
274       FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anObjIt);
275       if (aFolder)
276         dumpFolder(aFolder);
277       else {
278         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
279         if (aFeature) // dump common feature
280           dumpFeature(aFeature);
281       }
282     }
283   }
284   // dump folders if any
285   dumpPostponed(true);
286   return isOk;
287 }
288
289 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
290                                   bool isForce)
291 {
292   // increase composite features stack
293   ++gCompositeStackDepth;
294   // dump composite itself
295   if (!isDumped(EntityPtr(theComposite)) || isForce)
296     dumpFeature(FeaturePtr(theComposite), isForce);
297
298   // sub-part is processed independently, because it provides separate document
299   if (theComposite->getKind() == PartSetPlugin_Part::ID()) {
300     // dump name of the part if it is different from default
301     if (!myEntitiesStack.empty())
302       dumpEntitySetName();
303
304     // decrease composite features stack because we run into separate document
305     --gCompositeStackDepth;
306
307     ResultPartPtr aPartResult =
308         std::dynamic_pointer_cast<ModelAPI_ResultPart>(theComposite->lastResult());
309     if (!aPartResult)
310       return false;
311     DocumentPtr aSubDoc = aPartResult->partDoc();
312     if (!aSubDoc)
313       return false;
314     // set name of document
315     const std::string& aPartName = myNames[theComposite].myCurrentName;
316     std::string aDocName = aPartName + "_doc";
317     myNames[aSubDoc] = EntityName(aDocName, std::string(), true);
318
319     // dump document in a separate line
320     *this << aDocName << " = " << aPartName << ".document()" << std::endl;
321     // dump features in the document
322     bool aRes = process(aSubDoc);
323     *this << "model.do()" << std::endl;
324     return aRes;
325   }
326
327   // dump sub-features
328   bool isOk = processSubs(theComposite);
329   // decrease composite features stack
330   --gCompositeStackDepth;
331
332   // dump folders if any
333   dumpPostponed(true);
334   return isOk;
335 }
336
337 bool ModelHighAPI_Dumper::processSubs(
338   const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
339   bool theDumpModelDo)
340 {
341   bool isOk = true;
342   // dump all sub-features;
343   bool isSubDumped = false;
344   int aNbSubs = theComposite->numberOfSubs();
345   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
346     FeaturePtr aFeature = theComposite->subFeature(anIndex);
347     if (isDumped(EntityPtr(aFeature)))
348       continue;
349
350     isSubDumped = true;
351     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
352     if (aCompFeat) // iteratively process composite features
353       isOk = process(aCompFeat) && isOk;
354     else
355       dumpFeature(aFeature, true);
356   }
357
358   bool isDumpSetName = !myEntitiesStack.empty() &&
359       myEntitiesStack.top().myEntity == EntityPtr(theComposite);
360   bool isForceModelDo = isSubDumped && isDumpSetName &&
361       (myEntitiesStack.top().myUserName || !myEntitiesStack.top().myResults.empty());
362   // It is necessary for the sketch to create its result when complete (command "model.do()").
363   // This option is set by flat theDumpModelDo.
364   // However, nested sketches are rebuilt by parent feature, so, they do not need
365   // explicit call of "model.do()". This will be controlled by the depth of the stack.
366   if (isForceModelDo || (theDumpModelDo && gCompositeStackDepth <= 1))
367     *this << "model.do()" << std::endl;
368
369   // dump "setName" for composite feature
370   if (isDumpSetName)
371     dumpEntitySetName();
372   // dump folders if any
373   dumpPostponed(true);
374   return isOk;
375 }
376
377 void ModelHighAPI_Dumper::postpone(const EntityPtr& theEntity)
378 {
379   // keep the name
380   name(theEntity, false);
381   myPostponed.push_back(theEntity);
382 }
383
384 void ModelHighAPI_Dumper::dumpPostponed(bool theDumpFolders)
385 {
386   if (myDumpPostponedInProgress)
387     return;
388
389   myDumpPostponedInProgress = true;
390   // make a copy of postponed entities, because the list will be updated
391   // if some features are not able to be dumped
392   std::list<EntityPtr> aPostponedCopy = myPostponed;
393   myPostponed.clear();
394
395   // iterate over postponed entities and try to dump them
396   std::list<EntityPtr>::const_iterator anIt = aPostponedCopy.begin();
397   for (; anIt != aPostponedCopy.end(); ++anIt) {
398     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anIt);
399     if (aFolder) {
400       if (theDumpFolders)
401         dumpFolder(aFolder);
402       else
403         myPostponed.push_back(*anIt);
404     }
405     else {
406       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
407       if (aFeature)
408         dumpFeature(aFeature);
409     }
410   }
411   myDumpPostponedInProgress = false;
412 }
413
414 void ModelHighAPI_Dumper::dumpSubFeatureNameAndColor(const std::string theSubFeatureGet,
415                                                      const FeaturePtr& theSubFeature)
416 {
417   name(theSubFeature, false);
418   myNames[theSubFeature] = EntityName(theSubFeatureGet, theSubFeature->name(), false);
419
420   // store results if they have user-defined names or colors
421   std::list<ResultPtr> aResultsWithNameOrColor;
422   const std::list<ResultPtr>& aResults = theSubFeature->results();
423   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
424   for (; aResIt != aResults.end(); ++aResIt) {
425     std::string aResName = (*aResIt)->data()->name();
426     myNames[*aResIt] = EntityName(aResName, aResName, false);
427     aResultsWithNameOrColor.push_back(*aResIt);
428   }
429
430   // store just dumped entity to stack
431   myEntitiesStack.push(LastDumpedEntity(theSubFeature, true, aResultsWithNameOrColor));
432
433   dumpEntitySetName();
434 }
435
436 bool ModelHighAPI_Dumper::exportTo(const std::string& theFileName)
437 {
438   std::ofstream aFile;
439   OSD_OpenStream(aFile, theFileName.c_str(), std::ofstream::out);
440   if (!aFile.is_open())
441     return false;
442
443   // standard header
444   for (ModulesMap::const_iterator aModIt = myModules.begin();
445        aModIt != myModules.end(); ++aModIt) {
446     aFile << "from " << aModIt->first << " import ";
447     if (aModIt->second.empty() ||
448         aModIt->second.find(std::string()) != aModIt->second.end())
449       aFile << "*"; // import whole module
450     else {
451       // import specific features
452       std::set<std::string>::const_iterator anObjIt = aModIt->second.begin();
453       aFile << *anObjIt;
454       for (++anObjIt; anObjIt != aModIt->second.end(); ++anObjIt)
455         aFile << ", " << *anObjIt;
456     }
457     aFile << std::endl;
458   }
459   if (!myModules.empty())
460     aFile << std::endl;
461
462   aFile << "from salome.shaper import model" << std::endl << std::endl;
463   aFile << "model.begin()" << std::endl;
464
465   // dump collected data
466   aFile << myFullDump.str();
467   aFile << myDumpBuffer.str();
468
469   // standard footer
470   aFile << "model.end()" << std::endl;
471
472   aFile.close();
473   clear();
474
475   return true;
476 }
477
478 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName,
479                                        const std::string& theObject)
480 {
481   myModules[theModuleName].insert(theObject);
482 }
483
484 void ModelHighAPI_Dumper::dumpEntitySetName()
485 {
486   const LastDumpedEntity& aLastDumped = myEntitiesStack.top();
487   bool isBufferEmpty = myDumpBuffer.str().empty();
488
489   // dump "setName" for the entity
490   if (aLastDumped.myUserName) {
491     EntityName& anEntityNames = myNames[aLastDumped.myEntity];
492     if (!anEntityNames.myIsDefault)
493       myDumpBuffer << anEntityNames.myCurrentName << ".setName(\""
494                    << anEntityNames.myUserName << "\")" << std::endl;
495     // don't dump "setName" for the entity twice
496     anEntityNames.myUserName.clear();
497     anEntityNames.myIsDefault = true;
498   }
499   // dump "setName" for results
500   std::list<ResultPtr>::const_iterator aResIt = aLastDumped.myResults.begin();
501   std::list<ResultPtr>::const_iterator aResEnd = aLastDumped.myResults.end();
502   for (; aResIt != aResEnd; ++aResIt) {
503     // set result name
504     EntityName& anEntityNames = myNames[*aResIt];
505     if (!anEntityNames.myIsDefault) {
506       *this << *aResIt;
507       myDumpBuffer << ".setName(\"" << anEntityNames.myUserName << "\")" << std::endl;
508       // don't dump "setName" for the entity twice
509       anEntityNames.myUserName.clear();
510       anEntityNames.myIsDefault = true;
511     }
512     // set result color
513     if (!isDefaultColor(*aResIt)) {
514       AttributeIntArrayPtr aColor = (*aResIt)->data()->intArray(ModelAPI_Result::COLOR_ID());
515       if (aColor && aColor->isInitialized()) {
516         *this << *aResIt;
517         myDumpBuffer << ".setColor(" << aColor->value(0) << ", " << aColor->value(1)
518                      << ", " << aColor->value(2) << ")" << std::endl;
519       }
520     }
521     // set result deflection
522     if (!isDefaultDeflection(*aResIt)) {
523       AttributeDoublePtr aDeflectionAttr =
524         (*aResIt)->data()->real(ModelAPI_Result::DEFLECTION_ID());
525       if(aDeflectionAttr.get() && aDeflectionAttr->isInitialized()) {
526         *this << *aResIt;
527         myDumpBuffer << ".setDeflection(" << aDeflectionAttr->value() << ")" << std::endl;
528       }
529     }
530     // set result transparency
531     if (!isDefaultTransparency(*aResIt)) {
532       AttributeDoublePtr aTransparencyAttr =
533         (*aResIt)->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
534       if(aTransparencyAttr.get() && aTransparencyAttr->isInitialized()) {
535         *this << *aResIt;
536         myDumpBuffer << ".setTransparency(" << aTransparencyAttr->value() << ")" << std::endl;
537       }
538     }
539   }
540
541   myNames[aLastDumped.myEntity].myIsDumped = true;
542   myEntitiesStack.pop();
543
544   // clean buffer if it was clear before
545   if (isBufferEmpty) {
546     myFullDump << myDumpBuffer.str();
547     myDumpBuffer.str("");
548   }
549 }
550
551 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
552 {
553   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
554   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
555   return (aFound != myNames.end() && aFound->second.myIsDumped) ||
556          myFeaturesToSkip.find(aFeature) != myFeaturesToSkip.end();
557 }
558
559 bool ModelHighAPI_Dumper::isDumped(const AttributeRefAttrPtr& theRefAttr) const
560 {
561   FeaturePtr aFeature;
562   if (theRefAttr->isObject())
563     aFeature = ModelAPI_Feature::feature(theRefAttr->object());
564   else
565     aFeature = ModelAPI_Feature::feature(theRefAttr->attr()->owner());
566   return aFeature && isDumped(EntityPtr(aFeature));
567 }
568
569 bool ModelHighAPI_Dumper::isDumped(const AttributeRefListPtr& theRefList) const
570 {
571   std::list<ObjectPtr> aRefs = theRefList->list();
572   std::list<ObjectPtr>::iterator anIt = aRefs.begin();
573   for (; anIt != aRefs.end(); ++anIt) {
574     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
575     if (aFeature && !isDumped(EntityPtr(aFeature)))
576       return false;
577   }
578   return true;
579 }
580
581 bool ModelHighAPI_Dumper::isDefaultColor(const ResultPtr& theResult) const
582 {
583   AttributeIntArrayPtr aColor = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
584   if (!aColor || !aColor->isInitialized())
585     return true;
586
587   std::string aSection, aName, aDefault;
588   theResult->colorConfigInfo(aSection, aName, aDefault);
589
590   // dump current color
591   std::ostringstream aColorInfo;
592   aColorInfo << aColor->value(0) << "," << aColor->value(1) << "," << aColor->value(2);
593
594   return aDefault == aColorInfo.str();
595 }
596
597 bool ModelHighAPI_Dumper::isDefaultDeflection(const ResultPtr& theResult) const
598 {
599   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
600   if(!aDeflectionAttr || !aDeflectionAttr->isInitialized()) {
601     return true;
602   }
603
604   double aCurrent = aDeflectionAttr->value();
605   double aDefault = -1;
606
607   bool isConstruction = false;
608   std::string aResultGroup = theResult->groupName();
609   if (aResultGroup == ModelAPI_ResultConstruction::group())
610     isConstruction = true;
611   else if (aResultGroup == ModelAPI_ResultBody::group()) {
612     GeomShapePtr aGeomShape = theResult->shape();
613     if (aGeomShape.get()) {
614       // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
615       // correction of deviation for them should not influence to the application performance
616       GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
617       isConstruction = !anExp.more();
618     }
619   }
620   if (isConstruction)
621     aDefault = Config_PropManager::real("Visualization", "construction_deflection");
622   else
623     aDefault = Config_PropManager::real("Visualization", "body_deflection");
624
625   return fabs(aCurrent - aDefault) < 1.e-12;
626 }
627
628 bool ModelHighAPI_Dumper::isDefaultTransparency(const ResultPtr& theResult) const
629 {
630   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
631   if(!anAttribute || !anAttribute->isInitialized()) {
632     return true;
633   }
634   return fabs(anAttribute->value()) < 1.e-12;
635 }
636
637 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
638 {
639   myDumpBuffer << theChar;
640   return *this;
641 }
642
643 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
644 {
645   myDumpBuffer << theString;
646   return *this;
647 }
648
649 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
650 {
651   myDumpBuffer << theString;
652   return *this;
653 }
654
655 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
656 {
657   myDumpBuffer << (theValue ? "True" : "False");
658   return *this;
659 }
660
661 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
662 {
663   myDumpBuffer << theValue;
664   return *this;
665 }
666
667 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
668 {
669   myDumpBuffer << theValue;
670   return *this;
671 }
672
673 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
674 {
675   importModule("GeomAPI", "GeomAPI_Pnt");
676   myDumpBuffer << "GeomAPI_Pnt(" << thePoint->x() << ", "
677                << thePoint->y() << ", " << thePoint->z() << ")";
678   return *this;
679 }
680
681 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
682 {
683   importModule("GeomAPI", "GeomAPI_Dir");
684   myDumpBuffer << "GeomAPI_Dir(" << theDir->x() << ", "
685                << theDir->y() << ", " << theDir->z() << ")";
686   return *this;
687 }
688
689 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
690     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
691 {
692   myDumpBuffer << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
693   return *this;
694 }
695
696 static void dumpArray(std::ostringstream& theOutput, int theSize,
697                       double* theValues, std::string* theTexts)
698 {
699   for (int i = 0; i < theSize; ++i) {
700     if (i > 0)
701       theOutput << ", ";
702     if (theTexts[i].empty())
703       theOutput << theValues[i];
704     else
705       theOutput << "\"" << theTexts[i] << "\"";
706   }
707 }
708
709 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
710     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
711 {
712   static const int aSize = 3;
713   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
714   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY(), thePoint->textZ()};
715   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
716   return *this;
717 }
718
719 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
720     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
721 {
722   static const int aSize = 2;
723   double aValues[aSize] = {thePoint->x(), thePoint->y()};
724   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY()};
725   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
726   return *this;
727 }
728
729 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
730     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
731 {
732   myDumpBuffer << (theAttrBool->value() ? "True" : "False");
733   return *this;
734 }
735
736 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
737     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
738 {
739   std::string aText = theAttrInt->text();
740   if (aText.empty())
741     myDumpBuffer << theAttrInt->value();
742   else
743     myDumpBuffer << "\"" << aText << "\"";
744   return *this;
745 }
746
747 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
748     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
749 {
750   std::string aText = theAttrReal->text();
751   if (aText.empty())
752     myDumpBuffer << theAttrReal->value();
753   else
754     myDumpBuffer << "\"" << aText << "\"";
755   return *this;
756 }
757
758 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
759     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
760 {
761   myDumpBuffer << "\"" << theAttrStr->value() << "\"";
762   return *this;
763 }
764
765 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FolderPtr& theFolder)
766 {
767   myDumpBuffer << name(theFolder);
768   return *this;
769 }
770
771 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
772 {
773   myDumpBuffer << name(theEntity);
774
775   if (!myNames[theEntity].myIsDumped) {
776     bool isUserDefinedName = !myNames[theEntity].myIsDefault;
777     // store results if they have user-defined names or colors
778     std::list<ResultPtr> aResultsWithNameOrColor;
779     const std::list<ResultPtr>& aResults = theEntity->results();
780     std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
781     for (; aResIt != aResults.end(); ++aResIt) {
782       if (!myNames[*aResIt].myIsDefault || !isDefaultColor(*aResIt) ||
783           !isDefaultDeflection(*aResIt) || !isDefaultTransparency(*aResIt))
784         aResultsWithNameOrColor.push_back(*aResIt);
785
786       ResultCompSolidPtr aCompSolid =
787           std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIt);
788       if (aCompSolid) {
789         int aNbSubs = aCompSolid->numberOfSubs();
790         for (int i = 0; i < aNbSubs; ++i) {
791           ResultPtr aCurRes = aCompSolid->subResult(i);
792           if (!myNames[aCurRes].myIsDefault || !isDefaultColor(aCurRes) ||
793               !isDefaultDeflection(aCurRes) || !isDefaultTransparency(aCurRes))
794             aResultsWithNameOrColor.push_back(aCurRes);
795         }
796       }
797     }
798     // store just dumped entity to stack
799     if (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theEntity)
800       myEntitiesStack.push(
801           LastDumpedEntity(theEntity, isUserDefinedName, aResultsWithNameOrColor));
802   }
803
804   // remove entity from the list of not dumped items
805   myNotDumpedEntities.erase(theEntity);
806   return *this;
807 }
808
809 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
810 {
811   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
812   int anIndex = 0;
813   int aSubIndex = -1;
814   std::list<ResultPtr> aResults = aFeature->results();
815   for(std::list<ResultPtr>::const_iterator
816       anIt = aResults.cbegin(); anIt != aResults.cend(); ++anIt, ++anIndex) {
817     if(theResult->isSame(*anIt)) {
818       break;
819     }
820
821     ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*anIt);
822     if (aCompSolid) {
823       int aNbSubs = aCompSolid->numberOfSubs();
824       for (aSubIndex = 0; aSubIndex < aNbSubs; ++aSubIndex)
825         if (theResult->isSame(aCompSolid->subResult(aSubIndex)))
826           break;
827       if (aSubIndex < aNbSubs)
828         break;
829       aSubIndex = -1;
830     }
831   }
832
833   myDumpBuffer << name(aFeature);
834   if(anIndex == 0) {
835     myDumpBuffer << ".result()";
836   } else {
837     myDumpBuffer << ".results()[" << anIndex << "]";
838   }
839   if (aSubIndex >= 0) {
840     myDumpBuffer << ".subResult(" << aSubIndex << ")";
841   }
842   return *this;
843 }
844
845 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
846 {
847   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
848   if(aFeature.get()) {
849     myDumpBuffer << name(aFeature);
850     return *this;
851   }
852
853   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
854   if(aResult.get()) {
855     *this << aResult;
856     return *this;
857   }
858
859   return *this;
860 }
861
862 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
863 {
864   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
865
866   std::string aWrapperPrefix, aWrapperSuffix;
867   // Check the attribute belongs to copied (in multi-translation or multi-rotation) feature.
868   // In this case we need to cast explicitly feature to appropriate type.
869   AttributeBooleanPtr isCopy = anOwner->boolean("Copy");
870   if (isCopy.get() && isCopy->value()) {
871     aWrapperPrefix = featureWrapper(anOwner) + "(";
872     aWrapperSuffix = ")";
873     importModule("SketchAPI");
874   }
875
876   myDumpBuffer << aWrapperPrefix << name(anOwner) << aWrapperSuffix
877                << "." << attributeGetter(anOwner, theAttr->id()) << "()";
878   return *this;
879 }
880
881 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
882     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
883 {
884   if (theRefAttr->isObject())
885     *this << theRefAttr->object();
886   else
887     *this << theRefAttr->attr();
888   return *this;
889 }
890
891 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
892     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
893 {
894   myDumpBuffer << "[";
895   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
896   bool isAdded = false;
897   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
898   for (; anIt != aList.end(); ++anIt) {
899     if (isAdded)
900       myDumpBuffer << ", ";
901     else
902       isAdded = true;
903     if (anIt->first)
904       *this << anIt->first;
905     else if (anIt->second)
906       * this << anIt->second;
907   }
908   myDumpBuffer << "]";
909   return *this;
910 }
911
912 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
913     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
914 {
915   *this << theReference->value();
916   return *this;
917 }
918
919 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
920     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
921 {
922   static const int aThreshold = 2;
923   // if number of elements in the list if greater than a threshold,
924   // dump it in a separate line with specific name
925   std::string aDumped = myDumpBuffer.str();
926   if (aDumped.empty() || theRefList->size() <= aThreshold) {
927     myDumpBuffer << "[";
928     std::list<ObjectPtr> aList = theRefList->list();
929     bool isAdded = false;
930     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
931     for (; anIt != aList.end(); ++anIt) {
932       if (isAdded)
933         myDumpBuffer << ", ";
934       else
935         isAdded = true;
936
937       *this << *anIt;
938     }
939     myDumpBuffer << "]";
940   } else {
941     // clear buffer and store list "as is"
942     myDumpBuffer.str("");
943     *this << theRefList;
944     // save buffer and clear it again
945     std::string aDumpedList = myDumpBuffer.str();
946     myDumpBuffer.str("");
947     // obtain name of list
948     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
949     std::string aListName = name(anOwner) + "_objects";
950     // store all previous data
951     myDumpBuffer << aListName << " = " << aDumpedList << std::endl
952                  << aDumped << aListName;
953   }
954   return *this;
955 }
956
957 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
958     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
959 {
960   myDumpBuffer << "model.selection(";
961
962   if(!theAttrSelect->isInitialized()) {
963     myDumpBuffer << ")";
964     return *this;
965   }
966
967   GeomShapePtr aShape = theAttrSelect->value();
968   if(!aShape.get()) {
969     aShape = theAttrSelect->context()->shape();
970   }
971
972   if(!aShape.get()) {
973     myDumpBuffer << ")";
974     return *this;
975   }
976
977   myDumpBuffer << "\"" << aShape->shapeTypeStr() << "\", \"" <<
978     theAttrSelect->namingName() << "\")";
979   return *this;
980 }
981
982 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
983     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
984 {
985   static const int aThreshold = 2;
986   // if number of elements in the list if greater than a threshold,
987   // dump it in a separate line with specific name
988   std::string aDumped = myDumpBuffer.str();
989
990   if (aDumped.empty() || theAttrSelList->size() <= aThreshold) {
991     myDumpBuffer << "[";
992
993     GeomShapePtr aShape;
994     std::string aShapeTypeStr;
995
996     bool isAdded = false;
997
998     for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
999       AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
1000       aShape = anAttribute->value();
1001       if(!aShape.get()) {
1002         ResultPtr aContext = anAttribute->context();
1003         if (aContext.get())
1004           aShape = aContext->shape();
1005       }
1006
1007       if(!aShape.get()) {
1008         continue;
1009       }
1010
1011       if(isAdded) {
1012         myDumpBuffer << ", ";
1013       } else {
1014         isAdded = true;
1015       }
1016       myDumpBuffer << "model.selection(\"" <<
1017         aShape->shapeTypeStr() << "\", \"" << anAttribute->namingName() << "\")";
1018     }
1019
1020     myDumpBuffer << "]";
1021   } else {
1022     // clear buffer and store list "as is"
1023     myDumpBuffer.str("");
1024     *this << theAttrSelList;
1025     // save buffer and clear it again
1026     std::string aDumpedList = myDumpBuffer.str();
1027     myDumpBuffer.str("");
1028     // obtain name of list (the feature may contain several selection lists)
1029     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelList->owner());
1030     std::string aListName = name(anOwner) + "_objects";
1031     std::list<AttributePtr> aSelLists =
1032         anOwner->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1033     if (aSelLists.size() > 1) {
1034       int anIndex = 1;
1035       for (std::list<AttributePtr>::iterator aSIt = aSelLists.begin();
1036            aSIt != aSelLists.end(); ++aSIt, ++anIndex)
1037         if ((*aSIt).get() == theAttrSelList.get())
1038           break;
1039       std::ostringstream aSStream;
1040       aSStream << aListName << "_" << anIndex;
1041       aListName = aSStream.str();
1042     }
1043     // store all previous data
1044     myDumpBuffer << aListName << " = " << aDumpedList << std::endl
1045                  << aDumped << aListName;
1046   }
1047   return *this;
1048 }
1049
1050 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1051   const std::shared_ptr<ModelAPI_AttributeStringArray>& theArray)
1052 {
1053   myDumpBuffer<<"[";
1054   for(int anIndex = 0; anIndex < theArray->size(); ++anIndex) {
1055     if (anIndex != 0)
1056       myDumpBuffer<<", ";
1057
1058     myDumpBuffer<<"\""<<theArray->value(anIndex)<<"\"";
1059   }
1060
1061   myDumpBuffer<<"]";
1062   return *this;
1063 }
1064
1065 /// Dump std::endl
1066 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
1067                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
1068 {
1069   theDumper.myDumpBuffer << theEndl;
1070
1071   if (!theDumper.myEntitiesStack.empty()) {
1072     bool isCopy;
1073     // all copies have been stored into stack, pop them all
1074     do {
1075       isCopy = false;
1076       // Name for composite feature is dumped when all sub-entities are dumped
1077       // (see method ModelHighAPI_Dumper::processSubs).
1078       const ModelHighAPI_Dumper::LastDumpedEntity& aLastDumped = theDumper.myEntitiesStack.top();
1079       CompositeFeaturePtr aComposite =
1080           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aLastDumped.myEntity);
1081       if (!aComposite) {
1082         theDumper.dumpEntitySetName();
1083         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastDumped.myEntity);
1084         if (aFeature) {
1085           AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1086           isCopy = aCopyAttr.get() && aCopyAttr->value();
1087         }
1088       }
1089     } while (isCopy && !theDumper.myEntitiesStack.empty());
1090   }
1091
1092   // store all not-dumped entities first
1093   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
1094   std::string aBufCopy = theDumper.myDumpBuffer.str();
1095   theDumper.clear(true);
1096   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
1097   for (; anIt != aNotDumped.end(); ++anIt) {
1098     // if the feature is composite, dump it with all subs
1099     CompositeFeaturePtr aCompFeat =
1100         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
1101     if (aCompFeat)
1102       theDumper.process(aCompFeat, true);
1103     else {
1104       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1105       theDumper.dumpFeature(aFeature, true);
1106       // dump the Projection feature which produces this "Copy" entity
1107       AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1108       if (aCopyAttr.get() && aCopyAttr->value())
1109       {
1110         const std::set<AttributePtr>& aRefs = aFeature->data()->refsToMe();
1111         std::set<AttributePtr>::iterator aRefIt = aRefs.begin();
1112         for (; aRefIt != aRefs.end(); ++aRefIt)
1113           if ((*aRefIt)->id() == "ProjectedFeature")
1114           { // process projection only
1115             FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
1116             if (anOwner && !theDumper.isDumped(EntityPtr(anOwner)))
1117               theDumper.dumpFeature(anOwner, true);
1118           }
1119       }
1120     }
1121   }
1122
1123   // avoid multiple empty lines
1124   size_t anInd = std::string::npos;
1125   while ((anInd = aBufCopy.find("\n\n\n")) != std::string::npos)
1126     aBufCopy.erase(anInd, 1);
1127   // then store currently dumped string
1128   theDumper.myFullDump << aBufCopy;
1129
1130   // now, store all postponed features
1131   theDumper.dumpPostponed();
1132
1133   return theDumper;
1134 }