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