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