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