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