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