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