]> Creatis software - creaContours.git/blob - lib/Interface_ManagerContour_NDimensions/wxContourMainFrame.cxx
96049d3b7e13c9ab38fd81a58e69d32632d02525
[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->SetNumberOfContours( 1 );
1701         cntVTK->SetValue( 0, 255 );
1702 //EED 2017-01-01 Migration VTK7
1703 #if VTK_MAJOR_VERSION <= 5
1704         cntVTK->SetInput( idata );
1705         cntVTK->Update( );
1706         cntVTK->UpdateInformation();
1707 #else
1708         cntVTK->SetInputData( idata );
1709 #endif
1710
1711         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
1712
1713 //EED 2017-01-01 Migration VTK7
1714 #if VTK_MAJOR_VERSION <= 5
1715         cpd->SetInput( cntVTK->GetOutput( ) );
1716         cpd->Update( );
1717         cpd->UpdateInformation();
1718 #else
1719         cpd->SetInputData( cntVTK->GetOutput( ) );
1720 #endif
1721
1722
1723         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
1724         conn->SetExtractionModeToLargestRegion( );
1725 //EED 2017-01-01 Migration VTK7
1726 #if VTK_MAJOR_VERSION <= 5
1727         conn->SetInput( cpd->GetOutput( ) );
1728         conn->Update( );
1729         conn->UpdateInformation();
1730 #else
1731         conn->SetInputData( cpd->GetOutput( ) );
1732 #endif
1733
1734
1735         vtkStripper* vtkstripper = vtkStripper::New( );
1736
1737 //EED 2017-01-01 Migration VTK7
1738 #if VTK_MAJOR_VERSION <= 5
1739         vtkstripper->SetInput( conn->GetOutput() );
1740         vtkstripper->Update();
1741         vtkstripper->UpdateInformation();
1742 #else
1743         vtkstripper->SetInputData( conn->GetOutput() );
1744         cntVTK->Update();
1745 #endif
1746
1747         vtkPolyData* polyDataResult =  cntVTK->GetOutput();
1748         //std::cout<<"Points "<<polyDataResult->GetNumberOfPoints()<<std::endl;
1749
1750 //EED 2017-01-01 Migration VTK7
1751 #if VTK_MAJOR_VERSION <= 5
1752         polyDataResult->Update( );
1753         polyDataResult->UpdateInformation();
1754 #else
1755         // ..
1756 #endif
1757
1758         //EED
1759                 /*
1760         ofstream myfile;
1761         myfile.open ("C:/Creatis/example.txt");
1762         myfile << "\n";
1763         polyDataResult->Print(myfile);
1764         myfile << "-------------------------------------\n";
1765         polyDataResult->GetLines()->Print(myfile);
1766         myfile.close();*/
1767
1768         cntVTK          -> Delete();
1769         cpd                     -> Delete();
1770         conn            -> Delete();
1771
1772
1773         //--Calculating control points
1774
1775         std::vector<double> vecX;
1776         std::vector<double> vecY;
1777         std::vector<double> vecXo;
1778         std::vector<double> vecYo;
1779         std::vector<double>::iterator vecXoi;
1780         std::vector<double>::iterator vecYoi;
1781         std::vector<double> vecZ;
1782
1783         std::vector<double> vecCtrlPointX;
1784         std::vector<double> vecCtrlPointY;
1785         std::vector<double> vecCtrlPointZ;
1786
1787
1788         double *p;
1789         double xAct=0;
1790         double yAct=0;
1791         int ii,size=polyDataResult->GetNumberOfPoints();
1792         ofstream myfile;
1793         myfile.open ("C:/Creatis/example2.txt");
1794
1795         size=polyDataResult->GetNumberOfPoints();
1796         for (ii=0;ii<size;ii++)
1797         {
1798                 if(ii==0)
1799                 {
1800                         xAct=x;
1801                         yAct=y;
1802                 }
1803                 p       = polyDataResult->GetPoint(ii);
1804                 double x=p[0];
1805                 double y=p[1];
1806                 /*if(fabs(yAct-y)>20)
1807                 {
1808                         if((xAct-x)>1 || (xAct-x)<-1)
1809                         {
1810                         vecX.push_back( p[0] );
1811                         vecY.push_back( p[1] );
1812                         myfile <<p[0]<<","<<p[1]<<"\n";
1813                         std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1814                 std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1815                 std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1816                         vecZ.push_back( 900 );
1817                         xAct=x;
1818                         yAct=y;
1819                         }
1820                         else
1821                         {
1822                                 vecXo.push_back(p[0]);
1823                                 vecYo.push_back(p[1]);
1824                         }
1825
1826                 }
1827                 else*/ if(fabs(xAct-x)>11)
1828                 {
1829                         vecXo.push_back(p[0]);
1830                         vecYo.push_back(p[1]);
1831                 }
1832                 else
1833                 {
1834                 vecX.push_back( p[0] );
1835                 myfile <<p[0]<<","<<p[1]<<"\n";
1836                 //std::cout<<" x Anterior "<<xAct<<" x actual "<<x<<std::endl;
1837                 //std::cout<<" y Anterior "<<yAct<<" y actual "<<y<<std::endl;
1838                 //std::cout<<" x "<<p[0]<<" y "<<p[1]<<std::endl;
1839                 vecY.push_back( p[1] );
1840                 vecZ.push_back( 900 );
1841                 xAct=x;
1842                 yAct=y;
1843                 }
1844
1845
1846         }
1847
1848         while(!vecXo.empty())
1849         {
1850                 vecX.push_back(vecXo.back());
1851                 //std::cout<<" x Siguiente "<<vecXo.back();
1852                 vecXo.pop_back();
1853                 vecZ.push_back( 900 );
1854         }
1855         while(!vecYo.empty())
1856         {
1857                 vecY.push_back(vecYo.back());
1858                         vecYo.pop_back();
1859         }
1860         myfile.close();
1861
1862         /*for(int l=0;l<vecX.size();l++)
1863         {
1864                 if(l==0)
1865                 {
1866             vecXo.push_back(p[0]);
1867                         vecYo.push_back(p[1]);
1868                 }
1869                 else
1870                 {
1871                         if(vecXoi[l-1]==)
1872                         {
1873                         }
1874                 }
1875
1876         }*/
1877
1878         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1879
1880         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1881
1882         int method=2;
1883         if (method==0){
1884                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1885         }
1886         else if (method==1){
1887                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1888         }
1889         else if (method==2){
1890                 extractcontrolpoints2d->SetSamplingControlPoints( 15 );
1891                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1892         }
1893         //--Adding contour to the system
1894
1895         std::vector<int> actualInstantVector;
1896         _instantPanel->getInstant( actualInstantVector );
1897         actualInstantVector[1]=z;
1898
1899         int j,sizeCtrPt = vecCtrlPointX.size();
1900
1901         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
1902         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
1903         if (sizeCtrPt>=3){
1904                 for (j=0 ; j<sizeCtrPt ; j++)
1905                 {
1906                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1907                 } // for
1908                 std::string theName;
1909                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1910                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
1911                 bool addedModel = theName.compare("") != 0;
1912                 if( addedModel )
1913                 {
1914                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1915                         _theViewPanel->getSpacing(spc);
1916                         //Adding the manualContourControler to interface objects structure
1917                         //Adding the manualViewContour to interface objects structure
1918                         //_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.
1919                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
1920                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
1921                 }       // if addedModel
1922         } // if sizeCtrPt
1923
1924
1925 /*
1926 //EED10JUIN2011
1927                  WriterType::Pointer writer = WriterType::New();
1928          CastFilterType3::Pointer caster = CastFilterType3::New();
1929
1930                  caster->SetInput( gradientMagnitude->GetOutput() );
1931                  writer->SetInput( caster->GetOutput() );
1932                  writer->SetFileName("Gradient Magnitude.png");
1933                  caster->SetOutputMinimum(   0 );
1934                  caster->SetOutputMaximum( 255 );
1935                  writer->Update();
1936
1937                  CastFilterType3::Pointer caster2 = CastFilterType3::New();
1938                  WriterType::Pointer writer2 = WriterType::New();
1939
1940                  caster2->SetInput( sigmoid->GetOutput() );
1941                  writer2->SetInput( caster2->GetOutput() );
1942                  writer2->SetFileName("Sigmoid.png");
1943                  caster2->SetOutputMinimum(   0 );
1944                  caster2->SetOutputMaximum( 255 );
1945                  writer2->Update();
1946
1947                  CastFilterType3::Pointer caster3 = CastFilterType3::New();
1948                  WriterType::Pointer writer3 = WriterType::New();
1949
1950                  caster3->SetInput( fastMarching->GetOutput() );
1951                  writer3->SetInput( caster3->GetOutput() );
1952                  writer3->SetFileName("FastMarching.bmp");
1953                  caster3->SetOutputMinimum(   0 );
1954                  caster3->SetOutputMaximum( 255 );
1955                  writer3->Update();
1956
1957                  CastFilterType3::Pointer caster4 = CastFilterType3::New();
1958                  WriterType::Pointer writer4 = WriterType::New();
1959
1960                  caster4->SetInput( geodesicActiveContour->GetOutput() );
1961                  writer4->SetInput( caster4->GetOutput() );
1962                  writer4->SetFileName("GeodesicActiveContour.png");
1963                  caster4->SetOutputMinimum(   0 );
1964                  caster4->SetOutputMaximum( 255 );
1965                  writer4->Update();
1966
1967                  CastFilterType3::Pointer caster5 = CastFilterType3::New();
1968                  WriterType::Pointer writer5 = WriterType::New();
1969
1970                  caster5->SetInput( zeroCrossing->GetOutput() );
1971                  writer5->SetInput( caster5->GetOutput() );
1972                  writer5->SetFileName("ZeroCrossing.bmp");
1973                  caster5->SetOutputMinimum(   0 );
1974                  caster5->SetOutputMaximum( 255 );
1975                  writer5->Update();
1976 */
1977     }
1978   catch( itk::ExceptionObject & excep )
1979     {
1980     std::cerr << "Exception caught !" << std::endl;
1981     std::cerr << excep << std::endl;
1982     }
1983 }
1984
1985 void wxContourMainFrame::onSegmentationOneSlice(int isovalue,int sampling,int method){
1986
1987         //JCP 20-10-08 Undo redo implementation
1988         saveState();
1989         //JCP 20-10-08 Undo redo implementation
1990
1991         wxBusyCursor wait;
1992         int                                     x                                       = _theViewPanel->GetX();
1993         int                                     y                                       = _theViewPanel->GetY();
1994         int                                     z                                       = _theViewPanel->GetZ();
1995         SegmentationOneSlice( x,y,z,isovalue, sampling, method );
1996         RefreshInterface();
1997 }
1998
1999
2000 void wxContourMainFrame::SegmentationOneSlice( int x, int y, int z, int isovalue, int sampling, int method )
2001 {
2002         int typeofcontour = 1;
2003         //--Extracting Contour
2004         //vtkImageData  *imagedata      = _theViewPanel->getSceneManager()->GetImageData();
2005         vtkImageData    *imagedata      = getImageData();
2006 //              double                  *range          = imagedata->GetScalarRange();
2007 //              double                  thr                     = 1;
2008
2009         vtkImageReslice *imageReslice = vtkImageReslice::New();
2010 //EED
2011 //              double spc[3];
2012 //              imagedata->GetSpacing(spc);
2013 //              x = x*spc[0];
2014 //              y = y*spc[1];
2015 //              z = z*spc[3];
2016
2017 //EED 2017-01-01 Migration VTK7
2018 #if VTK_MAJOR_VERSION <= 5
2019         imageReslice->SetInput( imagedata );
2020 #else
2021         imageReslice->SetInputData( imagedata );
2022 #endif
2023         imageReslice->SetInformationInput(imagedata);
2024         imageReslice->SetResliceAxesDirectionCosines(1,0,0, 0,1,0 ,0,0,1);
2025         imageReslice->SetResliceAxesOrigin(0,0,z);
2026         imageReslice->SetOutputDimensionality(2);
2027         imageReslice->SetInterpolationModeToLinear();
2028
2029 //EED 2017-01-01 Migration VTK7
2030 #if VTK_MAJOR_VERSION <= 5
2031         // ..
2032 #else
2033         imageReslice->Update();
2034 #endif
2035
2036         imagedata = imageReslice->GetOutput();
2037 //EED 2017-01-01 Migration VTK7
2038 #if VTK_MAJOR_VERSION <= 5
2039         imagedata->Update();
2040         imagedata->UpdateInformation();
2041 #else
2042         // ..
2043 #endif
2044
2045         vtkContourFilter* cntVTK = vtkContourFilter::New( );
2046 //EED 2017-01-01 Migration VTK7
2047 #if VTK_MAJOR_VERSION <= 5
2048         cntVTK->SetInput( imagedata );
2049 #else
2050         cntVTK->SetInputData( imagedata );
2051 #endif
2052
2053         cntVTK->SetNumberOfContours( 1 );
2054         //cntVTK->SetValue( 0, vmin );
2055 //              cntVTK->SetValue( 0, (range[1]*thr/100) );
2056         cntVTK->SetValue( 1, isovalue );
2057 //      cntVTK->SetValue( 1, vmax );
2058         cntVTK->Update( );
2059         cntVTK->UpdateInformation();
2060
2061         vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
2062 //EED 2017-01-01 Migration VTK7
2063 #if VTK_MAJOR_VERSION <= 5
2064         cpd->SetInput( cntVTK->GetOutput( ) );
2065 #else
2066         cpd->SetInputData( cntVTK->GetOutput( ) );
2067 #endif
2068         cpd->ConvertLinesToPointsOff( );
2069         cpd->Update( );
2070         cpd->UpdateInformation();
2071
2072         vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
2073         conn->SetExtractionModeToClosestPointRegion( );
2074         //conn->SetMaxRecursionDepth( 3000 );
2075
2076 //EED 2017-01-01 Migration VTK7
2077 #if VTK_MAJOR_VERSION <= 5
2078         conn->SetInput( cpd->GetOutput( ) );
2079 #else
2080         conn->SetInputData( cpd->GetOutput( ) );
2081 #endif
2082
2083         conn->SetClosestPoint( x, y, 0 );
2084         conn->Update( );
2085         conn->UpdateInformation();
2086
2087         vtkCleanPolyData* cpd2 = vtkCleanPolyData::New( );
2088 //EED 2017-01-01 Migration VTK7
2089 #if VTK_MAJOR_VERSION <= 5
2090         cpd2->SetInput( conn->GetOutput( ) );
2091 #else
2092         cpd2->SetInputData( conn->GetOutput( ) );
2093 #endif
2094         cpd2->Update();
2095         cpd2->UpdateInformation();
2096
2097         vtkStripper* vtkstripper = vtkStripper::New( );
2098 //EED 2017-01-01 Migration VTK7
2099 #if VTK_MAJOR_VERSION <= 5
2100         vtkstripper->SetInput( cpd2->GetOutput() );
2101 #else
2102         vtkstripper->SetInputData( cpd2->GetOutput() );
2103 #endif
2104         vtkstripper->Update();
2105         vtkstripper->UpdateInformation();
2106
2107
2108         vtkPolyData* polyDataResult =  vtkstripper->GetOutput();
2109
2110 //EED 2017-01-01 Migration VTK7
2111 #if VTK_MAJOR_VERSION <= 5
2112         polyDataResult->Update( );
2113         polyDataResult->UpdateInformation();
2114 #else
2115         //...
2116 #endif
2117
2118 /* EED
2119 ofstream myfile;
2120 myfile.open ("c:/temp/example.txt");
2121 myfile << "\n";
2122 polyDataResult->Print(myfile);
2123 myfile << "-------------------------------------\n";
2124 polyDataResult->GetLines()->Print(myfile);
2125 myfile.close();
2126 */
2127
2128         cntVTK          -> Delete();
2129         cpd2            -> Delete();
2130         cpd                     -> Delete();
2131         conn            -> Delete();
2132
2133
2134 //--Calculating control points
2135
2136         std::vector<double> vecX;
2137         std::vector<double> vecY;
2138         std::vector<double> vecZ;
2139
2140         std::vector<double> vecCtrlPointX;
2141         std::vector<double> vecCtrlPointY;
2142         std::vector<double> vecCtrlPointZ;
2143
2144
2145         double *p;
2146         int ii,size=polyDataResult->GetNumberOfPoints();
2147         int id;
2148         for (ii=1;ii<=size;ii++)
2149         {
2150                 id      = polyDataResult->GetLines()->GetData()->GetValue(ii);
2151                 p       = polyDataResult->GetPoint(id);
2152 //              double x=p[0];
2153 //              double y=p[1];
2154                 vecX.push_back( p[0] );
2155                 vecY.push_back( p[1] );
2156                 vecZ.push_back( 900 );
2157 //                      vecZ.push_back( p[2] );
2158         }
2159
2160
2161         ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
2162         extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
2163
2164 //PROOFS
2165         /*if (methodRadiobox->GetSelection()==0){
2166                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2167         }
2168         if (methodRadiobox->GetSelection()==1){
2169                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2170         }
2171         if (methodRadiobox->GetSelection()==2){
2172                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
2173                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2174         }*/
2175
2176         if (method==0){
2177                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2178         }
2179         else if (method==1){
2180                 extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2181         }
2182         else if (method==2){
2183                 extractcontrolpoints2d->SetSamplingControlPoints( sampling );
2184                 extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
2185         }
2186
2187         //--Adding contour to the system
2188
2189         std::vector<int> actualInstantVector;
2190         _instantPanel->getInstant( actualInstantVector );
2191         actualInstantVector[1]=z;
2192
2193         int j,sizeCtrPt = vecCtrlPointX.size();
2194         manualBaseModel *manModelContour =  kernelManager->factoryManualContourModel( typeofcontour );
2195         manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
2196         if (sizeCtrPt>=3){
2197                 for (j=0 ; j<sizeCtrPt ; j++)
2198                 {
2199                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
2200                 } // for
2201                 std::string theName;
2202                 //theName = _modelManager->createOutline( manModelContour, actualInstantVector );
2203                 theName = kernelManager->createOutline( manModelContour, actualInstantVector );
2204                 bool addedModel = theName.compare("") != 0;
2205                 if( addedModel )
2206                 {
2207                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2208                         _theViewPanel->getSpacing(spc);
2209                         //Adding the manualContourControler to interface objects structure
2210                         //Adding the manualViewContour to interface objects structure
2211                         //_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.
2212                         _theViewPanel->configureViewControlTo(theName, manModelContour, spc, typeofcontour);
2213                         //_theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
2214                 }       // if addedModel
2215         } // if sizeCtrPt
2216 }
2217 int wxContourMainFrame::GetImageDataSizeZ(){
2218         return _theViewPanel->GetImageDataSizeZ();
2219 }
2220
2221 void wxContourMainFrame::GetImageDataRange(double *range){
2222         _theViewPanel->GetImageDataRange(range);
2223 }
2224
2225 void wxContourMainFrame::onSegmentationAllSlice(int minZ,int maxZ,int isovalue,int sampling,int method){
2226         //JCP 20-10-08 Undo redo implementation
2227         saveState();
2228         //JCP 20-10-08 Undo redo implementation
2229
2230         wxBusyCursor wait;
2231         int                                     x                                       = _theViewPanel->GetX();
2232         int                                     y                                       = _theViewPanel->GetY();
2233         int z;
2234         double porcent;
2235         wxString tmpString;
2236         double totalZ = maxZ-minZ+1;
2237         for( z=minZ ; z<=maxZ ; z++ )
2238         {
2239                 porcent = 100.0* (z-minZ)/totalZ;
2240                 tmpString.Printf(_T("  %d %c            %d/%d            %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ,z );
2241                 interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(tmpString);
2242                 //_staticTextSegmentation->SetLabel(tmpString);
2243                 SegmentationOneSlice( x,y,z,isovalue, sampling,method );
2244         }
2245         interfMainPanel::getInstance()->setLabelSegmentationPanelVTK(_T("   "));
2246         RefreshInterface();
2247 }
2248
2249
2250 //Creates a reference line to be used as the axis of the mirroring
2251 void wxContourMainFrame::referenceLine()
2252 {
2253         if (_refLineControl==NULL)
2254         {
2255                 wxBusyCursor wait;
2256                 double spc[3];
2257
2258                 vtkImageData *vtkimagedata = _theViewPanel->getImageData();
2259                 vtkimagedata->GetSpacing(spc);
2260
2261                 wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
2262
2263                 _refLineControl = new manualLineControler();
2264                 _refLineModel   = new manualContourModelLine();
2265                 _refLineView = new manualViewLine();
2266                 _refLineView->SetModel( _refLineModel );
2267                 _refLineView->SetWxVtkBaseView( viewer2D );
2268                 _refLineView->SetRange( 2 );
2269                 _refLineView->SetZ( 1200 );
2270
2271                 _refLineView->SetSpacing(spc);
2272
2273                 _refLineView->SetColorNormalContour(0, 0, 1);
2274                 _refLineView->SetColorEditContour(0, 0.5, 0.5);
2275                 _refLineView->SetWidthLine(4);
2276
2277                 _refLineControl->SetModelView( _refLineModel , _refLineView );
2278                 vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2279                 style->AddInteractorStyleMaracas( _refLineControl );
2280                 _refLineModel->SetCloseContour(false);
2281                 _refLineControl->CreateNewManualContour();
2282
2283 //AD: Inicializar el mirroring con una linea ya pintada
2284         /*
2285                 double z = _refLineControl->GetZ();
2286
2287                 int imageDim[3];
2288                 image->GetDimensions(imageDim);
2289                 double x = (double) imageDim[0]/2;
2290                 double y1 = (double) (imageDim[1]/2)+15;
2291                 double y2 = (double) (imageDim[1]/2)-15;
2292
2293                 _refLineControl->AddPoint(x,y1,z);
2294                 _refLineControl->AddPoint(x,y2,z);
2295                 _refLineControl->SetCompleteCreation(true);
2296
2297                 _refLineModel->AddPoint(x,y1,z);
2298                 _refLineModel->AddPoint(x,y2,z);
2299                 _refLineModel->UpdateSpline();
2300
2301                 _refLineView->UpdateViewPoint(0);
2302                 _refLineView->UpdateViewPoint(1);
2303         */
2304
2305                 _refLineControl->SetActive(true);
2306                 _refLineView->RefreshContour();
2307         }
2308 }
2309
2310 //Hides the referenceLine
2311 void wxContourMainFrame::refLineHide()
2312 {
2313         if (_refLineControl!=NULL)
2314         {
2315                 if (_refLineControl->GetActive())
2316                 {
2317                         _refLineView->RemoveCompleteContourActor();
2318                         _refLineControl->SetEditable(false);
2319                         _refLineControl->SetActive(false);
2320
2321                         RefreshInterface();
2322                 }
2323         }
2324 }
2325
2326 //Shows the referenceLine
2327 void wxContourMainFrame::refLineShow()
2328 {
2329         if (_refLineControl!=NULL)
2330         {
2331                 if (_refLineControl->GetActive()==false)
2332                 {
2333                         wxVtkBaseView * viewer2D = _theViewPanel->getWxVtkBaseView();
2334
2335                         _refLineView->SetModel( _refLineModel );
2336                         _refLineView->SetWxVtkBaseView( viewer2D );
2337                         _refLineView->SetRange( 2 );
2338                         _refLineView->SetZ( 1200 );
2339
2340                         _refLineControl->SetModelView( _refLineModel , _refLineView );
2341                         vtkInteractorStyleBaseView* style = (vtkInteractorStyleBaseView*)viewer2D->GetInteractorStyleBaseView();
2342                         style->AddInteractorStyleMaracas( _refLineControl );
2343                         _refLineControl->CreateNewManualContour();
2344                         _refLineControl->SetActive(true);
2345                         _refLineView->RefreshContour();
2346
2347                         RefreshInterface();
2348                 }
2349         }
2350 }
2351
2352 void wxContourMainFrame::refLineChangeWidth(int width)
2353 {
2354         _refLineView->SetWidthLine(width);
2355         _refLineView->RefreshContour();
2356
2357         RefreshInterface();
2358 }
2359
2360
2361 void wxContourMainFrame::onMirror()
2362 {
2363         //AD:02-09
2364         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2365         std::vector<std::string> filterCurrentSelection;
2366
2367         std::vector<int> tempVector;
2368         _instantPanel->getInstant( tempVector );
2369     _performingOperation->reset();
2370         _performingOperation->setStartCommand( COPY );
2371         _performingOperation->setStartOperationInstantVector( tempVector );
2372         _performingOperation->setKeyNamesOperationElems( currentSelection );
2373
2374         char theStartCommand = _performingOperation->getStartCommand();
2375         if (  theStartCommand == COPY )
2376         {
2377                 //JCP 20-10-08 Undo redo implementation
2378                 saveState();
2379                 //JCP 20-10-08 Undo redo implementation
2380                 std::vector<int> tempVector;
2381                 _instantPanel->getInstant( tempVector );
2382                 _performingOperation->setEndOperationInstantVector ( tempVector );
2383                 std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
2384                 int i,size = elems.size();
2385                 for( i=0; i<size; i++ )
2386                 {
2387                         createMirrorContourOf( elems[i], tempVector, i>0 );
2388                 }
2389         }
2390
2391         //deleteContour( _refName );
2392         //_refName = "";
2393 }
2394
2395
2396 void wxContourMainFrame::showAxis(bool show)
2397 {
2398         _theViewPanel->SetVisibleAxis(show);
2399         _theViewPanel->Refresh();
2400 }
2401
2402
2403 void wxContourMainFrame::onRigidPressed(){
2404         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
2405         int elementsSelected = currentSelection.size();
2406
2407         if ( elementsSelected >= 1 ){
2408                 //JCP 20-10-08 Undo redo implementation
2409                 saveState();
2410                 //JCP 20-10-08 Undo redo implementation
2411
2412                 std::vector<int> tempVector;
2413                 _instantPanel->getInstant( tempVector );
2414                 Instant instant(&tempVector);
2415
2416                 int i , size=currentSelection.size();
2417                 for ( i=0 ; i<size ; i++ )
2418                 {
2419                         kernelManager->changeContourOfManager(currentSelection[i], &instant);
2420                 } // i
2421         }
2422 }
2423
2424 void wxContourMainFrame::onWidthOfContour(double width){
2425
2426         _theViewPanel->removeSceneContours();
2427         _theViewPanel->SetWidthContour(width);
2428
2429         //_theViewPanel->getSceneManager()->SetWidthContour( width );
2430
2431         RefreshInterface();
2432 }
2433
2434 int wxContourMainFrame::getColorWindow()
2435 {
2436         /*
2437         double range[2];
2438         vtkImageData * img = getImageData();
2439         img->GetScalarRange(range);
2440
2441         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2442
2443         return (int)range[1];
2444         */
2445         return _theViewPanel->getColorWindow();
2446 }
2447
2448 int wxContourMainFrame::getWindowLevel()
2449 {
2450         /*
2451         double range[2];
2452         vtkImageData * img = getImageData();
2453         img->GetScalarRange(range);
2454
2455         std::cout<<"Val 1: "<<range[0]<<" Val 2: "<<range[1]<<std::endl;
2456
2457         return (int)range[1];
2458         */
2459         return _theViewPanel->getWindowLevel();
2460 }
2461
2462 void wxContourMainFrame::onBrigthnessColorWindowLevel(int colorwindow,int windowlevel){
2463         _theViewPanel->onBrigthnessColorWindowLevel(colorwindow, windowlevel);
2464
2465         RefreshInterface();
2466 }
2467
2468 void wxContourMainFrame::onInterpolation(bool interpolate){
2469         _theViewPanel->onInterpolation(interpolate);
2470         RefreshInterface();
2471 }
2472
2473 void wxContourMainFrame::onChangeInstant(std::string name,int actual){
2474         _instantPanel->setConceptValue( name, actual );
2475 }
2476
2477
2478 void wxContourMainFrame::resetAppend(){
2479         kernelManager->resetAppend();
2480
2481 }
2482
2483
2484 void wxContourMainFrame::onSpreadAdd(){
2485         std::vector<double> vecX;
2486         std::vector<double> vecY;
2487         std::vector<double> vecZ;
2488         _theViewPanel->GetPointsOfActualContour(&vecX , &vecY , &vecZ );
2489         std::vector<int> tempVector;
2490         _instantPanel->getInstant( tempVector );
2491         std::string val = kernelManager->onSpreadAdd(&vecX , &vecY , &vecZ, tempVector);
2492         interfMainPanel::getInstance()->appendStringSpread(val);
2493 }
2494
2495
2496 void wxContourMainFrame::onSpreadAddAll(){
2497 //EED02
2498         std::vector<int> tempVector;
2499         _instantPanel->getInstant( tempVector );
2500         int minZ,maxZ;
2501     minZ        = 0;
2502     maxZ        = interfMainPanel::getInstance()->GetImageDataSizeZ();
2503         int z;
2504         int sizeLstContourThings;
2505         for ( z=minZ ; z<=maxZ ; z++ )
2506         {
2507                 tempVector[1]=z;
2508                 Instant instant(&tempVector);
2509                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2510                 sizeLstContourThings = lstContourThings.size();
2511                 if (sizeLstContourThings>=1)
2512         {
2513             std::vector<double> vecX;
2514             std::vector<double> vecY;
2515             std::vector<double> vecZ;
2516             ContourThing **contourthing = lstContourThings[0];
2517                         manualBaseModel *cModel                         =  (*contourthing)->getModel();
2518                         int i,size = cModel->GetNumberOfPointsSpline();
2519                         double x,y,z;
2520                         for (i=0; i<size; i++)
2521                         {
2522                                 cModel->GetSpline_i_Point(i, &x, &y, &z);
2523                                 vecX.push_back(x);
2524                                 vecY.push_back(y);
2525                                 vecZ.push_back(z);
2526                         } // for i
2527             std::string val = kernelManager->onSpreadAdd(&vecX , &vecY , &vecZ, tempVector);
2528             interfMainPanel::getInstance()->appendStringSpread(val);
2529         }// if sizeLstContourThings
2530     } // for z
2531 }
2532
2533
2534 void wxContourMainFrame::onSpreadGo(int type){
2535         //JCP 20-10-08 Undo redo implementation
2536         saveState();
2537         //JCP 20-10-08 Undo redo implementation
2538         wxBusyCursor wait;
2539         std::vector<double> vecCtrlPointX;
2540         std::vector<double> vecCtrlPointY;
2541         std::vector<double> vecCtrlPointZ;
2542         double  minZ,maxZ;
2543         int z;
2544
2545         std::vector<int> tempVector;
2546         _instantPanel->getInstant( tempVector );
2547 //              tempVector[1];
2548
2549         kernelManager->getMaxMinZ(&minZ,&maxZ);
2550 //JSTG_16-07-08_----------------------------------------------------------------
2551         //_contourPropagation->setInterpolationNumber(maxZ-minZ+1);
2552         kernelManager->CalculeSplinePropagation();
2553
2554         double          totalZ = maxZ-minZ+1;
2555         double          porcent;
2556         wxString        tmpString;
2557 //--------------------------------------------------------------------
2558         for ( z=(int)minZ ; z<=(int)maxZ ; z++ )
2559         {
2560                 porcent = 100.0* (z-minZ)/totalZ;
2561                 int numero = (int)(z-minZ+1)/(int)totalZ;
2562                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2563
2564                 interfMainPanel::getInstance()->setStringSpread(stringtemp);
2565
2566                 int typeofcontour = 1;
2567                 std::string theName;
2568                 manualBaseModel* manModelContour = kernelManager->GetPoints(z, type, &vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ, theName,typeofcontour, tempVector);
2569
2570                 if( manModelContour!=NULL ){
2571                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2572                         this->_theViewPanel->getSpacing(spc);
2573                         //Adding the manualContourControler to interface objects structure
2574                         //Adding the manualViewContour to interface objects structure
2575                         //_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.
2576                         _theViewPanel->configureViewControlTo( theName, manModelContour,spc,typeofcontour ) ;
2577                 } // if addedModel
2578         }
2579         if(z > maxZ){
2580                 porcent = 100.0;
2581                 int numero = (int)(z-minZ+1)/(int)totalZ;
2582                 std::string stringtemp = "  "+kernelManager->intToString(porcent)+"%            "+kernelManager->intToString(numero)+"            "+kernelManager->intToString(z);
2583
2584                 interfMainPanel::getInstance()->setStringSpread(stringtemp);
2585         }// for z
2586         //RefreshInterface();
2587 }
2588
2589 void wxContourMainFrame::getInstantVector(std::vector<int>& tempVector){
2590
2591 }
2592
2593 std::vector<std::string> wxContourMainFrame::getOutlinesName(int slide){
2594         std::vector<int> tempVector;
2595         _instantPanel->getInstant(tempVector);
2596         //Asignation of slide number should be different ex by name
2597         tempVector[1]=slide;
2598         return kernelManager->getOutlinesNameAtInstant(tempVector);
2599 }
2600
2601
2602 void wxContourMainFrame::SetScalarRange(int grayRangeMin, int grayRangeMax)
2603 {
2604         _contourextractdata->SetScalarRange(grayRangeMin,grayRangeMax);
2605 }
2606
2607
2608 void wxContourMainFrame::onInformationContourLabels(int typeContourGroup,int selection,int minimumZ,int maximumZ,int grayRangeMin, int grayRangeMax)
2609 {
2610
2611         wxString tempString;
2612         int maxContourGroup     =       0;
2613
2614         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2615
2616         std::vector<manualBaseModel*> lstManConMod;
2617         std::vector<manualBaseModel*> lstManConModTmp;
2618         std::vector<manualBaseModel*> lstManConModExp;
2619         std::vector<double> pLstValue;
2620         std::vector<double> pLstValuePosX;
2621         std::vector<double> pLstValuePosY;
2622         std::vector<double> pLstValuePosZ;
2623
2624         int             resultSize;
2625         int             resultGrayRangeCount;
2626         double  resultMin;
2627         double  resultMax;
2628         double  resultAverage;
2629         double  resultStandardeviation;
2630
2631         std::vector<int> tempVector;
2632         _instantPanel->getInstant( tempVector );
2633
2634         int z;
2635         int ii,sizeLstContourThings;
2636
2637
2638         int minZ,maxZ;
2639         double totalZ;
2640         double porcent;
2641         wxString tmpString;
2642
2643
2644         if (selection==0 ) // actual slice
2645         {
2646                 int actualSlice = tempVector[1];
2647                 minZ    = actualSlice;
2648                 maxZ    = actualSlice;
2649         }       else  {  // slice range
2650                 minZ    = minimumZ;
2651                 maxZ    = maximumZ;
2652         }
2653
2654
2655         totalZ  = maxZ-minZ+1;
2656
2657         _contourextractdata->InitVolumeStatistics();
2658
2659 // For each slice..
2660         for ( z=minZ ; z<=maxZ ; z++ )
2661         {
2662
2663                 porcent = 100.0* (z-minZ)/totalZ;
2664                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2665
2666                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2667                 //_staticTextInformation->SetLabel(tmpString);
2668
2669                 //Extraction data from contours of each slice
2670                 _contourextractdata->SetZtoBeAnalys(z);
2671
2672                 tempVector[1]=z;
2673                 Instant instant(&tempVector);
2674                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
2675                 sizeLstContourThings = lstContourThings.size();
2676
2677                 lstManConMod.clear();
2678                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2679                 {
2680                         ContourThing **contourthing = lstContourThings[ii];
2681                         lstManConMod.push_back( (*contourthing)->getModel() );
2682                 }
2683
2684                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2685
2686                 tempString.Printf(_T("%d - %d"),z, sizeLstContourThings);
2687                 interfMainPanel::getInstance()->setRowLabelInfoPanel(z, tempString);
2688                 //_grid->SetRowLabelValue(z, tempString );
2689 //EED004
2690                 int iContourGroup,sizeContourGroup;
2691                 if (typeContourGroup==3) // contour separete
2692                 {
2693                         sizeContourGroup=lstManConModExp.size();
2694                         if ( maxContourGroup<sizeContourGroup )
2695                         {
2696                                 maxContourGroup=sizeContourGroup;
2697                         }
2698                 } else {  // contour AND OR XOR
2699                         sizeContourGroup=1;
2700                         maxContourGroup=1;
2701                 }
2702
2703                 int tmpIntA;
2704
2705                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2706                         lstManConModTmp.clear();
2707
2708
2709
2710                         if (typeContourGroup==3) // contour separete
2711                         {
2712                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2713                         } else {  // contour AND OR XOR
2714                                 lstManConModTmp = lstManConModExp;
2715                         }
2716
2717                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2718                         _contourextractdata->SetScalarRange(grayRangeMin,grayRangeMax);
2719
2720                         pLstValue.clear();
2721                         pLstValuePosX.clear();
2722                         pLstValuePosY.clear();
2723                         pLstValuePosZ.clear();
2724
2725
2726                         int numberOfPixels;
2727                         _contourextractdata->GetValuesInsideCrown(  &numberOfPixels,
2728                                                                                                                 &pLstValue,
2729                                                                                                                 &pLstValuePosX,
2730                                                                                                                 &pLstValuePosY,
2731                                                                                                                 &pLstValuePosZ);
2732
2733                         resultSize=numberOfPixels;
2734                         // Statistics of each slice.
2735                         _contourextractdata->Statistics( &pLstValue,
2736                                                                                         grayRangeMin,
2737                                                                                         grayRangeMax,
2738                                                                                         &resultGrayRangeCount,
2739                                                                                         &resultSize,
2740                                                                                         &resultMin,
2741                                                                                         &resultMax,
2742                                                                                         &resultAverage,
2743                                                                                         &resultStandardeviation);
2744
2745                         if (interfMainPanel::getInstance()->getNumberColsInformationPanel()<_numberOfVariablesStatistics*(iContourGroup+1)  )
2746                         {
2747                                 interfMainPanel::getInstance()->appendColsInformationPanel(_numberOfVariablesStatistics);
2748                         }
2749
2750                         tmpIntA=_numberOfVariablesStatistics*iContourGroup ;
2751
2752                         tempString.Printf(_T("%d"),numberOfPixels);
2753
2754                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA, tempString);
2755
2756                         tempString.Printf(_T("%d"),resultGrayRangeCount);
2757                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+1, tempString);
2758
2759                         tempString.Printf(_T("%f"),resultMin);
2760                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+2, tempString);
2761
2762                         tempString.Printf(_T("%f"),resultMax);
2763                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+3, tempString);
2764
2765                         tempString.Printf(_T("%f"),resultAverage);
2766                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+4, tempString);
2767
2768                         tempString.Printf(_T("%f"),resultStandardeviation);
2769                         interfMainPanel::getInstance()->setCellValueInfoPanel(z, tmpIntA+5, tempString);
2770
2771
2772                 } // for iContourGroup
2773         } // for z
2774
2775         // Print Volume Statistics
2776
2777
2778         int             vol_rCountRange;
2779         int             vol_rsize;
2780         double  vol_minValue;
2781         double  vol_maxValue;
2782         double  vol_average;
2783         double  vol_standardeviation;
2784
2785         if (selection!=0 ) // actual slice
2786         {
2787
2788                 _contourextractdata->GetVolumeStatistics(&vol_rCountRange, &vol_rsize,
2789                                                                                                  &vol_minValue, &vol_maxValue,
2790                                                                                                  &vol_average, &vol_standardeviation);
2791
2792                 interfMainPanel::getInstance()->setRowLabelInfoPanel(maxZ+2, _T("Total:"));
2793
2794                 tempString.Printf(_T("%d"),vol_rsize);
2795                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 0, tempString);
2796
2797                 tempString.Printf(_T("%d"),vol_rCountRange);
2798                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 1, tempString);
2799
2800                 tempString.Printf(_T("%f"),vol_minValue);
2801                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 2, tempString);
2802
2803                 tempString.Printf(_T("%f"),vol_maxValue);
2804                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 3, tempString);
2805
2806                 tempString.Printf(_T("%f"),vol_average);
2807                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 4, tempString);
2808
2809                 tempString.Printf(_T("%f"),vol_standardeviation);
2810                 interfMainPanel::getInstance()->setCellValueInfoPanel(maxZ+2, 5, tempString);
2811         }
2812         //-----------------------------------------
2813
2814         int iTitleGroup;
2815         wxString tmpTitleString;
2816         int tmpIntB;
2817         for ( iTitleGroup=0 ; iTitleGroup<maxContourGroup ; iTitleGroup++ )
2818         {
2819                 tmpIntB =_numberOfVariablesStatistics*iTitleGroup;
2820                 tmpTitleString.Printf(_T("%d-Size Data"),iTitleGroup);
2821                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString);
2822
2823                 interfMainPanel::getInstance()->setColLableInfoPanel(tmpIntB + 0, tmpTitleString );
2824                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 1, _T("Size Range") );
2825                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 2, _T("Min") );
2826                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 3, _T("Max") );
2827                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 4, _T("Average") );
2828                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 5, _T("St.Dev.") );
2829                 interfMainPanel::getInstance()->setColLableInfoPanel( tmpIntB + 6, _T(" ") );
2830         }// for title
2831         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
2832 }
2833
2834 //AD: 29-05-09
2835 void wxContourMainFrame::onSaveResults(std::string directory,std::string namefile, std::string filename,
2836         int typeContourGroup, int selection, int minZ, int maxZ, bool XYZValues, bool contourImage, bool statistics)
2837 {
2838         if (XYZValues)
2839         {
2840                 SaveValuesXYZ( directory , namefile, typeContourGroup );
2841         }
2842
2843         if (contourImage)
2844         {
2845                 vtkImageData * mask;
2846                 vtkImageData * value;
2847                 this->getMaskValue(&mask, &value, typeContourGroup,selection,minZ,maxZ);
2848                 this->SaveImageResult( directory , namefile, mask, value);
2849         }
2850
2851         if (statistics)
2852         {
2853                 std::ostringstream name;
2854                 name << filename << ".xls";
2855
2856
2857                 FILE *pFile=fopen(name.str().c_str(),"w+");
2858
2859
2860                 wxString tmpString;
2861                 int i,j,maxX;
2862
2863 //              int sizeZ = _theViewPanel->GetImageDataSizeZ();
2864 //              int maxY=sizeZ+2;
2865
2866                 maxX= interfMainPanel::getInstance()->getNumberColsInformationPanel();//this->_grid->GetNumberCols();
2867
2868                 // -- Title --
2869                 int iTitle,sizeTitle = (maxX / _numberOfVariablesStatistics);
2870                 for ( iTitle=0; iTitle<sizeTitle ; iTitle++)
2871                 {
2872                                 // fprintf(pFile,"-- \t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle,tmpString.c_str() );
2873                                 fprintf(pFile,"slice\t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle );
2874                 }
2875                 fprintf(pFile,"\n\n" );
2876
2877
2878
2879                 if (selection==0 ) // actual slice
2880                 {
2881                         std::vector<int> tempVector;
2882                         _instantPanel->getInstant( tempVector );
2883                         int actualSlice = tempVector[1];
2884                         minZ    = actualSlice;
2885                         maxZ    = actualSlice;
2886                 }
2887
2888                 // Stadistics...
2889                 for ( j=minZ; j<=maxZ ; j++)
2890                 {
2891                         fprintf(pFile,"%d\t" , j );
2892                         for (i=0 ; i<maxX ; i++){
2893                                 tmpString = interfMainPanel::getInstance()->getCellValue(j, i);//_grid->GetCellValue( j , i );
2894                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2895                         } // for i
2896                         fprintf(pFile,"\n"  );
2897                 } // for j
2898
2899
2900                 // Total of stadistics.....
2901                 if (selection!=0)
2902                 {
2903                         fprintf(pFile,"\n Total:\t"  );
2904                         for (i=0 ; i<maxX ; i++){
2905                                 tmpString = interfMainPanel::getInstance()->getCellValue(maxZ+2, i);//_grid->GetCellValue( maxZ+2 , i );
2906                                 fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
2907                         } // for i
2908                         fprintf(pFile,"\n"  );
2909                 }
2910
2911                 fclose(pFile);
2912         }
2913 }
2914
2915 //AD: 29-05-09
2916 void wxContourMainFrame::SaveValuesXYZ(std::string directory,std::string namefile,int typeContourGroup)
2917 {
2918         wxBusyCursor wait;
2919
2920         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
2921         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
2922
2923         std::vector<manualBaseModel*> lstManConMod;
2924         std::vector<manualBaseModel*> lstManConModTmp;
2925         std::vector<manualBaseModel*> lstManConModExp;
2926         std::vector<double> pLstValue;
2927         std::vector<double> pLstValuePosX;
2928         std::vector<double> pLstValuePosY;
2929         std::vector<double> pLstValuePosZ;
2930
2931         std::vector<int> tempVector;
2932         _instantPanel->getInstant( tempVector );
2933
2934         int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
2935         int z;
2936         int ii,sizeLstContourThings;
2937
2938
2939         int minZ,maxZ;
2940         double totalZ;
2941         double porcent;
2942         wxString tmpString;
2943         minZ    = 0;// _mbarrange->GetStart();
2944         maxZ    = sizeZ;//_mbarrange->GetEnd();
2945         totalZ  = maxZ-minZ+1;
2946
2947
2948 // For each slice..
2949         for ( z=0 ; z<sizeZ ; z++)
2950         {
2951
2952                 porcent = 100.0* (z-minZ)/totalZ;
2953
2954                 tmpString.Printf(_T("Saving Values"));
2955                 tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
2956                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
2957                 //_staticTextInformation->SetLabel(tmpString);
2958
2959
2960                 //Extraction data from contours of each slice
2961                 _contourextractdata->SetZtoBeAnalys( z);
2962
2963                 tempVector[1]=z;
2964                 Instant instant(&tempVector);
2965                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant(&instant);//this->_modelManager->getOutlinesAtInstant( &instant );
2966                 sizeLstContourThings = lstContourThings.size();
2967
2968                 lstManConMod.clear();
2969                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2970                 {
2971                         ContourThing **contourthing = lstContourThings[ii];
2972                         lstManConMod.push_back( (*contourthing)->getModel() );
2973                 }
2974                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
2975
2976
2977 //EED004
2978
2979                 int iContourGroup,sizeContourGroup;
2980                 if (typeContourGroup==3) // contour separete
2981                 {
2982                         sizeContourGroup=lstManConModExp.size();
2983                 } else {  // contour AND OR XOR
2984                         sizeContourGroup=1;
2985                 }
2986
2987                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
2988                         lstManConModTmp.clear();
2989                         if (typeContourGroup==3) // contour separete
2990                         {
2991                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
2992                         } else {  // contour AND OR XOR
2993                                 lstManConModTmp = lstManConModExp;
2994                         }
2995
2996                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
2997
2998                         pLstValue.clear();
2999                         pLstValuePosX.clear();
3000                         pLstValuePosY.clear();
3001                         pLstValuePosZ.clear();
3002                         int numberOfPixels;
3003                         _contourextractdata->GetValuesInsideCrown(      &numberOfPixels,
3004                                                                                                                 &pLstValue,
3005                                                                                                                 &pLstValuePosX,
3006                                                                                                                 &pLstValuePosY,
3007                                                                                                                 &pLstValuePosZ);
3008
3009                         std::string temp = directory + "/" + namefile + "-slice";
3010                         temp = temp + kernelManager->intToString(z) + "-cont" + kernelManager->intToString(iContourGroup);
3011                         temp = temp + ".txt";
3012
3013                         // LG 14/01/09 : using crea
3014                         wxString filename = crea::std2wx(temp);
3015                         /*filename.Printf(_T("%s"),directory.c_str());
3016                         filename.append(_T("\\"));
3017                         filename.append(_T("%s"),namefile.c_str());
3018                         filename.append(_T("-slice"));
3019                         filename.append(_T("%d"),z);
3020                         filename.append(_T("-cont"));
3021                         filename.append(_T("%d"),iContourGroup);
3022                         filename.append(_T(".txt"));*/
3023                         //                      filename.Printf(temp.c_str());
3024
3025
3026
3027                         FILE *pFile=fopen((const char *)filename.mb_str(),"w+");
3028                         fprintf(pFile,"value \t x \t y \t z\n"  );
3029                         int iLstValue,sizeLstValue=pLstValue.size();
3030                         for (iLstValue=0 ; iLstValue<sizeLstValue ; iLstValue++ )
3031                         {
3032                                 fprintf(pFile,"%f\t %f\t %f\t %f\n", (float)pLstValue[iLstValue] , (float)pLstValuePosX[iLstValue], (float)pLstValuePosY[iLstValue], (float)z );
3033                         }
3034                         fclose(pFile);
3035                 } // for  iContourGroup
3036         } // for z
3037         interfMainPanel::getInstance()->setStringInfoPanel(_T(""));
3038         //_staticTextInformation->SetLabel( _T("") );
3039
3040 }
3041
3042 void wxContourMainFrame::getMaskValue(vtkImageData ** mask,vtkImageData ** value,int typeContourGroup, int selection, int minZ, int maxZ){
3043         wxBusyCursor wait;
3044
3045         //int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
3046         if (typeContourGroup==3)
3047         {
3048                 typeContourGroup=1;
3049         }
3050         _contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
3051
3052         std::vector<manualBaseModel*> lstManConMod;
3053         std::vector<manualBaseModel*> lstManConModTmp;
3054         std::vector<manualBaseModel*> lstManConModExp;
3055
3056         std::vector<int> tempVector;
3057         _instantPanel->getInstant( tempVector );
3058
3059     vtkImageData *imagedata = _theViewPanel->getImageData();
3060         int ext[6];
3061         imagedata->GetExtent(ext);
3062         int sizeZimage = ext[5]-ext[4]+1;
3063         int z;
3064         int ii,sizeLstContourThings;
3065
3066
3067         double totalZ;
3068         double porcent;
3069
3070         wxString tmpString;
3071
3072
3073         if (selection==0 ) // actual slice
3074         {
3075                 int actualSlice = tempVector[1];
3076                 minZ    = actualSlice;
3077                 maxZ    = actualSlice;
3078         }
3079
3080         totalZ  = maxZ-minZ;
3081
3082
3083         // cleanning image before range
3084         for (z=0; z<minZ; z++){
3085                 _contourextractdata->ResetImageResult(z);
3086         }
3087         // cleanning image after range
3088         for (z=maxZ+1; z<sizeZimage; z++){
3089                 _contourextractdata->ResetImageResult(z);
3090         }
3091
3092
3093 // For each slice..
3094         for ( z=minZ ; z<=maxZ ; z++)
3095         {
3096
3097                 porcent = 100.0* (z-minZ)/totalZ;
3098                 tmpString.Printf(_T("Saving Values"));
3099                 tmpString.Printf(_T("%d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
3100                 interfMainPanel::getInstance()->setStringInfoPanel(tmpString);
3101
3102                 //Extraction data from contours of each slice
3103                 _contourextractdata->SetZtoBeAnalys( z);
3104
3105                 tempVector[1]=z;
3106                 Instant instant(&tempVector);
3107                 std::vector<ContourThing**> lstContourThings = kernelManager->getOutlinesAtInstant( &instant );
3108                 sizeLstContourThings = lstContourThings.size();
3109
3110                 lstManConMod.clear();
3111                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
3112                 {
3113                         ContourThing **contourthing = lstContourThings[ii];
3114                         lstManConMod.push_back( (*contourthing)->getModel() );
3115                 }
3116                 lstManConModExp =  kernelManager->ExploseEachModel( lstManConMod );
3117
3118
3119                 int iContourGroup,sizeContourGroup;
3120                 if (typeContourGroup==3) // contour separete
3121                 {
3122                         sizeContourGroup=lstManConModExp.size();
3123                 } else {  // contour AND OR XOR
3124                         sizeContourGroup=1;
3125                 }
3126
3127                 for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
3128                         lstManConModTmp.clear();
3129                         if (typeContourGroup==3) // contour separete
3130                         {
3131                                 lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
3132                         } else {  // contour AND OR XOR
3133                                 lstManConModTmp = lstManConModExp;
3134                         }
3135
3136                         _contourextractdata->SetLstManualContourModel( lstManConModTmp );
3137                         _contourextractdata->CalculateImageResult(); // with actual Z
3138
3139                 } // for  iContourGroup
3140         } // for z
3141
3142         (*value) = _contourextractdata->GetVtkImageValueResult();
3143         (*mask)  = _contourextractdata->GetVtkImageMaskResult();
3144
3145 }
3146
3147 void wxContourMainFrame::SaveImageResult(std::string directory,std::string namefile, vtkImageData* mask,vtkImageData* value)
3148 {
3149
3150         double spc[3];
3151         kernelManager->GetSpacing(spc,0);   // returns the spacing of the first image
3152         
3153         std::string temp = directory + "/" + namefile + "-image-Value.mhd";
3154
3155         wxString filename = crea::std2wx(temp);
3156
3157 // Image Value
3158         
3159         vtkImageChangeInformation *valueChInfo = vtkImageChangeInformation::New();
3160 //EED 2017-01-01 Migration VTK7
3161 #if VTK_MAJOR_VERSION <= 5
3162         valueChInfo->SetInput(value);
3163 #else
3164         valueChInfo->SetInputData(value);
3165 #endif
3166         valueChInfo->SetSpacingScale(spc);      
3167         vtkMetaImageWriter *writerValueImage = vtkMetaImageWriter::New( );
3168
3169 //EED 2017-01-01 Migration VTK7
3170 #if VTK_MAJOR_VERSION <= 5
3171         writerValueImage->SetInput( valueChInfo->GetOutput() );
3172 #else
3173         writerValueImage->SetInputData( valueChInfo->GetOutput() );
3174 #endif
3175         writerValueImage->SetFileName( (const char *)filename.mb_str() );
3176         writerValueImage->SetFileDimensionality( 3 );
3177         writerValueImage->SetCompression(false);
3178         writerValueImage->Write( );
3179
3180 // Image Mask
3181         temp = directory + "/" + namefile + "-image-Mask.mhd";
3182
3183         // LG 14/01/09 : using crea
3184         filename = crea::std2wx(temp);
3185         //      filename.Printf(_T(temp.c_str()));
3186
3187
3188         vtkImageChangeInformation *maskChInfo = vtkImageChangeInformation::New();
3189 //EED 2017-01-01 Migration VTK7
3190 #if VTK_MAJOR_VERSION <= 5
3191         maskChInfo->SetInput(mask);
3192 #else
3193         maskChInfo->SetInputData(mask);
3194 #endif
3195         maskChInfo->SetSpacingScale(spc);       
3196         vtkMetaImageWriter *writerMaskImage = vtkMetaImageWriter::New( );
3197
3198 //EED 2017-01-01 Migration VTK7
3199 #if VTK_MAJOR_VERSION <= 5
3200         writerMaskImage->SetInput( maskChInfo->GetOutput() );
3201 #else
3202         writerMaskImage->SetInputData( maskChInfo->GetOutput() );
3203 #endif
3204
3205         writerMaskImage->SetFileName( (const char *)filename.mb_str() );
3206         writerMaskImage->SetFileDimensionality( 3 );
3207         writerMaskImage->SetCompression(false);
3208         writerMaskImage->Write( );
3209
3210         interfMainPanel::getInstance()->setStringInfoPanel( _T("") );
3211
3212 }
3213
3214
3215
3216 void wxContourMainFrame::onChangeInstantInstantPanel(std::string name,int value, int minshow, int maxshow){
3217         if( name.compare( _theViewPanel->getVerticalConceptName() ) == 0){
3218                 _theViewPanel->setActualVertical( value);
3219         }
3220         else if( name.compare( _theViewPanel->getHorizontalConceptName() ) == 0|| _instantPanel->getIfConceptCheckedAt( name, 0 ) )     {
3221                 _theViewPanel->setHorizontalConcept( name, minshow, maxshow, minshow, maxshow, value);
3222         }
3223
3224         changeInstant();
3225 }
3226
3227 void wxContourMainFrame::onSnakePressed(){
3228         std::vector<double> vecX;
3229         std::vector<double> vecY;
3230         std::vector<double> vecZ;
3231         _theViewPanel->GetPointsOfActualContour( &vecX , &vecY , &vecZ );
3232
3233         if (vecX.size()!=0){
3234                 std::vector<int> tempVector;
3235                 _instantPanel->getInstant( tempVector );
3236                 int i,size=vecZ.size();
3237                 int actualSlice = tempVector[1];
3238                 for ( i=0 ; i<size ; i++ )
3239                 {
3240                         vecZ[i] = actualSlice;
3241                 } // for
3242
3243                 wxDialog* dialog = new wxDialog(this, -1, wxString(_T("Snake")));
3244                 wxPanel* panel = new wxPanel(dialog,-1);
3245                 //              wxStaticText* sttext = new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
3246          new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
3247                 dialog->ShowModal();
3248         } // if
3249
3250 }
3251
3252 void wxContourMainFrame::saveFileWithContoursAutomatique(){
3253         std::string filename = kernelManager->getCurrentFileName();
3254         if(filename.compare("")!=0){
3255                 saveFileWithContours(filename);
3256         }else{
3257                 onSave();
3258         }
3259 }
3260 void wxContourMainFrame::ShowToolsPanel(bool show){
3261         _pannew->Show(show);
3262 }
3263
3264
3265
3266 void wxContourMainFrame::SetContourGroup(int contourGroup)
3267 {
3268         _contourGroup = contourGroup;
3269 }
3270
3271
3272 wxPanel *wxContourMainFrame::getMaskImageViewPanel(wxWindow *parent)
3273 {
3274
3275         if      (_viewMaskImagePanel==NULL)
3276         {
3277                 _contourextractdata = new ContourExtractData(true);
3278                 _contourextractdata->SetImage( _theViewPanel->getImageData() );
3279 //              double range[2];
3280 //              _theViewPanel->getImageData()->GetScalarRange(range);
3281                 //int min = (int)floor (range[0]);
3282                 //int max = (int)ceil (range[1]);
3283                 int min = 254;
3284                 int max = 256;
3285                 _viewMaskImagePanel = new ThresholdImageViewPanel( parent, -1, -1 , 0);
3286                 _viewMaskImage = new ThresholdImageView();
3287                 _viewMaskImage->SetImage(_contourextractdata->GetVtkImageMaskResult() );
3288                 _viewMaskImage->SetminMaxValue( min, max);
3289                 _viewMaskImage->SetBaseColor( 0,0,1 );
3290                 _viewMaskImagePanel->SetThresholdImageView( _viewMaskImage );
3291                 _viewMaskImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
3292         }
3293         return _viewMaskImagePanel;
3294 }
3295
3296
3297 wxPanel *wxContourMainFrame::getColorLayerImageViewPanel(wxWindow *parent)
3298 {
3299         if      (_viewColorLayerImagePanel==NULL)
3300         {
3301                 double range[2];
3302                 _theViewPanel->getImageData()->GetScalarRange(range);
3303                 int min = (int)floor (range[0]);
3304                 int max = (int)ceil (range[1]);
3305                 _viewColorLayerImagePanel = new ColorLayerImageViewPanel( parent, min, max, 100, 1);
3306                 _viewColorLayerImagePanel->GetColorLayerImageViewManager()->SetwxVtkBaseView( 0 , _theViewPanel->getWxVtkBaseView() );
3307         }
3308         return _viewColorLayerImagePanel;
3309 }
3310
3311
3312 wxPanel *wxContourMainFrame::getThresholdImageViewPanel(wxWindow *parent)
3313 {
3314         if      (_viewThresholdImagePanel==NULL)
3315         {
3316                 double range[2];
3317                 _theViewPanel->getImageData()->GetScalarRange(range);
3318                 int min = (int)floor (range[0]);
3319                 int max = (int)ceil (range[1]);
3320                 _viewThresholdImagePanel = new ThresholdImageViewPanel( parent, min, max , 1);
3321                 _viewThresholdImage = new ThresholdImageView();
3322                 _viewThresholdImage->SetImage( _theViewPanel->getImageData() );
3323                 _viewThresholdImage->SetminMaxValue( min, max);
3324                 _viewThresholdImage->SetBaseColor( 1,0,0 );
3325                 _viewThresholdImagePanel->SetThresholdImageView( _viewThresholdImage );
3326                 _viewThresholdImage->SetwxVtkBaseView( _theViewPanel->getWxVtkBaseView() );
3327         }
3328         return _viewThresholdImagePanel;
3329 }
3330
3331 //CMRU 17-08-09-----------------------------------------------------------------------------------------------
3332 int wxContourMainFrame::getType ()
3333 {
3334         int tipo = 0;
3335         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
3336
3337         if(!currentSelection.empty())
3338         {
3339                 std::string cloneName = currentSelection [0];
3340                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);
3341                 tipo = manualModel-> GetTypeModel();
3342         }
3343         return tipo;
3344 }
3345
3346 double wxContourMainFrame::getContourSizeInPixels()
3347 {
3348         double contourSize = 0;
3349
3350         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();        if(!currentSelection.empty())
3351         if(!currentSelection.empty())
3352         {
3353                 std::string cloneName = currentSelection [0];
3354
3355                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
3356
3357 // EED 2017-05-30
3358 //              contourSize = manualModel->GetPathSize();
3359                 double spc[3];
3360                 spc[0]=1; 
3361                 spc[1]=1; 
3362                 spc[2]=1; 
3363                 contourSize = manualModel->GetPathSize( spc );
3364         }
3365         return contourSize;
3366 }
3367
3368 manualBaseModel * wxContourMainFrame::getContour ()
3369 {
3370         std::vector<std::string> currentSelection = _theViewPanel->getSelectedObjects();
3371
3372         if(!currentSelection.empty())
3373         {
3374                 std::string cloneName = currentSelection [0];
3375                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(cloneName);//_modelManager->getOutlineByKeyName( cloneName )->getModel();
3376                 return manualModel;
3377         }
3378         return NULL;
3379 }
3380 void wxContourMainFrame::onPrintLabel (wxString label, manualBaseModel* manualModel)
3381 {
3382         std::string labelAscii(label.ToAscii());
3383         int pos = labelAscii.find(" ");
3384
3385         int j;
3386
3387         for (j=0 ; pos != string::npos;j++)
3388         {
3389                 labelAscii.replace( pos, 1, "_" );
3390                 pos= labelAscii.find(" ");
3391         }
3392
3393         manualModel -> SetLabel(labelAscii);
3394 }
3395 void wxContourMainFrame::onInsertCalculation(manualBaseModel* manualModel)
3396 {
3397 // EED 2017-05-30
3398 //      double sizeInPixel      = manualModel ->GetPathSize(  );
3399         double spc[3];
3400         spc[0]=1; // ????
3401         spc[1]=1; // ????
3402         spc[2]=1; // ????
3403         double sizeInPixel      = manualModel ->GetPathSize( spc );
3404
3405         double onePixelRealSize = interfMainPanel::getInstance()->GetPixelValue();;
3406         double realContourSize  = sizeInPixel*onePixelRealSize;
3407         manualModel ->SetRealSize(realContourSize);
3408 }
3409
3410 double wxContourMainFrame::onePixelSize( double value)
3411 {
3412         return _onePixelSize = value;
3413 }
3414
3415 std::string wxContourMainFrame::GetFileLocation()
3416 {
3417         return _fileLocation;
3418 }
3419
3420 void wxContourMainFrame::SetFileLocation(std::string newFileLocation)
3421 {
3422         _fileLocation = newFileLocation;
3423         std::cout<<"GETFILELOCATION:"<<_fileLocation<<std::endl;
3424 }
3425 //------------------------------------------------------------------------------------------------------------
3426
3427
3428
3429
3430
3431
3432
3433
3434 void wxContourMainFrame::FlipSelectedContours(int flipDirection)
3435 {
3436         printf("EED wxContourMainFrame::FlipSelectedContours  flipDirection=%d  \n",  flipDirection ); 
3437         FlipLstOfContours( 
3438                             (std::vector<std::string>)_theViewPanel->getSceneManager()->getSelectedObjects() , 
3439                             flipDirection
3440                           );    
3441                 
3442 }
3443
3444 void wxContourMainFrame::FlipActualSliceContours(int flipDirection)
3445 {
3446         printf("EED wxContourMainFrame::FlipActualSliceContours  flipDirection=%d  \n",  flipDirection );       
3447         FlipLstOfContours( 
3448                             (std::vector<std::string>)_theViewPanel->getSceneManager()->GetlstContoursNameActualSlice() , 
3449                             flipDirection
3450                           );    
3451 }
3452
3453 void wxContourMainFrame::FlipAllContours(int flipDirection)
3454 {
3455         printf("EED wxContourMainFrame::FlipAllContours  flipDirection=%d  \n",  flipDirection );
3456         FlipLstOfContours( 
3457                             kernelManager->GetLstNameThings() , 
3458                             flipDirection
3459                           );
3460 }
3461
3462 void wxContourMainFrame::FlipLstOfContours(std::vector<std::string> lstNameThings, int flipDirection)
3463 {
3464         int ext[6];
3465         getImageData()->GetExtent(ext);         
3466         int sizeX = ext[1]-ext[0];
3467         int sizeY = ext[3]-ext[2];
3468
3469         
3470         int i,sizeLstNameThings;
3471         int ii,sizeLstPoints;
3472         
3473         sizeLstNameThings       = lstNameThings.size(); 
3474         for (i=0 ; i<sizeLstNameThings ; i++)
3475         {
3476                 printf("EED wxContourMainFrame::FlipAllContours contour=%d \n", i );
3477                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
3478                 if (flipDirection==0)
3479                 {
3480                         manualModel->Transform_Ax_Plus_B(-1,sizeX,1,0 );
3481                 } else {
3482                         manualModel->Transform_Ax_Plus_B(1,0,-1,sizeY );
3483                 }
3484         }// for i  list of Things
3485
3486         //-- Static Contours
3487
3488         lstNameThings           = kernelManager->GetLstNameThingsStatic();
3489         sizeLstNameThings       = lstNameThings.size();
3490         for (i=0 ; i<sizeLstNameThings ; i++)
3491         {
3492                 manualBaseModel * manualModel = kernelManager->getOutlineByKeyName(lstNameThings[i]);
3493                 if (flipDirection==0)
3494                 {
3495                         manualModel->Transform_Ax_Plus_B(-1,sizeX,1,0 );
3496                 } else {
3497                         manualModel->Transform_Ax_Plus_B(1,0,-1,sizeY );
3498                 }
3499         }// for i  list of static things        
3500 }
3501
3502 void wxContourMainFrame::FlipContours(int typeContourFlip, int flipDirection)
3503 {
3504         printf("EED wxContourMainFrame::FlipContours( %d , %d ) \n",typeContourFlip,  flipDirection );
3505
3506         saveState();
3507         
3508         if (typeContourFlip==0) // 
3509         {
3510                 FlipSelectedContours(flipDirection);
3511         }
3512
3513         if (typeContourFlip==1) // 
3514         {
3515                 FlipActualSliceContours(flipDirection);
3516         }
3517         
3518         if (typeContourFlip==2) // 
3519         {
3520                 FlipAllContours(flipDirection);
3521         }
3522         RefreshInterface();
3523 }
3524
3525
3526
3527
3528