Salome HOME
Merge branch V7_3_1_BR
[modules/paravis.git] / src / Plugins / MEDReader / IO / vtkMEDReader.cxx
1 // Copyright (C) 2010-2014  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony Geay
20
21 #include "vtkMEDReader.h"
22 #include "vtkGenerateVectors.h"
23
24 #include "vtkMultiBlockDataSet.h"
25 #include "vtkInformation.h"
26 #include "vtkDataSetAttributes.h"
27 #include "vtkStringArray.h"
28 #include "vtkMutableDirectedGraph.h"
29 #include "vtkInformationStringKey.h"
30 //
31 #include "vtkUnsignedCharArray.h"
32 #include "vtkInformationVector.h"
33 #include "vtkSmartPointer.h"
34 #include "vtkVariantArray.h"
35 #include "vtkExecutive.h"
36 #include "vtkStreamingDemandDrivenPipeline.h"
37 #include "vtkMultiTimeStepAlgorithm.h"
38 #include "vtkUnstructuredGrid.h"
39 #include "vtkInformationQuadratureSchemeDefinitionVectorKey.h"
40 #include "vtkQuadratureSchemeDefinition.h"
41 #include "vtkPointData.h"
42 #include "vtkCellData.h"
43 #include "vtkCellType.h"
44 #include "vtkCellArray.h"
45 #include "vtkDoubleArray.h"
46 #include "vtkObjectFactory.h"
47
48 #include "MEDFileFieldRepresentationTree.hxx"
49
50 #include <string>
51 #include <vector>
52 #include <sstream>
53 #include <algorithm>
54
55 class vtkMEDReader::vtkMEDReaderInternal
56 {
57
58 public:
59   vtkMEDReaderInternal():TK(0),IsMEDOrSauv(true),IsStdOrMode(false),GenerateVect(false),SIL(0),LastLev0(-1),FirstCall0(2)
60   {
61   }
62   
63   bool PluginStart0()
64   {
65     if(FirstCall0==0)
66       return false;
67     FirstCall0--;
68     return true;
69   }
70   
71   ~vtkMEDReaderInternal()
72   {
73     if(this->SIL)
74       this->SIL->Delete();
75   }
76 public:
77   MEDFileFieldRepresentationTree Tree;
78   TimeKeeper TK;
79   std::string FileName;
80   //when true the file is MED file. when false it is a Sauv file
81   bool IsMEDOrSauv;
82   //when false -> std, true -> mode. By default std (false).
83   bool IsStdOrMode;
84   //when false -> do nothing. When true cut off or extend to nbOfCompo=3 vector arrays.
85   bool GenerateVect;
86   std::string DftMeshName;
87   // Store the vtkMutableDirectedGraph that represents links between family, groups and cell types
88   vtkMutableDirectedGraph* SIL;
89   // store the lev0 id in Tree corresponding to the TIME_STEPS in the pipeline.
90   int LastLev0;
91 private:
92   unsigned char FirstCall0;
93 };
94
95 vtkStandardNewMacro(vtkMEDReader);
96
97 vtkMEDReader::vtkMEDReader():Internal(new vtkMEDReaderInternal)
98 {
99   this->SetNumberOfInputPorts(0);
100   this->SetNumberOfOutputPorts(1);
101 }
102
103 vtkMEDReader::~vtkMEDReader()
104 {
105   delete this->Internal;
106 }
107
108 void vtkMEDReader::Reload(int a)
109 {
110   if(a==0)
111     return;
112   std::cerr << "vtkMEDReader::Reload" << a << std::endl;
113   std::string fName((const char *)this->GetFileName());
114   delete this->Internal;
115   this->Internal=new vtkMEDReaderInternal;
116   this->SetFileName(fName.c_str());
117 }
118
119 void vtkMEDReader::GenerateVectors(int val)
120 {
121   bool val2((bool)val);
122   if(val2!=this->Internal->GenerateVect)
123     {
124       this->Internal->GenerateVect=val2;
125       this->Modified();
126     }
127 }
128
129 void vtkMEDReader::ChangeMode(int newMode)
130 {
131   this->Internal->IsStdOrMode=newMode!=0;
132   //std::cerr << "vtkMEDReader::ChangeMode : " << this->Internal->IsStdOrMode << std::endl;
133   this->Modified();
134 }
135
136 const char *vtkMEDReader::GetSeparator()
137 {
138   return MEDFileFieldRepresentationLeavesArrays::ZE_SEP;
139 }
140
141 void vtkMEDReader::SetFileName(const char *fname)
142 {
143   try
144     {
145       this->Internal->FileName=fname;
146       std::size_t pos(this->Internal->FileName.find_last_of('.'));
147       if(pos!=std::string::npos)
148         {
149           std::string ext(this->Internal->FileName.substr(pos));
150           if(ext.find("sauv")!=std::string::npos)
151             this->Internal->IsMEDOrSauv=false;
152         }
153       if(this->Internal->Tree.getNumberOfLeavesArrays()==0)
154         {
155           this->Internal->Tree.loadMainStructureOfFile(this->Internal->FileName.c_str(),this->Internal->IsMEDOrSauv);
156           this->Internal->Tree.activateTheFirst();//This line manually initialize the status of server (this) with the remote client.
157           this->Internal->TK.setMaxNumberOfTimeSteps(this->Internal->Tree.getMaxNumberOfTimeSteps());
158         }
159       this->Modified();
160     }
161   catch(INTERP_KERNEL::Exception& e)
162     {
163       delete this->Internal;
164       this->Internal=0;
165       std::ostringstream oss;
166       oss << "Exception has been thrown in vtkMEDReader::SetFileName : " << e.what() << std::endl;
167       if(this->HasObserver("ErrorEvent") )
168         this->InvokeEvent("ErrorEvent",const_cast<char *>(oss.str().c_str()));
169       else
170         vtkOutputWindowDisplayErrorText(const_cast<char *>(oss.str().c_str()));
171       vtkObject::BreakOnError();
172     }
173 }
174
175 char *vtkMEDReader::GetFileName()
176 {
177   return const_cast<char *>(this->Internal->FileName.c_str());
178 }
179
180 int vtkMEDReader::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector)
181 {
182   //std::cerr << "########################################## RequestInformation ##########################################" << std::endl;
183   if(!this->Internal)
184     return 0;
185   try
186     {
187       vtkInformation *outInfo(outputVector->GetInformationObject(0));
188       outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),-1);
189       outInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet");
190       this->UpdateSIL(outInfo);
191       //
192       bool dummy(false);
193       this->PublishTimeStepsIfNeeded(outInfo,dummy);
194     }
195   catch(INTERP_KERNEL::Exception& e)
196     {
197       std::cerr << "Exception has been thrown in vtkMEDReader::RequestInformation : " << e.what() << std::endl;
198       return 0;
199     }
200   return 1;
201 }
202
203 int vtkMEDReader::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector)
204 {
205   //std::cerr << "########################################## RequestData        ##########################################";
206   if(!this->Internal)
207     return 0;
208   try
209     {
210       vtkInformation *outInfo(outputVector->GetInformationObject(0));
211       vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())));
212       bool isUpdated(false);
213       double reqTS(0.);
214       if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
215         reqTS=outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
216       //std::cerr << reqTS << std::endl;
217       this->FillMultiBlockDataSetInstance(output,reqTS);
218       output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS);
219       this->UpdateSIL(outInfo);
220       //this->UpdateProgress((float) progress/((float) maxprogress-1));
221     }
222   catch(INTERP_KERNEL::Exception& e)
223     {
224       std::cerr << "Exception has been thrown in vtkMEDReader::RequestInformation : " << e.what() << std::endl;
225       return 0;
226     }
227   return 1;
228 }
229
230 void vtkMEDReader::SetFieldsStatus(const char* name, int status)
231 {
232   //std::cerr << "vtkMEDReader::SetFieldsStatus(" << name << "," << status << ") called !" << std::endl;
233   this->Internal->Tree.changeStatusOfAndUpdateToHaveCoherentVTKDataSet(this->Internal->Tree.getIdHavingZeName(name),status);
234   if(std::string(name)==GetFieldsTreeArrayName(GetNumberOfFieldsTreeArrays()-1))
235     if(!this->Internal->PluginStart0())
236       this->Modified();
237 }
238
239 int vtkMEDReader::GetNumberOfFieldsTreeArrays()
240 {
241   if(!this->Internal)
242     return 0;
243   int ret(this->Internal->Tree.getNumberOfLeavesArrays());
244   //std::cerr << "vtkMEDReader::GetNumberOfFieldsTreeArrays called ! " << ret << std::endl;
245   return ret;
246 }
247
248 const char *vtkMEDReader::GetFieldsTreeArrayName(int index)
249 {
250   std::string ret(this->Internal->Tree.getNameOf(index));
251   //std::cerr << "vtkMEDReader::GetFieldsTreeArrayName(" << index << ") called ! " << ret << std::endl;
252   return ret.c_str();
253 }
254
255 int vtkMEDReader::GetFieldsTreeArrayStatus(const char *name)
256 {
257   int zeId(this->Internal->Tree.getIdHavingZeName(name));
258   int ret(this->Internal->Tree.getStatusOf(zeId));
259   return ret;
260 }
261
262 void vtkMEDReader::SetTimesFlagsStatus(const char *name, int status)
263 {
264   int pos(0);
265   std::istringstream iss(name); iss >> pos;
266   this->Internal->TK.getTimesFlagArray()[pos].first=(bool)status;
267   if(pos==this->Internal->TK.getTimesFlagArray().size()-1)
268     if(!this->Internal->PluginStart0())
269       {
270         this->Modified();
271         //this->Internal->TK.printSelf(std::cerr);
272       }
273 }
274
275 int vtkMEDReader::GetNumberOfTimesFlagsArrays()
276 {
277   if(!this->Internal)
278     return 0;
279   return (int)this->Internal->TK.getTimesFlagArray().size();
280 }
281
282 const char *vtkMEDReader::GetTimesFlagsArrayName(int index)
283 {
284   return this->Internal->TK.getTimesFlagArray()[index].second.c_str();
285 }
286
287 int vtkMEDReader::GetTimesFlagsArrayStatus(const char *name)
288 {
289   int pos(0);
290   std::istringstream iss(name); iss >> pos;
291   return (int)this->Internal->TK.getTimesFlagArray()[pos].first;
292 }
293
294 void vtkMEDReader::UpdateSIL(vtkInformation *info)
295 {
296   if(!this->Internal)
297       return ;
298   vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::New());
299   std::string meshName(this->BuildSIL(sil));
300   if(meshName!=this->Internal->DftMeshName)
301     {
302       if(this->Internal->SIL)
303         this->Internal->SIL->Delete();
304       this->Internal->SIL=sil;
305       this->Internal->DftMeshName=meshName;
306       info->Set(vtkDataObject::SIL(),this->Internal->SIL);
307       //request->AppendUnique(vtkExecutive::KEYS_TO_COPY(),vtkDataObject::SIL());
308     }
309   else
310     {
311       sil->Delete();
312     }
313 }
314
315 /*!
316  * The returned string is the name of the mesh activated which groups and families are in \a sil.
317  */
318 std::string vtkMEDReader::BuildSIL(vtkMutableDirectedGraph* sil)
319 {
320   sil->Initialize();
321   vtkSmartPointer<vtkVariantArray> childEdge(vtkSmartPointer<vtkVariantArray>::New());
322   childEdge->InsertNextValue(0);
323   vtkSmartPointer<vtkVariantArray> crossEdge(vtkSmartPointer<vtkVariantArray>::New());
324   crossEdge->InsertNextValue(1);
325   // CrossEdge is an edge linking hierarchies.
326   vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New();
327   crossEdgesArray->SetName("CrossEdges");
328   sil->GetEdgeData()->AddArray(crossEdgesArray);
329   crossEdgesArray->Delete();
330   std::vector<std::string> names;
331   // Now build the hierarchy.
332   vtkIdType rootId=sil->AddVertex();
333   names.push_back("SIL");
334   // Add global fields root
335   vtkIdType fieldsRoot(sil->AddChild(rootId,childEdge));
336   names.push_back("FieldsStatusTree");
337   this->Internal->Tree.feedSIL(sil,fieldsRoot,childEdge,names);
338   vtkIdType meshesFamsGrpsRoot(sil->AddChild(rootId,childEdge));
339   names.push_back("MeshesFamsGrps");
340   std::string dftMeshName(this->Internal->Tree.feedSILForFamsAndGrps(sil,meshesFamsGrpsRoot,childEdge,names));
341   // This array is used to assign names to nodes.
342   vtkStringArray *namesArray(vtkStringArray::New());
343   namesArray->SetName("Names");
344   namesArray->SetNumberOfTuples(sil->GetNumberOfVertices());
345   sil->GetVertexData()->AddArray(namesArray);
346   namesArray->Delete();
347   std::vector<std::string>::const_iterator iter;
348   vtkIdType cc;
349   for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc)
350     namesArray->SetValue(cc,(*iter).c_str());
351   return dftMeshName;
352 }
353
354 double vtkMEDReader::PublishTimeStepsIfNeeded(vtkInformation *outInfo, bool& isUpdated)
355 {
356   int lev0(-1);
357   std::vector<double> tsteps;
358   if(!this->Internal->IsStdOrMode)
359     tsteps=this->Internal->Tree.getTimeSteps(lev0,this->Internal->TK);
360   else
361     { tsteps.resize(1); tsteps[0]=0.; }
362   isUpdated=false;
363   if(lev0!=this->Internal->LastLev0)
364     {
365       isUpdated=true;
366       double timeRange[2];
367       timeRange[0]=tsteps.front();
368       timeRange[1]=tsteps.back();
369       outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],tsteps.size());
370       outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2);
371       this->Internal->LastLev0=lev0;
372     }
373   return tsteps.front();
374 }
375
376 void vtkMEDReader::FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS)
377 {
378   std::string meshName;
379   vtkDataSet *ret(this->Internal->Tree.buildVTKInstance(this->Internal->IsStdOrMode,reqTS,meshName,this->Internal->TK));
380   if(this->Internal->GenerateVect)
381     {
382       vtkGenerateVectors::Operate(ret->GetPointData());
383       vtkGenerateVectors::Operate(ret->GetCellData());
384       vtkGenerateVectors::Operate(ret->GetFieldData());
385     }
386   output->SetBlock(0,ret);
387   ret->Delete();
388 }
389
390 void vtkMEDReader::PrintSelf(ostream& os, vtkIndent indent)
391 {
392   this->Superclass::PrintSelf(os, indent);
393 }