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