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