Salome HOME
Merge branch 'Port_SALOME_8.5.0'
[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   return isOk;
333 }
334
335 bool ModelHighAPI_Dumper::processSubs(
336   const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
337   bool theDumpModelDo)
338 {
339   bool isOk = true;
340   // dump all sub-features;
341   bool isSubDumped = false;
342   int aNbSubs = theComposite->numberOfSubs();
343   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
344     FeaturePtr aFeature = theComposite->subFeature(anIndex);
345     if (isDumped(EntityPtr(aFeature)))
346       continue;
347
348     isSubDumped = true;
349     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
350     if (aCompFeat) // iteratively process composite features
351       isOk = process(aCompFeat) && isOk;
352     else
353       dumpFeature(aFeature, true);
354   }
355
356   bool isDumpSetName = !myEntitiesStack.empty() &&
357       myEntitiesStack.top().myEntity == EntityPtr(theComposite);
358   bool isForceModelDo = isSubDumped && isDumpSetName &&
359       (myEntitiesStack.top().myUserName || !myEntitiesStack.top().myResults.empty());
360   // It is necessary for the sketch to create its result when complete (command "model.do()").
361   // This option is set by flat theDumpModelDo.
362   // However, nested sketches are rebuilt by parent feature, so, they do not need
363   // explicit call of "model.do()". This will be controlled by the depth of the stack.
364   if (isForceModelDo || (theDumpModelDo && gCompositeStackDepth <= 1))
365     *this << "model.do()" << std::endl;
366
367   // dump "setName" for composite feature
368   if (isDumpSetName)
369     dumpEntitySetName();
370   return isOk;
371 }
372
373 void ModelHighAPI_Dumper::postpone(const EntityPtr& theEntity)
374 {
375   // keep the name
376   name(theEntity, false);
377   myPostponed.push_back(theEntity);
378 }
379
380 void ModelHighAPI_Dumper::dumpPostponed(bool theDumpFolders)
381 {
382   if (myDumpPostponedInProgress)
383     return;
384
385   myDumpPostponedInProgress = true;
386   // make a copy of postponed entities, because the list will be updated
387   // if some features are not able to be dumped
388   std::list<EntityPtr> aPostponedCopy = myPostponed;
389   myPostponed.clear();
390
391   // iterate over postponed entities and try to dump them
392   std::list<EntityPtr>::const_iterator anIt = aPostponedCopy.begin();
393   for (; anIt != aPostponedCopy.end(); ++anIt) {
394     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anIt);
395     if (aFolder) {
396       if (theDumpFolders)
397         dumpFolder(aFolder);
398       else
399         myPostponed.push_back(*anIt);
400     }
401     else {
402       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
403       if (aFeature)
404         dumpFeature(aFeature, true);
405     }
406   }
407   myDumpPostponedInProgress = false;
408 }
409
410 void ModelHighAPI_Dumper::dumpSubFeatureNameAndColor(const std::string theSubFeatureGet,
411                                                      const FeaturePtr& theSubFeature)
412 {
413   name(theSubFeature, false);
414   myNames[theSubFeature] = EntityName(theSubFeatureGet, theSubFeature->name(), false);
415
416   // store results if they have user-defined names or colors
417   std::list<ResultPtr> aResultsWithNameOrColor;
418   const std::list<ResultPtr>& aResults = theSubFeature->results();
419   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
420   for (; aResIt != aResults.end(); ++aResIt) {
421     std::string aResName = (*aResIt)->data()->name();
422     myNames[*aResIt] = EntityName(aResName, aResName, false);
423     aResultsWithNameOrColor.push_back(*aResIt);
424   }
425
426   // store just dumped entity to stack
427   myEntitiesStack.push(LastDumpedEntity(theSubFeature, true, aResultsWithNameOrColor));
428
429   dumpEntitySetName();
430 }
431
432 bool ModelHighAPI_Dumper::exportTo(const std::string& theFileName)
433 {
434   std::ofstream aFile;
435   OSD_OpenStream(aFile, theFileName.c_str(), std::ofstream::out);
436   if (!aFile.is_open())
437     return false;
438
439   // standard header (encoding + imported modules)
440   aFile << "# -*- coding: utf-8 -*-" << std::endl << std::endl;
441   for (ModulesMap::const_iterator aModIt = myModules.begin();
442        aModIt != myModules.end(); ++aModIt) {
443     aFile << "from " << aModIt->first << " import ";
444     if (aModIt->second.empty() ||
445         aModIt->second.find(std::string()) != aModIt->second.end())
446       aFile << "*"; // import whole module
447     else {
448       // import specific features
449       std::set<std::string>::const_iterator anObjIt = aModIt->second.begin();
450       aFile << *anObjIt;
451       for (++anObjIt; anObjIt != aModIt->second.end(); ++anObjIt)
452         aFile << ", " << *anObjIt;
453     }
454     aFile << std::endl;
455   }
456   if (!myModules.empty())
457     aFile << std::endl;
458
459   aFile << "from salome.shaper import model" << std::endl << std::endl;
460   aFile << "model.begin()" << std::endl;
461
462   // dump collected data
463   aFile << myFullDump.str();
464   aFile << myDumpBuffer.str();
465
466   // standard footer
467   aFile << "model.end()" << std::endl;
468
469   aFile.close();
470   clear();
471
472   return true;
473 }
474
475 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName,
476                                        const std::string& theObject)
477 {
478   myModules[theModuleName].insert(theObject);
479 }
480
481 void ModelHighAPI_Dumper::dumpEntitySetName()
482 {
483   const LastDumpedEntity& aLastDumped = myEntitiesStack.top();
484   bool isBufferEmpty = myDumpBuffer.str().empty();
485
486   // dump "setName" for the entity
487   if (aLastDumped.myUserName) {
488     EntityName& anEntityNames = myNames[aLastDumped.myEntity];
489     if (!anEntityNames.myIsDefault)
490       myDumpBuffer << anEntityNames.myCurrentName << ".setName(\""
491                    << anEntityNames.myUserName << "\")" << std::endl;
492     // don't dump "setName" for the entity twice
493     anEntityNames.myUserName.clear();
494     anEntityNames.myIsDefault = true;
495   }
496   // dump "setName" for results
497   std::list<ResultPtr>::const_iterator aResIt = aLastDumped.myResults.begin();
498   std::list<ResultPtr>::const_iterator aResEnd = aLastDumped.myResults.end();
499   for (; aResIt != aResEnd; ++aResIt) {
500     // set result name
501     EntityName& anEntityNames = myNames[*aResIt];
502     if (!anEntityNames.myIsDefault) {
503       *this << *aResIt;
504       myDumpBuffer << ".setName(\"" << anEntityNames.myUserName << "\")" << std::endl;
505       // don't dump "setName" for the entity twice
506       anEntityNames.myUserName.clear();
507       anEntityNames.myIsDefault = true;
508     }
509     // set result color
510     if (!isDefaultColor(*aResIt)) {
511       AttributeIntArrayPtr aColor = (*aResIt)->data()->intArray(ModelAPI_Result::COLOR_ID());
512       if (aColor && aColor->isInitialized()) {
513         *this << *aResIt;
514         myDumpBuffer << ".setColor(" << aColor->value(0) << ", " << aColor->value(1)
515                      << ", " << aColor->value(2) << ")" << std::endl;
516       }
517     }
518     // set result deflection
519     if (!isDefaultDeflection(*aResIt)) {
520       AttributeDoublePtr aDeflectionAttr =
521         (*aResIt)->data()->real(ModelAPI_Result::DEFLECTION_ID());
522       if(aDeflectionAttr.get() && aDeflectionAttr->isInitialized()) {
523         *this << *aResIt;
524         myDumpBuffer << ".setDeflection(" << aDeflectionAttr->value() << ")" << std::endl;
525       }
526     }
527     // set result transparency
528     if (!isDefaultTransparency(*aResIt)) {
529       AttributeDoublePtr aTransparencyAttr =
530         (*aResIt)->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
531       if(aTransparencyAttr.get() && aTransparencyAttr->isInitialized()) {
532         *this << *aResIt;
533         myDumpBuffer << ".setTransparency(" << aTransparencyAttr->value() << ")" << std::endl;
534       }
535     }
536   }
537
538   myNames[aLastDumped.myEntity].myIsDumped = true;
539   myEntitiesStack.pop();
540
541   // clean buffer if it was clear before
542   if (isBufferEmpty) {
543     myFullDump << myDumpBuffer.str();
544     myDumpBuffer.str("");
545   }
546 }
547
548 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
549 {
550   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
551   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
552   return (aFound != myNames.end() && aFound->second.myIsDumped) ||
553          myFeaturesToSkip.find(aFeature) != myFeaturesToSkip.end();
554 }
555
556 bool ModelHighAPI_Dumper::isDumped(const AttributeRefAttrPtr& theRefAttr) const
557 {
558   FeaturePtr aFeature;
559   if (theRefAttr->isObject())
560     aFeature = ModelAPI_Feature::feature(theRefAttr->object());
561   else
562     aFeature = ModelAPI_Feature::feature(theRefAttr->attr()->owner());
563   return aFeature && isDumped(EntityPtr(aFeature));
564 }
565
566 bool ModelHighAPI_Dumper::isDumped(const AttributeRefListPtr& theRefList) const
567 {
568   std::list<ObjectPtr> aRefs = theRefList->list();
569   std::list<ObjectPtr>::iterator anIt = aRefs.begin();
570   for (; anIt != aRefs.end(); ++anIt) {
571     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
572     if (aFeature && !isDumped(EntityPtr(aFeature)))
573       return false;
574   }
575   return true;
576 }
577
578 bool ModelHighAPI_Dumper::isDefaultColor(const ResultPtr& theResult) const
579 {
580   AttributeIntArrayPtr aColor = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
581   if (!aColor || !aColor->isInitialized())
582     return true;
583
584   std::string aSection, aName, aDefault;
585   theResult->colorConfigInfo(aSection, aName, aDefault);
586
587   // dump current color
588   std::ostringstream aColorInfo;
589   aColorInfo << aColor->value(0) << "," << aColor->value(1) << "," << aColor->value(2);
590
591   return aDefault == aColorInfo.str();
592 }
593
594 bool ModelHighAPI_Dumper::isDefaultDeflection(const ResultPtr& theResult) const
595 {
596   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
597   if(!aDeflectionAttr || !aDeflectionAttr->isInitialized()) {
598     return true;
599   }
600
601   double aCurrent = aDeflectionAttr->value();
602   double aDefault = -1;
603
604   bool isConstruction = false;
605   std::string aResultGroup = theResult->groupName();
606   if (aResultGroup == ModelAPI_ResultConstruction::group())
607     isConstruction = true;
608   else if (aResultGroup == ModelAPI_ResultBody::group()) {
609     GeomShapePtr aGeomShape = theResult->shape();
610     if (aGeomShape.get()) {
611       // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
612       // correction of deviation for them should not influence to the application performance
613       GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
614       isConstruction = !anExp.more();
615     }
616   }
617   if (isConstruction)
618     aDefault = Config_PropManager::real("Visualization", "construction_deflection");
619   else
620     aDefault = Config_PropManager::real("Visualization", "body_deflection");
621
622   return fabs(aCurrent - aDefault) < 1.e-12;
623 }
624
625 bool ModelHighAPI_Dumper::isDefaultTransparency(const ResultPtr& theResult) const
626 {
627   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
628   if(!anAttribute || !anAttribute->isInitialized()) {
629     return true;
630   }
631   return fabs(anAttribute->value()) < 1.e-12;
632 }
633
634 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
635 {
636   myDumpBuffer << theChar;
637   return *this;
638 }
639
640 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
641 {
642   myDumpBuffer << theString;
643   return *this;
644 }
645
646 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
647 {
648   myDumpBuffer << theString;
649   return *this;
650 }
651
652 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
653 {
654   myDumpBuffer << (theValue ? "True" : "False");
655   return *this;
656 }
657
658 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
659 {
660   myDumpBuffer << theValue;
661   return *this;
662 }
663
664 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
665 {
666   myDumpBuffer << theValue;
667   return *this;
668 }
669
670 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
671 {
672   importModule("GeomAPI", "GeomAPI_Pnt");
673   myDumpBuffer << "GeomAPI_Pnt(" << thePoint->x() << ", "
674                << thePoint->y() << ", " << thePoint->z() << ")";
675   return *this;
676 }
677
678 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
679 {
680   importModule("GeomAPI", "GeomAPI_Dir");
681   myDumpBuffer << "GeomAPI_Dir(" << theDir->x() << ", "
682                << theDir->y() << ", " << theDir->z() << ")";
683   return *this;
684 }
685
686 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
687     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
688 {
689   myDumpBuffer << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
690   return *this;
691 }
692
693 static void dumpArray(std::ostringstream& theOutput, int theSize,
694                       double* theValues, std::string* theTexts)
695 {
696   for (int i = 0; i < theSize; ++i) {
697     if (i > 0)
698       theOutput << ", ";
699     if (theTexts[i].empty())
700       theOutput << theValues[i];
701     else
702       theOutput << "\"" << theTexts[i] << "\"";
703   }
704 }
705
706 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
707     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
708 {
709   static const int aSize = 3;
710   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
711   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY(), thePoint->textZ()};
712   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
713   return *this;
714 }
715
716 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
717     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
718 {
719   static const int aSize = 2;
720   double aValues[aSize] = {thePoint->x(), thePoint->y()};
721   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY()};
722   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
723   return *this;
724 }
725
726 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
727     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
728 {
729   myDumpBuffer << (theAttrBool->value() ? "True" : "False");
730   return *this;
731 }
732
733 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
734     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
735 {
736   std::string aText = theAttrInt->text();
737   if (aText.empty())
738     myDumpBuffer << theAttrInt->value();
739   else
740     myDumpBuffer << "\"" << aText << "\"";
741   return *this;
742 }
743
744 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
745     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
746 {
747   std::string aText = theAttrReal->text();
748   if (aText.empty())
749     myDumpBuffer << theAttrReal->value();
750   else
751     myDumpBuffer << "\"" << aText << "\"";
752   return *this;
753 }
754
755 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
756     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
757 {
758   myDumpBuffer << "\"" << theAttrStr->value() << "\"";
759   return *this;
760 }
761
762 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FolderPtr& theFolder)
763 {
764   myDumpBuffer << name(theFolder);
765
766   // add dumped folder to a stack
767   if (!myNames[theFolder].myIsDumped &&
768      (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theFolder))
769     myEntitiesStack.push(LastDumpedEntity(theFolder, !myNames[theFolder].myIsDefault));
770
771   return *this;
772 }
773
774 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
775 {
776   myDumpBuffer << name(theEntity);
777
778   if (!myNames[theEntity].myIsDumped) {
779     bool isUserDefinedName = !myNames[theEntity].myIsDefault;
780     // store results if they have user-defined names or colors
781     std::list<ResultPtr> aResultsWithNameOrColor;
782     const std::list<ResultPtr>& aResults = theEntity->results();
783     std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
784     for (; aResIt != aResults.end(); ++aResIt) {
785       if (!myNames[*aResIt].myIsDefault || !isDefaultColor(*aResIt) ||
786           !isDefaultDeflection(*aResIt) || !isDefaultTransparency(*aResIt))
787         aResultsWithNameOrColor.push_back(*aResIt);
788
789       ResultCompSolidPtr aCompSolid =
790           std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIt);
791       if (aCompSolid) {
792         int aNbSubs = aCompSolid->numberOfSubs();
793         for (int i = 0; i < aNbSubs; ++i) {
794           ResultPtr aCurRes = aCompSolid->subResult(i);
795           if (!myNames[aCurRes].myIsDefault || !isDefaultColor(aCurRes) ||
796               !isDefaultDeflection(aCurRes) || !isDefaultTransparency(aCurRes))
797             aResultsWithNameOrColor.push_back(aCurRes);
798         }
799       }
800     }
801     // store just dumped entity to stack
802     if (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theEntity)
803       myEntitiesStack.push(
804           LastDumpedEntity(theEntity, isUserDefinedName, aResultsWithNameOrColor));
805   }
806
807   // remove entity from the list of not dumped items
808   myNotDumpedEntities.erase(theEntity);
809   return *this;
810 }
811
812 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
813 {
814   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
815   int anIndex = 0;
816   int aSubIndex = -1;
817   std::list<ResultPtr> aResults = aFeature->results();
818   for(std::list<ResultPtr>::const_iterator
819       anIt = aResults.cbegin(); anIt != aResults.cend(); ++anIt, ++anIndex) {
820     if(theResult->isSame(*anIt)) {
821       break;
822     }
823
824     ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*anIt);
825     if (aCompSolid) {
826       int aNbSubs = aCompSolid->numberOfSubs();
827       for (aSubIndex = 0; aSubIndex < aNbSubs; ++aSubIndex)
828         if (theResult->isSame(aCompSolid->subResult(aSubIndex)))
829           break;
830       if (aSubIndex < aNbSubs)
831         break;
832       aSubIndex = -1;
833     }
834   }
835
836   myDumpBuffer << name(aFeature);
837   if(anIndex == 0) {
838     myDumpBuffer << ".result()";
839   } else {
840     myDumpBuffer << ".results()[" << anIndex << "]";
841   }
842   if (aSubIndex >= 0) {
843     myDumpBuffer << ".subResult(" << aSubIndex << ")";
844   }
845   return *this;
846 }
847
848 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
849 {
850   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
851   if(aFeature.get()) {
852     myDumpBuffer << name(aFeature);
853     return *this;
854   }
855
856   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
857   if(aResult.get()) {
858     *this << aResult;
859     return *this;
860   }
861
862   return *this;
863 }
864
865 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
866 {
867   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
868
869   std::string aWrapperPrefix, aWrapperSuffix;
870   // Check the attribute belongs to copied (in multi-translation or multi-rotation) feature.
871   // In this case we need to cast explicitly feature to appropriate type.
872   AttributeBooleanPtr isCopy = anOwner->boolean("Copy");
873   if (isCopy.get() && isCopy->value()) {
874     aWrapperPrefix = featureWrapper(anOwner) + "(";
875     aWrapperSuffix = ")";
876     importModule("SketchAPI");
877   }
878
879   myDumpBuffer << aWrapperPrefix << name(anOwner) << aWrapperSuffix
880                << "." << attributeGetter(anOwner, theAttr->id()) << "()";
881   return *this;
882 }
883
884 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
885     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
886 {
887   if (theRefAttr->isObject())
888     *this << theRefAttr->object();
889   else
890     *this << theRefAttr->attr();
891   return *this;
892 }
893
894 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
895     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
896 {
897   myDumpBuffer << "[";
898   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
899   bool isAdded = false;
900   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
901   for (; anIt != aList.end(); ++anIt) {
902     if (isAdded)
903       myDumpBuffer << ", ";
904     else
905       isAdded = true;
906     if (anIt->first)
907       *this << anIt->first;
908     else if (anIt->second)
909       * this << anIt->second;
910   }
911   myDumpBuffer << "]";
912   return *this;
913 }
914
915 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
916     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
917 {
918   *this << theReference->value();
919   return *this;
920 }
921
922 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
923     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
924 {
925   static const int aThreshold = 2;
926   // if number of elements in the list if greater than a threshold,
927   // dump it in a separate line with specific name
928   std::string aDumped = myDumpBuffer.str();
929   if (aDumped.empty() || theRefList->size() <= aThreshold) {
930     myDumpBuffer << "[";
931     std::list<ObjectPtr> aList = theRefList->list();
932     bool isAdded = false;
933     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
934     for (; anIt != aList.end(); ++anIt) {
935       if (isAdded)
936         myDumpBuffer << ", ";
937       else
938         isAdded = true;
939
940       *this << *anIt;
941     }
942     myDumpBuffer << "]";
943   } else {
944     // clear buffer and store list "as is"
945     myDumpBuffer.str("");
946     *this << theRefList;
947     // save buffer and clear it again
948     std::string aDumpedList = myDumpBuffer.str();
949     myDumpBuffer.str("");
950     // obtain name of list
951     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
952     std::string aListName = name(anOwner) + "_objects";
953     // store all previous data
954     myDumpBuffer << aListName << " = " << aDumpedList << std::endl
955                  << aDumped << aListName;
956   }
957   return *this;
958 }
959
960 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
961     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
962 {
963   myDumpBuffer << "model.selection(";
964
965   if(!theAttrSelect->isInitialized()) {
966     myDumpBuffer << ")";
967     return *this;
968   }
969
970   GeomShapePtr aShape = theAttrSelect->value();
971   if(!aShape.get()) {
972     aShape = theAttrSelect->context()->shape();
973   }
974
975   if(!aShape.get()) {
976     myDumpBuffer << ")";
977     return *this;
978   }
979
980   myDumpBuffer << "\"" << aShape->shapeTypeStr() << "\", \"" <<
981     theAttrSelect->namingName() << "\")";
982   return *this;
983 }
984
985 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
986     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
987 {
988   static const int aThreshold = 2;
989   // if number of elements in the list if greater than a threshold,
990   // dump it in a separate line with specific name
991   std::string aDumped = myDumpBuffer.str();
992
993   if (aDumped.empty() || theAttrSelList->size() <= aThreshold) {
994     myDumpBuffer << "[";
995
996     GeomShapePtr aShape;
997     std::string aShapeTypeStr;
998
999     bool isAdded = false;
1000
1001     for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
1002       AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
1003       aShape = anAttribute->value();
1004       if(!aShape.get()) {
1005         ResultPtr aContext = anAttribute->context();
1006         if (aContext.get())
1007           aShape = aContext->shape();
1008       }
1009
1010       if(!aShape.get()) {
1011         continue;
1012       }
1013
1014       if(isAdded) {
1015         myDumpBuffer << ", ";
1016       } else {
1017         isAdded = true;
1018       }
1019       myDumpBuffer << "model.selection(\"" <<
1020         aShape->shapeTypeStr() << "\", \"" << anAttribute->namingName() << "\")";
1021     }
1022
1023     myDumpBuffer << "]";
1024   } else {
1025     // clear buffer and store list "as is"
1026     myDumpBuffer.str("");
1027     *this << theAttrSelList;
1028     // save buffer and clear it again
1029     std::string aDumpedList = myDumpBuffer.str();
1030     myDumpBuffer.str("");
1031     // obtain name of list (the feature may contain several selection lists)
1032     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelList->owner());
1033     std::string aListName = name(anOwner) + "_objects";
1034     std::list<AttributePtr> aSelLists =
1035         anOwner->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1036     if (aSelLists.size() > 1) {
1037       int anIndex = 1;
1038       for (std::list<AttributePtr>::iterator aSIt = aSelLists.begin();
1039            aSIt != aSelLists.end(); ++aSIt, ++anIndex)
1040         if ((*aSIt).get() == theAttrSelList.get())
1041           break;
1042       std::ostringstream aSStream;
1043       aSStream << aListName << "_" << anIndex;
1044       aListName = aSStream.str();
1045     }
1046     // store all previous data
1047     myDumpBuffer << aListName << " = " << aDumpedList << std::endl
1048                  << aDumped << aListName;
1049   }
1050   return *this;
1051 }
1052
1053 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1054   const std::shared_ptr<ModelAPI_AttributeStringArray>& theArray)
1055 {
1056   myDumpBuffer<<"[";
1057   for(int anIndex = 0; anIndex < theArray->size(); ++anIndex) {
1058     if (anIndex != 0)
1059       myDumpBuffer<<", ";
1060
1061     myDumpBuffer<<"\""<<theArray->value(anIndex)<<"\"";
1062   }
1063
1064   myDumpBuffer<<"]";
1065   return *this;
1066 }
1067
1068 /// Dump std::endl
1069 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
1070                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
1071 {
1072   theDumper.myDumpBuffer << theEndl;
1073
1074   if (!theDumper.myEntitiesStack.empty()) {
1075     bool isCopy;
1076     // all copies have been stored into stack, pop them all
1077     do {
1078       isCopy = false;
1079       // Name for composite feature is dumped when all sub-entities are dumped
1080       // (see method ModelHighAPI_Dumper::processSubs).
1081       const ModelHighAPI_Dumper::LastDumpedEntity& aLastDumped = theDumper.myEntitiesStack.top();
1082       CompositeFeaturePtr aComposite =
1083           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aLastDumped.myEntity);
1084       if (!aComposite) {
1085         theDumper.dumpEntitySetName();
1086         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastDumped.myEntity);
1087         if (aFeature) {
1088           AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1089           isCopy = aCopyAttr.get() && aCopyAttr->value();
1090         }
1091       }
1092     } while (isCopy && !theDumper.myEntitiesStack.empty());
1093   }
1094
1095   // store all not-dumped entities first
1096   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
1097   std::string aBufCopy = theDumper.myDumpBuffer.str();
1098   theDumper.clear(true);
1099   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
1100   for (; anIt != aNotDumped.end(); ++anIt) {
1101     // if the feature is composite, dump it with all subs
1102     CompositeFeaturePtr aCompFeat =
1103         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
1104     if (aCompFeat)
1105       theDumper.process(aCompFeat, true);
1106     else {
1107       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1108       theDumper.dumpFeature(aFeature, true);
1109       // dump the Projection feature which produces this "Copy" entity
1110       AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1111       if (aCopyAttr.get() && aCopyAttr->value())
1112       {
1113         const std::set<AttributePtr>& aRefs = aFeature->data()->refsToMe();
1114         std::set<AttributePtr>::iterator aRefIt = aRefs.begin();
1115         for (; aRefIt != aRefs.end(); ++aRefIt)
1116           if ((*aRefIt)->id() == "ProjectedFeature")
1117           { // process projection only
1118             FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
1119             if (anOwner && !theDumper.isDumped(EntityPtr(anOwner)))
1120               theDumper.dumpFeature(anOwner, true);
1121           }
1122       }
1123     }
1124   }
1125
1126   // avoid multiple empty lines
1127   size_t anInd = std::string::npos;
1128   while ((anInd = aBufCopy.find("\n\n\n")) != std::string::npos)
1129     aBufCopy.erase(anInd, 1);
1130   // then store currently dumped string
1131   theDumper.myFullDump << aBufCopy;
1132
1133   // now, store all postponed features
1134   theDumper.dumpPostponed();
1135
1136   return theDumper;
1137 }