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