Salome HOME
PAL5887. In Restore(), create field convertor for imported timestamp
[modules/visu.git] / src / VISU_I / VISU_Result_i.cc
1 //  VISU OBJECT : interactive object for VISU entities implementation
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
21 //
22 //
23 //  File   : VISU_Result_i.cc
24 //  Author : Alexey PETROV
25 //  Module : VISU
26
27 #include "VISU_Result_i.hh"
28
29 #include "VISU_Convertor_impl.hxx"
30 #include "VISU_CorbaMedConvertor.hxx"
31 #include "VISU_PipeLine.hxx"
32
33 #include "SUIT_ResourceMgr.h"
34
35 #include "SALOMEDS_Tool.hxx"
36 #include "HDFascii.hxx"
37
38 // QT Includes
39 #include <qstring.h>
40 #include <qfileinfo.h>
41
42 // VTK Includes
43 #include <vtkCell.h>
44 #include <vtkUnstructuredGrid.h>
45
46 // OCCT Includes
47 #include <Bnd_Box.hxx>
48
49 using namespace VISU;
50 using namespace std;
51
52 #ifdef _DEBUG_
53 static int MYDEBUG = 0;
54 #else
55 static int MYDEBUG = 0;
56 #endif
57
58 VISU::Result_var VISU::FindResult (SALOMEDS::SObject_ptr theSObject)
59 {
60   SALOMEDS::SComponent_var aSComponent = theSObject->GetFatherComponent();
61   SALOMEDS::SObject_var aFather = theSObject->GetFather();
62   CORBA::String_var aComponentID (aSComponent->GetID());
63   CORBA::String_var aFatherID    (aFather->GetID());
64   VISU::Result_var aResult;
65   while (strcmp(aComponentID, aFatherID) != 0) {
66     CORBA::Object_var anObject = VISU::SObjectToObject(aFather);
67     if (!CORBA::is_nil(anObject)) {
68       aResult = VISU::Result::_narrow(anObject);
69       if (!aResult->_is_nil()) return aResult;
70     }
71     aFather = aFather->GetFather();
72     aFatherID = aFather->GetID();
73   }
74   return aResult;
75 }
76
77 QString GenerateName (const char* theName)
78 {
79   typedef map<string,int> TNameMap;
80   static TNameMap aMap;
81   TNameMap::const_iterator i = aMap.find(theName);
82   QString tmp;
83   if (i == aMap.end()) {
84     aMap[theName] = 0;
85     tmp = theName;
86   } else {
87     tmp = VISU::GenerateName(theName,++aMap[theName]);
88   }
89   if(MYDEBUG) MESSAGE("GenerateName - "<<tmp<<" from - "<<theName<<"; " <<aMap[theName]);
90   return tmp;
91 }
92
93 QString GenerateFieldName (const string& theName, const string& theUnits)
94 {
95   static QString aName;
96   const string tmp (theUnits.size(),' ');
97   if (theUnits == "" || theUnits == tmp)
98     aName.sprintf("%s, -",theName.c_str());
99   else
100     aName.sprintf("%s, %s",theName.c_str(),theUnits.c_str());
101   aName = aName.simplifyWhiteSpace();
102   return aName.latin1();
103 }
104
105 void CreateReference (SALOMEDS::Study_ptr theStudyDocument,
106                       const string& theFatherEntry, const string& theRefEntry)
107 {
108   SALOMEDS::StudyBuilder_var aStudyBuilder = theStudyDocument->NewBuilder();
109   SALOMEDS::SObject_var aFather = theStudyDocument->FindObjectID(theFatherEntry.c_str());
110   SALOMEDS::SObject_var newObj = aStudyBuilder->NewObject(aFather);
111   SALOMEDS::SObject_var aRefSObj = theStudyDocument->FindObjectID(theRefEntry.c_str());
112   aStudyBuilder->Addreference(newObj,aRefSObj);
113 }
114
115 string GetComponentDataType (SALOMEDS::SObject_ptr theSObject)
116 {
117   SALOMEDS::SComponent_var aCompRefSObj = theSObject->GetFatherComponent();
118   CORBA::String_var aDataType = aCompRefSObj->ComponentDataType();
119   return aDataType.in();
120 }
121
122 //==============================================================================
123
124 const string VISU::Result_i::myComment = "RESULT";
125 const char* VISU::Result_i::GetComment() const { return myComment.c_str();}
126
127 VISU::Result_i::Result_i (SALOMEDS::Study_ptr theStudy,
128                           const ESourceId& theSourceId,
129                           const ECreationId& theCreationId):
130   myStudyDocument(SALOMEDS::Study::_duplicate(theStudy)),
131   myCreationId(theCreationId),
132   mySourceId(theSourceId),
133   myInput(NULL),
134   myIsDone(0)
135 {
136 }
137
138
139 void VISU::Result_i::RemoveFromStudy()
140 {
141   // Remove the result with all presentations and other possible sub-objects
142   VISU::RemoveFromStudy(mySObject,false);
143 }
144
145
146 int
147 VISU::Result_i::
148 IsPossible()
149 {
150   try{
151     float aSize = myInput->GetSize();
152     bool aResult = VISU_PipeLine::CheckAvailableMemory(aSize);
153     MESSAGE("Result_i::IsPossible - CheckAvailableMemory = "<<float(aSize)<<"; aResult = "<<float(aResult));
154     return aResult;
155   }catch(std::exception& exc){
156     INFOS("Follow exception was occured :\n"<<exc.what());
157   }catch(...){
158     INFOS("Unknown exception was occured!");
159   }
160   return 0;
161 }
162
163
164 CORBA::Boolean
165 VISU::Result_i::
166 BuildAll()
167 {
168   if(MYDEBUG) MESSAGE("Result_i::Build - myIsDone = "<<myIsDone);
169   if(myIsDone) return 1;
170   if(!IsPossible()) return 0;
171   try{
172     const VISU::TMeshMap& aMeshMap = myInput->GetMeshMap();
173     VISU::TMeshMap::const_iterator aMeshMapIter = aMeshMap.begin();
174     for(; aMeshMapIter != aMeshMap.end(); aMeshMapIter++){
175       const string& aMeshName = aMeshMapIter->first;
176       const VISU::PMesh aMesh = aMeshMapIter->second;
177       const VISU::TMeshOnEntityMap& aMeshOnEntityMap = aMesh->myMeshOnEntityMap;
178       VISU::TMeshOnEntityMap::const_iterator aMeshOnEntityMapIter;
179       //Import fields
180       aMeshOnEntityMapIter = aMeshOnEntityMap.begin();
181       for(; aMeshOnEntityMapIter != aMeshOnEntityMap.end(); aMeshOnEntityMapIter++){
182         const VISU::TEntity& anEntity = aMeshOnEntityMapIter->first;
183         const VISU::PMeshOnEntity aMeshOnEntity = aMeshOnEntityMapIter->second;
184         const VISU::TFieldMap& aFieldMap = aMeshOnEntity->myFieldMap;
185         VISU::TFieldMap::const_iterator aFieldMapIter = aFieldMap.begin();
186         for(; aFieldMapIter != aFieldMap.end(); aFieldMapIter++){
187           const string& aFieldName = aFieldMapIter->first;
188           const VISU::PField aField = aFieldMapIter->second;
189           const VISU::TValField& aValField = aField->myValField;
190           VISU::TValField::const_iterator aValFieldIter = aValField.begin();
191           for(; aValFieldIter != aValField.end(); aValFieldIter++){
192             int aTimeStamp = aValFieldIter->first;
193             try{
194               myInput->GetTimeStampOnMesh(aMeshName,anEntity,aFieldName,aTimeStamp);
195             }catch(std::exception& exc){
196               INFOS("Follow exception was occured :\n"<<exc.what());
197             }catch(...){
198               INFOS("Unknown exception was occured!!!");
199             }
200           }
201         }
202         //Importing groups
203         const VISU::TGroupMap& aGroupMap = aMesh->myGroupMap;
204         VISU::TGroupMap::const_iterator aGroupMapIter = aGroupMap.begin();
205         for(; aGroupMapIter != aGroupMap.end(); aGroupMapIter++){
206           const string& aGroupName = aGroupMapIter->first;
207           try{
208             myInput->GetMeshOnGroup(aMeshName,aGroupName);
209           }catch(std::exception& exc){
210             INFOS("Follow exception was occured :\n"<<exc.what());
211           }catch(...){
212             INFOS("Unknown exception was occured!!!");
213           }
214         }
215         //Import families
216         const VISU::TFamilyMap& aFamilyMap = aMeshOnEntity->myFamilyMap;
217         VISU::TFamilyMap::const_iterator aFamilyMapIter = aFamilyMap.begin();
218         for(; aFamilyMapIter != aFamilyMap.end(); aFamilyMapIter++){
219           const string& aFamilyName = aFamilyMapIter->first;
220           try{
221             myInput->GetMeshOnEntity(aMeshName,anEntity,aFamilyName);
222           }catch(std::exception& exc){
223             INFOS("Follow exception was occured :\n"<<exc.what());
224           }catch(...){
225             INFOS("Unknown exception was occured!!!");
226           }
227         }
228         //Import mesh on entity
229         try{
230           myInput->GetMeshOnEntity(aMeshName,anEntity);
231         }catch(std::exception& exc){
232           INFOS("Follow exception was occured :\n"<<exc.what());
233         }catch(...){
234           INFOS("Unknown exception was occured!!!");
235         }
236       }
237     }
238     myIsDone = 1;
239   }catch(std::exception& exc){
240     INFOS("Follow exception was occured :\n"<<exc.what());
241   }catch(...){
242     INFOS("Unknown exception was occured!!!");
243   }
244   return myIsDone;
245 }
246
247
248 VISU::Storable*
249 VISU::Result_i::
250 Build(SALOMEDS::SObject_ptr theSObject)
251 {
252   if(MYDEBUG) MESSAGE("Result_i::Build");
253
254   SALOMEDS::StudyBuilder_var aStudyBuilder = myStudyDocument->NewBuilder();
255   aStudyBuilder->NewCommand();  // There is a transaction
256
257   try {
258     const TMeshMap& aMeshMap = myInput->GetMeshMap();
259     if (aMeshMap.empty())
260       throw std::runtime_error("Build - There is no any mesh information in the file !!!");
261
262     mySComponent = FindOrCreateVisuComponent(myStudyDocument);
263     CORBA::String_var aSComponentEntry = mySComponent->GetID(), anIOR(GetID());
264     string aRefFatherEntry = GetRefFatherEntry();
265
266     QString aComment;
267     aComment.sprintf("myComment=%s;myType=%d;myFileName=%s;myInitFileName=%s",
268                      GetComment(), VISU::TRESULT, myFileInfo.filePath().latin1(),
269                      myInitFileName.c_str()); // Restoring of Python dump
270     string aResultEntry =
271       CreateAttributes(myStudyDocument, aSComponentEntry, aRefFatherEntry.c_str(),
272                        anIOR, myName.c_str(), "", aComment.latin1(), true);
273
274     mySObject = myStudyDocument->FindObjectID(aResultEntry.c_str());
275     if (mySObject->_is_nil())
276       throw std::runtime_error("Build - There is no SObject for the Result !!!");
277
278     if (!CORBA::is_nil(theSObject)) {
279       CORBA::String_var aString = theSObject->GetID();
280       CreateReference(myStudyDocument, aResultEntry, aString.in());
281     }
282
283     TMeshMap::const_iterator aMeshMapIter = aMeshMap.begin();
284     for (; aMeshMapIter != aMeshMap.end(); aMeshMapIter++) {
285       const string& aMeshName = aMeshMapIter->first;
286       const VISU::PMesh aMesh = aMeshMapIter->second;
287       aComment.sprintf("myComment=MESH;myName=%s;myDim=%d",
288                        aMeshName.c_str(), aMesh->myDim);
289       string aMeshEntry =
290         CreateAttributes(myStudyDocument, aResultEntry.c_str(), aRefFatherEntry.c_str(),
291                          "", aMeshName.c_str(), "", aComment.latin1(), true);
292
293       const VISU::TMeshOnEntityMap& aMeshOnEntityMap = aMesh->myMeshOnEntityMap;
294       if (aMeshOnEntityMap.empty()) continue;
295
296       aComment.sprintf("myComment=FAMILIES;myMeshName=%s", aMeshName.c_str());
297       string aSubMeshesEntry =
298         CreateAttributes(myStudyDocument, aMeshEntry.c_str(), aRefFatherEntry.c_str(),
299                          "", "Families", "", aComment.latin1(), true);
300
301       //Import entities and according families
302       typedef std::map<std::string,std::string> TComment2EntryMap;
303       typedef std::map<VISU::TEntity,std::string> TEntity2EntryMap;
304       TComment2EntryMap aComment2EntryMap;
305       TEntity2EntryMap aEntity2EntryMap;
306
307       VISU::TMeshOnEntityMap::const_iterator aMeshOnEntityMapIter = aMeshOnEntityMap.begin();
308       for (; aMeshOnEntityMapIter != aMeshOnEntityMap.end(); aMeshOnEntityMapIter++) {
309         const VISU::TEntity& anEntity = aMeshOnEntityMapIter->first;
310         aComment.sprintf("myComment=ENTITY;myType=%d;myMeshName=%s;myId=%d",
311                          VISU::TENTITY, aMeshName.c_str(), anEntity);
312         string anEntityName;
313         switch (anEntity) {
314         case VISU::NODE_ENTITY : anEntityName = "onNodes"; break;
315         case VISU::EDGE_ENTITY : anEntityName = "onEdges"; break;
316         case VISU::FACE_ENTITY : anEntityName = "onFaces"; break;
317         case VISU::CELL_ENTITY : anEntityName = "onCells"; break;
318         default:
319           throw std::runtime_error("Build >> Value of entity is incorrect!");
320         }
321         aEntity2EntryMap[anEntity] = CreateAttributes
322           (myStudyDocument, aSubMeshesEntry.c_str(), aRefFatherEntry.c_str(),
323            "", anEntityName.c_str(), "", aComment.latin1(), true);
324
325         const VISU::PMeshOnEntity aMeshOnEntity = aMeshOnEntityMapIter->second;
326         const VISU::TFamilyMap& aFamilyMap = aMeshOnEntity->myFamilyMap;
327         VISU::TFamilyMap::const_iterator aFamilyMapIter = aFamilyMap.begin();
328         for (; aFamilyMapIter != aFamilyMap.end(); aFamilyMapIter++) {
329           const string& aFamilyName = aFamilyMapIter->first;
330           aComment.sprintf("myComment=FAMILY;myType=%d;myMeshName=%s;myEntityId=%d;myName=%s",
331                            VISU::TFAMILY, aMeshName.c_str(), anEntity, aFamilyName.c_str());
332           aComment2EntryMap[aComment.latin1()] =
333             CreateAttributes(myStudyDocument, aEntity2EntryMap[anEntity].c_str(), aRefFatherEntry.c_str(),
334                              "", aFamilyName.c_str(), "", aComment.latin1(), true);
335         }
336       }
337
338       //Importing groups
339       const VISU::TGroupMap& aGroupMap = aMesh->myGroupMap;
340       if (aGroupMap.size() > 0) {
341         aComment.sprintf("myComment=GROUPS;myMeshName=%s", aMeshName.c_str());
342         string aGroupsEntry =
343           CreateAttributes(myStudyDocument, aMeshEntry.c_str(), aRefFatherEntry.c_str(),
344                            "", "Groups", "", aComment.latin1(), true);
345
346         VISU::TGroupMap::const_iterator aGroupMapIter = aGroupMap.begin();
347         for (; aGroupMapIter != aGroupMap.end(); aGroupMapIter++) {
348           const string& aGroupName = aGroupMapIter->first;
349           aComment.sprintf("myComment=GROUP;myType=%d;myMeshName=%s;myName=%s",
350                            VISU::TGROUP, aMeshName.c_str(), aGroupName.c_str());
351           string aGroupEntry =
352             CreateAttributes(myStudyDocument, aGroupsEntry.c_str(), aRefFatherEntry.c_str(),
353                              "", aGroupName.c_str(), "", aComment.latin1(), true);
354
355           const VISU::PGroup aGroup = aGroupMapIter->second;
356           const VISU::TFamilyAndEntitySet& aFamilyAndEntitySet = aGroup->myFamilyAndEntitySet;
357           VISU::TFamilyAndEntitySet::const_iterator aFamilyAndEntitySetIter = aFamilyAndEntitySet.begin();
358           for (; aFamilyAndEntitySetIter != aFamilyAndEntitySet.end(); aFamilyAndEntitySetIter++) {
359             const VISU::TFamilyAndEntity& aFamilyAndEntity = *aFamilyAndEntitySetIter;
360             const string& aFamilyName = aFamilyAndEntity.first;
361             const VISU::TEntity& anEntity = aFamilyAndEntity.second;
362             aComment.sprintf("myComment=FAMILY;myType=%d;myMeshName=%s;myEntityId=%d;myName=%s",
363                              VISU::TFAMILY, aMeshName.c_str(), anEntity, aFamilyName.c_str());
364             if (aComment2EntryMap.count(aComment.latin1()) > 0)
365               CreateReference(myStudyDocument, aGroupEntry, aComment2EntryMap[aComment.latin1()]);
366           }
367         }
368       }
369
370       //Import fields
371       string aFieldsEntry;
372       bool isFieldEntryCreated = 0;
373       aMeshOnEntityMapIter = aMeshOnEntityMap.begin();
374       for (; aMeshOnEntityMapIter != aMeshOnEntityMap.end(); aMeshOnEntityMapIter++) {
375         const VISU::TEntity& anEntity = aMeshOnEntityMapIter->first;
376         const VISU::PMeshOnEntity aMeshOnEntity = aMeshOnEntityMapIter->second;
377         const VISU::TFieldMap& aFieldMap = aMeshOnEntity->myFieldMap;
378         VISU::TFieldMap::const_iterator aFieldMapIter = aFieldMap.begin();
379         for (; aFieldMapIter != aFieldMap.end(); aFieldMapIter++) {
380           if (!isFieldEntryCreated) {
381             aComment.sprintf("myComment=FIELDS;myMeshName=%s", aMeshName.c_str());
382             aFieldsEntry =
383               CreateAttributes(myStudyDocument, aMeshEntry.c_str(), aRefFatherEntry.c_str(),
384                                "", "Fields", "", aComment.latin1(), true);
385             isFieldEntryCreated = true;
386           }
387           const string& aFieldName = aFieldMapIter->first;
388           const VISU::PField aField = aFieldMapIter->second;
389           const VISU::TValField& aValField = aField->myValField;
390           QString aFieldNameWithUnit = ::GenerateFieldName(aFieldName,aField->myUnitNames[0]);
391           aComment.sprintf("myComment=FIELD;myType=%d;myMeshName=%s;myEntityId=%d;myName=%s;"
392                            "myNbTimeStamps=%d;myNumComponent=%d",
393                            VISU::TFIELD, aMeshName.c_str(), anEntity, aFieldName.c_str(),
394                            aValField.size(), aField->myNbComp);
395           string aFieldEntry =
396             CreateAttributes(myStudyDocument, aFieldsEntry.c_str(), aRefFatherEntry.c_str(),
397                              "", aFieldNameWithUnit.latin1(), "", aComment.latin1(), true);
398           CreateReference(myStudyDocument, aFieldEntry, aEntity2EntryMap[anEntity]);
399
400           VISU::TValField::const_iterator aValFieldIter = aValField.begin();
401           for (; aValFieldIter != aValField.end(); aValFieldIter++) {
402             int aTimeStamp = aValFieldIter->first;
403             const VISU::PValForTime aValForTime = aValFieldIter->second;
404             aComment.sprintf("myComment=TIMESTAMP;myType=%d;myMeshName=%s;myEntityId=%d;"
405                              "myFieldName=%s;myTimeStampId=%d;myNumComponent=%d",
406                              VISU::TTIMESTAMP, aMeshName.c_str(), anEntity,
407                              aFieldName.c_str(), aTimeStamp, aField->myNbComp);
408             string aTimeStampId = VISU_Convertor::GenerateName(aValForTime->myTime);
409             CreateAttributes(myStudyDocument, aFieldEntry.c_str(), aRefFatherEntry.c_str(),
410                              "", aTimeStampId.c_str(), "", aComment.latin1(), true);
411           }
412         }
413       }
414     }
415     bool isBuildAll = VISU::GetResourceMgr()->booleanValue("VISU", "full_med_loading", false);
416     if (isBuildAll) BuildAll();
417   } catch(std::exception& exc) {
418     INFOS("Follow exception was occured :\n"<<exc.what());
419     return NULL;
420   } catch(...) {
421     INFOS("Unknown exception was occured!!!");
422     return NULL;
423   }
424   aStudyBuilder->CommitCommand();
425   return this;
426 }
427
428
429 VISU::Storable*
430 VISU::Result_i::
431 Create(const char* theFileName)
432 {
433   try{
434     myFileInfo.setFile(theFileName);
435     myInitFileName = myFileInfo.filePath().latin1();
436     myName = ::GenerateName(myFileInfo.fileName()).latin1();
437     if(mySourceId == eRestoredFile){
438       std::string aTmpDir(SALOMEDS_Tool::GetTmpDir());
439       static QString aCommand;
440       aCommand.sprintf("cp %s %s",myFileInfo.absFilePath().latin1(),aTmpDir.c_str());
441       if(system(aCommand) == -1){
442         MESSAGE("Create - Can't execute the command :"<<aCommand);
443         return NULL;
444       }
445       if(MYDEBUG) MESSAGE("Result_i::Create - aCommand = "<<aCommand);
446       myFileInfo.setFile(QString(aTmpDir.c_str()) + myFileInfo.fileName());
447     }
448     myInput = CreateConvertor(myFileInfo.absFilePath().latin1());
449     if(!myInput)
450       throw std::runtime_error("Create - Cannot create a Convertor for this file!!!");
451     return Build();
452   }catch(std::exception& exc){
453     INFOS("Follow exception was occured :\n"<<exc.what());
454   }catch(...){
455     INFOS("Unknown exception was occured!!!");
456   }
457   return NULL;
458 }
459
460
461 VISU::Storable*
462 VISU::Result_i::
463 Create(SALOMEDS::SObject_ptr theMedSObject)
464 {
465   if(MYDEBUG)  MESSAGE("Result_i::Create MedObject from SALOMEDS::SObject_ptr");
466   try{
467     myInput = CreateMEDConvertor(theMedSObject);
468     if(myInput == NULL)
469       return NULL;
470
471     string aCompDataType = GetComponentDataType(theMedSObject);
472     myFileInfo.setFile(aCompDataType.c_str());
473     myInitFileName = aCompDataType;
474
475     myName = ::GenerateName("aResult").latin1();
476
477     VISU::Storable* aStorable = Build(theMedSObject);
478     return aStorable;
479   }catch(std::exception& exc){
480     INFOS("Follow exception was occured :\n"<<exc.what());
481   }catch(...){
482     INFOS("Unknown exception was occured!!!");
483   }
484   return NULL;
485 }
486
487 VISU::Storable*
488 VISU::Result_i::
489 Create(SALOME_MED::FIELD_ptr theField)
490 {
491   if(MYDEBUG)  MESSAGE("Result_i::Create MedObject from SALOME_MED::FIELD_ptr");
492   try{
493     myInput = CreateMEDFieldConvertor(theField);
494     if(myInput == NULL)
495       return NULL;
496
497     string aCompDataType = "MED";
498     myFileInfo.setFile(aCompDataType.c_str());
499     myInitFileName = aCompDataType;
500
501     myName = ::GenerateName("aResult").latin1();
502
503     CORBA::String_var anIOR = myStudyDocument->ConvertObjectToIOR(theField);
504     SALOMEDS::SObject_var aFieldSObject = myStudyDocument->FindObjectIOR(anIOR);
505
506     VISU::Storable* aStorable = Build(aFieldSObject);
507     return aStorable;
508   }catch(std::exception& exc){
509     INFOS("Follow exception was occured :\n"<<exc.what());
510   }catch(...){
511     INFOS("Unknown exception was occured!!!");
512   }
513   return NULL;
514 }
515
516
517 VISU::Storable*
518 VISU::Result_i::
519 Restore(SALOMEDS::SObject_ptr theSObject,
520         const Storable::TRestoringMap& theMap,
521         const string& thePrefix)
522 {
523   if(MYDEBUG) MESSAGE("Result_i::Restore - " << thePrefix);
524   try {
525     mySObject = SALOMEDS::SObject::_duplicate(theSObject);
526     myStudyDocument = mySObject->GetStudy();
527     mySComponent = mySObject->GetFatherComponent();
528     myName = VISU::Storable::FindValue(theMap, "myName").latin1();
529     myInitFileName = VISU::Storable::FindValue(theMap, "myInitFileName").latin1();
530
531     SALOMEDS::SObject_var aRefSObj, aTargetRefSObj;
532     if (mySObject->FindSubObject(1, aRefSObj) &&
533         aRefSObj->ReferencedObject(aTargetRefSObj)) {
534       if(MYDEBUG) MESSAGE("Result_i::GetInput - There is some reference.");
535       SALOMEDS::SComponent_var aCompRefSObj = aTargetRefSObj->GetFatherComponent();
536       CORBA::String_var aDataType = aCompRefSObj->ComponentDataType();
537       myFileInfo.setFile(aDataType.in());
538       if(MYDEBUG) MESSAGE("Result_i::GetInput - aDataType = " << aDataType);
539       Engines::Component_var aEngComp =
540         Base_i::myEnginesLifeCycle->FindOrLoad_Component("FactoryServer", aDataType.in());
541       if (CORBA::is_nil(aEngComp))
542         throw std::runtime_error("Restore - There is no aEngComp for the aDataType !!!");
543       SALOMEDS::StudyBuilder_var aStudyBuilder = myStudyDocument->NewBuilder();
544       SALOMEDS::Driver_var aDriver = SALOMEDS::Driver::_narrow(aEngComp);
545       aStudyBuilder->LoadWith(aCompRefSObj, aDriver);
546       if (strcmp(aDataType, "MED") == 0) {
547         // create field or MED converter
548         CORBA::Object_var aMedObject = VISU::SObjectToObject(aTargetRefSObj);
549         SALOME_MED::FIELD_var aField = SALOME_MED::FIELD::_narrow(aMedObject);
550         if(!CORBA::is_nil(aField))
551           myInput = CreateMEDFieldConvertor(aField);
552         else
553           myInput = CreateMEDConvertor(aTargetRefSObj);
554       }
555       else
556         throw std::runtime_error("GetInput - There is no convertor for the aDataType !!!");
557     } else {
558       myFileInfo.setFile(thePrefix.c_str());
559
560       string aStudyPrefix ("");
561       if (IsMultifile())
562         aStudyPrefix = SALOMEDS_Tool::GetNameFromPath(myStudyDocument->URL());
563       if (!myFileInfo.isFile()) {
564         string aFileName = thePrefix + aStudyPrefix + "_" + myName;
565         myFileInfo.setFile(aFileName.c_str());
566       }
567       if(MYDEBUG)
568         MESSAGE("Result_i::Restore - aFileName = " << myFileInfo.filePath() << "; " << myFileInfo.isFile());
569
570       const char* aPathLatin = myFileInfo.filePath().latin1();
571       if (HDFascii::isASCII(aPathLatin)) {
572         MESSAGE("ConvertFromASCIIToHDF(" << aPathLatin << ")");
573         char* aResultPath = HDFascii::ConvertFromASCIIToHDF(aPathLatin);
574         MESSAGE("ConvertFromASCIIToHDF() DONE : " << aResultPath);
575         char* aHDFFileName = new char[strlen(aResultPath) + 19];
576         sprintf(aHDFFileName, "%shdf_from_ascii.hdf", aResultPath);
577
578         if (IsMultifile()) { // set this file as new - temporary
579           static QString aCommand;
580           aCommand.sprintf("mv %s %s%s",aHDFFileName, aResultPath, myFileInfo.baseName().latin1());
581           if (system(aCommand) == -1) {
582             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - Can't execute the command :" << aCommand);
583             return NULL;
584           } else {
585             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - " << aCommand);
586           }
587           myFileInfo.setFile(QString(aResultPath) + QString(myFileInfo.baseName().latin1()));
588         } else { // change current temporary file to the new: with hdf-format
589           static QString aCommand;
590           aCommand.sprintf("mv %s %s\0",aHDFFileName, myFileInfo.filePath().latin1());
591           if (system(aCommand.latin1()) == -1) {
592             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - Can't execute the command :" << aCommand);
593             return NULL;
594           } else {
595             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - " << aCommand);
596           }
597           SALOMEDS::ListOfFileNames_var anEmptyList = new SALOMEDS::ListOfFileNames;
598           SALOMEDS_Tool::RemoveTemporaryFiles(aResultPath, anEmptyList.in(), true);
599         }
600         mySourceId = eRestoredFile;
601         delete(aResultPath);
602         delete(aHDFFileName);
603       } else if (!IsMultifile()) {
604         mySourceId = eRestoredFile;
605       } else {
606         mySourceId = eFile;
607       }
608       if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - mySourceId = " << mySourceId);
609       myInput = CreateConvertor(myFileInfo.filePath().latin1());
610       QString aComment;
611       aComment.sprintf("myComment=%s;myType=%d;myFileName=%s;myInitFileName=%s",
612                        GetComment(), VISU::TRESULT, myFileInfo.filePath().latin1(),
613                        myInitFileName.c_str()); // Restoring of Python dump
614       SALOMEDS::GenericAttribute_var anAttr;
615       if (!theSObject->FindAttribute(anAttr, "AttributeComment"))
616         throw std::runtime_error("Build - There is no AttributeComment for the SObject !!!");
617       SALOMEDS::AttributeComment_var aCmnt = SALOMEDS::AttributeComment::_narrow(anAttr);
618       aCmnt->SetValue(aComment.latin1());
619     }
620     bool isBuildAll = VISU::GetResourceMgr()->booleanValue("VISU", "full_med_loading", false);
621     if (isBuildAll)
622       BuildAll();
623     return this;
624   } catch(std::exception& exc) {
625     INFOS("Follow exception was occured :\n"<<exc.what());
626   } catch(...) {
627     INFOS("Unknown exception was occured!!!");
628   }
629   return NULL;
630 }
631
632 VISU::Result_i::TInput* VISU::Result_i::GetInput() {
633   return myInput;
634 }
635
636 void VISU::Result_i::ToStream(std::ostringstream& theStr){
637   if(MYDEBUG) MESSAGE(GetComment());
638   Storable::DataToStream(theStr,"myName",myName.c_str());
639   Storable::DataToStream(theStr,"myInitFileName",myInitFileName.c_str());
640   Storable::DataToStream(theStr,"myCreationId",myCreationId);
641 }
642
643 VISU::Storable*
644 VISU::Result_i::Restore(SALOMEDS::SObject_ptr theSObject,
645                         const string& thePrefix,
646                         const Storable::TRestoringMap& theMap)
647 {
648   SALOMEDS::Study_var aStudy = theSObject->GetStudy();
649
650   ECreationId aCreationId = ECreationId(Storable::FindValue(theMap,"myCreationId").toInt());
651   ESourceId aSourceId = eRestoredFile;
652   if(aCreationId == eImportMed || aCreationId == eImportMedField)
653     aSourceId = eRestoredComponent;
654
655   VISU::Result_i* pResult = new VISU::Result_i(aStudy,aSourceId,aCreationId);
656   if (pResult == NULL)
657     return NULL;
658
659   return pResult->Restore(theSObject,theMap,thePrefix);
660 }
661
662 string VISU::Result_i::GetRefFatherEntry() {
663   //return QAD_Application::getDesktop()->getActiveStudy()->getActiveStudyFrame()->entry();
664   return "";
665 }
666
667 string VISU::Result_i::GetEntry(){
668   CORBA::String_var anEntry = mySObject->GetID();
669   return string(anEntry);
670 }
671
672 const SALOMEDS::SObject_var& VISU::Result_i::GetSObject() const { return mySObject;}
673 const SALOMEDS::Study_var& VISU::Result_i::GetStudyDocument() const { return myStudyDocument;}
674 const SALOMEDS::SComponent_var& VISU::Result_i::GetSComponent() const { return mySComponent;}
675 std::string VISU::Result_i::GetEntry(const std::string& theComment)
676 {
677   return FindEntryWithComment(myStudyDocument,GetEntry().c_str(),theComment.c_str());
678 }
679
680 VISU::Result_i::~Result_i()
681 {
682   MESSAGE("Result_i::~Result_i() - this = "<<this);
683   if (mySourceId == eRestoredFile) {
684     static QString aCommand;
685     aCommand.sprintf("rm %s",myFileInfo.filePath().latin1());
686     MESSAGE("Result_i::~Result_i - system("<<aCommand<<") = "<<system(aCommand));
687     aCommand.sprintf("rmdir --ignore-fail-on-non-empty %s",myFileInfo.dirPath().latin1());
688     MESSAGE("Result_i::~Result_i - system("<<aCommand<<") = "<<system(aCommand));
689   }
690   if(myInput) delete myInput;
691 }
692
693 //=======================================================================
694 //function : GetAxisInfo
695 //purpose  :
696 //=======================================================================
697 const vector< float >* Result_i::GetAxisInfo(const string& theMeshName,
698                                              TAxis         theAxis,
699                                              gp_Dir&       thePlaneNormal)
700 {
701   const vector< float >* components = NULL;
702
703   if ( theAxis < AXIS_X || theAxis > AXIS_Z ) {
704     MESSAGE(" Bad axis index " << theAxis );
705     return components;
706   }
707
708   map< string, TGridInfo >::iterator name_info;
709   name_info = myMeshName2GridInfoMap.find( theMeshName );
710   TGridInfo * gInfo = 0;
711
712   if ( name_info != myMeshName2GridInfoMap.end() )
713   {
714     gInfo = & name_info->second;
715   }
716   else if ( myInput && IsPossible() && theAxis >= AXIS_X && theAxis <= AXIS_Z )
717   {
718     // check presence of theMeshName
719     const VISU::TMeshMap& meshMap = myInput->GetMeshMap();
720     if ( meshMap.find( theMeshName ) == meshMap.end() ) {
721       MESSAGE("No mesh named " << theMeshName );
722       return components;
723     }
724     VISU_Convertor::TOutput* vtkMesh = myInput->GetMeshOnEntity (theMeshName,
725                                                                  CELL_ENTITY);
726     if ( !vtkMesh || vtkMesh->GetNumberOfCells() == 0 ) {
727       MESSAGE( "No cells in the mesh: " << theMeshName );
728       return components;
729     }
730
731     // define axis directions and min cell size in each direction
732     const int nbAxes = 3;
733     int iAx;
734     gp_Vec axDirs[ nbAxes ];
735     float minSize[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
736     bool axesComputed = false;
737     for ( vtkIdType iCell = 0; iCell < vtkMesh->GetNumberOfCells(); ++iCell )
738     {
739       vtkCell* cell = vtkMesh->GetCell( iCell );
740       int nbPnt = cell->GetNumberOfPoints();
741       if ( nbPnt != 8 )
742         continue;
743       vtkPoints * points = cell->GetPoints();
744       float* coords[ 4 ];
745       coords[0] = points->GetPoint( 0 );
746       coords[1] = points->GetPoint( 1 );
747       coords[2] = points->GetPoint( 3 );
748       coords[3] = points->GetPoint( 4 );
749       gp_Pnt p0( coords[0][0], coords[0][1], coords[0][2] );
750       for ( iAx = 0; iAx < nbAxes; ++iAx )
751       {
752         float* coo = coords[ iAx + 1 ];
753         gp_Pnt p( coo[0], coo[1], coo[2] );
754         // min size
755         float size = p0.SquareDistance( p );
756         if ( size > FLT_MIN && size < minSize[ iAx ] )
757           minSize[ iAx ] = size;
758         // axis direction
759         if ( !axesComputed ) {
760           gp_Vec dir( p0, p );
761           if ( dir.SquareMagnitude() <= DBL_MIN )
762             break;
763           axDirs[ iAx ] = dir;
764         }
765       }
766       if ( iAx == nbAxes )
767         axesComputed = true;
768     }
769     if ( !axesComputed ) {
770       MESSAGE("No good hexahedrons in the mesh: " << theMeshName );
771       return components;
772     }
773
774     // compute axes dirs
775     gInfo = & myMeshName2GridInfoMap[ theMeshName ];
776     for ( iAx = 0; iAx < nbAxes; ++iAx )
777     {
778       int iPrev = ( iAx == 0 ) ? 2 : iAx - 1;
779       int iNext = ( iAx == 2 ) ? 0 : iAx + 1;
780       gInfo->myAxis[ iAx ] = axDirs[ iPrev ] ^ axDirs[ iNext ];
781     }
782
783     // get and sort intermediate component values - projections of nodes
784     // on axis direction; define bnd box
785     set< float > comps[ 3 ];
786     Bnd_Box box;
787     vtkPoints * points = vtkMesh->GetPoints();
788     vtkIdType iP, nbP = vtkMesh->GetNumberOfPoints();
789     for ( iP = 0; iP < nbP; ++iP )
790     {
791       float* coo = points->GetPoint( iP );
792       gp_Pnt p( coo[0], coo[1], coo[2] );
793       box.Add( p );
794       for ( iAx = 0; iAx < nbAxes; ++iAx ) {
795         const gp_Dir& dir = gInfo->myAxis[ iAx ];
796         float dot = dir.XYZ() * p.XYZ();
797         comps[ iAx ].insert( dot );
798       }
799     }
800
801     // find a range of projections of bnd box corners on each axis
802     float range[3], firstValue[3];
803     double x[2],y[2],z[2];
804     box.Get(x[0],y[0],z[0],x[1],y[1],z[1]);
805     for ( iAx = 0; iAx < nbAxes; ++iAx ) {
806       set< float > bndComps;
807       const gp_Dir& dir = gInfo->myAxis[ iAx ];
808       for ( int iX = 0; iX < 2; ++iX ) {
809         for ( int iY = 0; iY < 2; ++iY ) {
810           for ( int iZ = 0; iZ < 2; ++iZ ) {
811             gp_Pnt p( x[ iX ], y[ iY ], z[ iZ ] );
812             float dot = dir.XYZ() * p.XYZ();
813             bndComps.insert( dot );
814           }
815         }
816       }
817       firstValue[ iAx ] = *bndComps.begin();
818       range[ iAx ] = *bndComps.rbegin() - *bndComps.begin();
819     }
820
821     // compute component values
822     for ( iAx = 0; iAx < nbAxes; ++iAx )
823     {
824       list< float > values;
825       int nbVals = 0;
826       set< float >& comp = comps[ iAx ];
827       set< float >::iterator val = comp.begin();
828       float bnd = -1., rng = range[ iAx ], first = firstValue[ iAx ];
829       float tol = 0.1 * sqrt( minSize[ iAx ]) / rng;
830       for ( ; val != comp.end(); ++val ) {
831         float value = ( *val - first ) / rng;
832         if ( value > bnd ) {
833           values.push_back( value );
834           bnd = value + tol;
835           nbVals++;
836         }
837       }
838       // store values in gInfo
839       vector< float >& myComp = gInfo->myComponets[ iAx ];
840       myComp.resize( nbVals );
841       list< float >::iterator v = values.begin();
842       for ( int i = 0; v != values.end(); ++v )
843         myComp[ i++ ] = *v;
844     }
845   }
846
847   // set return values
848   if ( gInfo )
849   {
850     thePlaneNormal = gInfo->myAxis[ theAxis ];
851     components = & gInfo->myComponets[ theAxis ];
852   }
853
854   return components;
855 }