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