]> SALOME platform Git repositories - modules/visu.git/blob - src/VISU_I/VISU_Result_i.cc
Salome HOME
Preferences for VISU module.
[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     bool isBuildAll = VISU::GetResourceMgr()->booleanValue("VISU", "full_med_loading", false);
437     if(isBuildAll) BuildAll();
438   }catch(std::exception& exc){
439     INFOS("Follow exception was occured :\n"<<exc.what());
440     return NULL;
441   }catch(...){
442     INFOS("Unknown exception was occured!!!");
443     return NULL;
444   }
445   aStudyBuilder->CommitCommand();
446   return this;
447 }
448
449
450 VISU::Storable*
451 VISU::Result_i::
452 Create(const char* theFileName)
453 {
454   try{
455     myFileInfo.setFile(theFileName);
456     myInitFileName = myFileInfo.filePath().latin1();
457     myName = ::GenerateName(myFileInfo.fileName()).latin1();
458     if(mySourceId == eRestoredFile){
459       std::string aTmpDir(SALOMEDS_Tool::GetTmpDir());
460       static QString aCommand;
461       aCommand.sprintf("cp %s %s",myFileInfo.absFilePath().latin1(),aTmpDir.c_str());
462       if(system(aCommand) == -1){
463         MESSAGE("Create - Can't execute the command :"<<aCommand);
464         return NULL;
465       }
466       if(MYDEBUG) MESSAGE("Result_i::Create - aCommand = "<<aCommand);
467       myFileInfo.setFile(QString(aTmpDir.c_str()) + myFileInfo.fileName());
468     }
469     myInput = CreateConvertor(myFileInfo.absFilePath().latin1());
470     if(!myInput)
471       throw std::runtime_error("Create - Cannot create a Convertor for this file!!!"); return Build();
472   }catch(std::exception& exc){
473     INFOS("Follow exception was occured :\n"<<exc.what());
474   }catch(...){
475     INFOS("Unknown exception was occured!!!");
476   }
477   return NULL;
478 }
479
480
481 VISU::Storable*
482 VISU::Result_i::
483 Create(SALOMEDS::SObject_ptr theMedSObject)
484 {
485   if(MYDEBUG)  MESSAGE("Result_i::Create MedObject from SALOMEDS::SObject_ptr");
486   try{
487     myInput = CreateMEDConvertor(theMedSObject);
488     if(myInput == NULL)
489       return NULL;
490
491     string aCompDataType = GetComponentDataType(theMedSObject);
492     myFileInfo.setFile(aCompDataType.c_str());
493     myInitFileName = aCompDataType;
494
495     myName = ::GenerateName("aResult").latin1();
496
497     VISU::Storable* aStorable = Build(theMedSObject);
498     return aStorable;
499   }catch(std::exception& exc){
500     INFOS("Follow exception was occured :\n"<<exc.what());
501   }catch(...){
502     INFOS("Unknown exception was occured!!!");
503   }
504   return NULL;
505 }
506
507 VISU::Storable*
508 VISU::Result_i::
509 Create(SALOME_MED::FIELD_ptr theField)
510 {
511   if(MYDEBUG)  MESSAGE("Result_i::Create MedObject from SALOME_MED::FIELD_ptr");
512   try{
513     myInput = CreateMEDFieldConvertor(theField);
514     if(myInput == NULL)
515       return NULL;
516
517     string aCompDataType = "MED";
518     myFileInfo.setFile(aCompDataType.c_str());
519     myInitFileName = aCompDataType;
520
521     myName = ::GenerateName("aResult").latin1();
522
523     CORBA::String_var anIOR = myStudyDocument->ConvertObjectToIOR(theField);
524     SALOMEDS::SObject_var aFieldSObject = myStudyDocument->FindObjectIOR(anIOR);
525
526     VISU::Storable* aStorable = Build(aFieldSObject);
527     return aStorable;
528   }catch(std::exception& exc){
529     INFOS("Follow exception was occured :\n"<<exc.what());
530   }catch(...){
531     INFOS("Unknown exception was occured!!!");
532   }
533   return NULL;
534 }
535
536
537 VISU::Storable*
538 VISU::Result_i::
539 Restore(SALOMEDS::SObject_ptr theSObject,
540         const Storable::TRestoringMap& theMap,
541         const string& thePrefix)
542 {
543   if(MYDEBUG)  MESSAGE("Result_i::Restore - "<<thePrefix);
544   try{
545     mySObject = SALOMEDS::SObject::_duplicate(theSObject);
546     myStudyDocument = mySObject->GetStudy();
547     mySComponent = mySObject->GetFatherComponent();
548     myName = VISU::Storable::FindValue(theMap,"myName").latin1();
549     myInitFileName = VISU::Storable::FindValue(theMap,"myInitFileName").latin1();
550     SALOMEDS::SObject_var aRefSObj, aTargetRefSObj;
551     if(mySObject->FindSubObject(1,aRefSObj) && aRefSObj->ReferencedObject(aTargetRefSObj)){
552       if(MYDEBUG)  MESSAGE("Result_i::GetInput - There is some reference.");
553       SALOMEDS::SComponent_var aCompRefSObj = aTargetRefSObj->GetFatherComponent();
554       CORBA::String_var aDataType = aCompRefSObj->ComponentDataType();
555       myFileInfo.setFile(aDataType.in());
556       if(MYDEBUG)  MESSAGE("Result_i::GetInput - aDataType = "<<aDataType);
557       Engines::Component_var aEngComp = Base_i::myEnginesLifeCycle->FindOrLoad_Component("FactoryServer", aDataType.in());
558       if (CORBA::is_nil(aEngComp))
559         throw std::runtime_error("Restore - There is no aEngComp for the aDataType !!!");
560       SALOMEDS::StudyBuilder_var  aStudyBuilder = myStudyDocument->NewBuilder();
561       SALOMEDS::Driver_var aDriver = SALOMEDS::Driver::_narrow(aEngComp);
562       aStudyBuilder->LoadWith(aCompRefSObj,aDriver);
563       if(strcmp(aDataType,"MED") == 0)
564         myInput = CreateMEDConvertor(aTargetRefSObj);
565       else
566         throw std::runtime_error("GetInput - There is no convertor for the aDataType !!!");
567     }else{
568       myFileInfo.setFile(thePrefix.c_str());
569
570       string aStudyPrefix("");
571       if (IsMultifile()) aStudyPrefix = (SALOMEDS_Tool::GetNameFromPath(myStudyDocument->URL()));
572       if(!myFileInfo.isFile()){
573         string aFileName = thePrefix + aStudyPrefix + "_" + myName;
574         myFileInfo.setFile(aFileName.c_str());
575       }
576       if(MYDEBUG)
577         MESSAGE("Result_i::Restore - aFileName = "<<myFileInfo.filePath()<<"; "<<myFileInfo.isFile());
578
579       if (HDFascii::isASCII(myFileInfo.filePath().latin1())) {
580         char* aResultPath = HDFascii::ConvertFromASCIIToHDF(myFileInfo.filePath().latin1());
581         char* aHDFFileName = new char[strlen(aResultPath) + 19];
582         sprintf(aHDFFileName, "%shdf_from_ascii.hdf", aResultPath);
583
584         if (IsMultifile()) { // set this file as new - temporary
585           static QString aCommand;
586           aCommand.sprintf("mv %s %s%s",aHDFFileName, aResultPath, myFileInfo.baseName().latin1());
587           if(system(aCommand) == -1){
588             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - Can't execute the command :"<<aCommand);
589             return NULL;
590           } else if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - "<<aCommand);
591           myFileInfo.setFile(QString(aResultPath)+QString(myFileInfo.baseName().latin1()));
592         } else { // change current temporary file to the new: with hdf-format
593           static QString aCommand;
594           aCommand.sprintf("mv %s %s\0",aHDFFileName, myFileInfo.filePath().latin1());
595           if(system(aCommand.latin1()) == -1) {
596             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - Can't execute the command :"<<aCommand);
597             return NULL;
598           } else if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - "<<aCommand);
599           SALOMEDS::ListOfFileNames_var anEmptyList = new SALOMEDS::ListOfFileNames;
600           SALOMEDS_Tool::RemoveTemporaryFiles(aResultPath, anEmptyList.in(), true);
601         }
602         mySourceId = eRestoredFile;
603         delete(aResultPath);
604         delete(aHDFFileName);
605       } else if (!IsMultifile())
606         mySourceId = eRestoredFile;
607       else
608         mySourceId = eFile;
609       if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - mySourceId = "<<mySourceId);
610       myInput = CreateConvertor(myFileInfo.filePath().latin1());
611       QString aComment;
612       aComment.sprintf("myComment=%s;myType=%d;myFileName=%s;myInitFileName=%s",
613                        GetComment(),VISU::TRESULT,myFileInfo.filePath().latin1(),
614                        myInitFileName.c_str()); // Restoring of Python dump
615       SALOMEDS::GenericAttribute_var anAttr;
616       if(!theSObject->FindAttribute(anAttr, "AttributeComment"))
617         throw std::runtime_error("Build - There is no AttributeComment for the SObject !!!");
618       SALOMEDS::AttributeComment_var aCmnt = SALOMEDS::AttributeComment::_narrow(anAttr);
619       aCmnt->SetValue(aComment.latin1());
620     }
621     bool isBuildAll = VISU::GetResourceMgr()->booleanValue("VISU", "full_med_loading", false);
622     if(isBuildAll) 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   MESSAGE("Result_i::~Result_i() - this = "<<this);
682   if(mySourceId == eRestoredFile){
683     static QString aCommand;
684     aCommand.sprintf("rm %s",myFileInfo.filePath().latin1());
685     MESSAGE("Result_i::~Result_i - system("<<aCommand<<") = "<<system(aCommand));
686     aCommand.sprintf("rmdir --ignore-fail-on-non-empty %s",myFileInfo.dirPath().latin1());
687     MESSAGE("Result_i::~Result_i - system("<<aCommand<<") = "<<system(aCommand));
688   }
689   if(myInput) delete myInput;
690 }
691
692 //=======================================================================
693 //function : GetAxisInfo
694 //purpose  :
695 //=======================================================================
696 const vector< float >* Result_i::GetAxisInfo(const string& theMeshName,
697                                              TAxis         theAxis,
698                                              gp_Dir&       thePlaneNormal)
699 {
700   const vector< float >* components = NULL;
701
702   if ( theAxis < AXIS_X || theAxis > AXIS_Z ) {
703     MESSAGE(" Bad axis index " << theAxis );
704     return components;
705   }
706
707   map< string, TGridInfo >::iterator name_info;
708   name_info = myMeshName2GridInfoMap.find( theMeshName );
709   TGridInfo * gInfo = 0;
710
711   if ( name_info != myMeshName2GridInfoMap.end() )
712   {
713     gInfo = & name_info->second;
714   }
715   else if ( myInput && IsPossible() && theAxis >= AXIS_X && theAxis <= AXIS_Z )
716   {
717     // check presence of theMeshName
718     const VISU::TMeshMap& meshMap = myInput->GetMeshMap();
719     if ( meshMap.find( theMeshName ) == meshMap.end() ) {
720       MESSAGE("No mesh named " << theMeshName );
721       return components;
722     }
723     VISU_Convertor::TOutput* vtkMesh = myInput->GetMeshOnEntity (theMeshName,
724                                                                  CELL_ENTITY);
725     if ( !vtkMesh || vtkMesh->GetNumberOfCells() == 0 ) {
726       MESSAGE( "No cells in the mesh: " << theMeshName );
727       return components;
728     }
729
730     // define axis directions and min cell size in each direction
731     const int nbAxes = 3;
732     int iAx;
733     gp_Vec axDirs[ nbAxes ];
734     float minSize[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
735     bool axesComputed = false;
736     for ( vtkIdType iCell = 0; iCell < vtkMesh->GetNumberOfCells(); ++iCell )
737     {
738       vtkCell* cell = vtkMesh->GetCell( iCell );
739       int nbPnt = cell->GetNumberOfPoints();
740       if ( nbPnt != 8 )
741         continue;
742       vtkPoints * points = cell->GetPoints();
743       float* coords[ 4 ];
744       coords[0] = points->GetPoint( 0 );
745       coords[1] = points->GetPoint( 1 );
746       coords[2] = points->GetPoint( 3 );
747       coords[3] = points->GetPoint( 4 );
748       gp_Pnt p0( coords[0][0], coords[0][1], coords[0][2] );
749       for ( iAx = 0; iAx < nbAxes; ++iAx )
750       {
751         float* coo = coords[ iAx + 1 ];
752         gp_Pnt p( coo[0], coo[1], coo[2] );
753         // min size
754         float size = p0.SquareDistance( p );
755         if ( size > FLT_MIN && size < minSize[ iAx ] )
756           minSize[ iAx ] = size;
757         // axis direction
758         if ( !axesComputed ) {
759           gp_Vec dir( p0, p );
760           if ( dir.SquareMagnitude() <= DBL_MIN )
761             break;
762           axDirs[ iAx ] = dir;
763         }
764       }
765       if ( iAx == nbAxes )
766         axesComputed = true;
767     }
768     if ( !axesComputed ) {
769       MESSAGE("No good hexahedrons in the mesh: " << theMeshName );
770       return components;
771     }
772
773     // compute axes dirs
774     gInfo = & myMeshName2GridInfoMap[ theMeshName ];
775     for ( iAx = 0; iAx < nbAxes; ++iAx )
776     {
777       int iPrev = ( iAx == 0 ) ? 2 : iAx - 1;
778       int iNext = ( iAx == 2 ) ? 0 : iAx + 1;
779       gInfo->myAxis[ iAx ] = axDirs[ iPrev ] ^ axDirs[ iNext ];
780     }
781
782     // get and sort intermediate component values - projections of nodes
783     // on axis direction; define bnd box
784     set< float > comps[ 3 ];
785     Bnd_Box box;
786     vtkPoints * points = vtkMesh->GetPoints();
787     vtkIdType iP, nbP = vtkMesh->GetNumberOfPoints();
788     for ( iP = 0; iP < nbP; ++iP )
789     {
790       float* coo = points->GetPoint( iP );
791       gp_Pnt p( coo[0], coo[1], coo[2] );
792       box.Add( p );
793       for ( iAx = 0; iAx < nbAxes; ++iAx ) {
794         const gp_Dir& dir = gInfo->myAxis[ iAx ];
795         float dot = dir.XYZ() * p.XYZ();
796         comps[ iAx ].insert( dot );
797       }
798     }
799
800     // find a range of projections of bnd box corners on each axis
801     float range[3], firstValue[3];
802     double x[2],y[2],z[2];
803     box.Get(x[0],y[0],z[0],x[1],y[1],z[1]);
804     for ( iAx = 0; iAx < nbAxes; ++iAx ) {
805       set< float > bndComps;
806       const gp_Dir& dir = gInfo->myAxis[ iAx ];
807       for ( int iX = 0; iX < 2; ++iX ) {
808         for ( int iY = 0; iY < 2; ++iY ) {
809           for ( int iZ = 0; iZ < 2; ++iZ ) {
810             gp_Pnt p( x[ iX ], y[ iY ], z[ iZ ] );
811             float dot = dir.XYZ() * p.XYZ();
812             bndComps.insert( dot );
813           }
814         }
815       }
816       firstValue[ iAx ] = *bndComps.begin();
817       range[ iAx ] = *bndComps.rbegin() - *bndComps.begin();
818     }
819
820     // compute component values
821     for ( iAx = 0; iAx < nbAxes; ++iAx )
822     {
823       list< float > values;
824       int nbVals = 0;
825       set< float >& comp = comps[ iAx ];
826       set< float >::iterator val = comp.begin();
827       float bnd = -1., rng = range[ iAx ], first = firstValue[ iAx ];
828       float tol = 0.1 * sqrt( minSize[ iAx ]) / rng;
829       for ( ; val != comp.end(); ++val ) {
830         float value = ( *val - first ) / rng;
831         if ( value > bnd ) {
832           values.push_back( value );
833           bnd = value + tol;
834           nbVals++;
835         }
836       }
837       // store values in gInfo
838       vector< float >& myComp = gInfo->myComponets[ iAx ];
839       myComp.resize( nbVals );
840       list< float >::iterator v = values.begin();
841       for ( int i = 0; v != values.end(); ++v )
842         myComp[ i++ ] = *v;
843     }
844   }
845
846   // set return values
847   if ( gInfo )
848   {
849     thePlaneNormal = gInfo->myAxis[ theAxis ];
850     components = & gInfo->myComponets[ theAxis ];
851   }
852
853   return components;
854 }