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