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