File: ImageVis3D_Capturing.cpp

package info (click to toggle)
imagevis3d 2.0.1-5
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 7,872 kB
  • sloc: cpp: 53,586; sh: 788; ansic: 292; xml: 258; python: 35; makefile: 16
file content (389 lines) | stat: -rw-r--r-- 15,713 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.


   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/


//!    File   : ImageVis3D_Capturing.cpp
//!    Author : Jens Krueger
//!             SCI Institute
//!             University of Utah
//!    Date   : September 2008
//
//!    Copyright (C) 2008 SCI Institute

#include <sstream>
#include <QtGui/QFileDialog>
#include <QtGui/QInputDialog>
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include "ImageVis3D.h"
#include "../Tuvok/Basics/SysTools.h"
#include "../Tuvok/Controller/Controller.h"

#include "PleaseWait.h"
#include "MIPRotDialog.h"

using namespace std;
using namespace tuvok;

void MainWindow::CaptureFrame() {
  if (m_pActiveRenderWin) {
    if (!CaptureFrame(lineEditCaptureFile->text().toStdString())) {
      QString msg = tr("Error writing image file %1").arg(lineEditCaptureFile->text());
      ShowWarningDialog( tr("Error"), msg);
      T_ERROR("%s", msg.toAscii().data());
    }
  }
}

void MainWindow::CaptureSequence() {
  if (m_pActiveRenderWin) {
    string strSequenceName;
    if (!CaptureSequence(lineEditCaptureFile->text().toStdString(),
                         &strSequenceName)){
      QString msg = tr("Error writing image file %1").arg(strSequenceName.c_str());
      ShowWarningDialog( tr("Error"), msg);
      T_ERROR("%s", msg.toAscii().data());
    }
  }
}

bool MainWindow::CaptureFrame(const std::string& strTargetName) {
  if (m_pActiveRenderWin) {
    const bool checked = checkBox_PreserveTransparency->isChecked();
    return m_pActiveRenderWin->CaptureFrame(strTargetName, checked);
  } else {
    WARNING("No render window is open!");
    return false;
  }
}

bool MainWindow::CaptureSequence(const std::string& strTargetName,
                                 std::string* strRealFilename) {
  if (m_pActiveRenderWin) {
    const bool checked = checkBox_PreserveTransparency->isChecked();
    return m_pActiveRenderWin->CaptureSequenceFrame(strTargetName,
                                                    checked,
                                                    strRealFilename);
  } else {
    WARNING("No render window is open!");
    return false;
  }
}

void MainWindow::CaptureRotation() {
  if (m_pActiveRenderWin) {
    assert(m_pActiveRenderWin->GetActiveRenderRegions().size() == 1);

    const RenderRegion *renderRegion =
      m_pActiveRenderWin->GetActiveRenderRegions()[0];

    QSettings settings;
    int  iNumImages = settings.value("Renderer/ImagesPerRotation", 360).toInt();
    bool bOrthoView = settings.value("Renderer/RotationUseOrtho", true).toBool();
    bool bStereo    = settings.value("Renderer/RotationUseStereo", false).toBool();
    bool bUseLOD    = settings.value("Renderer/RotationUseLOD", true).toBool();
    int iEyeDist    = settings.value("Renderer/RotationEyeDist", 3).toInt();

    bool ok;
    if (renderRegion->is2D() &&
        m_pActiveRenderWin->GetRenderer()->GetUseMIP(renderRegion)) {
      MIPRotDialog mipRotDialog(iNumImages, bOrthoView, bStereo, bUseLOD,
                                iEyeDist, this);
      if (mipRotDialog.exec() == QDialog::Accepted) {
        ok = true;
        iNumImages = mipRotDialog.GetNumImages();
        bOrthoView = mipRotDialog.GetUseOrtho();
        bStereo    = mipRotDialog.GetUseStereo();
        bUseLOD    = mipRotDialog.GetUseLOD();
        iEyeDist   = mipRotDialog.GetEyeDist();

        settings.setValue("Renderer/RotationUseOrtho", bOrthoView);
        settings.setValue("Renderer/RotationUseStereo", bStereo);
        settings.setValue("Renderer/RotationUseLOD", bUseLOD);
        settings.setValue("Renderer/RotationEyeDist", iEyeDist);

      } else {
        ok = false;
      }
    } else {
      iNumImages = QInputDialog::getInteger(this,
                     tr("How many images to you want to compute?"),
                     tr("How many images to you want to compute:"),
                     iNumImages, 1, 3600, 1, &ok
                   );
    }
    if (!ok) return;

    settings.setValue("Renderer/ImagesPerRotation", iNumImages);

    m_pActiveRenderWin->ToggleHQCaptureMode();

    PleaseWaitDialog pleaseWait(this, Qt::Tool, true);
    QTLabelOut* labelOut = pleaseWait.AttachLabel(&m_MasterController);

    if (renderRegion->is3D()) {
      pleaseWait.SetText("Capturing a full 360 rotation, please wait  ...");

      int i = 0;
      float fAngle = 0.0f;
      // Kill the timer, and flush the existing event queue.  This ensures any
      // timers that have fired get processed, and we've got nothing scheduled
      // other than the capture.
      m_pRedrawTimer->stop();
      QCoreApplication::processEvents();
      while (i < iNumImages && !pleaseWait.Canceled()) {
        labelOut->SetOutput(true, true, true, false);
        std::ostringstream progress;
        progress << "Processing Image " << i+1 << " of " << iNumImages;
        if (i==0) {
          progress << " (the first image may be slower due to caching)";
        }
        progress << "\n" << static_cast<int>(100.0f*i/iNumImages)
                 << "% completed.";
        MESSAGE("%s", progress.str().c_str());
        labelOut->SetOutput(false, false, false, false);
        fAngle = float(i)/float(iNumImages) * 360.0f;
        m_pActiveRenderWin->SetCaptureRotationAngle(fAngle);

        m_pActiveRenderWin->GetRenderer()->SetRendererTarget(AbstrRenderer::RT_CAPTURE);
        while(m_pActiveRenderWin->GetRenderer()->CheckForRedraw() &&
              !pleaseWait.Canceled()) {
          const AbstrRenderer *ren = m_pActiveRenderWin->GetRenderer();
          unsigned sframes = ren->GetCurrentSubFrameCount();
          unsigned sframe = ren->GetWorkingSubFrame();
          unsigned bricks =  ren->GetCurrentBrickCount();
          unsigned brick =  ren->GetWorkingBrick();
          unsigned lod = ren->GetMinLODIndex();
          SetRenderProgressAnUpdateInfo(sframes, sframe, bricks, brick, lod,
                                        m_pActiveRenderWin);
          QCoreApplication::processEvents();
          m_pActiveRenderWin->UpdateWindow();
        }
        if(!pleaseWait.Canceled()) {
          string strSequenceName;
          if (!m_pActiveRenderWin->CaptureSequenceFrame(
              lineEditCaptureFile->text().toStdString(),
              checkBox_PreserveTransparency->isChecked(), &strSequenceName)) {
            QString msg = tr("Error writing image file %1").
                             arg(strSequenceName.c_str());
            ShowWarningDialog(tr("Error"), msg);
            T_ERROR("%s", msg.toAscii().data());
            break;
          }
          i++;
          // Make sure what we've just rendered gets blitted to the RW; user
          // should visually see the progress of the rotation.
          m_pActiveRenderWin->UpdateWindow();
        }
      }
      
    } else {
      if (m_pActiveRenderWin->GetRenderer()->GetUseMIP(renderRegion)) {
        bool bReUse = true;
        int iReUseOffset = 0;
        string strImageFilename = lineEditCaptureFile->text().toStdString();
        vector<string> vstrLeftEyeImageVector(iNumImages);
        vector<string> vstrRightEyeImageVector(iNumImages);
        if (bStereo) {
          double fDegreePerImage = 360.0/iNumImages;
          iReUseOffset = int(iEyeDist/fDegreePerImage);
          bReUse = (iReUseOffset == iEyeDist/fDegreePerImage);

          if (bReUse)
            strImageFilename = SysTools::AppendFilename(strImageFilename,"_LR");
          else
            strImageFilename = SysTools::AppendFilename(strImageFilename,"_L");
        }

        pleaseWait.SetText("Capturing a full 360 MIP rotation,"
                           "please wait  ...");
        float fAngle = 0.0f;
        for (int i = 0;i<iNumImages && !pleaseWait.Canceled();i++) {
          labelOut->SetOutput(true, true, true, false);
          if (bStereo) {
            std::ostringstream progress;
            progress << "Phase 1 of 3: "
                     << static_cast<int>(100.0f*i/iNumImages) << "% completed."
                     << "\nProcessing Image " << i+1 << " of " << iNumImages;
            if(i==0) {
              progress << " (the first image may be slower due to caching)";
            }
            MESSAGE("%s", progress.str().c_str());
          } else {
            std::ostringstream progress;
            progress << static_cast<int>(100.0f*i/iNumImages) << "% completed"
                     << "\nProcessing Image " << i+1 << iNumImages;
            if(i==0) {
              progress << " (the first image may be slower due to caching)";
            }
            MESSAGE("%s", progress.str().c_str());
          }
          labelOut->SetOutput(false, false, false, false);

          fAngle = float(i)/float(iNumImages) * 360.0f;
          string strSequenceName;

          if (!m_pActiveRenderWin->CaptureMIPFrame(
                  strImageFilename, fAngle, bOrthoView, i==(iNumImages-1),
                  bUseLOD, checkBox_PreserveTransparency->isChecked(),
                  &strSequenceName)) {
            QString msg = tr("Error writing image file %1.").
                          arg(strSequenceName.c_str());
            ShowWarningDialog( tr("Error"), msg);
            T_ERROR("%s", msg.toAscii().data());
            break;
          }

          if (bStereo) {
            vstrLeftEyeImageVector[i] = strSequenceName;
            if (bReUse) {
              vstrRightEyeImageVector[(i+iReUseOffset)%iNumImages] =
                strSequenceName;
            } else {
              fAngle -= 3.0f;
              string strImageFilenameRight =
                SysTools::AppendFilename(lineEditCaptureFile->text().
                                                            toStdString(),"_R");
              if (!m_pActiveRenderWin->CaptureMIPFrame(
                    strImageFilenameRight, fAngle, bOrthoView, bUseLOD,
                    i==(iNumImages-1),
                    checkBox_PreserveTransparency->isChecked(),
                    &strSequenceName)) {
                QString msg = tr("Error writing image file %1.").
                              arg(strImageFilenameRight.c_str());
                ShowWarningDialog( tr("Error"), msg);
                T_ERROR("%s", msg.toAscii().data());
                break;
              }
              vstrRightEyeImageVector[i] = strSequenceName;
            }
          }
        }

        if (!pleaseWait.Canceled() &&
            m_pActiveRenderWin->GetRenderer()->GetUseMIP(renderRegion) &&
            bStereo) {
          labelOut->SetOutput(true, true, true, false);

          for (size_t i = 0;i<vstrRightEyeImageVector.size();i++) {
            string strSourceL = vstrLeftEyeImageVector[i];
            string strSourceR = vstrRightEyeImageVector[i];
            string strTarget  = SysTools::FindNextSequenceName(
              lineEditCaptureFile->text().toStdString()
            );

            MESSAGE("Phase 2 of 3: %u%% completed\nCreating stereo image "
                    "%s from %s and %s\nProcessing Image %u of %i",
                    static_cast<unsigned>(100.0f*i/iNumImages),
                    SysTools::GetFilename(strTarget).c_str(),
                    SysTools::GetFilename(strSourceL).c_str(),
                    SysTools::GetFilename(strSourceR).c_str(),
                    static_cast<unsigned>(i+1), iNumImages);

            QImage imageLeft(strSourceL.c_str());
            QImage imageRight(strSourceR.c_str());

            for (int y = 0;y<imageLeft.height();y++) {
                for (int x = 0;x<imageLeft.width();x++) {
                  QRgb pixelLeft  = imageLeft.pixel(x,y);
                  QRgb pixelRight = imageRight.pixel(x,y);

                  int iGrayLeft  = static_cast<int>(qRed(pixelLeft)  * 0.3f +
                                                    qGreen(pixelLeft)  * 0.59f +
                                                    qBlue(pixelLeft)  * 0.11f);
                  int iGrayRight = static_cast<int>(qRed(pixelRight) * 0.3f +
                                                    qGreen(pixelRight) * 0.59f +
                                                    qBlue(pixelRight) * 0.11f);

                  QRgb pixelStereo = qRgba(iGrayLeft,
                                          iGrayRight/2,
                                          iGrayRight,
                                          255);

                  imageRight.setPixel(x,y,pixelStereo);
                }
            }


            imageRight.save(strTarget.c_str());
          }
          for (size_t i = 0;i<vstrRightEyeImageVector.size();i++) {
            MESSAGE("Phase 3 of 3: %u%% completed\nCleanup\nProcessing Image "
                    "%u of %i", static_cast<unsigned>(100.0f*i/iNumImages),
                    static_cast<unsigned>(i+1), iNumImages);
            remove(vstrRightEyeImageVector[i].c_str());
            if (SysTools::FileExists(vstrLeftEyeImageVector[i])) {
              remove(vstrLeftEyeImageVector[i].c_str());
            }
          }
        }
      } else {
        pleaseWait.SetText("Slicing through the dataset, please wait  ...");
        /// \todo TODO slice capturing
        QString msg = tr("Slice Capturing is not implemented yet. Aborting.");
        ShowWarningDialog( tr("Error"), msg);
      }
    }
    m_pActiveRenderWin->ToggleHQCaptureMode();
    m_pRedrawTimer->start(20);
    pleaseWait.close();
    pleaseWait.DetachLabel();
    m_pActiveRenderWin->GetRenderer()->ScheduleCompleteRedraw();  // to make sure front and backbuffer are valid
  }
}

void MainWindow::SetCaptureFilename() {
  QFileDialog::Options options;
#ifdef DETECTED_OS_APPLE
  options |= QFileDialog::DontUseNativeDialog;
#endif
  QString selectedFilter;

  QSettings settings;
  QString strLastDir = settings.value("Folders/CaptureFilename", ".").toString();

  QString fileName = QFileDialog::getSaveFileName(this, "Select Image File",
             strLastDir, "All Files (*.*)", &selectedFilter, options);

  if (!fileName.isEmpty()) {
    // add png as the default filetype if the user forgot to enter one
    if (SysTools::GetExt(fileName.toStdString()) == "")
      fileName = fileName + ".png";

    settings.setValue("Folders/CaptureFilename",
                      QFileInfo(fileName).absoluteDir().path());
    settings.setValue("Files/CaptureFilename", fileName);
    lineEditCaptureFile->setText(fileName);
  }
}


void MainWindow::PreserveTransparencyChanged() {
  QSettings settings;
  settings.setValue("PreserveTransparency", checkBox_PreserveTransparency->isChecked());
}