]> Creatis software - creaContours.git/blob - lib/Interface_ManagerContour_NDimensions/wxContourMainFrame.cxx
8941bde86d9e44287e06a66071e3e4e6164291c1
[creaContours.git] / lib / Interface_ManagerContour_NDimensions / wxContourMainFrame.cxx
1 //----------------------------------------------------------------------------------------------------------------
2 // Class definition include
3 //----------------------------------------------------------------------------------------------------------------
4 #include "wxContourMainFrame.h"
5
6
7
8 //----------------------------------------------------------------------------------------------------------------
9 // Includes
10 //----------------------------------------------------------------------------------------------------------------
11
12
13 #include "NameWrapper.h"
14 #include "wx/artprov.h"
15 #include "ConceptDataWrap.h"
16 #include <creaWx.h>
17
18 #include <string>
19 using namespace std;
20
21 //----------------------------------------------------------------------------------------------------------------
22 // Class implementation
23 //----------------------------------------------------------------------------------------------------------------
24 /** @file wxContourMainFrame.cxx */
25
26         //------------------------------------------------------------------------------------------------------------
27         // Constructors & Destructors
28         //------------------------------------------------------------------------------------------------------------
29
30 wxContourMainFrame* wxContourMainFrame:: instance = NULL;
31 char wxContourMainFrame::COPY = 'C';
32                 
33         wxContourMainFrame :: wxContourMainFrame(wxWindow* parent, wxWindowID id,const wxString& title,const wxPoint& pos,const wxSize& size,long style)
34                 //: wxPanel(parent, id, title, pos, size, style)
35                 //: wxWindow(parent, id, pos, size, style)
36                 : wxPanel(parent, id, pos, size, style)
37         {
38                 m_mgr.SetManagedWindow(this);
39                 _contourGroup                           = 1;
40                 _creatingContoursActive         = false;
41                 _theViewPanel                           = NULL;
42 //              _modelManager                           = NULL;
43                 _instantPanel                           = NULL;
44 //              _buttonsBar                                     = NULL;
45 //              _gridPanel                                      = NULL; 
46 //              _drawToolsPanel                         = NULL;
47 //              _operationsToolsPanel           = NULL;
48                 //_autoFormsPanel                               = NULL; 
49 //              _standardToolsPanel                     = NULL;
50 //              _editionToolsPanel                      = NULL;
51 //              _listViewPanel                          = NULL;
52 //              _sceneManager                           = NULL;
53                 //_actualInstant                                = NULL;
54                 _numberOfVariablesStatistics = 6+1;
55
56                 _refLineControl                         = NULL;
57                 _refLineModel                           = NULL;
58                 _refLineView                            = NULL;
59 //              _actorPresent                           = false;
60
61                 // set up default notebook style
62 //              m_notebook_style =wxAUI_NB_TAB_SPLIT | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER;
63 //              m_notebook_theme = 0;   
64                 //wxContour_ActionCommandsID a;
65                 
66                 _contourextractdata                     = NULL;
67                 _viewMaskImage                          = NULL;
68                 _viewMaskImagePanel                     = NULL;
69                 _viewThresholdImage                     = NULL;
70                 _viewThresholdImagePanel        = NULL;
71
72         }
73
74         wxContourMainFrame :: wxContourMainFrame(wxWindow* parent, wxWindowID id,const wxString& title,const wxPoint& pos,const wxSize& size,std::vector<vtkImageData*> images, long style,std::string datadir)         
75                 : wxPanel(parent, id, pos, size, style)
76         {
77                 m_mgr.SetManagedWindow(this);
78                 _contourGroup                           = 1;
79                 _creatingContoursActive         = false;
80                 _theViewPanel                           = NULL;
81
82                 _instantPanel                           = NULL;
83                 _refLineControl                         = NULL;
84                 _refLineModel                           = NULL;
85                 _refLineView                            = NULL;
86 //              _actorPresent                           = false;
87                 _viewMaskImage                          = NULL;
88                 _viewMaskImagePanel                     = NULL;
89                 _viewThresholdImage                     = NULL;
90                 _viewThresholdImagePanel        = NULL;
91
92                 // set up default notebook style
93                 m_notebook_style =wxAUI_NB_TAB_SPLIT | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER;
94                 m_notebook_theme = 0;   
95                 //wxContour_ActionCommandsID a;
96                 _numberOfVariablesStatistics = 7;
97
98                 _datadir = datadir;
99
100         
101                 inredo = 0;
102                 inundo = 0;
103
104                 _pannew = interfMainPanel::getInstance(this,datadir+"/data/Icons");//, eventHandler);
105                 _performingOperation = new PerformingOperation();
106
107                 if(images.size() > 0)
108                 {
109                         this->setVectImages(images);
110                 }
111                 
112                 _contourextractdata                     = NULL;
113 }
114
115 void wxContourMainFrame::setVectImages(std::vector<vtkImageData*> imgs)
116 {
117
118         _images = imgs;
119
120         #if defined(__GNUC__)
121                 std::string str_home(getenv("HOME"));
122         #elif defined(_WIN32)
123                         std::string str_home(getenv("USERPROFILE"));
124         #endif
125                 std::string strCreaContourDataTmp = str_home + "/.creaContourDataTemp/";
126
127         std::vector<std::string> conceptNameVect;
128         std::vector<int> conceptSizeVect;
129
130         notebook = this->createNotebook();              
131
132
133         kernelManager = new KernelManagerContour( imgs , _datadir+"/data/" , strCreaContourDataTmp );
134
135
136         _instantPanel                           = new wxInstantChooserPanel( notebook, "Instant Chooser", true, false, "c" );
137         _theViewPanel                           = new wxContourViewPanel( kernelManager->getSourceImage(), notebook );  
138                 
139 //-------------------------------------------------------------
140         kernelManager->getConceptsInformation(conceptNameVect, conceptSizeVect);
141         _instantPanel->addConcepts(conceptNameVect, conceptSizeVect);
142                 
143
144         double val = _theViewPanel->getCurrentDeep();
145         _instantPanel->setConceptValue( "Axe Depth", (int)val );
146         //JCP _instantPanel->setConceptValue("time", num de imagenes);
147         ConceptDataWrap * data = _instantPanel->getConceptDataOf( "Axe Depth" );
148         //*******************changeInstant();
149         _theViewPanel->setVerticalConcept( "Axe Depth", data->getMinValue(), data->getMaxValue(), data->getMinShowedValue(),  data->getMaxShowedValue(), data->getActualValue() );
150
151         this->configurePanels( );
152
153 }
154
155
156         wxContourMainFrame* wxContourMainFrame :: getInstance(wxWindow* parent, wxWindowID id,const wxString& title,const wxPoint& pos,const wxSize& size,std::vector<vtkImageData*> images, long style,std::string datadir ){
157                 if(instance == NULL){
158                         instance = new wxContourMainFrame(parent, id, title, pos, size, images, style,datadir);
159                 }
160                 return instance;
161         }
162
163         std::vector<vtkImageData*> wxContourMainFrame ::getVectImages()
164         {
165                 return kernelManager->getVectImages();
166         }
167
168         wxContourMainFrame* wxContourMainFrame :: getInstance()
169         {
170                 return instance;        
171         }
172
173         void wxContourMainFrame :: resetInstance()
174         {
175                 instance->Destroy();
176         }
177
178         wxContourMainFrame :: ~wxContourMainFrame()
179         {
180                 delete _contourextractdata;
181                 deleteAllContours();
182                 _pannew->Close();
183                 interfMainPanel::resetInstance();
184                 delete kernelManager;
185                 instance = NULL;
186                 //_pannew->Destroy();
187                 //delete _pannew;
188
189                 m_mgr.UnInit();
190                 //delete m_mgr;
191
192                 //El problema al cerrar la aplicacion puede estar asociado 
193                 //a que  wxAUINotebook esta en la aplicacion 
194                 //principal (wxContourGUIExample)tambien
195                 //EED????               delete _theViewPanel;             
196                 //EED????               delete _instantPanel;
197                 //EED????               delete _buttonsBar;
198                 //EED????               delete _actualInstant;           
199                 //EED????               delete _sceneManager;
200         }
201
202
203         //------------------------------------------------------------------------------------------------------------
204         // Creational and initialization methods using WxAui
205         //------------------------------------------------------------------------------------------------------------
206         //
207         wxAuiNotebook * wxContourMainFrame :: createNotebook()
208         {
209                 wxSize client_size = GetClientSize();
210                 wxAuiNotebook* noteBook = new wxAuiNotebook(this, -1, wxPoint(client_size.x, client_size.y), wxSize(430,200), m_notebook_style);
211                 wxBitmap page_bmp = wxArtProvider::GetBitmap(wxART_NORMAL_FILE, wxART_OTHER, wxSize(16,16));
212                 return noteBook;
213         }
214         
215
216         //------------------------------------------------------------------------------------------------------------
217         // Creational and initialization methods 
218         //------------------------------------------------------------------------------------------------------------
219         bool wxContourMainFrame :: configurePanels( )
220         {
221                 bool configured = _theViewPanel!=NULL;
222                                         
223                 configured &= _theViewPanel!=NULL;
224                 if( _theViewPanel!=NULL )
225                 {
226                         notebook->AddPage( _theViewPanel, wxT("       View       ") );          
227                         m_mgr.Update();
228                 }
229
230
231                 if( configured )
232                 {
233                         notebook->AddPage( _instantPanel, wxT("Instant Page") );
234                         m_mgr.Update();
235                 }
236
237                 m_mgr.AddPane(notebook, wxAuiPaneInfo().Name(wxT("notebook_content")).CenterPane().PaneBorder(false));
238                 m_mgr.Update();
239                  
240                 SetMinSize(wxSize(300,300));
241                 m_mgr.Update();
242                 return configured;
243         }
244
245
246         bool wxContourMainFrame::addNewPanel(wxPanel* panel)
247                 {
248                 bool configured = panel!=NULL;
249                 configured &= panel!=NULL;
250                 
251                 if( configured )
252                 {
253                         notebook->AddPage( panel, wxT("       Viewer       "), true );
254                         m_mgr.Update();
255                 }
256                 return configured;
257         }
258
259         //------------------------------------------------------------------------------------------------------------
260         //  Attributes getters and setters
261         //------------------------------------------------------------------------------------------------------------
262         
263
264         
265         void wxContourMainFrame :: setInstantChooserPanel(  wxInstantChooserPanel * theInstantChooserPanel )
266         {
267                 _instantPanel = theInstantChooserPanel; 
268         }
269
270 //      void wxContourMainFrame :: setButtonsBar(  wxContour_ButtonsBar * theButtonsBar )
271 //      {
272 //              _buttonsBar = theButtonsBar;
273 //      }
274
275 //      void wxContourMainFrame :: setGrid(  wxContour_Grid * theGridPanel )
276 //      {
277 //              _gridPanel = theGridPanel;
278 //      }
279
280 //      void wxContourMainFrame :: setDrawToolsPanel(  wxContour_DrawToolsPanel * theDrawToolsPanel )
281 //      {
282 //              _drawToolsPanel = theDrawToolsPanel;
283 //      }
284
285 //      void wxContourMainFrame :: setOperationsToolsPanel(  wxContour_OperationsToolsPanel * theOperationsToolsPanel )
286 //      {       
287 //              _operationsToolsPanel = theOperationsToolsPanel;
288 //      }
289
290 //      void wxContourMainFrame :: setAutomaticFormsPanel(  wxContour_AutomaticFormsToolsPanel * theAutoFormsPanel )
291 //      {
292 //              _autoFormsPanel = theAutoFormsPanel;
293 //      }
294
295 //      void wxContourMainFrame :: setStandardToolsPanel(  wxContour_StandardToolsPanel * theStandardToolsPanel )
296 //      {
297 //              _standardToolsPanel= theStandardToolsPanel;
298 //      }
299
300 //      void wxContourMainFrame :: setEditionToolsPanel(  wxContour_EdtionToolsPanel * theEditionToolsPanel )
301 //      {
302 //              _editionToolsPanel =  theEditionToolsPanel;
303 //      }
304
305 //      void wxContourMainFrame :: setListViewPanel(  wxContour_ListViewPanel * theListViewPanel )
306 //      {
307 //              _listViewPanel = theListViewPanel;
308 //      }
309
310
311
312 void wxContourMainFrame::onCreateContourSpline( ){
313         
314         //JCP 20-10-08 Undo redo implementation
315         saveState();
316         //JCP 20-10-08 Undo redo implementation
317         createContour( 1 );
318         
319 }
320 void wxContourMainFrame::onCreateContourRectangle( ){
321     //JCP 20-10-08 Undo redo implementation
322         saveState();
323         //JCP 20-10-08 Undo redo implementation 
324         createContour( 2 );
325 }
326 void wxContourMainFrame::onCreateContourCircle( ){
327     //JCP 20-10-08 Undo redo implementation
328         saveState();
329         //JCP 20-10-08 Undo redo implementation 
330         createContour( 3 );
331 }
332
333 void wxContourMainFrame::onCreateContourLine( ){
334     //JCP 20-10-08 Undo redo implementation
335         saveState();
336         //JCP 20-10-08 Undo redo implementation 
337         createContour( 6 );
338 }
339
340 // RaC 09-09 --------------------------------------
341 void wxContourMainFrame::onCreateContourPoints( ){
342     //JCP 20-10-08 Undo redo implementation
343         saveState();
344         //JCP 20-10-08 Undo redo implementation 
345         createContour( 7 );
346 }
347 // RaC 09-09 --------------------------------------
348
349 // RaC 10-09 --------------------------------------
350 void wxContourMainFrame::onCreateContourPolygon( ){
351     //JCP 20-10-08 Undo redo implementation
352         saveState();
353         //JCP 20-10-08 Undo redo implementation 
354         createContour( 10 );
355 }
356 // RaC 10-09 --------------------------------------
357
358 //------------------------------------------------------------------------------------------------------------
359
360 void wxContourMainFrame :: onCreateContourBullEye(wxPanel* panel )
361 {
362         //Creating the manualBaseModel and including in the model
363         manualBaseModel * manModelContour = factoryManualContourModel(panel );
364
365         std::vector<int> instantVector;
366         _instantPanel->getInstant( instantVector );
367         std::string theName = kernelManager->createOutline(manModelContour, instantVector);
368         
369         /*std::vector<int> instantVector;
370         _instantPanel->getInstant( instantVector );
371         std::string theName;
372         theName= _modelManager->createOutline( manModelContour, instantVector );*/
373         bool addedModel = theName.compare("") != 0;//??
374
375         if( addedModel )
376         {
377                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
378                 _theViewPanel->getSpacing(spc);                                 
379                 //Adding the manualContourControler to interface objects structure
380                 //Adding the manualViewContour to interface objects structure           
381                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
382                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , 4) ;
383         }
384 }
385 void wxContourMainFrame :: createContour( int typeContour )
386 {
387         //Creating the manualContourModel and including in the model
388         manualBaseModel * manModelContour = kernelManager->factoryManualContourModel(typeContour);
389
390         std::vector<int> instantVector;
391         _instantPanel->getInstant( instantVector );
392         std::string theName = kernelManager->createOutline(manModelContour, instantVector);
393         
394         /*std::vector<int> instantVector;
395         _instantPanel->getInstant( instantVector );
396         std::string theName;
397         theName= _modelManager->createOutline( manModelContour, instantVector );*/
398         bool addedModel = theName.compare("") != 0;//??
399         if( addedModel )
400         {
401                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
402                 _theViewPanel->getSpacing(spc);                                 
403                 //Adding the manualContourControler to interface objects structure
404                 //Adding the manualViewContour to interface objects structure           
405                 //_sceneManager->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
406                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeContour) ;
407         }       
408
409 }
410 manualBaseModel * wxContourMainFrame::factoryManualContourModel(wxPanel* panel){
411
412         manualContourModelBullEye *manModelContourBullEye = new manualContourModelBullEye();
413         manualBaseModel *manModelContour=NULL;
414         manModelContour = manModelContourBullEye;
415         if (panel!=NULL){
416                 int iCrown,sizeCrowns,iSector,sizeSectors;
417                 double radioA,radioB,ang,angDelta ;
418                 sizeCrowns = ((PanelBullEyeOptions*)panel)->GetNumberOfCrowns();
419                 for ( iCrown=0 ; iCrown<sizeCrowns ; iCrown++ )
420                 {
421                         sizeSectors = ((PanelBullEyeOptions*)panel)->GetNumberOfSections(iCrown);
422                         radioB  = ((PanelBullEyeOptions*)panel)->GetRadioOfCrown(iCrown);
423                         if (iCrown==sizeCrowns-1)
424                         {
425                                 radioA  = 0;
426                         } else {
427                                 radioA  = ((PanelBullEyeOptions*)panel)->GetRadioOfCrown(iCrown+1);
428                         }
429                         radioA=radioA/100.0;
430                         radioB=radioB/100.0;
431                         for ( iSector=0 ; iSector<sizeSectors  ; iSector++ )
432                         {
433                                 ang             = ((PanelBullEyeOptions*)panel)->GetAngOfCrownSection(iCrown,iSector);
434                                 angDelta= ((PanelBullEyeOptions*)panel)->GetAngDeltaOfCrownSection(iCrown);                                     
435                                 manModelContourBullEye->AddSector(radioA,radioB,ang,angDelta);
436                         } // for iSector
437                 } // for iCrown
438         } // if _panelBullEyeOptions
439         
440         return manModelContour;
441 }
442 void wxContourMainFrame :: saveState(){ 
443                 
444         std::string temp = kernelManager->saveState();
445         saveFileWithContours(temp);     
446 }
447
448 void wxContourMainFrame::onDeleteContour(){
449         //JCP 20-10-08 Undo redo implementation
450                 saveState();
451                 //JCP 20-10-08 Undo redo implementation
452
453                 std::vector<std::string> lstKeyNameToBeErase;
454                 lstKeyNameToBeErase             = _theViewPanel->getSceneManager()->getSelectedObjects();
455                 deleteContours( lstKeyNameToBeErase );
456 /*JCP 19 - 11 - 08
457                 int i,size=_sceneManager->getSelectedObjects().size();
458                 for(i=0;i<size;i++)
459                 {
460                         std::string keyName             = _sceneManager->getSelectedObjects()[i];
461                         int ispartofstaticlist  = this->_modelManager->IsPartOfStaticList( keyName );
462                         if ( ispartofstaticlist>=0 )
463                         {
464                                 std::vector<int> tempVector;
465                                 _instantPanel->getInstant( tempVector );
466                                 Instant instant(&tempVector);
467                                 this->_modelManager->ChangeContourOfList(keyName, &instant);
468                         }
469                 }
470
471                 std::vector<std::string> lstKeyName;
472                 std::vector<std::string> lstKeyNameActualSlice;
473                 std::vector<std::string> lstKeyNameToBeErase;
474
475                 lstKeyNameToBeErase             = _sceneManager->getSelectedObjects();
476                 lstKeyNameActualSlice   = _sceneManager->GetlstContoursNameActualSlice();
477                 int k,kSize=lstKeyNameToBeErase.size();
478                 int j,jSize=lstKeyNameActualSlice.size();
479                 bool ok;
480                 for (k=0;k<kSize; k++)
481                 {
482                         ok=false;
483                         for (j=0;j<jSize; j++)
484                         {
485                                 if (lstKeyNameToBeErase[k]==lstKeyNameActualSlice[j])
486                                 { 
487                                         ok=true;
488                                 }
489                         } // for j
490                         if (ok==true)
491                         {
492                                 lstKeyName.push_back( lstKeyNameToBeErase[k] );
493                         } // if ok
494                 } // for k
495
496                 deleteContours( lstKeyName );
497 JCP 19 - 11 - 08*/
498 }
499
500 void wxContourMainFrame :: deleteContours( std::vector<std::string>  keyNamesVector )
501 {
502         int i,size=keyNamesVector.size();
503         for (i=0;i<size;i++)
504         {
505                 deleteContour( keyNamesVector[i] );
506         }
507 }
508
509 void wxContourMainFrame :: deleteContour( std::string theKeyName ){
510         /*
511         manualContourModel                      * cModel;
512         manualViewBaseContour           * cViewer;
513         manualContourBaseControler      * cControler;
514
515         ContourWrap_ViewControl *conwrapviewControl =  _theViewPanel->getSceneManager()->getContourWrap_ViewControlOf( theKeyName );
516         cControler      = conwrapviewControl->getControler();*/
517
518         //JCP 21 - 11 - 2008
519         bool isedit = _theViewPanel->isEditableCControler(theKeyName);
520         bool ispartofstaticlst = kernelManager->IsPartOfStaticList(theKeyName);
521
522         if (isedit  && ispartofstaticlst)
523         {
524                 _theViewPanel->removeFromScene(theKeyName);
525
526                 kernelManager->deleteCModel(theKeyName);
527                 //_theViewPanel->getSceneManager()->removeFromScene( theKeyName );                      
528                 //cViewer               = conwrapviewControl->getViewer();
529                 //_theViewPanel->getSceneManager()->removeWrap( theKeyName );
530                 //cControler* conwrapviewControl->getControler();                       
531         //      delete cModel;
532         //      delete cViewer;
533         //      delete cControler;
534         } // if editable
535 //JCP 21 - 11 - 08
536 }
537
538 void wxContourMainFrame::onDeleteContoursActSlice(){
539         //JCP 20-10-08 Undo redo implementation
540         saveState();
541         //JCP 20-10-08 Undo redo implementation
542         deleteContours( (std::vector<std::string>)_theViewPanel->getSceneManager()->GetlstContoursNameActualSlice() );
543 }
544 void wxContourMainFrame::onDeleteAllContours(){
545         //JCP 20-10-08 Undo redo implementation
546         saveState();
547         deleteAllContours();
548 }
549 void wxContourMainFrame::deleteAllContours(){
550         //JCP 20-10-08 Undo redo implementation
551
552         wxBusyCursor wait;
553         std::vector<int> tempVector;
554         _instantPanel->getInstant( tempVector );
555
556 //JCP --08-09-2008 When using a diferent interface the _mbarrangeDeleteAll might not be initialize
557 //              the values in GetStart and GetEnd will then not be initialize also.
558 //              We use instead the values given when initializing the _deletepanel.
559
560         //int minZ = _mbarrangeDeleteAll->GetStart();
561         //int maxZ = _mbarrangeDeleteAll->GetEnd();
562         int minZ, maxZ;
563         
564         minZ = 0;
565         maxZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
566         
567 //JCP --08-09-2008
568         
569         _theViewPanel->getSceneManager()->removeSceneContours( );       
570         _theViewPanel->getSceneManager()->removeAllOutlines();
571         kernelManager->removeAllOutlines();     
572 //JCP --08-09-2008
573         /*
574         if ( (minZ==0) && (maxZ==_mbarrangeDeleteAll->GetMax() ))
575         {
576                 _theViewPanel->getSceneManager()->removeSceneContours( );
577                 _modelManager->removeAllOutlines();
578                 _theViewPanel->getSceneManager()->removeAllOutlines();
579
580         } else {
581                 for ( z=minZ ; z<=maxZ ; z++)
582                 {
583                         tempVector[1]=z;
584                         Instant instant(&tempVector);
585                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
586
587                         sizeLstContourThings = lstContourThings.size();
588                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
589                         {
590                                 ContourThing **contourthing = lstContourThings[ii];
591                                 deleteContour( (*contourthing)->getName() );
592                         } //for ii
593                 }// for z
594         } // if 
595 JCP --08-09-2008 */
596 }
597
598 void wxContourMainFrame::setConceptValue( std::string name, int value ){
599         _instantPanel->setConceptValue(name, value);
600 }
601
602
603 ConceptDataWrap* wxContourMainFrame::getLastConceptData(){
604         return _instantPanel->getLastConceptData();
605 }
606
607
608 bool wxContourMainFrame::getIfConceptCheckedAt( std::string name, int pos ){
609         return _instantPanel->getIfConceptCheckedAt( name, pos );
610 }
611
612
613
614 void wxContourMainFrame::ShowResultImages(int typeContourGroup, int selection, int minZ, int maxZ)
615 {
616         vtkImageData * mask;
617         vtkImageData * value;
618         this->getMaskValue(&mask, &value, typeContourGroup, selection, minZ, maxZ);
619         
620         std::vector<int> nTypeView;
621         nTypeView.push_back(5);
622         nTypeView.push_back(1);
623         nTypeView.push_back(2);
624         nTypeView.push_back(0); 
625         
626         wxFrame *frame = new wxFrame(this, -1,_T("Result image extracted.."),wxDefaultPosition,wxSize(600,600), wxDEFAULT_FRAME_STYLE|wxSTAY_ON_TOP);
627         wxAuiManager *m_mgr_noteBookViewerResult = new wxAuiManager();
628         m_mgr_noteBookViewerResult->SetManagedWindow(frame);
629         
630         wxAuiNotebook* noteBookViewerResult = new wxAuiNotebook(frame, -1, wxPoint(600, 600), wxSize(430,200), m_notebook_style);
631         m_mgr_noteBookViewerResult->AddPane(noteBookViewerResult, wxAuiPaneInfo().Name(wxT("notebook_content")).CenterPane().PaneBorder(false));
632
633         wxPanel *panelViewer1 = new wxMaracas_N_ViewersWidget(noteBookViewerResult, value,&nTypeView);
634         wxPanel *panelViewer2 = new wxMaracas_N_ViewersWidget(noteBookViewerResult, mask,&nTypeView);
635         
636
637         noteBookViewerResult->AddPage( panelViewer1, wxT("Image result") );
638         noteBookViewerResult->AddPage( panelViewer2, wxT("Mask result") );
639         m_mgr_noteBookViewerResult->Update();
640         frame->Show();
641 }
642
643
644
645
646 void wxContourMainFrame::changeInstant()
647 {
648                 std::vector<int> instantVect;
649                 _instantPanel->getInstant( instantVect );
650                 int actualSlice = instantVect[1];
651
652                 kernelManager->setInstant(instantVect);
653                         
654             // Refresh Mask image
655                 if(_viewMaskImage!=NULL){
656                         _viewMaskImage->SetZ(actualSlice);                      
657                         if (_viewMaskImagePanel->IsVisible()==true)
658                         {
659                                 vtkImageData *mask, *value;
660                                 getMaskValue(&mask,&value, _contourGroup , 0, -1, -1);
661                                 _viewMaskImage->onThreshold();
662                         }
663                 }
664         
665         // Refresh Threshold image
666                 if(_viewThresholdImage!=NULL){
667                         _viewThresholdImage->SetZ(actualSlice);                 
668                         if (_viewThresholdImagePanel->IsVisible()==true){
669                                 _viewThresholdImage->onThreshold();
670                         }
671                 }
672         
673                 updateInstantOutlines();
674                 updateInstantImageData();
675                 updateInstantAxes();
676 }
677
678
679
680 void wxContourMainFrame :: updateInstantOutlines()
681 {
682         _theViewPanel->removeSceneContours();
683         _theViewPanel->addNameWrapperToScene();
684
685         //for( int i=0; i<size; i++)
686         //{                     
687         //      _theViewPanel->getSceneManager()->addToScene(namesWrapping[i]->getKeyName(), true, true, true, false, false );
688         //}
689 }
690
691 int wxContourMainFrame::getNamesWrappingSize(){
692         return kernelManager->getNamesWrappingSize();
693 }
694 std::string wxContourMainFrame::getNameWrapping(int i){
695         return kernelManager->getNameWrapping(i);
696 }
697
698 void wxContourMainFrame::updateInstantImageData()
699 {
700         std::vector<int> inst;
701         _instantPanel->getInstant(inst);
702
703         vtkImageData* img = kernelManager->getImageAtInstant(inst);
704         if(img!=NULL){
705                 _theViewPanel->changeImage(img);
706                 showAxis(false);
707         }else{
708                 int z = _instantPanel->getConceptDataOf("Axe Depth")->getActualValue();
709                 _theViewPanel->setImageSlice(z);
710         }
711 }
712
713 void wxContourMainFrame::updateInstantAxes()
714 {
715 }
716
717
718 void wxContourMainFrame::onChangeDeep(int val){
719         _instantPanel->setConceptValue( "Axe Depth", (int)val );        
720         changeInstant();
721 }
722
723
724 void wxContourMainFrame::onCopy(){
725         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
726
727         std::vector<int> tempVector;
728         _instantPanel->getInstant( tempVector );
729     _performingOperation->reset();
730         _performingOperation->setStartCommand( COPY );
731         _performingOperation->setStartOperationInstantVector( tempVector );
732         _performingOperation->setKeyNamesOperationElems( currentSelection );
733 }
734
735 void wxContourMainFrame::onPaste(){
736
737
738         char theStartCommand = _performingOperation->getStartCommand();
739         if (  theStartCommand == COPY )
740         {
741                 //JCP 20-10-08 Undo redo implementation
742                 saveState();
743                 //JCP 20-10-08 Undo redo implementation
744                 std::vector<int> tempVector;
745                 _instantPanel->getInstant( tempVector );
746                 _performingOperation->setEndOperationInstantVector ( tempVector );
747                 std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
748                 int i,size = elems.size();                      
749                 for( i=0; i<size; i++ )
750                 {                               
751                         createCopyContourOf( elems[i], tempVector, i>0 );
752                 }               
753         }
754 }
755 void wxContourMainFrame::onUndo(){
756         std::string filename;
757         if(kernelManager->onUndoSaveFile(filename)){
758                 saveFileWithContours(filename);
759         }
760         if(kernelManager->onUndo(filename)){
761                 loadState(filename);
762         }
763 }
764 void wxContourMainFrame::onRedo(){
765         std::string filename;
766         if(kernelManager->onRedo(filename)){
767                 loadState(filename);
768         }
769         
770 }
771 void wxContourMainFrame :: createCopyContourOf ( std::string anExistingKName, std::vector<int> &instantNoTouchData, bool append )
772 {
773         std::string cloneName = kernelManager->createCopyContourOf( anExistingKName, instantNoTouchData );
774         manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
775         _theViewPanel->getSceneManager()->createCopyContourOf( anExistingKName, cloneName, manualModel , append );
776 }
777
778 ///AD: 03-09    Copy the object and apply the given transformation
779 void wxContourMainFrame :: createMirrorContourOf ( std::string anExistingKName, std::vector<int> &instantNoTouchData, bool append )
780 {
781         std::string cloneName = kernelManager->createCopyContourOf( anExistingKName, instantNoTouchData );
782         manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);
783
784         manualPoint * refPoint1 = _refLineModel->GetManualPoint(0);
785         manualPoint * refPoint2 = _refLineModel->GetManualPoint(1);
786
787         double pnt1X = refPoint1->GetX();
788         double pnt1Y = refPoint1->GetY();
789 //      double pnt1Z = refPoint1->GetZ();
790         double pnt2X = refPoint2->GetX();
791         double pnt2Y = refPoint2->GetY();
792 //      double pnt2Z = refPoint2->GetZ();
793
794         double angle = (atan2(pnt2Y - pnt1Y, pnt2X - pnt1X) * 180 / 3.1415926535897932384626433832795)+90;
795         vtkTransform *t = vtkTransform::New();
796
797         t->PostMultiply();
798         t->Identity();
799         t->Translate(-pnt1X, -pnt1Y, 0);
800         t->RotateZ(-angle);
801         t->Scale(-1,1,1);
802         t->RotateZ(angle);
803         t->Translate(pnt1X, pnt1Y, 0);
804         t->Update();
805
806         int i,size=manualModel->GetSizeLstPoints();
807         for (i=0;i<size;i++)
808         {
809                 manualPoint * mp = manualModel->GetManualPoint(i);
810                 float vecIn[3];
811                 float vecOut[3];
812                 vecIn[0]=mp->GetX();
813                 vecIn[1]=mp->GetY();
814                 vecIn[2]=mp->GetZ();
815                 t->TransformPoint( vecIn, vecOut );
816                 mp->SetPointX( vecOut[0] );
817                 mp->SetPointY( vecOut[1] );
818                 mp->SetPointZ( vecOut[2] );
819         }
820
821         _theViewPanel->getSceneManager()->createCopyContourOf( anExistingKName, cloneName, manualModel , append );
822 }
823
824 void wxContourMainFrame ::loadState(std::string filename){
825         char tmp[255];
826         FILE *pFile=fopen(filename.c_str(),"r+");
827
828         fscanf(pFile,"%s",tmp); // --CreaContour--
829
830         fscanf(pFile,"%s",tmp); // Version
831         fscanf(pFile,"%s",tmp); // 1.0.2 || 1.0.1 || 1.0.0
832
833         deleteAllContours();
834
835         loadContours(pFile, false);
836         loadContours(pFile, true);      
837
838         fclose(pFile);
839 }
840
841 void wxContourMainFrame ::loadContours( FILE *pFile, bool staticContour )
842 {
843         char tmp[255];
844
845         fscanf(pFile,"%s",tmp); // ImageDimensions
846         fscanf(pFile,"%s",tmp); // X
847         fscanf(pFile,"%s",tmp); // Y
848         fscanf(pFile,"%s",tmp); // Z
849
850         fscanf(pFile,"%s",tmp); // ImageSpacing
851         fscanf(pFile,"%s",tmp); // X
852         fscanf(pFile,"%s",tmp); // Y
853         fscanf(pFile,"%s",tmp); // Z
854         
855         fscanf(pFile,"%s",tmp); // NumberOfContours 
856         fscanf(pFile,"%s",tmp); // ##
857         int numberOfContours = atoi(tmp);  
858
859         std::vector<int> instantVector;
860         int typeContourModel;
861         manualBaseModel *manModelContour;
862         int typeView;
863
864         int i;
865         for (i=0;i<numberOfContours;i++)
866         {
867                 instantVector.clear();
868                 fscanf(pFile,"%s",tmp); // Instant
869                 fscanf(pFile,"%s",tmp); // 1
870                 instantVector.push_back( atoi(tmp) );
871                 fscanf(pFile,"%s",tmp); // 2
872                 instantVector.push_back( atoi(tmp) );
873                 fscanf(pFile,"%s",tmp); // 3
874                 instantVector.push_back( atoi(tmp) );
875                 fscanf(pFile,"%s",tmp); // 4
876                 instantVector.push_back( atoi(tmp) );
877                 fscanf(pFile,"%s",tmp); // 5
878                 instantVector.push_back( atoi(tmp) );
879                 fscanf(pFile,"%s",tmp); // 6
880                 instantVector.push_back( atoi(tmp) );
881
882                 fscanf(pFile,"%s",tmp); // TypeContourModel
883                 fscanf(pFile,"%s",tmp); // ##
884                 typeContourModel = atoi(tmp);
885
886                 manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
887                 manModelContour->Open(pFile);
888
889                 fscanf(pFile,"%s",tmp); // TypeView
890                 fscanf(pFile,"%s",tmp); // ##
891                 typeView = atoi(tmp);  
892
893                 std::string theName;
894                 theName = kernelManager->createOutline( manModelContour, instantVector );
895                 bool addedModel = theName.compare("") != 0;
896                 if( addedModel )
897                 {
898                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
899                         _theViewPanel->getSpacing(spc);                                 
900                         //Adding the manualContourControler to interface objects structure
901                         //Adding the manualViewContour to interface objects structure           
902                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
903                         _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
904                 }       
905                 
906                 if (staticContour==true)
907                 {
908                         Instant instant(&instantVector);
909                         kernelManager->changeContourOfManager( theName , &instant );
910                 }
911         }// for  numberOfContours
912 }
913
914 void wxContourMainFrame::onLoad()
915 {       
916         std::string fileNameContourROI = GetFileLocation();
917 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
918         if(GetFileLocation().empty())
919         {
920 //------------------------------------------------------------------------------------------------------------
921                 wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxOPEN );
922                 if (dialog.ShowModal() == wxID_OK)
923                 {
924                         fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
925                 }
926         }
927
928         onLoadContours(fileNameContourROI);
929 }
930
931 void wxContourMainFrame::onLoadContours(std::string fileNameContourROI){
932         char tmp[255];
933         char tmpD[255];
934
935         FILE *pFile =fopen(fileNameContourROI.c_str(),"r+");
936
937
938 //CMRU 03-09-09- ----------------------------------------------------------------------------------------------
939         if(pFile != NULL)
940         {
941 //------------------------------------------------------------------------------------------------------------
942         fileNameContourROI.append("data");      
943                 FILE *pFileData=fopen(fileNameContourROI.c_str(),"r+");
944                 if(pFileData != NULL)
945                 {
946                         fscanf(pFileData,"%s",tmpD); // --CreaContour--
947                         fscanf(pFileData,"%s",tmpD); // Version
948                         fscanf(pFileData,"%s",tmpD); // 1.0.2 || 1.0.1 || 1.0.0
949                         
950                         fscanf(pFileData,"%s",tmpD); // onePixelSize
951                         fscanf(pFileData,"%s",tmpD); // #
952                         _onePixelSize = atof(tmpD);             
953                         fscanf(pFileData,"%s",tmpD); // NumberOfContours  
954                         fscanf(pFileData,"%s",tmpD); // #
955                 }
956
957                 fscanf(pFile,"%s",tmp); // --CreaContour--
958
959                 fscanf(pFile,"%s",tmp); // Version
960                 fscanf(pFile,"%s",tmp); // 1.0.2 || 1.0.1 || 1.0.0
961                 std::string version(tmp);
962                 
963                 //AD:02-06-09
964                 if (version=="1.0.2")
965                 {
966                         openContours(pFile,pFileData,2,false);
967                         openContours(pFile,pFileData,2,true);   //Load StaticContours
968                 }
969                 
970                 //AD:02-06-09
971                 else if (version=="1.0.1")
972                 {
973                         openContours(pFile,pFileData,1,false); //Skips ImageDimensions and ImageSpacing
974                         openContours(pFile,pFileData,1,true); //Load StaticContours, skips ImageDimensions and ImageSpacing
975                 }
976                 
977                 //AD:02-06-09
978                 else if (version=="1.0.0")
979                 {
980                         openContours(pFile,pFileData,1,false); //Skips ImageDimensions and ImageSpacing
981                 }
982
983                 fclose(pFile);
984
985                 if(pFileData != NULL)
986                 {
987                         fclose(pFileData);
988                 }
989         }
990         _theViewPanel->getSceneManager()->removeSceneContours();
991         changeInstant();
992
993 }
994
995 void wxContourMainFrame::onImport(){
996         std::string filename, filenamecontours;
997         wxFileDialog dialog(NULL, _T("Choose a XML Osirix File"), _T(""), _T(""), _T("*.xml"), wxOPEN );
998
999         if (dialog.ShowModal() == wxID_OK)
1000         {
1001                 filename = dialog.GetPath().mb_str();           
1002                 filenamecontours = kernelManager->parseOsirixFile(filename);
1003
1004                 if(filenamecontours.compare("") != 0){
1005                         onLoadContours(filenamecontours);
1006                 }
1007
1008         }
1009 }
1010
1011 //AD: 29-05-09
1012 void wxContourMainFrame::onSave(){
1013 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1014         if(GetFileLocation().empty())
1015         {
1016 //------------------------------------------------------------------------------------------------------------
1017                 wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxSAVE );
1018                 if (dialog.ShowModal() == wxID_OK)
1019                 {
1020                         std::string fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
1021                         kernelManager->setCurrentFileName(fileNameContourROI);
1022                         saveFileWithContours( fileNameContourROI );
1023                 }
1024         }
1025 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1026         else
1027         {
1028                 std::cout<<"Nombre del archivo: "<<GetFileLocation()<<std::endl;                
1029                 std::string fileNameContourROI = GetFileLocation();
1030                 std::cout<<"Nombre del archivo: "<<fileNameContourROI<<std::endl;               
1031                 kernelManager->setCurrentFileName(fileNameContourROI);
1032                 saveFileWithContours( fileNameContourROI);
1033         }
1034 //------------------------------------------------------------------------------------------------------------
1035 }
1036
1037 //AD: 29-05-09
1038 void wxContourMainFrame::saveFileWithContours( std::string filename )
1039 {
1040
1041         FILE *pFile=fopen(filename.c_str(),"w+");
1042
1043 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1044         filename.append("data");
1045         std::cout<<"Nombre del archivo: "<<filename<<std::endl;         
1046         FILE *pFileData=fopen(filename.c_str(),"w+");
1047 //------------------------------------------------------------------------------------------------------------
1048
1049         std::vector< std::string > lstNameThings;
1050         int i,sizeLstNameThings; 
1051
1052         fprintf(pFile,"--CreaContour--\n");
1053         fprintf(pFile,"Version %s\n", "1.0.2" );
1054
1055 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1056         fprintf(pFileData,"--CreaContour--\n");
1057         fprintf(pFileData,"Version %s\n", "1.0.2" );
1058         fprintf(pFileData,"OnePixelSize %f\n", _onePixelSize);
1059         
1060 //------------------------------------------------------------------------------------------------------------
1061         
1062         vtkImageData *image = _images[0];
1063
1064         int dimRange[3];
1065         image->GetDimensions(dimRange);
1066
1067         fprintf(pFile,"ImageDimensions %d %d %d\n", dimRange[0], dimRange[1], dimRange[2] );
1068
1069         double spaRange[3];
1070         image->GetSpacing(spaRange);
1071
1072         fprintf(pFile,"ImageSpacing %f %f %f\n", spaRange[0], spaRange[1], spaRange[2] );
1073
1074         // Normal Contours
1075         
1076         lstNameThings           = kernelManager->GetLstNameThings();
1077         sizeLstNameThings       = lstNameThings.size(); 
1078         fprintf(pFile,"NumberOfContours %d\n", sizeLstNameThings );
1079
1080 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1081         fprintf(pFileData,"NumberOfContours %d\n", sizeLstNameThings );
1082 //------------------------------------------------------------------------------------------------------------
1083
1084         for (i=0 ; i<sizeLstNameThings ; i++) 
1085         {
1086 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1087                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
1088                 double sizeInPixel = manualModel ->GetPathSize();
1089                 double realContourSize = sizeInPixel*_onePixelSize;
1090                 manualModel ->SetRealSize(realContourSize);
1091 //------------------------------------------------------------------------------------------------------------
1092
1093         //int size= kernelManager->GetLstNameThings().size();
1094
1095                 kernelManager->SaveThingName( pFile, pFileData, lstNameThings[i] );
1096                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
1097         }// for i
1098
1099         //-- Static Contours
1100
1101         fprintf(pFile,"ImageDimensions %d %d %d\n", dimRange[0], dimRange[1], dimRange[2] );
1102         
1103         fprintf(pFile,"ImageSpacing %f %f %f\n", spaRange[0], spaRange[1], spaRange[2] );
1104         
1105         lstNameThings           = kernelManager->GetLstNameThingsStatic();
1106         sizeLstNameThings       = lstNameThings.size(); 
1107         fprintf(pFile,"NumberOfContoursStatic %d\n", sizeLstNameThings );
1108
1109 //CMRU 03-09-09-----------------------------------------------------------------------------------------------
1110         fprintf(pFileData,"NumberOfContoursStatic %d\n", sizeLstNameThings );
1111 //------------------------------------------------------------------------------------------------------------
1112
1113         for (i=0 ; i<sizeLstNameThings ; i++) 
1114         {
1115                 kernelManager->SaveThingName( pFile, pFileData, lstNameThings[i] );
1116                 _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
1117         }// for i
1118         fclose(pFile);
1119         fclose(pFileData);
1120 }
1121
1122 //AD:04-06-09
1123 void wxContourMainFrame::openContours( FILE *pFile, FILE *pFileData, int version, bool staticContour )
1124 {
1125         char tmp[255];
1126         
1127         vtkImageData *image = _images[0];
1128         int imageDim[3];
1129         double imageSpac[3];
1130         int tempDim[3];
1131         double tempSpac[3];
1132         
1133         bool compatible = true;
1134         
1135         //Version==2    
1136         if (version==2)
1137         {
1138                 image->GetDimensions(imageDim);
1139                 image->GetSpacing(imageSpac);
1140
1141                 fscanf(pFile,"%s",tmp); // ImageDimensions
1142                 fscanf(pFile,"%s",tmp); // X
1143                 tempDim[0] = atoi(tmp);
1144                 fscanf(pFile,"%s",tmp); // Y
1145                 tempDim[1] = atoi(tmp);
1146                 fscanf(pFile,"%s",tmp); // Z
1147                 tempDim[2] = atoi(tmp);
1148
1149                 fscanf(pFile,"%s",tmp); // ImageSpacing
1150                 fscanf(pFile,"%s",tmp); // X
1151                 tempSpac[0] = atof(tmp);
1152                 fscanf(pFile,"%s",tmp); // Y
1153                 tempSpac[1] = atof(tmp);
1154                 fscanf(pFile,"%s",tmp); // Z
1155                 tempSpac[2] = atof(tmp);
1156                 
1157                 //Compare Spacing and Dims in X and Y (Necessary in Z?) - Just for Version 2
1158                 if (imageDim[0]!=tempDim[0] || imageDim[1]!=tempDim[1] || imageSpac[0]!=tempSpac[0] || imageSpac[1]!=tempSpac[1])
1159                 {
1160                         compatible = false;
1161                 }
1162         }
1163         
1164         fscanf(pFile,"%s",tmp); // NumberOfContours 
1165         fscanf(pFile,"%s",tmp); // ##
1166         int numberOfContours = atoi(tmp);  
1167
1168         std::vector<int> instantVector;
1169         int typeContourModel;
1170         manualBaseModel *manModelContour;
1171         int typeView;
1172
1173         if (compatible==true)
1174         {
1175                 int i;
1176                 for (i=0;i<numberOfContours;i++)
1177                 {
1178                         instantVector.clear();
1179                         fscanf(pFile,"%s",tmp); // Instant
1180
1181                         fscanf(pFile,"%s",tmp); // 1
1182                         instantVector.push_back( atoi(tmp) );
1183                         fscanf(pFile,"%s",tmp); // 2
1184                         instantVector.push_back( atoi(tmp) );
1185                         fscanf(pFile,"%s",tmp); // 3
1186                         instantVector.push_back( atoi(tmp) );
1187                         fscanf(pFile,"%s",tmp); // 4
1188                         instantVector.push_back( atoi(tmp) );
1189                         fscanf(pFile,"%s",tmp); // 5
1190                         instantVector.push_back( atoi(tmp) );
1191                         fscanf(pFile,"%s",tmp); // 6
1192                         instantVector.push_back( atoi(tmp) );
1193
1194
1195                         fscanf(pFile,"%s",tmp); // TypeContourModel
1196                         fscanf(pFile,"%s",tmp); // ##
1197                         typeContourModel = atoi(tmp);
1198
1199                         manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
1200                         manModelContour->Open(pFile);
1201                         if(pFileData != NULL)
1202                         {
1203                                 manModelContour->OpenData(pFileData);
1204                         }
1205
1206                         fscanf(pFile,"%s",tmp); // TypeView
1207                         fscanf(pFile,"%s",tmp); // ##
1208                         typeView = atoi(tmp);  
1209
1210                         std::string theName;
1211                         theName = kernelManager->createOutline( manModelContour, instantVector );
1212                         bool addedModel = theName.compare("") != 0;
1213                         if( addedModel )
1214                         {
1215                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1216                                 _theViewPanel->getSpacing(spc);                                 
1217                                 //Adding the manualContourControler to interface objects structure
1218                                 //Adding the manualViewContour to interface objects structure           
1219                                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1220                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
1221                         }       
1222
1223                         if (staticContour) //StaticContours (will appear in all slices)
1224                         {
1225                                 Instant instant(&instantVector);
1226                                 kernelManager->changeContourOfManager( theName , &instant );
1227                         }
1228
1229                 }// for  numberOfContours       
1230         }
1231
1232         else if (compatible==false)
1233         {
1234                 wxDialog* dial = new wxDialog (this,-1,_T("Tools"),wxDefaultPosition, wxSize(260,160));
1235                 wxSizer* buttonsSizer = dial->CreateSeparatedButtonSizer(wxOK|wxCANCEL);
1236                 wxBoxSizer *dialSizer = new wxBoxSizer(wxVERTICAL);
1237
1238                 wxString lstOptOperation[2];
1239                 lstOptOperation[0]=_T("By Dimension");
1240                 lstOptOperation[1]=_T("By Spacing");
1241                 wxRadioBox * radioOpts = new wxRadioBox(dial, -1, _T("Type of Transformation"), wxDefaultPosition, wxSize(270,45), 2 , lstOptOperation,  2, wxRA_SPECIFY_COLS);         
1242                 
1243                 dialSizer->Add( new wxStaticText(dial,-1,_T("The image resolution is not compatible with the "))  , 0, wxGROW );
1244                 dialSizer->Add( new wxStaticText(dial,-1,_T("selected Roi file. Do you want to tranform it?"))  , 0, wxGROW );  
1245                 dialSizer->Add( new wxStaticText(dial,-1,_T(" "))  , 0, wxGROW );               
1246                 dialSizer->Add(radioOpts,0,wxGROW);
1247                 dialSizer->Add( new wxStaticText(dial,-1,_T(" "))  , 0, wxGROW );       
1248                 dialSizer->Add(buttonsSizer,0,wxGROW);
1249                 dial->SetSizer(dialSizer, true);
1250                 dial->Layout();
1251                 dial->ShowModal();
1252                 
1253                 int typeOfTransformation = -1;
1254                 bool transform = false;
1255
1256                 if (dial->GetReturnCode() == wxID_OK)
1257                 {
1258                         typeOfTransformation = radioOpts->GetSelection();
1259                         transform = true;
1260                 }
1261         
1262                 int i;
1263                 for (i=0;i<numberOfContours;i++)
1264                 {
1265                         instantVector.clear();
1266                         fscanf(pFile,"%s",tmp); // Instant
1267
1268                         fscanf(pFile,"%s",tmp); // 1
1269                         instantVector.push_back( atoi(tmp) );
1270                         fscanf(pFile,"%s",tmp); // 2
1271                         instantVector.push_back( atoi(tmp) );
1272                         fscanf(pFile,"%s",tmp); // 3
1273                         instantVector.push_back( atoi(tmp) );
1274                         fscanf(pFile,"%s",tmp); // 4
1275                         instantVector.push_back( atoi(tmp) );
1276                         fscanf(pFile,"%s",tmp); // 5
1277                         instantVector.push_back( atoi(tmp) );
1278                         fscanf(pFile,"%s",tmp); // 6
1279                         instantVector.push_back( atoi(tmp) );
1280
1281                         fscanf(pFile,"%s",tmp); // TypeContourModel
1282                         fscanf(pFile,"%s",tmp); // ##
1283                         typeContourModel = atoi(tmp);
1284
1285                         manModelContour =  kernelManager->factoryManualContourModel(typeContourModel);
1286                         manModelContour->Open(pFile);
1287                         if(pFileData != NULL)
1288                         {
1289                                 manModelContour->OpenData(pFileData);
1290                         }
1291                         if (transform==true)
1292                         {
1293                                 if (typeOfTransformation==0)
1294                                 {
1295                                         double transX, transY;
1296                                         transX = (double) imageDim[0]/tempDim[0];
1297                                         transY = (double) imageDim[1]/tempDim[1];
1298                                         manModelContour->Transform_Ax_Plus_B(transX,0,transY,0);
1299                                 }
1300                                 else if (typeOfTransformation==1)
1301                                 {
1302                                         double transX, transY;
1303                                         transX = (double) tempSpac[0]/imageSpac[0];
1304                                         transY = (double) tempSpac[1]/imageSpac[1];
1305                                         manModelContour->Transform_Ax_Plus_B(transX,0,transY,0);
1306                                 }
1307                         }
1308
1309                         fscanf(pFile,"%s",tmp); // TypeView
1310                         fscanf(pFile,"%s",tmp); // ##
1311                         typeView = atoi(tmp);  
1312
1313                         std::string theName;
1314                         theName = kernelManager->createOutline( manModelContour, instantVector );
1315                         bool addedModel = theName.compare("") != 0;
1316                         if( addedModel )
1317                         {
1318                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1319                                 _theViewPanel->getSpacing(spc);                                 
1320                                 //Adding the manualContourControler to interface objects structure
1321                                 //Adding the manualViewContour to interface objects structure           
1322                                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1323                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
1324                         }       
1325
1326                         if (staticContour) //StaticContours (will appear in all slices)
1327                         {
1328                                 Instant instant(&instantVector);
1329                                 kernelManager->changeContourOfManager( theName , &instant );
1330                         }
1331                 }// for  numberOfContours       
1332         }
1333 }
1334
1335 void wxContourMainFrame::RefreshInterface(){
1336         changeInstant();
1337         _theViewPanel->RefreshInterface();
1338         //wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
1339         //wxvtk2dbaseview->Refresh();
1340 }
1341
1342 vtkImageData* wxContourMainFrame::getImageData(){
1343         return _theViewPanel->getImageData();
1344 }
1345
1346 void wxContourMainFrame::onSegmentationOneSliceITK(wxString distance, wxString sigma, wxString alfa, wxString beta, wxString propagation, wxString iterations, wxString inflation)
1347 {
1348         //JCP 20-10-08 Undo redo implementation
1349         saveState();
1350         //JCP 20-10-08 Undo redo implementation
1351         
1352         wxBusyCursor wait;
1353         int                                     x                                       = _theViewPanel->GetX();
1354         int                                     y                                       = _theViewPanel->GetY();
1355         int                                     z                                       = _theViewPanel->GetZ();
1356         SegmentationOneSliceITK( x,y,z,distance, sigma, alfa, beta, propagation, iterations, inflation);
1357         RefreshInterface();
1358 }
1359
1360 void wxContourMainFrame::SegmentationOneSliceITK(int x, int y, int z, wxString distanc, wxString sigm, wxString alf, wxString bet, wxString prop, wxString iter, wxString inflation)
1361 {
1362         int typeofcontour = 1;
1363         //Image Data
1364         vtkImageData    *imagedata      = getImageData();
1365         
1366         //Tipo de pixeles a utilizar internamente en ITK
1367         typedef   float  InternalPixelType;
1368         const     unsigned int    Dimension = 2;
1369         typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;
1370
1371         //Tipo de pixeles de salida 1
1372         typedef unsigned char OutputPixelType;
1373         typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
1374
1375         //Tipo de pixeles de salida 2
1376         typedef unsigned short OutputPixelType2;
1377         typedef itk::Image< OutputPixelType2, Dimension > OutputImageType2;
1378
1379         //DefiniciÛn del thresholder
1380         typedef itk::BinaryThresholdImageFilter< 
1381                                                         InternalImageType, 
1382                                                         OutputImageType    >    ThresholdingFilterType;
1383           
1384         //DefiniciÛn del primer filtro de conversiÛn de pixeles
1385         typedef itk::CastImageFilter<
1386                                 OutputImageType, OutputImageType2 >  CastFilterType;
1387
1388         //DefiniciÛn del segundo tipo de conversiÛn de pixeles
1389         typedef itk::CastImageFilter<
1390                                 OutputImageType2, InternalImageType >  CastFilterType2;
1391
1392         //Tercer tipo de conversiÛn
1393         typedef itk::RescaleIntensityImageFilter< 
1394                                                                 InternalImageType, 
1395                                                                 OutputImageType >   CastFilterType3;
1396
1397         //Cuarto tipo de conversiÛn
1398         typedef itk::RescaleIntensityImageFilter< 
1399                                                                 OutputImageType, 
1400                                                                 OutputImageType >   CastFilterType4;
1401
1402         ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New();
1403                                 
1404         thresholder->SetLowerThreshold( 0.0 );
1405         thresholder->SetUpperThreshold( 128 );
1406
1407         thresholder->SetOutsideValue(  255  );
1408         thresholder->SetInsideValue(  0 );
1409
1410         //DefinciÛn de conexiÛnes entre VTK e ITK y el writer
1411         typedef itk::VTKImageToImageFilter<OutputImageType2> ConnectorType;
1412         typedef itk::ImageToVTKImageFilter<OutputImageType> ConnectorType2;
1413         typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;
1414
1415         ConnectorType::Pointer connector= ConnectorType::New();
1416         ConnectorType2::Pointer connector2= ConnectorType2::New();
1417           
1418
1419         CastFilterType::Pointer filter=CastFilterType::New();
1420         CastFilterType2::Pointer filter2=CastFilterType2::New();
1421
1422         connector->SetInput( imagedata );
1423         filter2->SetInput(connector->GetOutput());
1424
1425         typedef   itk::CurvatureAnisotropicDiffusionImageFilter< 
1426                                                                 InternalImageType, 
1427                                                                 InternalImageType >  SmoothingFilterType;
1428
1429         SmoothingFilterType::Pointer smoothing = SmoothingFilterType::New();
1430
1431         typedef   itk::GradientMagnitudeRecursiveGaussianImageFilter< 
1432                                                                 InternalImageType, 
1433                                                                 InternalImageType >  GradientFilterType;
1434
1435         typedef   itk::SigmoidImageFilter<                               
1436                                                                 InternalImageType, 
1437                                                                 InternalImageType >  SigmoidFilterType;
1438
1439         GradientFilterType::Pointer  gradientMagnitude = GradientFilterType::New();
1440
1441         SigmoidFilterType::Pointer sigmoid = SigmoidFilterType::New();
1442
1443         sigmoid->SetOutputMinimum(  0.0  );
1444         sigmoid->SetOutputMaximum(  255.0  );
1445
1446
1447         typedef  itk::FastMarchingImageFilter< 
1448                                                                 InternalImageType, 
1449                                                                 InternalImageType >    FastMarchingFilterType;
1450
1451
1452         FastMarchingFilterType::Pointer  fastMarching = FastMarchingFilterType::New();
1453
1454         typedef  itk::GeodesicActiveContourLevelSetImageFilter< InternalImageType, 
1455                                         InternalImageType >    GeodesicActiveContourFilterType;
1456         GeodesicActiveContourFilterType::Pointer geodesicActiveContour = 
1457                                                                                 GeodesicActiveContourFilterType::New();
1458
1459         typedef  itk::ZeroCrossingImageFilter< 
1460                                                                 InternalImageType, 
1461                                                                 InternalImageType >    ZeroCrossingFilterType;
1462         ZeroCrossingFilterType::Pointer zeroCrossing =
1463                                                         ZeroCrossingFilterType::New();
1464
1465         const double propagationScaling = atof( crea::wx2std(prop).c_str() );
1466
1467         geodesicActiveContour->SetPropagationScaling( propagationScaling );
1468         geodesicActiveContour->SetCurvatureScaling( 1.0 );
1469         geodesicActiveContour->SetAdvectionScaling( 1.0 );
1470
1471         geodesicActiveContour->SetMaximumRMSError( 0.02 );
1472         int it=atoi(  crea::wx2std(iter).c_str() );
1473         geodesicActiveContour->SetNumberOfIterations( it );
1474
1475         smoothing->SetInput( filter2->GetOutput() );
1476         gradientMagnitude->SetInput( smoothing->GetOutput() );
1477         sigmoid->SetInput( gradientMagnitude->GetOutput() );
1478         fastMarching->SetInput( sigmoid->GetOutput() );
1479         geodesicActiveContour->SetInput( fastMarching->GetOutput() );
1480         geodesicActiveContour->SetFeatureImage( sigmoid->GetOutput() );
1481           
1482         zeroCrossing->SetInput( geodesicActiveContour->GetOutput() );
1483         //thresholder->SetInput( zeroCrossing->GetOutput() );
1484         thresholder->SetInput( geodesicActiveContour->GetOutput() );
1485         connector2->SetInput( thresholder->GetOutput()  );
1486           
1487
1488         smoothing->SetTimeStep( 0.125 );
1489         smoothing->SetNumberOfIterations(  5 );
1490         smoothing->SetConductanceParameter( 9.0 );
1491
1492
1493         const double sigma = atof(  crea::wx2std(sigm).c_str() );
1494         gradientMagnitude->SetSigma(  sigma  );
1495
1496         const double alpha =  atof(  crea::wx2std(alf).c_str() );
1497         const double beta  =  atof(  crea::wx2std(bet).c_str() );
1498
1499         sigmoid->SetAlpha( alpha );
1500         sigmoid->SetBeta(  beta  );
1501           
1502         typedef FastMarchingFilterType::NodeContainer  NodeContainer;
1503         typedef FastMarchingFilterType::NodeType       NodeType;
1504
1505         NodeContainer::Pointer seeds = NodeContainer::New();
1506
1507         InternalImageType::IndexType  seedPosition;
1508         seedPosition[0] = x;
1509         seedPosition[1] = y;
1510
1511         const double initialDistance = atof( crea::wx2std(distanc).c_str() );
1512
1513         NodeType node;
1514
1515         const double seedValue = - initialDistance;
1516
1517         node.SetValue( seedValue );
1518         node.SetIndex( seedPosition );
1519                 
1520         seeds->Initialize();
1521         seeds->InsertElement( 0, node );
1522
1523         fastMarching->SetTrialPoints( seeds );
1524
1525         fastMarching->SetSpeedConstant( 1.0 );
1526           
1527         fastMarching->SetOutputSize( 
1528                         connector->GetOutput()->GetBufferedRegion().GetSize() );
1529           
1530         fastMarching->SetStoppingValue( 800 );
1531         try
1532     {
1533                 
1534         connector2->Update();
1535         vtkImageData *idata = connector2->GetOutput();
1536
1537         vtkMarchingContourFilter* cntVTK = vtkMarchingContourFilter::New( );
1538         
1539         cntVTK->SetInput( idata );
1540         
1541         cntVTK->SetNumberOfContours( 1 );
1542         cntVTK->SetValue( 0, 255 );
1543         cntVTK->Update( );
1544         cntVTK->UpdateInformation();
1545                 
1546         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1547         cpd->SetInput( cntVTK->GetOutput( ) );
1548         cpd->Update( );
1549         cpd->UpdateInformation();
1550
1551         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1552         conn->SetExtractionModeToLargestRegion( );
1553         conn->SetInput( cpd->GetOutput( ) );
1554         conn->Update( );
1555         conn->UpdateInformation();
1556
1557         vtkStripper* vtkstripper = vtkStripper::New( );
1558         vtkstripper->SetInput( conn->GetOutput() );
1559         vtkstripper->Update();
1560         vtkstripper->UpdateInformation();
1561
1562
1563         vtkPolyData* polyDataResult =  cntVTK->GetOutput();
1564         //std::cout<<"Points "<<polyDataResult->GetNumberOfPoints()<<std::endl;
1565         polyDataResult->Update( );
1566         polyDataResult->UpdateInformation();
1567
1568         //EED
1569                 /*
1570         ofstream myfile;
1571         myfile.open ("C:/Creatis/example.txt");
1572         myfile << "\n";
1573         polyDataResult->Print(myfile);
1574         myfile << "-------------------------------------\n";
1575         polyDataResult->GetLines()->Print(myfile);
1576         myfile.close();*/
1577
1578         cntVTK          -> Delete();
1579         cpd                     -> Delete();
1580         conn            -> Delete();
1581
1582
1583         //--Calculating control points
1584
1585         std::vector<double> vecX;
1586         std::vector<double> vecY;
1587         std::vector<double> vecXo;
1588         std::vector<double> vecYo;
1589         std::vector<double>::iterator vecXoi;
1590         std::vector<double>::iterator vecYoi;
1591         std::vector<double> vecZ;
1592
1593         std::vector<double> vecCtrlPointX;
1594         std::vector<double> vecCtrlPointY;
1595         std::vector<double> vecCtrlPointZ;
1596
1597
1598         double *p;
1599         double xAct=0;
1600         double yAct=0;
1601         int ii,size=polyDataResult->GetNumberOfPoints();
1602         ofstream myfile;
1603         myfile.open ("C:/Creatis/example2.txt");
1604
1605         size=polyDataResult->GetNumberOfPoints();
1606         for (ii=0;ii<size;ii++)
1607         {
1608                 if(ii==0)
1609                 {
1610                         xAct=x;
1611                         yAct=y;
1612                 }
1613                 p       = polyDataResult->GetPoint(ii);
1614                 double x=p[0];
1615                 double y=p[1];
1616                 /*if(fabs(yAct-y)>20)
1617                 {
1618                         if((xAct-x)>1 || (xAct-x)<-1)
1619                         {
1620                         vecX.push_back( p[0] );
1621                         vecY.push_back( p[1] );
1622                         myfile <<p[0]<<","<<p[1]<<"\n";
1623                         std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1624                 std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1625                 std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1626                         vecZ.push_back( 900 );
1627                         xAct=x;
1628                         yAct=y;
1629                         }
1630                         else
1631                         {
1632                                 vecXo.push_back(p[0]);
1633                                 vecYo.push_back(p[1]);
1634                         }
1635                         
1636                 }
1637                 else*/ if(fabs(xAct-x)>11)
1638                 {
1639                         vecXo.push_back(p[0]);
1640                         vecYo.push_back(p[1]);
1641                 }
1642                 else
1643                 {
1644                 vecX.push_back( p[0] );
1645                 myfile <<p[0]<<","<<p[1]<<"\n";
1646                 //std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1647                 //std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1648                 //std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1649                 vecY.push_back( p[1] );
1650                 vecZ.push_back( 900 );
1651                 xAct=x;
1652                 yAct=y;
1653                 }
1654                 
1655                 
1656         }
1657
1658         while(!vecXo.empty())
1659         {
1660                 vecX.push_back(vecXo.back());
1661                 //std::cout<<" x Siguiente "<<vecXo.back();
1662                 vecXo.pop_back();
1663                 vecZ.push_back( 900 );
1664         }
1665         while(!vecYo.empty())
1666         {
1667                 vecY.push_back(vecYo.back());
1668                         vecYo.pop_back();
1669         }
1670         myfile.close();
1671
1672         /*for(int l=0;l<vecX.size();l++)
1673         {
1674                 if(l==0)
1675                 {
1676             vecXo.push_back(p[0]);
1677                         vecYo.push_back(p[1]);
1678                 }
1679                 else
1680                 {
1681                         if(vecXoi[l-1]==)
1682                         {
1683                         }
1684                 }
1685
1686         }*/
1687
1688         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1689
1690         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1691         
1692         int method=2;
1693         if (method==0){
1694                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1695         }
1696         else if (method==1){
1697                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1698         }
1699         else if (method==2){
1700                 extractcontrolpoints2d->SetSamplingControlPoints( 15 );
1701                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1702         }
1703         //--Adding contour to the system
1704
1705         std::vector<int> actualInstantVector;
1706         _instantPanel->getInstant( actualInstantVector );
1707         actualInstantVector[1]=z;
1708
1709         int j,sizeCtrPt = vecCtrlPointX.size();
1710         
1711         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1712         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1713         if (sizeCtrPt>=3){
1714                 for (j=0 ; j<sizeCtrPt ; j++)
1715                 {
1716                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1717                 } // for
1718                 std::string theName;
1719                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1720                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1721                 bool addedModel = theName.compare("") != 0;
1722                 if( addedModel )
1723                 {
1724                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1725                         _theViewPanel->getSpacing(spc); 
1726                         //Adding the manualContourControler to interface objects structure
1727                         //Adding the manualViewContour to interface objects structure           
1728                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1729                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1730                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1731                 }       // if addedModel
1732         } // if sizeCtrPt
1733
1734                 
1735                  
1736                  WriterType::Pointer writer = WriterType::New();
1737          CastFilterType3::Pointer caster = CastFilterType3::New();
1738                  
1739                  caster->SetInput( gradientMagnitude->GetOutput() );
1740                  writer->SetInput( caster->GetOutput() );
1741                  writer->SetFileName("Gradient Magnitude.png");
1742                  caster->SetOutputMinimum(   0 );
1743                  caster->SetOutputMaximum( 255 );
1744                  writer->Update();
1745                 
1746                  CastFilterType3::Pointer caster2 = CastFilterType3::New();
1747                  WriterType::Pointer writer2 = WriterType::New();
1748
1749                  caster2->SetInput( sigmoid->GetOutput() );
1750                  writer2->SetInput( caster2->GetOutput() );
1751                  writer2->SetFileName("Sigmoid.png");
1752                  caster2->SetOutputMinimum(   0 );
1753                  caster2->SetOutputMaximum( 255 );
1754                  writer2->Update();
1755
1756                  CastFilterType3::Pointer caster3 = CastFilterType3::New();
1757                  WriterType::Pointer writer3 = WriterType::New();
1758
1759                  caster3->SetInput( fastMarching->GetOutput() );
1760                  writer3->SetInput( caster3->GetOutput() );
1761                  writer3->SetFileName("FastMarching.bmp");
1762                  caster3->SetOutputMinimum(   0 );
1763                  caster3->SetOutputMaximum( 255 );
1764                  writer3->Update();
1765
1766                  CastFilterType3::Pointer caster4 = CastFilterType3::New();
1767                  WriterType::Pointer writer4 = WriterType::New();
1768
1769                  caster4->SetInput( geodesicActiveContour->GetOutput() );
1770                  writer4->SetInput( caster4->GetOutput() );
1771                  writer4->SetFileName("GeodesicActiveContour.png");
1772                  caster4->SetOutputMinimum(   0 );
1773                  caster4->SetOutputMaximum( 255 );
1774                  writer4->Update();
1775
1776                  CastFilterType3::Pointer caster5 = CastFilterType3::New();
1777                  WriterType::Pointer writer5 = WriterType::New();
1778
1779                  caster5->SetInput( zeroCrossing->GetOutput() );
1780                  writer5->SetInput( caster5->GetOutput() );
1781                  writer5->SetFileName("ZeroCrossing.bmp");
1782                  caster5->SetOutputMinimum(   0 );
1783                  caster5->SetOutputMaximum( 255 );
1784                  writer5->Update();
1785     }
1786   catch( itk::ExceptionObject & excep )
1787     {
1788     std::cerr << "Exception caught !" << std::endl;
1789     std::cerr << excep << std::endl;
1790     }
1791 }
1792
1793 void wxContourMainFrame::onSegmentationOneSlice(int isovalue,int sampling,int method){
1794         
1795         //JCP 20-10-08 Undo redo implementation
1796         saveState();
1797         //JCP 20-10-08 Undo redo implementation
1798         
1799         wxBusyCursor wait;
1800         int                                     x                                       = _theViewPanel->GetX();
1801         int                                     y                                       = _theViewPanel->GetY();
1802         int                                     z                                       = _theViewPanel->GetZ();
1803         SegmentationOneSlice( x,y,z,isovalue, sampling, method );
1804         RefreshInterface();
1805 }
1806
1807
1808 void wxContourMainFrame::SegmentationOneSlice( int x, int y, int z, int isovalue, int sampling, int method )
1809 {               
1810         int typeofcontour = 1;
1811         //--Extracting Contour
1812         //vtkImageData  *imagedata      = _theViewPanel->getSceneManager()->GetImageData();
1813         vtkImageData    *imagedata      = getImageData();
1814 //              double                  *range          = imagedata->GetScalarRange();  
1815 //              double                  thr                     = 1;
1816
1817         vtkImageReslice *imageReslice = vtkImageReslice::New();
1818 //EED
1819 //              double spc[3];
1820 //              imagedata->GetSpacing(spc);
1821 //              x = x*spc[0];
1822 //              y = y*spc[1];
1823 //              z = z*spc[3];
1824
1825         imageReslice->SetInput( imagedata );
1826         imageReslice->SetInformationInput(imagedata);
1827         imageReslice->SetResliceAxesDirectionCosines(1,0,0, 0,1,0 ,0,0,1);
1828         imageReslice->SetResliceAxesOrigin(0,0,z);
1829         imageReslice->SetOutputDimensionality(2);
1830         imageReslice->SetInterpolationModeToLinear();
1831
1832         imagedata = imageReslice->GetOutput();
1833         imagedata->Update();
1834         imagedata->UpdateInformation();
1835
1836         vtkContourFilter* cntVTK = vtkContourFilter::New( );
1837         cntVTK->SetInput( imagedata );
1838
1839         cntVTK->SetNumberOfContours( 1 );
1840         //cntVTK->SetValue( 0, vmin );
1841 //              cntVTK->SetValue( 0, (range[1]*thr/100) );
1842         cntVTK->SetValue( 1, isovalue );
1843 //      cntVTK->SetValue( 1, vmax );
1844         cntVTK->Update( );
1845         cntVTK->UpdateInformation();
1846                 
1847         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1848         cpd->SetInput( cntVTK->GetOutput( ) );
1849         cpd->ConvertLinesToPointsOff( );
1850         cpd->Update( );
1851         cpd->UpdateInformation();
1852
1853         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1854         conn->SetExtractionModeToClosestPointRegion( );
1855         //conn->SetMaxRecursionDepth( 3000 );
1856                 
1857         conn->SetInput( cpd->GetOutput( ) );
1858                 
1859         conn->SetClosestPoint( x, y, 0 );
1860         conn->Update( );
1861         conn->UpdateInformation();
1862                 
1863         vtkCleanPolyData* cpd2 = vtkCleanPolyData::New( );
1864         cpd2->SetInput( conn->GetOutput( ) );
1865         cpd2->Update();
1866         cpd2->UpdateInformation();
1867
1868         vtkStripper* vtkstripper = vtkStripper::New( );
1869         vtkstripper->SetInput( cpd2->GetOutput() );
1870         vtkstripper->Update();
1871         vtkstripper->UpdateInformation();
1872
1873
1874         vtkPolyData* polyDataResult =  vtkstripper->GetOutput();
1875
1876         polyDataResult->Update( );
1877         polyDataResult->UpdateInformation();
1878
1879 /* EED
1880 ofstream myfile;
1881 myfile.open ("c:/temp/example.txt");
1882 myfile << "\n";
1883 polyDataResult->Print(myfile);
1884 myfile << "-------------------------------------\n";
1885 polyDataResult->GetLines()->Print(myfile);
1886 myfile.close();
1887 */
1888
1889         cntVTK          -> Delete();
1890         cpd2            -> Delete();
1891         cpd                     -> Delete();
1892         conn            -> Delete();
1893
1894
1895 //--Calculating control points
1896
1897         std::vector<double> vecX;
1898         std::vector<double> vecY;
1899         std::vector<double> vecZ;
1900
1901         std::vector<double> vecCtrlPointX;
1902         std::vector<double> vecCtrlPointY;
1903         std::vector<double> vecCtrlPointZ;
1904
1905
1906         double *p;
1907         int ii,size=polyDataResult->GetNumberOfPoints();
1908         int id;
1909         for (ii=1;ii<=size;ii++)
1910         {
1911                 id      = polyDataResult->GetLines()->GetData()->GetValue(ii);
1912                 p       = polyDataResult->GetPoint(id);
1913 //              double x=p[0];
1914 //              double y=p[1];
1915                 vecX.push_back( p[0] );
1916                 vecY.push_back( p[1] );
1917                 vecZ.push_back( 900 );
1918 //                      vecZ.push_back( p[2] );
1919         }
1920
1921
1922         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1923         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1924
1925 //PROOFS
1926         /*if (methodRadiobox->GetSelection()==0){
1927                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1928         }
1929         if (methodRadiobox->GetSelection()==1){
1930                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1931         }
1932         if (methodRadiobox->GetSelection()==2){
1933                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
1934                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1935         }*/
1936
1937         if (method==0){
1938                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1939         }
1940         else if (method==1){
1941                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1942         }
1943         else if (method==2){
1944                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
1945                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1946         }
1947
1948         //--Adding contour to the system
1949
1950         std::vector<int> actualInstantVector;
1951         _instantPanel->getInstant( actualInstantVector );
1952         actualInstantVector[1]=z;
1953
1954         int j,sizeCtrPt = vecCtrlPointX.size();
1955         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1956         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1957         if (sizeCtrPt>=3){
1958                 for (j=0 ; j<sizeCtrPt ; j++)
1959                 {
1960                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1961                 } // for
1962                 std::string theName;
1963                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1964                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1965                 bool addedModel = theName.compare("") != 0;
1966                 if( addedModel )
1967                 {
1968                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1969                         _theViewPanel->getSpacing(spc);                                 
1970                         //Adding the manualContourControler to interface objects structure
1971                         //Adding the manualViewContour to interface objects structure           
1972                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1973                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1974                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1975                 }       // if addedModel
1976         } // if sizeCtrPt
1977 }
1978 int wxContourMainFrame::GetImageDataSizeZ(){
1979         return _theViewPanel->GetImageDataSizeZ();
1980 }
1981
1982 void wxContourMainFrame::GetImageDataRange(double *range){
1983         _theViewPanel->GetImageDataRange(range);
1984 }
1985
1986 void wxContourMainFrame::onSegmentationAllSlice(int minZ,int maxZ,int isovalue,int sampling,int method){
1987         //JCP 20-10-08 Undo redo implementation
1988         saveState();
1989         //JCP 20-10-08 Undo redo implementation
1990         
1991         wxBusyCursor wait;
1992         int                                     x                                       = _theViewPanel->GetX();
1993         int                                     y                                       = _theViewPanel->GetY();
1994         int z;
1995         double porcent; 
1996         wxString tmpString;     
1997         double totalZ = maxZ-minZ+1;
1998         for( z=minZ ; z<=maxZ ; z++ )
1999         {
2000                 porcent = 100.0* (z-minZ)/totalZ;
2001                 tmpString.Printf(_T("  %d %c            %d/%d            %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ,z );
2002                 interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(tmpString);
2003                 //_staticTextSegmentation->SetLabel(tmpString);
2004                 SegmentationOneSlice( x,y,z,isovalue, sampling,method );
2005         }
2006         interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(_T("   "));
2007         RefreshInterface();
2008 }
2009
2010
2011 //Creates a reference line to be used as the axis of the mirroring
2012 void wxContourMainFrame::referenceLine()
2013 {
2014         if (_refLineControl==NULL)
2015         {
2016                 wxBusyCursor wait;
2017                 double spc[3];
2018
2019                 vtkImageData *vtkimagedata = _theViewPanel->getImageData();
2020                 vtkimagedata->GetSpacing(spc);
2021
2022                 wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
2023
2024                 _refLineControl = new manualLineControler();
2025                 _refLineModel   = new manualContourModelLine();
2026                 _refLineView = new manualViewLine();
2027                 _refLineView->SetModel( _refLineModel );
2028                 _refLineView->SetWxVtkBaseView( viewer2D );
2029                 _refLineView->SetRange( 2 );
2030                 _refLineView->SetZ( 1200 );
2031
2032                 _refLineView->SetSpacing(spc);
2033
2034                 _refLineView->SetColorNormalContour(0, 0, 1);
2035                 _refLineView->SetColorEditContour(0, 0.5, 0.5);
2036                 _refLineView->SetWidthLine(4);
2037
2038                 _refLineControl->SetModelView( _refLineModel , _refLineView );
2039                 vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2040                 style->AddInteractorStyleMaracas( _refLineControl );
2041                 _refLineModel->SetCloseContour(false);
2042                 _refLineControl->CreateNewManualContour();
2043
2044 //AD: Inicializar el mirroring con una linea ya pintada 
2045         /*
2046                 double z = _refLineControl->GetZ();
2047
2048                 int imageDim[3];
2049                 image->GetDimensions(imageDim);
2050                 double x = (double) imageDim[0]/2;
2051                 double y1 = (double) (imageDim[1]/2)+15;
2052                 double y2 = (double) (imageDim[1]/2)-15;
2053
2054                 _refLineControl->AddPoint(x,y1,z);
2055                 _refLineControl->AddPoint(x,y2,z);
2056                 _refLineControl->SetCompleteCreation(true);
2057
2058                 _refLineModel->AddPoint(x,y1,z);
2059                 _refLineModel->AddPoint(x,y2,z);
2060                 _refLineModel->UpdateSpline();
2061
2062                 _refLineView->UpdateViewPoint(0);
2063                 _refLineView->UpdateViewPoint(1);
2064         */
2065
2066                 _refLineControl->SetActive(true);
2067                 _refLineView->RefreshContour();
2068         }
2069 }
2070
2071 //Hides the referenceLine
2072 void wxContourMainFrame::refLineHide()
2073 {
2074         if (_refLineControl!=NULL)
2075         {
2076                 if (_refLineControl->GetActive())
2077                 {
2078                         _refLineView->RemoveCompleteContourActor();
2079                         _refLineControl->SetEditable(false);
2080                         _refLineControl->SetActive(false);
2081
2082                         RefreshInterface();
2083                 }
2084         }
2085 }
2086
2087 //Shows the referenceLine
2088 void wxContourMainFrame::refLineShow()
2089 {
2090         if (_refLineControl!=NULL)
2091         {
2092                 if (_refLineControl->GetActive()==false)
2093                 {
2094                         wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
2095
2096                         _refLineView->SetModel( _refLineModel );
2097                         _refLineView->SetWxVtkBaseView( viewer2D );
2098                         _refLineView->SetRange( 2 );
2099                         _refLineView->SetZ( 1200 );
2100
2101                         _refLineControl->SetModelView( _refLineModel , _refLineView );
2102                         vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2103                         style->AddInteractorStyleMaracas( _refLineControl );
2104                         _refLineControl->CreateNewManualContour();
2105                         _refLineControl->SetActive(true);
2106                         _refLineView->RefreshContour();
2107
2108                         RefreshInterface();
2109                 }
2110         }
2111 }
2112
2113 void wxContourMainFrame::refLineChangeWidth(int width)
2114 {
2115         _refLineView->SetWidthLine(width);
2116         _refLineView->RefreshContour();
2117
2118         RefreshInterface();
2119 }
2120
2121
2122 void wxContourMainFrame::onMirror()
2123 {
2124         //AD:02-09
2125         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2126         std::vector<std::string> filterCurrentSelection;
2127
2128         std::vector<int> tempVector;
2129         _instantPanel->getInstant( tempVector );
2130     _performingOperation->reset();
2131         _performingOperation->setStartCommand( COPY );
2132         _performingOperation->setStartOperationInstantVector( tempVector );
2133         _performingOperation->setKeyNamesOperationElems( currentSelection );
2134
2135         char theStartCommand = _performingOperation->getStartCommand();
2136         if (  theStartCommand == COPY )
2137         {
2138                 //JCP 20-10-08 Undo redo implementation
2139                 saveState();
2140                 //JCP 20-10-08 Undo redo implementation
2141                 std::vector<int> tempVector;
2142                 _instantPanel->getInstant( tempVector );
2143                 _performingOperation->setEndOperationInstantVector ( tempVector );
2144                 std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
2145                 int i,size = elems.size();                      
2146                 for( i=0; i<size; i++ )
2147                 {                               
2148                         createMirrorContourOf( elems[i], tempVector, i>0 );
2149                 }               
2150         }
2151
2152         //deleteContour( _refName );
2153         //_refName = "";
2154 }
2155
2156
2157 void wxContourMainFrame::showAxis(bool show)
2158 {
2159         _theViewPanel->SetVisibleAxis(show);
2160         _theViewPanel->Refresh();
2161 }
2162
2163
2164 void wxContourMainFrame::onRigidPressed(){
2165         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2166         int elementsSelected = currentSelection.size();
2167
2168         if ( elementsSelected >= 1 ){
2169                 //JCP 20-10-08 Undo redo implementation
2170                 saveState();
2171                 //JCP 20-10-08 Undo redo implementation
2172
2173                 std::vector<int> tempVector;
2174                 _instantPanel->getInstant( tempVector );
2175                 Instant instant(&tempVector);
2176
2177                 int i , size=currentSelection.size();
2178                 for ( i=0 ; i<size ; i++ )
2179                 {
2180                         kernelManager->changeContourOfManager(currentSelection[i], &instant);
2181                 } // i
2182         }
2183 }
2184
2185 void wxContourMainFrame::onWidthOfContour(double width){
2186
2187         _theViewPanel->removeSceneContours();
2188         _theViewPanel->SetWidthContour(width);
2189         
2190         //_theViewPanel->getSceneManager()->SetWidthContour( width );
2191
2192         RefreshInterface();
2193 }
2194
2195 int wxContourMainFrame::getColorWindow()
2196 {
2197         /*
2198         double range[2];
2199         vtkImageData * img = getImageData();
2200         img->GetScalarRange(range);
2201
2202         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2203         
2204         return (int)range[1];
2205         */
2206         return _theViewPanel->getColorWindow();
2207 }
2208
2209 int wxContourMainFrame::getWindowLevel()
2210 {
2211         /*
2212         double range[2];
2213         vtkImageData * img = getImageData();
2214         img->GetScalarRange(range);
2215
2216         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2217         
2218         return (int)range[1];
2219         */
2220         return _theViewPanel->getWindowLevel();
2221 }
2222
2223 void wxContourMainFrame::onBrigthnessColorWindowLevel(int colorwindow,int windowlevel){
2224         _theViewPanel->onBrigthnessColorWindowLevel(colorwindow, windowlevel);
2225
2226         RefreshInterface();
2227 }
2228
2229 void wxContourMainFrame::onInterpolation(bool interpolate){
2230         _theViewPanel->onInterpolation(interpolate);    
2231         RefreshInterface();
2232 }
2233
2234 void wxContourMainFrame::onChangeInstant(std::string name,int actual){
2235         _instantPanel->setConceptValue( name, actual );
2236 }
2237
2238 void wxContourMainFrame::resetAppend(){
2239         kernelManager->resetAppend();
2240         
2241 }
2242
2243 void wxContourMainFrame::onSpreadAdd(){
2244         std::vector<double> vecX; 
2245         std::vector<double> vecY; 
2246         std::vector<double> vecZ; 
2247         _theViewPanel->GetPointsOfActualContour(&vecX , &vecY , &vecZ );
2248         
2249         std::vector<int> tempVector;
2250         _instantPanel->getInstant( tempVector );
2251
2252         std::string val = kernelManager->onSpreadAdd(&vecX , &vecY , &vecZ, tempVector);
2253
2254         interfMainPanel::getInstance()->appendStringSpread(val);
2255         
2256 }
2257
2258 void wxContourMainFrame::onSpreadGo(int type){
2259
2260         //JCP 20-10-08 Undo redo implementation
2261         saveState();
2262         //JCP 20-10-08 Undo redo implementation
2263
2264         wxBusyCursor wait;      
2265         std::vector<double> vecCtrlPointX;
2266         std::vector<double> vecCtrlPointY;
2267         std::vector<double> vecCtrlPointZ;
2268         double  minZ,maxZ;
2269         int z;
2270
2271         std::vector<int> tempVector;
2272         _instantPanel->getInstant( tempVector );
2273 //              tempVector[1];
2274
2275         kernelManager->getMaxMinZ(&minZ,&maxZ);
2276 //JSTG_16-07-08_----------------------------------------------------------------
2277         //_contourPropagation->setInterpolationNumber(maxZ-minZ+1);
2278         kernelManager->CalculeSplinePropagation();
2279
2280         double          totalZ = maxZ-minZ+1;
2281         double          porcent;
2282         wxString        tmpString;
2283 //--------------------------------------------------------------------
2284         for ( z=(int)minZ ; z<=(int)maxZ ; z++ )
2285         {
2286                 porcent = 100.0* (z-minZ)/totalZ;
2287                 int numero = (int)(z-minZ+1)/(int)totalZ;
2288                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2289                 
2290                 interfMainPanel::getInstance()->setStringSpread(stringtemp);    
2291
2292                 int typeofcontour = 1;
2293                 std::string theName;
2294                 manualBaseModel* manModelContour = kernelManager->GetPoints(z, type, &vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ, theName,typeofcontour, tempVector);
2295
2296                 if( manModelContour!=NULL ){
2297                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2298                         this->_theViewPanel->getSpacing(spc);                                   
2299                         //Adding the manualContourControler to interface objects structure
2300                         //Adding the manualViewContour to interface objects structure           
2301                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
2302                         _theViewPanel->configureViewControlTo( theName, manModelContour,spc,typeofcontour ) ;
2303                 } // if addedModel
2304         } 
2305         if(z > maxZ){
2306                 porcent = 100.0;
2307                 int numero = (int)(z-minZ+1)/(int)totalZ;
2308                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2309                 
2310                 interfMainPanel::getInstance()->setStringSpread(stringtemp);
2311         }// for z
2312         //RefreshInterface();
2313 }
2314
2315 void wxContourMainFrame::getInstantVector(std::vector<int>& tempVector){
2316         
2317 }
2318
2319 std::vector<std::string> wxContourMainFrame::getOutlinesName(int slide){
2320         std::vector<int> tempVector;
2321         _instantPanel->getInstant(tempVector);
2322         //Asignation of slide number should be different ex by name
2323         tempVector[1]=slide;
2324         return kernelManager->getOutlinesNameAtInstant(tempVector);
2325 }
2326
2327
2328 void wxContourMainFrame::SetScalarRange(int grayRangeMin, int grayRangeMax)
2329 {
2330         _contourextractdata->SetScalarRange(grayRangeMin,grayRangeMax);
2331 }
2332
2333
2334 void wxContourMainFrame::onInformationContourLabels(int typeContourGroup,int selection,int minimumZ,int maximumZ,int grayRangeMin, int grayRangeMax)
2335 {
2336 //EED01Juillet2009      GenerateContourExtractData();
2337         
2338         wxString tempString;
2339         int maxContourGroup     =       0;
2340         
2341         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2342
2343         std::vector<manualBaseModel*> lstManConMod;
2344         std::vector<manualBaseModel*> lstManConModTmp;
2345         std::vector<manualBaseModel*> lstManConModExp;
2346         std::vector<double> pLstValue;
2347         std::vector<double> pLstValuePosX;
2348         std::vector<double> pLstValuePosY;
2349         std::vector<double> pLstValuePosZ;
2350
2351         int             resultSize; 
2352         int             resultGrayRangeCount;
2353         double  resultMin; 
2354         double  resultMax;
2355         double  resultAverage;
2356         double  resultStandardeviation;
2357
2358         std::vector<int> tempVector;
2359         _instantPanel->getInstant( tempVector );
2360
2361 //EED01Juillet2009      vtkImageData *imagedata = _theViewPanel->getImageData();
2362 //      int sizeZ = _theViewPanel->GetImageDataSizeZ();
2363         int z;
2364         int ii,sizeLstContourThings;
2365
2366
2367         int minZ,maxZ;
2368         double totalZ;
2369         double porcent; 
2370         wxString tmpString;
2371
2372
2373         if (selection==0 ) // actual slice
2374         {
2375                 int actualSlice = tempVector[1];
2376                 minZ    = actualSlice;
2377                 maxZ    = actualSlice;
2378         }       else  {  // slice range
2379                 minZ    = minimumZ;
2380                 maxZ    = maximumZ;
2381         }
2382         
2383
2384         totalZ  = maxZ-minZ+1;
2385 //EED01Juillet2009      _contourextractdata->SetImage( imagedata);
2386
2387         _contourextractdata->InitVolumeStatistics();
2388         
2389 // For each slice..
2390         for ( z=minZ ; z<=maxZ ; z++ )
2391         {
2392                 
2393                 porcent = 100.0* (z-minZ)/totalZ;
2394                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2395
2396                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);          
2397                 //_staticTextInformation->SetLabel(tmpString);
2398
2399                 //Extraction data from contours of each slice
2400                 _contourextractdata->SetZtoBeAnalys(z);
2401
2402                 tempVector[1]=z;
2403                 Instant instant(&tempVector);
2404                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2405                 sizeLstContourThings = lstContourThings.size();
2406
2407                 lstManConMod.clear();
2408                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2409                 {
2410                         ContourThing **contourthing = lstContourThings[ii];
2411                         lstManConMod.push_back( (*contourthing)->getModel() );
2412                 }
2413
2414                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2415
2416                 tempString.Printf(_T("%d - %d"),z, sizeLstContourThings);
2417                 interfMainPanel::getInstance()->setRowLabelInfoPanel(z, tempString);
2418                 //_grid->SetRowLabelValue(z, tempString );
2419 //EED004
2420                 int iContourGroup,sizeContourGroup;
2421                 if (typeContourGroup==3) // contour separete
2422                 {
2423                         sizeContourGroup=lstManConModExp.size();
2424                         if ( maxContourGroup<sizeContourGroup ) 
2425                         {
2426                                 maxContourGroup=sizeContourGroup;
2427                         }
2428                 } else {  // contour AND OR XOR
2429                         sizeContourGroup=1;
2430                         maxContourGroup=1;
2431                 }
2432
2433                 int tmpIntA;
2434
2435                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2436                         lstManConModTmp.clear();
2437
2438                         
2439
2440                         if (typeContourGroup==3) // contour separete
2441                         {
2442                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2443                         } else {  // contour AND OR XOR
2444                                 lstManConModTmp = lstManConModExp;
2445                         }
2446
2447                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2448                         _contourextractdata->SetScalarRange(grayRangeMin,grayRangeMax);
2449
2450                         pLstValue.clear();
2451                         pLstValuePosX.clear();
2452                         pLstValuePosY.clear();
2453                         pLstValuePosZ.clear();
2454
2455                         
2456                         int numberOfPixels;
2457                         _contourextractdata->GetValuesInsideCrown(  &numberOfPixels,
2458                                                                                                                 &pLstValue,
2459                                                                                                                 &pLstValuePosX,
2460                                                                                                                 &pLstValuePosY,
2461                                                                                                                 &pLstValuePosZ);
2462
2463                         resultSize=numberOfPixels;
2464                         // Statistics of each slice.
2465                         _contourextractdata->Statistics( &pLstValue,
2466                                                                                         grayRangeMin,
2467                                                                                         grayRangeMax,
2468                                                                                         &resultGrayRangeCount, 
2469                                                                                         &resultSize, 
2470                                                                                         &resultMin, 
2471                                                                                         &resultMax,
2472                                                                                         &resultAverage,
2473                                                                                         &resultStandardeviation);
2474
2475                         if (interfMainPanel::getInstance()->getNumberColsInformationPanel()<_numberOfVariablesStatistics*(iContourGroup+1)  )
2476                         {
2477                                 interfMainPanel::getInstance()->appendColsInformationPanel(_numberOfVariablesStatistics);
2478                         }
2479
2480                         tmpIntA=_numberOfVariablesStatistics*iContourGroup ;
2481
2482                         tempString.Printf(_T("%d"),numberOfPixels);
2483
2484                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA, tempString);  
2485
2486                         tempString.Printf(_T("%d"),resultGrayRangeCount);
2487                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+1, tempString);
2488                         
2489                         tempString.Printf(_T("%f"),resultMin);
2490                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+2, tempString);
2491                         
2492                         tempString.Printf(_T("%f"),resultMax);
2493                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+3, tempString);
2494                         
2495                         tempString.Printf(_T("%f"),resultAverage);
2496                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+4, tempString);
2497                         
2498                         tempString.Printf(_T("%f"),resultStandardeviation);
2499                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+5, tempString);
2500                         
2501
2502                 } // for iContourGroup
2503         } // for z
2504
2505         // Print Volume Statistics
2506
2507
2508         int             vol_rCountRange; 
2509         int             vol_rsize;
2510         double  vol_minValue;
2511         double  vol_maxValue;
2512         double  vol_average;
2513         double  vol_standardeviation;
2514         
2515         if (selection!=0 ) // actual slice
2516         {
2517
2518                 _contourextractdata->GetVolumeStatistics(&vol_rCountRange, &vol_rsize,
2519                                                                                                  &vol_minValue, &vol_maxValue,
2520                                                                                                  &vol_average, &vol_standardeviation);
2521
2522                 interfMainPanel::getInstance()->setRowLabelInfoPanel(maxZ+2, _T("Total:"));
2523         
2524                 tempString.Printf(_T("%d"),vol_rsize);
2525                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 0, tempString);   
2526         
2527                 tempString.Printf(_T("%d"),vol_rCountRange);
2528                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 1, tempString);
2529         
2530                 tempString.Printf(_T("%f"),vol_minValue);
2531                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 2, tempString);
2532         
2533                 tempString.Printf(_T("%f"),vol_maxValue);
2534                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 3, tempString);
2535         
2536                 tempString.Printf(_T("%f"),vol_average);
2537                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 4, tempString);
2538         
2539                 tempString.Printf(_T("%f"),vol_standardeviation);
2540                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 5, tempString);
2541         }
2542         //-----------------------------------------
2543         
2544         int iTitleGroup;
2545         wxString tmpTitleString;
2546         int tmpIntB;
2547         for ( iTitleGroup=0 ; iTitleGroup<maxContourGroup ; iTitleGroup++ )
2548         {
2549                 tmpIntB =_numberOfVariablesStatistics*iTitleGroup;
2550                 tmpTitleString.Printf(_T("%d-Size Data"),iTitleGroup);
2551                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString);
2552
2553                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString );
2554                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 1, _T("Size Range") );
2555                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 2, _T("Min") );
2556                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 3, _T("Max") );
2557                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 4, _T("Average") );
2558                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 5, _T("St.Dev.") );
2559                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 6, _T(" ") );
2560         }// for title
2561         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2562 }
2563
2564 //AD: 29-05-09
2565 void wxContourMainFrame::onSaveResults(std::string directory,std::string namefile, std::string filename, 
2566         int typeContourGroup, int selection, int minZ, int maxZ, bool XYZValues, bool contourImage, bool statistics)
2567 {
2568         if (XYZValues)
2569         {
2570                 SaveValuesXYZ( directory , namefile, typeContourGroup );
2571         }
2572
2573         if (contourImage)
2574         {
2575                 vtkImageData * mask;
2576                 vtkImageData * value;
2577                 this->getMaskValue(&mask, &value, typeContourGroup,selection,minZ,maxZ);
2578                 this->SaveImageResult( directory , namefile, mask, value);
2579         }
2580         
2581         if (statistics)
2582         {
2583                 std::ostringstream name;
2584                 name << filename << ".xls";
2585                 
2586
2587                 FILE *pFile=fopen(name.str().c_str(),"w+");
2588
2589
2590                 wxString tmpString;
2591                 int i,j,maxX;
2592                 
2593 //              int sizeZ = _theViewPanel->GetImageDataSizeZ();
2594 //              int maxY=sizeZ+2;
2595                 
2596                 maxX= interfMainPanel::getInstance()->getNumberColsInformationPanel();//this->_grid->GetNumberCols();
2597
2598                 // -- Title --
2599                 int iTitle,sizeTitle = (maxX / _numberOfVariablesStatistics);
2600                 for ( iTitle=0; iTitle<sizeTitle ; iTitle++)
2601                 {
2602                                 // fprintf(pFile,"-- \t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle,tmpString.c_str() );
2603                                 fprintf(pFile,"slice\t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle );
2604                 }
2605                 fprintf(pFile,"\n\n" );
2606
2607                 
2608                 
2609                 if (selection==0 ) // actual slice
2610                 {
2611                         std::vector<int> tempVector;
2612                         _instantPanel->getInstant( tempVector );
2613                         int actualSlice = tempVector[1];
2614                         minZ    = actualSlice;
2615                         maxZ    = actualSlice;
2616                 }
2617                 
2618                 // Stadistics...
2619                 for ( j=minZ; j<=maxZ ; j++)
2620                 {
2621                         fprintf(pFile,"%d\t" , j );
2622                         for (i=0 ; i<maxX ; i++){
2623                                 tmpString = interfMainPanel::getInstance()->getCellValue(j, i);//_grid->GetCellValue( j , i );
2624                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2625                         } // for i
2626                         fprintf(pFile,"\n"  );
2627                 } // for j
2628
2629                 
2630                 // Total of stadistics.....
2631                 if (selection!=0)
2632                 {
2633                         fprintf(pFile,"\n Total:\t"  );
2634                         for (i=0 ; i<maxX ; i++){
2635                                 tmpString = interfMainPanel::getInstance()->getCellValue(maxZ+2, i);//_grid->GetCellValue( maxZ+2 , i );
2636                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2637                         } // for i
2638                         fprintf(pFile,"\n"  );
2639                 }
2640                 
2641                 fclose(pFile);
2642         }
2643 }
2644
2645 //AD: 29-05-09
2646 void wxContourMainFrame::SaveValuesXYZ(std::string directory,std::string namefile,int typeContourGroup)
2647 {
2648         wxBusyCursor wait;
2649 //EED01Juillet2009      GenerateContourExtractData();
2650         
2651         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2652         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2653
2654         std::vector<manualBaseModel*> lstManConMod;
2655         std::vector<manualBaseModel*> lstManConModTmp;
2656         std::vector<manualBaseModel*> lstManConModExp;
2657         std::vector<double> pLstValue;
2658         std::vector<double> pLstValuePosX;
2659         std::vector<double> pLstValuePosY;
2660         std::vector<double> pLstValuePosZ;
2661
2662         std::vector<int> tempVector;
2663         _instantPanel->getInstant( tempVector );
2664
2665 //EED01Juillet2009      vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
2666         int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
2667         int z;
2668         int ii,sizeLstContourThings;
2669
2670
2671         int minZ,maxZ;
2672         double totalZ;
2673         double porcent; 
2674         wxString tmpString;
2675         minZ    = 0;// _mbarrange->GetStart();
2676         maxZ    = sizeZ;//_mbarrange->GetEnd();
2677         totalZ  = maxZ-minZ+1;
2678
2679 //EED01Juillet2009      _contourextractdata->SetImage( imagedata);
2680
2681 // For each slice..
2682         for ( z=0 ; z<sizeZ ; z++)
2683         {
2684
2685                 porcent = 100.0* (z-minZ)/totalZ;
2686                 
2687                 tmpString.Printf(_T("Saving Values"));
2688                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2689                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2690                 //_staticTextInformation->SetLabel(tmpString);
2691
2692
2693                 //Extraction data from contours of each slice
2694                 _contourextractdata->SetZtoBeAnalys( z);
2695
2696                 tempVector[1]=z;
2697                 Instant instant(&tempVector);
2698                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant(&instant);//this->_modelManager->getOutlinesAtInstant( &instant );
2699                 sizeLstContourThings = lstContourThings.size();
2700
2701                 lstManConMod.clear();
2702                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2703                 {
2704                         ContourThing **contourthing = lstContourThings[ii];
2705                         lstManConMod.push_back( (*contourthing)->getModel() );
2706                 }
2707                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2708
2709
2710 //EED004
2711
2712                 int iContourGroup,sizeContourGroup;
2713                 if (typeContourGroup==3) // contour separete
2714                 {
2715                         sizeContourGroup=lstManConModExp.size();
2716                 } else {  // contour AND OR XOR
2717                         sizeContourGroup=1;
2718                 }
2719
2720                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2721                         lstManConModTmp.clear();
2722                         if (typeContourGroup==3) // contour separete
2723                         {
2724                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2725                         } else {  // contour AND OR XOR
2726                                 lstManConModTmp = lstManConModExp;
2727                         }
2728
2729                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2730
2731                         pLstValue.clear();
2732                         pLstValuePosX.clear();
2733                         pLstValuePosY.clear();
2734                         pLstValuePosZ.clear();
2735                         int numberOfPixels;
2736                         _contourextractdata->GetValuesInsideCrown(      &numberOfPixels,
2737                                                                                                                 &pLstValue,
2738                                                                                                                 &pLstValuePosX,
2739                                                                                                                 &pLstValuePosY,
2740                                                                                                                 &pLstValuePosZ);
2741
2742                         std::string temp = directory + "/" + namefile + "-slice";
2743                         temp = temp + kernelManager->intToString(z) + "-cont" + kernelManager->intToString(iContourGroup);
2744                         temp = temp + ".txt";
2745
2746                         // LG 14/01/09 : using crea
2747                         wxString filename = crea::std2wx(temp);
2748                         /*filename.Printf(_T("%s"),directory.c_str());
2749                         filename.append(_T("\\"));
2750                         filename.append(_T("%s"),namefile.c_str());
2751                         filename.append(_T("-slice"));
2752                         filename.append(_T("%d"),z);
2753                         filename.append(_T("-cont"));
2754                         filename.append(_T("%d"),iContourGroup);
2755                         filename.append(_T(".txt"));*/
2756                         //                      filename.Printf(temp.c_str());
2757
2758                         
2759
2760                         FILE *pFile=fopen((const char *)filename.mb_str(),"w+");
2761                         fprintf(pFile,"value \t x \t y \t z\n"  );
2762                         int iLstValue,sizeLstValue=pLstValue.size();
2763                         for (iLstValue=0 ; iLstValue<sizeLstValue ; iLstValue++ )
2764                         {
2765                                 fprintf(pFile,"%f\t %f\t %f\t %f\n", (float)pLstValue[iLstValue] , (float)pLstValuePosX[iLstValue], (float)pLstValuePosY[iLstValue], (float)z );
2766                         }
2767                         fclose(pFile);
2768                 } // for  iContourGroup
2769         } // for z
2770         interfMainPanel::getInstance()->setStringInfoPanel(_T(""));
2771         //_staticTextInformation->SetLabel( _T("") );
2772
2773 }
2774
2775 void wxContourMainFrame::getMaskValue(vtkImageData ** mask,vtkImageData ** value,int typeContourGroup, int selection, int minZ, int maxZ){
2776         wxBusyCursor wait;
2777 //EED01Juillet2009      GenerateContourExtractData();
2778
2779         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2780         if (typeContourGroup==3)
2781         {
2782                 typeContourGroup=1;
2783         }
2784         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2785
2786         std::vector<manualBaseModel*> lstManConMod;
2787         std::vector<manualBaseModel*> lstManConModTmp;
2788         std::vector<manualBaseModel*> lstManConModExp;
2789
2790         std::vector<int> tempVector;
2791         _instantPanel->getInstant( tempVector );
2792
2793     vtkImageData *imagedata = _theViewPanel->getImageData();
2794         int ext[6];
2795         imagedata->GetExtent(ext);
2796         int sizeZimage = ext[5]-ext[4]+1;
2797         int z;
2798         int ii,sizeLstContourThings;
2799
2800
2801         double totalZ;
2802         double porcent; 
2803
2804         wxString tmpString;
2805         
2806         
2807         if (selection==0 ) // actual slice
2808         {
2809                 int actualSlice = tempVector[1];
2810                 minZ    = actualSlice;
2811                 maxZ    = actualSlice;
2812         }       
2813         
2814         totalZ  = maxZ-minZ;
2815
2816 //EED01Juillet2009      _contourextractdata->SetImage( imagedata);
2817
2818         // cleanning image before range 
2819         for (z=0; z<minZ; z++){
2820                 _contourextractdata->ResetImageResult(z);
2821         }
2822         // cleanning image after range 
2823         for (z=maxZ+1; z<sizeZimage; z++){
2824                 _contourextractdata->ResetImageResult(z);
2825         }
2826         
2827         
2828 // For each slice..
2829         for ( z=minZ ; z<=maxZ ; z++)
2830         {
2831
2832                 porcent = 100.0* (z-minZ)/totalZ;
2833                 tmpString.Printf(_T("Saving Values"));
2834                 tmpString.Printf(_T("%d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2835                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2836
2837                 //Extraction data from contours of each slice
2838                 _contourextractdata->SetZtoBeAnalys( z);
2839
2840                 tempVector[1]=z;
2841                 Instant instant(&tempVector);
2842                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2843                 sizeLstContourThings = lstContourThings.size();
2844
2845                 lstManConMod.clear();
2846                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2847                 {
2848                         ContourThing **contourthing = lstContourThings[ii];
2849                         lstManConMod.push_back( (*contourthing)->getModel() );
2850                 }
2851                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2852
2853
2854                 int iContourGroup,sizeContourGroup;
2855                 if (typeContourGroup==3) // contour separete
2856                 {
2857                         sizeContourGroup=lstManConModExp.size();
2858                 } else {  // contour AND OR XOR
2859                         sizeContourGroup=1;
2860                 }
2861
2862                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2863                         lstManConModTmp.clear();
2864                         if (typeContourGroup==3) // contour separete
2865                         {
2866                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2867                         } else {  // contour AND OR XOR
2868                                 lstManConModTmp = lstManConModExp;
2869                         }
2870
2871                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2872                         _contourextractdata->CalculateImageResult(); // with actual Z
2873
2874                 } // for  iContourGroup
2875         } // for z
2876
2877         (*value) = _contourextractdata->GetVtkImageValueResult();
2878         (*mask)  = _contourextractdata->GetVtkImageMaskResult();
2879
2880 }
2881
2882 void wxContourMainFrame::SaveImageResult(std::string directory,std::string namefile, vtkImageData* mask,vtkImageData* value)
2883 {
2884         
2885         std::string temp = directory + "/" + namefile + "-Value.mhd";
2886
2887         wxString filename = crea::std2wx(temp);
2888         // LG 
2889         //      filename.Printf(_T(temp.c_str()));
2890         //filename.Printf(_T("%s\\%s-Value.mhd",directory.c_str(),namefile.c_str(),z);
2891         /*filename.Printf(_T("%s"),directory.c_str());
2892         filename.append(_T("\\"));
2893         filename.append(_T("%s"),namefile.c_str());
2894         filename.append(_T("-Value.mhd"));*/
2895
2896 // Image Value
2897         vtkMetaImageWriter *writerValueImage = vtkMetaImageWriter::New( );
2898         writerValueImage->SetInput( value );
2899         writerValueImage->SetFileName( (const char *)filename.mb_str() );
2900         writerValueImage->SetFileDimensionality( 3 );
2901         writerValueImage->Write( );
2902
2903 // Image Mask
2904         //              filename.Printf("%s\\%s-Mask.mhd",directory.c_str(),namefile.c_str(),z);
2905         temp = directory + "/" + namefile + "-Mask.mhd";
2906
2907         // LG 14/01/09 : using crea
2908         filename = crea::std2wx(temp);
2909         //      filename.Printf(_T(temp.c_str()));
2910
2911         /*filename.Printf(_T("%s"),directory.c_str());
2912         filename.append(_T("\\"));
2913         filename.append(_T("%s"),namefile.c_str());
2914         filename.append(_T("-Mask.mhd"));*/
2915
2916         vtkMetaImageWriter *writerMaskImage = vtkMetaImageWriter::New( );
2917         writerMaskImage->SetInput( mask );
2918         writerMaskImage->SetFileName( (const char *)filename.mb_str() );
2919         writerMaskImage->SetFileDimensionality( 3 );
2920         writerMaskImage->Write( );
2921
2922         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2923         
2924 }
2925
2926
2927
2928 void wxContourMainFrame::onChangeInstantInstantPanel(std::string name,int value, int minshow, int maxshow){
2929         if( name.compare( _theViewPanel->getVerticalConceptName() ) == 0){
2930                 _theViewPanel->setActualVertical( value);
2931         }
2932         else if( name.compare( _theViewPanel->getHorizontalConceptName() ) == 0|| _instantPanel->getIfConceptCheckedAt( name, 0 ) )     {
2933                 _theViewPanel->setHorizontalConcept( name, minshow, maxshow, minshow, maxshow, value);
2934         }
2935
2936         changeInstant();
2937 }
2938
2939 void wxContourMainFrame::onSnakePressed(){
2940         std::vector<double> vecX; 
2941         std::vector<double> vecY; 
2942         std::vector<double> vecZ; 
2943         _theViewPanel->GetPointsOfActualContour( &vecX , &vecY , &vecZ );       
2944
2945         if (vecX.size()!=0){
2946                 std::vector<int> tempVector;
2947                 _instantPanel->getInstant( tempVector );
2948                 int i,size=vecZ.size();
2949                 int actualSlice = tempVector[1];
2950                 for ( i=0 ; i<size ; i++ )
2951                 {
2952                         vecZ[i] = actualSlice;
2953                 } // for
2954
2955                 wxDialog* dialog = new wxDialog(this, -1, wxString(_T("Snake")));
2956                 wxPanel* panel = new wxPanel(dialog,-1); 
2957                 //              wxStaticText* sttext = new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
2958          new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
2959                 dialog->ShowModal();
2960         } // if 
2961
2962 }
2963
2964 void wxContourMainFrame::saveFileWithContoursAutomatique(){
2965         std::string filename = kernelManager->getCurrentFileName();
2966         if(filename.compare("")!=0){
2967                 saveFileWithContours(filename);
2968         }else{
2969                 onSave();
2970         }
2971 }
2972 void wxContourMainFrame::ShowToolsPanel(bool show){
2973         _pannew->Show(show);
2974 }
2975
2976
2977
2978 void wxContourMainFrame::SetContourGroup(int contourGroup)
2979 {
2980         _contourGroup = contourGroup;
2981 }
2982
2983
2984 wxPanel *wxContourMainFrame::getMaskImageViewPanel(wxWindow *parent)
2985 {
2986         
2987         if      (_viewMaskImagePanel==NULL)
2988         {
2989                 _contourextractdata = new ContourExtractData(true);
2990                 _contourextractdata->SetImage( _theViewPanel->getImageData() );
2991                 
2992 //              double range[2];
2993 //              _theViewPanel->getImageData()->GetScalarRange(range);
2994                 //int min = (int)floor (range[0]);
2995                 //int max = (int)ceil (range[1]);
2996                 int min = 254;
2997                 int max = 256;
2998                 
2999                 _viewMaskImagePanel = new ThresholdImageViewPanel( parent, -1, -1 , 0);
3000                 _viewMaskImage = new ThresholdImageView();
3001                 _viewMaskImage->SetImage(_contourextractdata->GetVtkImageMaskResult() );
3002                 _viewMaskImage->SetminMaxValue( min, max);
3003                 _viewMaskImage->SetBaseColor( 0,0,1 );
3004                 _viewMaskImagePanel->SetThresholdImageView( _viewMaskImage );
3005                 _viewMaskImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
3006                 
3007         }
3008         return _viewMaskImagePanel;
3009 }
3010
3011 wxPanel *wxContourMainFrame::getThresholdImageViewPanel(wxWindow *parent)
3012 {
3013         if      (_viewThresholdImagePanel==NULL)
3014         {
3015                 double range[2];
3016                 _theViewPanel->getImageData()->GetScalarRange(range);
3017                 int min = (int)floor (range[0]);
3018                 int max = (int)ceil (range[1]);         
3019                 _viewThresholdImagePanel = new ThresholdImageViewPanel( parent, min, max , 1);
3020                 _viewThresholdImage = new ThresholdImageView();
3021                 _viewThresholdImage->SetImage( _theViewPanel->getImageData() );
3022                 _viewThresholdImage->SetminMaxValue( min, max);
3023                 _viewThresholdImage->SetBaseColor( 1,0,0 );
3024                 _viewThresholdImagePanel->SetThresholdImageView( _viewThresholdImage );
3025                 _viewThresholdImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
3026         }
3027         return _viewThresholdImagePanel;
3028 }
3029
3030 //CMRU 17-08-09-----------------------------------------------------------------------------------------------
3031 int wxContourMainFrame::getType ()
3032 {
3033         int tipo = 0;
3034         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
3035
3036         if(!currentSelection.empty())
3037         {
3038                 std::string cloneName = currentSelection [0];
3039                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);
3040                 tipo = manualModel-> GetTypeModel();    
3041         }
3042         return tipo;
3043 }
3044
3045 double wxContourMainFrame::getContourSizeInPixels()
3046 {
3047         double contourSize = 0; 
3048
3049         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();        if(!currentSelection.empty())
3050         if(!currentSelection.empty())
3051         {
3052                 std::string cloneName = currentSelection [0];
3053                 
3054                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
3055                 contourSize = manualModel-> GetPathSize();
3056         }       
3057         return contourSize;
3058 }
3059 manualBaseModel * wxContourMainFrame::getContour ()
3060 {
3061         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
3062
3063         if(!currentSelection.empty())
3064         {
3065                 std::string cloneName = currentSelection [0];
3066                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
3067                 return manualModel; 
3068         }
3069         return NULL;
3070 }
3071 void wxContourMainFrame::onPrintLabel (wxString label, manualBaseModel* manualModel) 
3072 {
3073         std::string labelAscii(label.ToAscii());
3074         int pos = labelAscii.find(" ");
3075
3076         int j;
3077         
3078         for (j=0 ; pos != string::npos;j++) 
3079         {
3080                 labelAscii.replace( pos, 1, "_" );
3081                 pos= labelAscii.find(" ");
3082         }
3083
3084         manualModel -> SetLabel(labelAscii); 
3085 }
3086 void wxContourMainFrame::onInsertCalculation(manualBaseModel* manualModel)
3087 {
3088         double sizeInPixel = manualModel ->GetPathSize();
3089         double onePixelRealSize = interfMainPanel::getInstance()->GetPixelValue();;
3090         double realContourSize = sizeInPixel*onePixelRealSize;
3091         manualModel ->SetRealSize(realContourSize); 
3092 }
3093
3094 double wxContourMainFrame::onePixelSize( double value)
3095 {
3096         return _onePixelSize = value;   
3097 }
3098
3099 std::string wxContourMainFrame::GetFileLocation()
3100 {
3101         return _fileLocation;
3102 }
3103
3104 void wxContourMainFrame::SetFileLocation(std::string newFileLocation)
3105 {
3106         _fileLocation = newFileLocation;
3107         std::cout<<"GETFILELOCATION:"<<_fileLocation<<std::endl;
3108 }
3109 //------------------------------------------------------------------------------------------------------------