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