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