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