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