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