<commit_before>//------------------------------------------------------------------------------
//  IOFacadeTest.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "IO/IO.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "IO/Stream/BinaryStreamReader.h"
#include "IO/Stream/BinaryStreamWriter.h"
#include "IO/Stream/MemoryStream.h"

using namespace Oryol;

std::atomic<int32> numGetHandled{0};
std::atomic<int32> numGetRangeHandled{0};

class TestFileSystem : public FileSystem {
    OryolClassDecl(TestFileSystem);
    OryolClassCreator(TestFileSystem);
public:
    /// called when the IOProtocol::Get message is received
    virtual void onGet(const Ptr<IOProtocol::Get>& msg) {
        Log::Info("TestFileSystem::onGet() called!\n");
        numGetHandled++;

        // create a stream object, and just write the URL from the msg to it
        Ptr<MemoryStream> stream = MemoryStream::Create();
        stream->Open(OpenMode::WriteOnly);
        Ptr<BinaryStreamWriter> writer = BinaryStreamWriter::Create(stream);
        writer->Write(msg->GetURL().Get());
        stream->Close();

        msg->SetStream(stream);
        msg->SetStatus(IOStatus::OK);
        msg->SetHandled();
    };
    /// called when the IOProtocol::GetRange message is received
    virtual void onGetRange(const Ptr<IOProtocol::GetRange>& msg) {
        Log::Info("TestFileSystem::onGetRange() called!\n");
        numGetRangeHandled++;
        msg->SetHandled();
    }
};
OryolClassImpl(TestFileSystem);

TEST(IOFacadeTest) {
    IO::Setup(IOSetup());

    // register our test file-system as URI scheme "test"
    IO::RegisterFileSystem("test", TestFileSystem::Creator());

    // setup an assign which resolves to the test file system
    IO::SetAssign("bla:", "test://blub.com/");

    // an URL which should resolve to test://blub.com/blob.txt
    URL url("bla:blob.txt");
    CHECK(url.IsValid());

    // asynchronously 'load' a file
    Ptr<IOProtocol::Get> msg = IO::LoadFile(url);

    // trigger the runloop until our message is handled
    while (!msg->Handled()) {
        Core::PreRunLoop()->Run();
    }
    CHECK(numGetHandled == 1);
    CHECK(numGetRangeHandled == 0);

    // check the msg result
    CHECK(msg->GetStream().isValid());
    CHECK(msg->GetStatus() == IOStatus::OK);
    const Ptr<Stream>& stream = msg->GetStream();
    stream->Open(OpenMode::ReadOnly);
    Ptr<BinaryStreamReader> reader = BinaryStreamReader::Create(stream);
    StringAtom str;
    CHECK(reader->Read(str));
    stream->Close();
    CHECK(str == msg->GetURL().Get());

    // FIXME: dynamically add/remove/replace filesystems, ...

    IO::Discard();
}
<commit_msg>Fixed IO test<commit_after>//------------------------------------------------------------------------------
//  IOFacadeTest.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "IO/IO.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "IO/Stream/BinaryStreamReader.h"
#include "IO/Stream/BinaryStreamWriter.h"
#include "IO/Stream/MemoryStream.h"

using namespace Oryol;

std::atomic<int32> numRequestsHandled{0};

class TestFileSystem : public FileSystem {
    OryolClassDecl(TestFileSystem);
    OryolClassCreator(TestFileSystem);
public:
    /// called when the IOProtocol::Get message is received
    virtual void onRequest(const Ptr<IOProtocol::Request>& msg) {
        Log::Info("TestFileSystem::onRequest() called!\n");
        numRequestsHandled++;

        // create a stream object, and just write the URL from the msg to it
        Ptr<MemoryStream> stream = MemoryStream::Create();
        stream->Open(OpenMode::WriteOnly);
        Ptr<BinaryStreamWriter> writer = BinaryStreamWriter::Create(stream);
        writer->Write(msg->GetURL().Get());
        stream->Close();

        msg->SetStream(stream);
        msg->SetStatus(IOStatus::OK);
        msg->SetHandled();
    };
};
OryolClassImpl(TestFileSystem);

TEST(IOFacadeTest) {
    IO::Setup(IOSetup());

    // register our test file-system as URI scheme "test"
    IO::RegisterFileSystem("test", TestFileSystem::Creator());

    // setup an assign which resolves to the test file system
    IO::SetAssign("bla:", "test://blub.com/");

    // an URL which should resolve to test://blub.com/blob.txt
    URL url("bla:blob.txt");
    CHECK(url.IsValid());

    // asynchronously 'load' a file
    Ptr<IOProtocol::Request> msg = IO::LoadFile(url);

    // trigger the runloop until our message is handled
    while (!msg->Handled()) {
        Core::PreRunLoop()->Run();
    }
    CHECK(numRequestsHandled == 1);

    // check the msg result
    CHECK(msg->GetStream().isValid());
    CHECK(msg->GetStatus() == IOStatus::OK);
    const Ptr<Stream>& stream = msg->GetStream();
    stream->Open(OpenMode::ReadOnly);
    Ptr<BinaryStreamReader> reader = BinaryStreamReader::Create(stream);
    StringAtom str;
    CHECK(reader->Read(str));
    stream->Close();
    CHECK(str == msg->GetURL().Get());

    // FIXME: dynamically add/remove/replace filesystems, ...

    IO::Discard();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    BinaryMedianImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : eginCommandLineArgs
//    INPUTS: {BrainProtonDensitySlice.png}
//    OUTPUTS: {BinaryMedianImageFilterOutput.png}
//    2
//  Software Guide : ndCommandLineArgs

//  Software Guide : BeginLatex
//
//  The \doxygen{BinaryMedianImageFilter} is commonly used as a robust approach
//  for noise reduction. BinaryMedianImageFilter computes the value of each
//  output pixel as the statistical median of the neighborhood of values around
//  the corresponding input pixel. When the input images are binary, the
//  implementation can be optimized by simply counting the number of pixels
//  ON/OFF around the current pixel.
//
//  This filter will work on images of any dimension thanks to the internal use
//  of \doxygen{NeighborhoodIterator} and \doxygen{NeighborhoodOperator}. The
//  size of the neighborhood over which the median is computed can be set by
//  the user.
//
//  \index{itk::BinaryMedianImageFilter}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

//  Software Guide : BeginLatex
//
//  The header file corresponding to this filter should be included first.
//
//  \index{itk::BinaryMedianImageFilter!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkBinaryMedianImageFilter.h"
// Software Guide : EndCodeSnippet

int main( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile outputImageFile radiusX radiusY" << std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  Then the pixel and image types of the input and output must be defined.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef   unsigned char  InputPixelType;
  typedef   unsigned char  OutputPixelType;

  typedef itk::Image< InputPixelType,  2 >   InputImageType;
  typedef itk::Image< OutputPixelType, 2 >   OutputImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[1] );
  writer->SetFileName( argv[2] );

  //  Software Guide : BeginLatex
  //
  //  Using the image types, it is now possible to define the filter type
  //  and create the filter object.
  //
  //  \index{itk::BinaryMedianImageFilter!instantiation}
  //  \index{itk::BinaryMedianImageFilter!New()}
  //  \index{itk::BinaryMedianImageFilter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::BinaryMedianImageFilter<
               InputImageType, OutputImageType >  FilterType;

  FilterType::Pointer filter = FilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The size of the neighborhood is defined along every dimension by
  //  passing a \code{SizeType} object with the corresponding values. The
  //  value on each dimension is used as the semi-size of a rectangular
  //  box. For example, in $2D$ a size of \(1,2\) will result in a $3 \times
  //  5$ neighborhood.
  //
  //  \index{itk::BinaryMedianImageFilter!Radius}
  //  \index{itk::BinaryMedianImageFilter!Neighborhood}
  //
  //  Software Guide : EndLatex

  const unsigned int radiusX = atoi( argv[3] );
  const unsigned int radiusY = atoi( argv[4] );

  // Software Guide : BeginCodeSnippet
  InputImageType::SizeType indexRadius;

  indexRadius[0] = radiusX; // radius along x
  indexRadius[1] = radiusY; // radius along y

  filter->SetRadius( indexRadius );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input to the filter can be taken from any other filter, for example
  //  a reader. The output can be passed down the pipeline to other filters,
  //  for example, a writer. An update call on any downstream filter will
  //  trigger the execution of the median filter.
  //
  //  \index{itk::BinaryMedianImageFilter!SetInput()}
  //  \index{itk::BinaryMedianImageFilter!GetOutput()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetInput( reader->GetOutput() );
  writer->SetInput( filter->GetOutput() );
  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
  // \includegraphics[width=0.44\textwidth]{BinaryMedianImageFilterOutput.eps}
  // \itkcaption[Effect of the BinaryMedian filter.]{Effect of the
  // BinaryMedianImageFilter on a slice from a MRI proton density brain image
  // that has been thresholded in order to produce a binary image.}
  // \label{fig:BinaryMedianImageFilterOutput}
  // \end{figure}
  //
  //  Figure \ref{fig:BinaryMedianImageFilterOutput} illustrates the effect of
  //  the BinaryMedianImageFilter filter on a slice of MRI brain image using a
  //  neighborhood radius of \(2,2\), which corresponds to a $ 5 \times 5 $
  //  classical neighborhood.  The filtered image demonstrates the capability
  //  of this filter for reducing noise both in the background and foregrund of
  //  the image, as well as smoothing the contours of the regions.
  //
  //  Software Guide : EndLatex

  return 0;
}

<commit_msg>ENH: Command line argument tags for automatic generation of figures for Software Guide<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    BinaryMedianImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {BrainProtonDensitySlice.png}
//    OUTPUTS: {BinaryMedianImageFilterOutput.png}
//    2
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  The \doxygen{BinaryMedianImageFilter} is commonly used as a robust approach
//  for noise reduction. BinaryMedianImageFilter computes the value of each
//  output pixel as the statistical median of the neighborhood of values around
//  the corresponding input pixel. When the input images are binary, the
//  implementation can be optimized by simply counting the number of pixels
//  ON/OFF around the current pixel.
//
//  This filter will work on images of any dimension thanks to the internal use
//  of \doxygen{NeighborhoodIterator} and \doxygen{NeighborhoodOperator}. The
//  size of the neighborhood over which the median is computed can be set by
//  the user.
//
//  \index{itk::BinaryMedianImageFilter}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

//  Software Guide : BeginLatex
//
//  The header file corresponding to this filter should be included first.
//
//  \index{itk::BinaryMedianImageFilter!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkBinaryMedianImageFilter.h"
// Software Guide : EndCodeSnippet

int main( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile outputImageFile radiusX radiusY" << std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  Then the pixel and image types of the input and output must be defined.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef   unsigned char  InputPixelType;
  typedef   unsigned char  OutputPixelType;

  typedef itk::Image< InputPixelType,  2 >   InputImageType;
  typedef itk::Image< OutputPixelType, 2 >   OutputImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName( argv[1] );
  writer->SetFileName( argv[2] );

  //  Software Guide : BeginLatex
  //
  //  Using the image types, it is now possible to define the filter type
  //  and create the filter object.
  //
  //  \index{itk::BinaryMedianImageFilter!instantiation}
  //  \index{itk::BinaryMedianImageFilter!New()}
  //  \index{itk::BinaryMedianImageFilter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::BinaryMedianImageFilter<
               InputImageType, OutputImageType >  FilterType;

  FilterType::Pointer filter = FilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The size of the neighborhood is defined along every dimension by
  //  passing a \code{SizeType} object with the corresponding values. The
  //  value on each dimension is used as the semi-size of a rectangular
  //  box. For example, in $2D$ a size of \(1,2\) will result in a $3 \times
  //  5$ neighborhood.
  //
  //  \index{itk::BinaryMedianImageFilter!Radius}
  //  \index{itk::BinaryMedianImageFilter!Neighborhood}
  //
  //  Software Guide : EndLatex

  const unsigned int radiusX = atoi( argv[3] );
  const unsigned int radiusY = atoi( argv[4] );

  // Software Guide : BeginCodeSnippet
  InputImageType::SizeType indexRadius;

  indexRadius[0] = radiusX; // radius along x
  indexRadius[1] = radiusY; // radius along y

  filter->SetRadius( indexRadius );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input to the filter can be taken from any other filter, for example
  //  a reader. The output can be passed down the pipeline to other filters,
  //  for example, a writer. An update call on any downstream filter will
  //  trigger the execution of the median filter.
  //
  //  \index{itk::BinaryMedianImageFilter!SetInput()}
  //  \index{itk::BinaryMedianImageFilter!GetOutput()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetInput( reader->GetOutput() );
  writer->SetInput( filter->GetOutput() );
  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
  // \includegraphics[width=0.44\textwidth]{BinaryMedianImageFilterOutput.eps}
  // \itkcaption[Effect of the BinaryMedian filter.]{Effect of the
  // BinaryMedianImageFilter on a slice from a MRI proton density brain image
  // that has been thresholded in order to produce a binary image.}
  // \label{fig:BinaryMedianImageFilterOutput}
  // \end{figure}
  //
  //  Figure \ref{fig:BinaryMedianImageFilterOutput} illustrates the effect of
  //  the BinaryMedianImageFilter filter on a slice of MRI brain image using a
  //  neighborhood radius of \(2,2\), which corresponds to a $ 5 \times 5 $
  //  classical neighborhood.  The filtered image demonstrates the capability
  //  of this filter for reducing noise both in the background and foregrund of
  //  the image, as well as smoothing the contours of the regions.
  //
  //  Software Guide : EndLatex

  return 0;
}

<|endoftext|>


<commit_before>#include "FAST/Tests/catch.hpp"
#include "TubeSegmentationAndCenterlineExtraction.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
#include "FAST/Algorithms/ImageCropper/ImageCropper.hpp"

namespace fast {

/*
TEST_CASE("TSF", "[tsf]") {
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd");

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(importer->getOutputPort());
    tubeExtraction->extractBrightTubes();
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(8);
    tubeExtraction->setSensitivity(0.99);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(tubeExtraction->getTDFOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->start();
}
*/

TEST_CASE("TSF Airway", "[tsf][airway][visual]") {
    //Report::setReportMethod(Report::COUT);
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");

    ImageCropper::pointer cropper = ImageCropper::New();
    cropper->setOffset(Vector3ui(56, 119, 155));
    cropper->setSize(Vector3ui(400, 232, 509));
    cropper->setInputConnection(importer->getOutputPort());

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(cropper->getOutputPort());
    tubeExtraction->extractDarkTubes();
    tubeExtraction->setMinimumIntensity(-1024);
    tubeExtraction->setMaximumIntensity(100);
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(50);
    tubeExtraction->setSensitivity(0.8);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(importer->getOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->start();
}

}
<commit_msg>added timeout to test<commit_after>#include "FAST/Tests/catch.hpp"
#include "TubeSegmentationAndCenterlineExtraction.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
#include "FAST/Algorithms/ImageCropper/ImageCropper.hpp"

namespace fast {

/*
TEST_CASE("TSF", "[tsf]") {
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd");

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(importer->getOutputPort());
    tubeExtraction->extractBrightTubes();
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(8);
    tubeExtraction->setSensitivity(0.99);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(tubeExtraction->getTDFOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->start();
}
*/

TEST_CASE("TSF Airway", "[tsf][airway][visual]") {
    //Report::setReportMethod(Report::COUT);
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");

    ImageCropper::pointer cropper = ImageCropper::New();
    cropper->setOffset(Vector3ui(56, 119, 155));
    cropper->setSize(Vector3ui(400, 232, 509));
    cropper->setInputConnection(importer->getOutputPort());

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(cropper->getOutputPort());
    tubeExtraction->extractDarkTubes();
    tubeExtraction->setMinimumIntensity(-1024);
    tubeExtraction->setMaximumIntensity(100);
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(50);
    tubeExtraction->setSensitivity(0.8);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(importer->getOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->setTimeout(3*1000);
    window->start();
}

}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>

int main(int argc, char *argv[])
{
    QtSingleApplication app(argc, argv);
    if (app.isRunning()) {
        return 0;
    }
    QQmlApplicationEngine engine;
    app.setWindowIcon(QIcon("resources/icons/ykman.png"));
    QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
    putenv(pythonNoBytecode.toUtf8().data());
    QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
    putenv(frameworks.toUtf8().data());
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    return app.exec();
}
<commit_msg>Raise window if new instance is started<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>

int main(int argc, char *argv[])
{
    // Only allow a single instance running.
    QtSingleApplication app(argc, argv);
    if (app.sendMessage("")) {
        return 0;
    }

    QQmlApplicationEngine engine;
    app.setWindowIcon(QIcon("resources/icons/ykman.png"));
    QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
    putenv(pythonNoBytecode.toUtf8().data());
    QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
    putenv(frameworks.toUtf8().data());
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    // Raise the root window on a message from new instance.
    for (auto object : engine.rootObjects()) {
        if (QWindow *window = qobject_cast<QWindow*>(object)) {
            QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
                window->raise();
            });
        }
    }
    return app.exec();
}
<|endoftext|>


<commit_before>#include <GL/glew.h>
#include "SofaGL.h"
#include "VisualPickVisitor.h"

namespace sofa {
namespace simplegui {

template <typename T> inline T sqr(const T& t){ return t*t; }

SofaGL::SofaGL(SofaScene *s) :
    _sofaScene(s)
{
    if(!_sofaScene)
    {
        std::cerr << "Error: you are trying to create a SofaGL object with a null SofaScene" << std::endl;
        return;
    }

    glewInit();

    _vparams = sofa::core::visual::VisualParams::defaultInstance();
    _vparams->drawTool() = &_drawToolGL;
    _vparams->setSupported(sofa::core::visual::API_OpenGL);

    _isPicking = false;

    sofa::simulation::getSimulation()->initTextures(_sofaScene->groot().get());
}

void SofaGL::draw()
{
    glGetIntegerv (GL_VIEWPORT, _viewport);
    glGetDoublev (GL_MODELVIEW_MATRIX, _mvmatrix);
    glGetDoublev (GL_PROJECTION_MATRIX, _projmatrix);

    if(_vparams)
    {
        _vparams->viewport() = sofa::helper::fixed_array<int, 4>(_viewport[0], _viewport[1], _viewport[2], _viewport[3]);
        _vparams->sceneBBox() = _sofaScene->groot()->f_bbox.getValue();
        _vparams->setProjectionMatrix(_projmatrix);
        _vparams->setModelViewMatrix(_mvmatrix);
    }

    sofa::simulation::getSimulation()->updateVisual(_sofaScene->groot().get()); // needed to update normals and VBOs ! (i think it should be better if updateVisual() was called from draw(), why it is not already the case ?)

    if( _isPicking ){

        // start picking
        glSelectBuffer(BUFSIZE,selectBuf);
        glRenderMode(GL_SELECT);

        glInitNames();

        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();

        gluPickMatrix(pickX,_viewport[3]-pickY,5,5,_viewport);
        glMultMatrixd(_projmatrix);
        glMatrixMode(GL_MODELVIEW);

        // draw
        _vparams->pass() = sofa::core::visual::VisualParams::Std;
        VisualPickVisitor pick ( _vparams );
        pick.setTags(_sofaScene->groot()->getTags());
        _sofaScene->groot()->execute ( &pick );

        // stop picking
        glMatrixMode(GL_PROJECTION);
        glPopMatrix();
        glMatrixMode(GL_MODELVIEW);
        glFlush();
        hits = glRenderMode(GL_RENDER);
        if (hits != 0)
        {
            GLuint* buffer = selectBuf;
            // process the hits
            GLint i, j, numberOfNames;
            GLuint names, *ptr, minZ,*ptrNames;

            ptr = (GLuint *) buffer;
            minZ = 0xffffffff;
            for (i = 0; i < hits; i++) {
                names = *ptr;
                ptr++;
                if (*ptr < minZ) {
                    numberOfNames = names;
                    minZ = *ptr;
                    ptrNames = ptr+2;
                }

                ptr += names+2;
            }
            if (numberOfNames > 0) {
                cerr << "You picked object  ";
                ptr = ptrNames;
                for (j = 0; j < numberOfNames; j++,ptr++) {
                    cerr<< pick.names[*ptr] << " ";
                }
            }
            else
                cerr<<"You didn't click a snowman!";
            cerr<<endl;
        }
        else cerr<<"no hits !" << endl;
        _isPicking = false;

    }
    sofa::simulation::getSimulation()->draw(_vparams, _sofaScene->groot().get());
}

void SofaGL::getPickDirection( GLdouble* dx, GLdouble* dy, GLdouble* dz, int x, int y )
{
    // Intersection of the ray with the near and far planes
    GLint realy = _viewport[3] - (GLint) y - 1; // convert coordinates from image space (y downward) to window space (y upward)
    GLdouble wx, wy, wz;  /*  returned world x, y, z coords  */
    gluUnProject ((GLdouble) x, (GLdouble) realy, 0.0, _mvmatrix, _projmatrix, _viewport, &wx, &wy, &wz); // z=0: near plane
    //cout<<"World coords at z=0.0 are ("<<wx<<","<<wy<<","<<wz<<")"<<endl;
    GLdouble wx1, wy1, wz1;
    gluUnProject ((GLdouble) x, (GLdouble) realy, 1.0, _mvmatrix, _projmatrix, _viewport, &wx1, &wy1, &wz1); // z=1: far plane

    GLdouble nrm = sqrt( sqr(wx1-wx) + sqr(wy1-wy) + sqr(wz1-wz) );
    *dx = (wx1-wx)/nrm;
    *dy = (wy1-wy)/nrm;
    *dz = (wz1-wz)/nrm;

}

void SofaGL::glPick(int x, int y )
{
    pickX = x; pickY = y;
    _isPicking = true;
}

PickedPoint SofaGL::pick(GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{
    Vec3 origin(ox,oy,oz), direction;
    getPickDirection(&direction[0],&direction[1],&direction[2],x,y);

    double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
    //    cout<< "SofaGL::rayPick from origin " << origin << ", in direction " << direction << endl;
    sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth );
    picker.execute( _sofaScene->groot()->getContext() );

    PickedPoint pickedPoint;
    if (!picker.particles.empty())
    {
        sofa::core::behavior::BaseMechanicalState *mstate = picker.particles.begin()->second.first;
        unsigned index = picker.particles.begin()->second.second;

        pickedPoint.state = mstate;
        pickedPoint.index = index;
        pickedPoint.point = Vec3(mstate->getPX(index), mstate->getPY(index), mstate->getPZ(index));
    }

    return pickedPoint;
}

Interactor* SofaGL::getInteractor( const PickedPoint& glpicked )
{
    cout << "SofaGL::getInteractor, looking for " << glpicked << endl;
    for( Picked_to_Interactor::iterator i=_picked_to_interactor.begin(); i!=_picked_to_interactor.end(); i++ )
    {
        cout << "SofaGL::getInteractor, map contains " << (*i).first << endl;
    }
    if( _picked_to_interactor.find(glpicked)!=_picked_to_interactor.end() ) // there is already an interactor on this particle
    {
        return _picked_to_interactor[glpicked];
    }
    else {                                             // new interactor
        return NULL;
    }
}

Interactor* SofaGL::pickInteractor( GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{

    Vec3 origin(ox,oy,oz), direction;
    getPickDirection(&direction[0],&direction[1],&direction[2],x,y);
    double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
    //    cout<< "SofaScene::rayPick from origin " << origin << ", in direction " << direction << endl;
    sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth, Tag("!NoPicking") );
    picker.execute(_sofaScene->groot()->getContext());

    if (!picker.particles.empty())
    {
        PickedPoint pickedPoint(picker.particles.begin()->second.first, picker.particles.begin()->second.second);
        if( _picked_to_interactor.find(pickedPoint)!=_picked_to_interactor.end() )
            return _picked_to_interactor[pickedPoint];
    }

    return NULL;
}

void SofaGL::attach( Interactor* interactor )
{
    interactor->attach( _sofaScene );
    _picked_to_interactor[interactor->getPickedPoint()] = interactor;
    //    cout<<"SofaGL::attach "<< endl; _sofaScene->printGraph();
}

void SofaGL::move( Interactor* interactor, int x, int y)
{
    if( !interactor )
        return;

    // get the distance to the current point
    Vec3 current = interactor->getPoint();
    GLdouble wcur[3]; // window coordinates of the current point
    gluProject(current[0],current[1],current[2],_mvmatrix,_projmatrix,_viewport,wcur,wcur+1,wcur+2);
    //        cout << "current point = " << current << endl;
    //        cout<<"move anchor, distance = " << wcur[2] << endl;

    // compute and set the position of the new point
    GLdouble p[3];
    gluUnProject ( x, _viewport[3]-y-1, wcur[2], _mvmatrix, _projmatrix, _viewport, &p[0], &p[1], &p[2]); // new position of the picked point
    //        cout<<"x="<< x <<", y="<< y <<", X="<<p[0]<<", Y="<<p[1]<<", Z="<<p[2]<<endl;
    interactor->setPoint(Vec3(p[0], p[1], p[2]));
}

void SofaGL::detach( Interactor* drag)
{
    if( !drag )
        return;

    // remove it from the map
    Picked_to_Interactor::iterator i=_picked_to_interactor.begin();
    while( i!=_picked_to_interactor.end() && (*i).second != drag )
        i++;
    if( i!=_picked_to_interactor.end() ){
        //                cout << "Deleted interactor at " << (*i).first << endl;
        _picked_to_interactor.erase(i);
        //                cout << "new count of interactors: " << picked_to_interactor.size() << endl;
    }
    else assert( false && "Active interactor not found in the map" );

    drag->detach();
    //    cout<<"SofaGL::detach "<< endl; _sofaScene->printGraph();
}

void SofaGL::getSceneBBox( float* xmin, float* ymin, float* zmin, float* xmax, float* ymax, float* zmax )
{
    SReal xm, xM, ym, yM, zm, zM;
    _sofaScene->getBoundingBox(&xm,&xM,&ym,&yM,&zm,&zM);
    //    cerr << "SofaGL::getSceneBBox, xm=" << xm <<", xM=" << xM << endl;
    *xmin=xm, *xmax=xM, *ymin=ym, *ymax=yM, *zmin=zm, *zmax=zM;
}

void SofaGL::viewAll( SReal* xcam, SReal* ycam, SReal* zcam, SReal* xcen, SReal* ycen, SReal* zcen, SReal a, SReal* nearPlane, SReal* farPlane)
{
    // scene center and radius
    SReal xmin, xmax, ymin, ymax, zmin, zmax;
    _sofaScene->getBoundingBox(&xmin,&xmax,&ymin,&ymax,&zmin,&zmax);
    cout<<"SofaGL::viewAll, bounding box = ("<< xmin <<" "<<ymin<<" "<<zmin<<"),("<<xmax<<" "<<ymax<<" "<<zmax<<")"<<endl;
    *xcen = (xmin+xmax)*0.5;
    *ycen = (ymin+ymax)*0.5;
    *zcen = (zmin+zmax)*0.5;
    SReal radius = sqrt( sqr(xmin-xmax) + sqr(ymin-ymax) + sqr(zmin-zmax) );

    // Desired distance:  distance * tan(a) = radius
    SReal distance = 2 * radius / tan(a);
    //    SReal ratio = ((SReal) _viewport[3] - _viewport[1])/(_viewport[2] - _viewport[0]);
    //    distance *= ratio;
    cout<<"SofaGL::viewAll, angle = " << a << ", tan = " << tan(a) << ", distance = " << distance << endl;
    cout<<"SofaGL::viewAll, xmin xmax ymin ymax zmin zmax = " << xmin << " " << xmax <<" "<<ymin<<" "<<ymax<<" "<<zmin<<" "<<zmax<< endl;

    // move the camera along the current camera-center line, at the right distance
    // cam = cen + distance * (cam-cen)/|cam-cen|
    SReal curdist = sqrt( sqr(*xcam-*xcen)+sqr(*ycam-*ycen)+sqr(*zcam-*zcen) );
    *xcam = *xcen + distance * (*xcam-*xcen) / curdist;
    *ycam = *ycen + distance * (*ycam-*ycen) / curdist;
    *zcam = *zcen + distance * (*zcam-*zcen) / curdist;

    // update the depth bounds
    *nearPlane = distance - radius*1.5;
    *farPlane  = distance + radius*1.5;
}

}//newgui
}//sofa
<commit_msg>CHANGE: a comment<commit_after>#include <GL/glew.h>
#include "SofaGL.h"
#include "VisualPickVisitor.h"

namespace sofa {
namespace simplegui {

template <typename T> inline T sqr(const T& t){ return t*t; }

SofaGL::SofaGL(SofaScene *s) :
    _sofaScene(s)
{
    if(!_sofaScene)
    {
        std::cerr << "Error: you are trying to create a SofaGL object with a null SofaScene" << std::endl;
        return;
    }

    glewInit();

    _vparams = sofa::core::visual::VisualParams::defaultInstance();
    _vparams->drawTool() = &_drawToolGL;
    _vparams->setSupported(sofa::core::visual::API_OpenGL);

    _isPicking = false;

    sofa::simulation::getSimulation()->initTextures(_sofaScene->groot().get());
}

void SofaGL::draw()
{
    glGetIntegerv (GL_VIEWPORT, _viewport);
    glGetDoublev (GL_MODELVIEW_MATRIX, _mvmatrix);
    glGetDoublev (GL_PROJECTION_MATRIX, _projmatrix);

    if(_vparams)
    {
        _vparams->viewport() = sofa::helper::fixed_array<int, 4>(_viewport[0], _viewport[1], _viewport[2], _viewport[3]);
        _vparams->sceneBBox() = _sofaScene->groot()->f_bbox.getValue();
        _vparams->setProjectionMatrix(_projmatrix);
        _vparams->setModelViewMatrix(_mvmatrix);
    }

    sofa::simulation::getSimulation()->updateVisual(_sofaScene->groot().get()); // needed to update normals and VBOs !

    if( _isPicking ){

        // start picking
        glSelectBuffer(BUFSIZE,selectBuf);
        glRenderMode(GL_SELECT);

        glInitNames();

        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();

        gluPickMatrix(pickX,_viewport[3]-pickY,5,5,_viewport);
        glMultMatrixd(_projmatrix);
        glMatrixMode(GL_MODELVIEW);

        // draw
        _vparams->pass() = sofa::core::visual::VisualParams::Std;
        VisualPickVisitor pick ( _vparams );
        pick.setTags(_sofaScene->groot()->getTags());
        _sofaScene->groot()->execute ( &pick );

        // stop picking
        glMatrixMode(GL_PROJECTION);
        glPopMatrix();
        glMatrixMode(GL_MODELVIEW);
        glFlush();
        hits = glRenderMode(GL_RENDER);
        if (hits != 0)
        {
            GLuint* buffer = selectBuf;
            // process the hits
            GLint i, j, numberOfNames;
            GLuint names, *ptr, minZ,*ptrNames;

            ptr = (GLuint *) buffer;
            minZ = 0xffffffff;
            for (i = 0; i < hits; i++) {
                names = *ptr;
                ptr++;
                if (*ptr < minZ) {
                    numberOfNames = names;
                    minZ = *ptr;
                    ptrNames = ptr+2;
                }

                ptr += names+2;
            }
            if (numberOfNames > 0) {
                cerr << "You picked object  ";
                ptr = ptrNames;
                for (j = 0; j < numberOfNames; j++,ptr++) {
                    cerr<< pick.names[*ptr] << " ";
                }
            }
            else
                cerr<<"You didn't click a snowman!";
            cerr<<endl;
        }
        else cerr<<"no hits !" << endl;
        _isPicking = false;

    }
    sofa::simulation::getSimulation()->draw(_vparams, _sofaScene->groot().get());
}

void SofaGL::getPickDirection( GLdouble* dx, GLdouble* dy, GLdouble* dz, int x, int y )
{
    // Intersection of the ray with the near and far planes
    GLint realy = _viewport[3] - (GLint) y - 1; // convert coordinates from image space (y downward) to window space (y upward)
    GLdouble wx, wy, wz;  /*  returned world x, y, z coords  */
    gluUnProject ((GLdouble) x, (GLdouble) realy, 0.0, _mvmatrix, _projmatrix, _viewport, &wx, &wy, &wz); // z=0: near plane
    //cout<<"World coords at z=0.0 are ("<<wx<<","<<wy<<","<<wz<<")"<<endl;
    GLdouble wx1, wy1, wz1;
    gluUnProject ((GLdouble) x, (GLdouble) realy, 1.0, _mvmatrix, _projmatrix, _viewport, &wx1, &wy1, &wz1); // z=1: far plane

    GLdouble nrm = sqrt( sqr(wx1-wx) + sqr(wy1-wy) + sqr(wz1-wz) );
    *dx = (wx1-wx)/nrm;
    *dy = (wy1-wy)/nrm;
    *dz = (wz1-wz)/nrm;

}

void SofaGL::glPick(int x, int y )
{
    pickX = x; pickY = y;
    _isPicking = true;
}

PickedPoint SofaGL::pick(GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{
    Vec3 origin(ox,oy,oz), direction;
    getPickDirection(&direction[0],&direction[1],&direction[2],x,y);

    double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
    //    cout<< "SofaGL::rayPick from origin " << origin << ", in direction " << direction << endl;
    sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth );
    picker.execute( _sofaScene->groot()->getContext() );

    PickedPoint pickedPoint;
    if (!picker.particles.empty())
    {
        sofa::core::behavior::BaseMechanicalState *mstate = picker.particles.begin()->second.first;
        unsigned index = picker.particles.begin()->second.second;

        pickedPoint.state = mstate;
        pickedPoint.index = index;
        pickedPoint.point = Vec3(mstate->getPX(index), mstate->getPY(index), mstate->getPZ(index));
    }

    return pickedPoint;
}

Interactor* SofaGL::getInteractor( const PickedPoint& glpicked )
{
    cout << "SofaGL::getInteractor, looking for " << glpicked << endl;
    for( Picked_to_Interactor::iterator i=_picked_to_interactor.begin(); i!=_picked_to_interactor.end(); i++ )
    {
        cout << "SofaGL::getInteractor, map contains " << (*i).first << endl;
    }
    if( _picked_to_interactor.find(glpicked)!=_picked_to_interactor.end() ) // there is already an interactor on this particle
    {
        return _picked_to_interactor[glpicked];
    }
    else {                                             // new interactor
        return NULL;
    }
}

Interactor* SofaGL::pickInteractor( GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{

    Vec3 origin(ox,oy,oz), direction;
    getPickDirection(&direction[0],&direction[1],&direction[2],x,y);
    double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
    //    cout<< "SofaScene::rayPick from origin " << origin << ", in direction " << direction << endl;
    sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth, Tag("!NoPicking") );
    picker.execute(_sofaScene->groot()->getContext());

    if (!picker.particles.empty())
    {
        PickedPoint pickedPoint(picker.particles.begin()->second.first, picker.particles.begin()->second.second);
        if( _picked_to_interactor.find(pickedPoint)!=_picked_to_interactor.end() )
            return _picked_to_interactor[pickedPoint];
    }

    return NULL;
}

void SofaGL::attach( Interactor* interactor )
{
    interactor->attach( _sofaScene );
    _picked_to_interactor[interactor->getPickedPoint()] = interactor;
    //    cout<<"SofaGL::attach "<< endl; _sofaScene->printGraph();
}

void SofaGL::move( Interactor* interactor, int x, int y)
{
    if( !interactor )
        return;

    // get the distance to the current point
    Vec3 current = interactor->getPoint();
    GLdouble wcur[3]; // window coordinates of the current point
    gluProject(current[0],current[1],current[2],_mvmatrix,_projmatrix,_viewport,wcur,wcur+1,wcur+2);
    //        cout << "current point = " << current << endl;
    //        cout<<"move anchor, distance = " << wcur[2] << endl;

    // compute and set the position of the new point
    GLdouble p[3];
    gluUnProject ( x, _viewport[3]-y-1, wcur[2], _mvmatrix, _projmatrix, _viewport, &p[0], &p[1], &p[2]); // new position of the picked point
    //        cout<<"x="<< x <<", y="<< y <<", X="<<p[0]<<", Y="<<p[1]<<", Z="<<p[2]<<endl;
    interactor->setPoint(Vec3(p[0], p[1], p[2]));
}

void SofaGL::detach( Interactor* drag)
{
    if( !drag )
        return;

    // remove it from the map
    Picked_to_Interactor::iterator i=_picked_to_interactor.begin();
    while( i!=_picked_to_interactor.end() && (*i).second != drag )
        i++;
    if( i!=_picked_to_interactor.end() ){
        //                cout << "Deleted interactor at " << (*i).first << endl;
        _picked_to_interactor.erase(i);
        //                cout << "new count of interactors: " << picked_to_interactor.size() << endl;
    }
    else assert( false && "Active interactor not found in the map" );

    drag->detach();
    //    cout<<"SofaGL::detach "<< endl; _sofaScene->printGraph();
}

void SofaGL::getSceneBBox( float* xmin, float* ymin, float* zmin, float* xmax, float* ymax, float* zmax )
{
    SReal xm, xM, ym, yM, zm, zM;
    _sofaScene->getBoundingBox(&xm,&xM,&ym,&yM,&zm,&zM);
    //    cerr << "SofaGL::getSceneBBox, xm=" << xm <<", xM=" << xM << endl;
    *xmin=xm, *xmax=xM, *ymin=ym, *ymax=yM, *zmin=zm, *zmax=zM;
}

void SofaGL::viewAll( SReal* xcam, SReal* ycam, SReal* zcam, SReal* xcen, SReal* ycen, SReal* zcen, SReal a, SReal* nearPlane, SReal* farPlane)
{
    // scene center and radius
    SReal xmin, xmax, ymin, ymax, zmin, zmax;
    _sofaScene->getBoundingBox(&xmin,&xmax,&ymin,&ymax,&zmin,&zmax);
    cout<<"SofaGL::viewAll, bounding box = ("<< xmin <<" "<<ymin<<" "<<zmin<<"),("<<xmax<<" "<<ymax<<" "<<zmax<<")"<<endl;
    *xcen = (xmin+xmax)*0.5;
    *ycen = (ymin+ymax)*0.5;
    *zcen = (zmin+zmax)*0.5;
    SReal radius = sqrt( sqr(xmin-xmax) + sqr(ymin-ymax) + sqr(zmin-zmax) );

    // Desired distance:  distance * tan(a) = radius
    SReal distance = 2 * radius / tan(a);
    //    SReal ratio = ((SReal) _viewport[3] - _viewport[1])/(_viewport[2] - _viewport[0]);
    //    distance *= ratio;
    cout<<"SofaGL::viewAll, angle = " << a << ", tan = " << tan(a) << ", distance = " << distance << endl;
    cout<<"SofaGL::viewAll, xmin xmax ymin ymax zmin zmax = " << xmin << " " << xmax <<" "<<ymin<<" "<<ymax<<" "<<zmin<<" "<<zmax<< endl;

    // move the camera along the current camera-center line, at the right distance
    // cam = cen + distance * (cam-cen)/|cam-cen|
    SReal curdist = sqrt( sqr(*xcam-*xcen)+sqr(*ycam-*ycen)+sqr(*zcam-*zcen) );
    *xcam = *xcen + distance * (*xcam-*xcen) / curdist;
    *ycam = *ycen + distance * (*ycam-*ycen) / curdist;
    *zcam = *zcen + distance * (*zcam-*zcen) / curdist;

    // update the depth bounds
    *nearPlane = distance - radius*1.5;
    *farPlane  = distance + radius*1.5;
}

}//newgui
}//sofa
<|endoftext|>


<commit_before>#include "bdb_common.hpp"

#include DB_CXX_HEADER

#include <bitcoin/utility/assert.hpp>
#include <bitcoin/utility/logger.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/address.hpp>

namespace libbitcoin {

bdb_common::bdb_common(DbEnv* env, Db* db_blocks, Db* db_blocks_hash,
    Db* db_txs, Db* db_spends, Db* db_address)
  : env_(env), db_blocks_(db_blocks), db_blocks_hash_(db_blocks_hash),
    db_txs_(db_txs), db_spends_(db_spends), db_address_(db_address)
{
}

uint32_t bdb_common::find_last_block_depth(txn_guard_ptr txn)
{
    Dbc* cursor;
    db_blocks_->cursor(txn->get(), &cursor, 0);
    BITCOIN_ASSERT(cursor != nullptr);
    writable_data_type key, data;
    if (cursor->get(key.get(), data.get(), DB_LAST) == DB_NOTFOUND)
        return std::numeric_limits<uint32_t>::max();
    BITCOIN_ASSERT(key.get()->get_size() == 4);
    uint32_t last_block_depth = cast_chunk<uint32_t>(key.data());
    cursor->close();
    return last_block_depth;
}

bool bdb_common::fetch_spend(txn_guard_ptr txn,
    const message::output_point& spent_output,
    message::input_point& input_spend)
{
    readable_data_type search_spend;
    search_spend.set(create_spent_key(spent_output));
    writable_data_type raw_spend;
    if (db_spends_->get(txn->get(), search_spend.get(),
            raw_spend.get(), 0) != 0)
        return false;
    const data_chunk raw_spend_data = raw_spend.data();
    deserializer deserial(raw_spend_data);
    input_spend.hash = deserial.read_hash();
    input_spend.index = deserial.read_4_bytes();
    return true;
}

bool bdb_common::save_block(txn_guard_ptr txn,
    uint32_t depth, const message::block& serial_block)
{
    protobuf::Block proto_block =
        block_header_to_protobuf(depth, serial_block);
    for (uint32_t tx_index = 0;
        tx_index < serial_block.transactions.size(); ++tx_index)
    {
        const message::transaction& block_tx =
            serial_block.transactions[tx_index];
        const hash_digest& tx_hash = hash_transaction(block_tx);
        if (!save_transaction(txn, depth, tx_index, tx_hash, block_tx))
        {
            log_fatal() << "Could not save transaction";
            return false;
        }
        proto_block.add_transactions(
            std::string(tx_hash.begin(), tx_hash.end()));
    }
    std::ostringstream oss;
    if (!proto_block.SerializeToOstream(&oss))
    {
        log_fatal() << "Protobuf serialization failed";
        return false;
    }
    readable_data_type key, value;
    key.set(depth);
    value.set(oss.str());
    if (db_blocks_->put(txn->get(), key.get(), value.get(), 0) != 0)
    {
        log_fatal() << "bdb put() failed";
        return false;
    }
    return true;
}

bool bdb_common::save_transaction(txn_guard_ptr txn, uint32_t block_depth,
    uint32_t tx_index, const hash_digest& tx_hash,
    const message::transaction& block_tx)
{
    if (dupli_save(txn, tx_hash, block_depth, tx_index))
        return true;
    // Actually add block
    protobuf::Transaction proto_tx = transaction_to_protobuf(block_tx);
    proto_tx.set_is_coinbase(is_coinbase(block_tx));
    // Add parent block to transaction
    protobuf::Transaction_BlockPointer* proto_parent = proto_tx.add_parent();
    proto_parent->set_depth(block_depth);
    proto_parent->set_index(tx_index);
    // Save tx to bdb
    std::ostringstream oss;
    if (!proto_tx.SerializeToOstream(&oss))
        return false;
    readable_data_type key, value;
    key.set(tx_hash);
    value.set(oss.str());
    // Checks for duplicates first
    if (db_txs_->put(txn->get(), key.get(), value.get(), DB_NOOVERWRITE) != 0)
        return false;
    if (is_coinbase(block_tx))
        return true;
    for (uint32_t input_index = 0; input_index < block_tx.inputs.size();
        ++input_index)
    {
        const message::transaction_input& input =
            block_tx.inputs[input_index];
        const message::input_point inpoint{tx_hash, input_index};
        if (!mark_spent_outputs(txn, input.previous_output, inpoint))
            return false;
    }
    for (uint32_t output_index = 0; output_index < block_tx.outputs.size();
        ++output_index)
    {
        const message::transaction_output& output =
            block_tx.outputs[output_index];
        if (!add_address(txn, output.output_script, {tx_hash, output_index}))
            return false;
    }
    return true;
}

bool bdb_common::dupli_save(txn_guard_ptr txn, const hash_digest& tx_hash,
    uint32_t block_depth, uint32_t tx_index)
{
    protobuf::Transaction proto_tx = fetch_proto_transaction(txn, tx_hash);
    if (!proto_tx.IsInitialized())
        return false;
    BITCOIN_ASSERT(block_depth == 91842 || block_depth == 91880);
    protobuf::Transaction::BlockPointer* parent = proto_tx.add_parent();
    parent->set_depth(block_depth);
    parent->set_index(tx_index);
    return rewrite_transaction(txn, tx_hash, proto_tx);
}

bool bdb_common::mark_spent_outputs(txn_guard_ptr txn,
    const message::output_point& previous_output,
    const message::input_point& current_input)
{
    readable_data_type spent_key, spend_value;
    spent_key.set(create_spent_key(previous_output));
    spend_value.set(create_spent_key(current_input));
    if (db_spends_->put(txn->get(), spent_key.get(), spend_value.get(),
            DB_NOOVERWRITE) != 0)
        return false;
    return true;
}

bool bdb_common::add_address(txn_guard_ptr txn,
    const script& output_script, const message::output_point& outpoint)
{
    data_chunk raw_address = create_address_key(output_script);
    if (raw_address.empty())
        return true;
    readable_data_type address_key, output_value;
    address_key.set(raw_address);
    output_value.set(create_spent_key(outpoint));
    if (db_address_->put(txn->get(), address_key.get(),
            output_value.get(), 0) != 0)
        return false;
    return true;
}

bool bdb_common::rewrite_transaction(txn_guard_ptr txn,
    const hash_digest& tx_hash, const protobuf::Transaction& replace_proto_tx)
{
    // Now rewrite tx
    // First delete old
    readable_data_type tx_key;
    tx_key.set(tx_hash);
    if (db_txs_->del(txn->get(), tx_key.get(), 0) != 0)
        return false;
    // Save tx to bdb
    std::ostringstream write_oss;
    if (!replace_proto_tx.SerializeToOstream(&write_oss))
        return false;
    readable_data_type tx_data;
    tx_data.set(write_oss.str());
    // Checks for duplicates first
    if (db_txs_->put(txn->get(), tx_key.get(), tx_data.get(),
        DB_NOOVERWRITE) != 0)
    {
        return false;
    }
    return true;
}

template<typename Index, typename ProtoType>
bool proto_read(Db* database, txn_guard_ptr txn,
    const Index& index, ProtoType& proto_object)
{
    readable_data_type key;
    key.set(index);
    writable_data_type data;
    if (database->get(txn->get(), key.get(), data.get(), 0) != 0)
        return false;
    std::stringstream ss;
    data_chunk raw_object(data.data());
    std::copy(raw_object.begin(), raw_object.end(),
        std::ostream_iterator<byte>(ss));
    proto_object.ParseFromIstream(&ss);
    return true;
}

protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
    uint32_t depth)
{
    protobuf::Block proto_block;
    if (!proto_read(db_blocks_, txn, depth, proto_block))
        return protobuf::Block();
    return proto_block;
}

protobuf::Transaction bdb_common::fetch_proto_transaction(
    txn_guard_ptr txn, const hash_digest& tx_hash)
{
    protobuf::Transaction proto_tx;
    if (!proto_read(db_txs_, txn, tx_hash, proto_tx))
        return protobuf::Transaction();
    return proto_tx;
}

protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
    const hash_digest& block_hash)
{
    protobuf::Block proto_block;
    if (!proto_read(db_blocks_hash_, txn, block_hash, proto_block))
        return protobuf::Block();
    return proto_block;
}

bool bdb_common::reconstruct_block(txn_guard_ptr txn,
    const protobuf::Block& proto_block_header,
    message::block& result_block)
{
    result_block = protobuf_to_block_header(proto_block_header);
    for (const std::string& raw_tx_hash: proto_block_header.transactions())
    {
        protobuf::Transaction proto_tx;
        if (!proto_read(db_txs_, txn, raw_tx_hash, proto_tx))
            return false;
        result_block.transactions.push_back(protobuf_to_transaction(proto_tx));
    }
    return true;
}

data_chunk create_address_key(const script& output_script)
{
    payment_address address;
    if (!extract(address, output_script))
        return data_chunk();
    serializer serial;
    serial.write_byte(address.version());
    serial.write_short_hash(address.hash());
    return serial.data();
}

} // namespace libbitcoin

<commit_msg>bugfix: coinbase output addresses not getting indexed.<commit_after>#include "bdb_common.hpp"

#include DB_CXX_HEADER

#include <bitcoin/utility/assert.hpp>
#include <bitcoin/utility/logger.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/address.hpp>

namespace libbitcoin {

bdb_common::bdb_common(DbEnv* env, Db* db_blocks, Db* db_blocks_hash,
    Db* db_txs, Db* db_spends, Db* db_address)
  : env_(env), db_blocks_(db_blocks), db_blocks_hash_(db_blocks_hash),
    db_txs_(db_txs), db_spends_(db_spends), db_address_(db_address)
{
}

uint32_t bdb_common::find_last_block_depth(txn_guard_ptr txn)
{
    Dbc* cursor;
    db_blocks_->cursor(txn->get(), &cursor, 0);
    BITCOIN_ASSERT(cursor != nullptr);
    writable_data_type key, data;
    if (cursor->get(key.get(), data.get(), DB_LAST) == DB_NOTFOUND)
        return std::numeric_limits<uint32_t>::max();
    BITCOIN_ASSERT(key.get()->get_size() == 4);
    uint32_t last_block_depth = cast_chunk<uint32_t>(key.data());
    cursor->close();
    return last_block_depth;
}

bool bdb_common::fetch_spend(txn_guard_ptr txn,
    const message::output_point& spent_output,
    message::input_point& input_spend)
{
    readable_data_type search_spend;
    search_spend.set(create_spent_key(spent_output));
    writable_data_type raw_spend;
    if (db_spends_->get(txn->get(), search_spend.get(),
            raw_spend.get(), 0) != 0)
        return false;
    const data_chunk raw_spend_data = raw_spend.data();
    deserializer deserial(raw_spend_data);
    input_spend.hash = deserial.read_hash();
    input_spend.index = deserial.read_4_bytes();
    return true;
}

bool bdb_common::save_block(txn_guard_ptr txn,
    uint32_t depth, const message::block& serial_block)
{
    protobuf::Block proto_block =
        block_header_to_protobuf(depth, serial_block);
    for (uint32_t tx_index = 0;
        tx_index < serial_block.transactions.size(); ++tx_index)
    {
        const message::transaction& block_tx =
            serial_block.transactions[tx_index];
        const hash_digest& tx_hash = hash_transaction(block_tx);
        if (!save_transaction(txn, depth, tx_index, tx_hash, block_tx))
        {
            log_fatal() << "Could not save transaction";
            return false;
        }
        proto_block.add_transactions(
            std::string(tx_hash.begin(), tx_hash.end()));
    }
    std::ostringstream oss;
    if (!proto_block.SerializeToOstream(&oss))
    {
        log_fatal() << "Protobuf serialization failed";
        return false;
    }
    readable_data_type key, value;
    key.set(depth);
    value.set(oss.str());
    if (db_blocks_->put(txn->get(), key.get(), value.get(), 0) != 0)
    {
        log_fatal() << "bdb put() failed";
        return false;
    }
    return true;
}

bool bdb_common::save_transaction(txn_guard_ptr txn, uint32_t block_depth,
    uint32_t tx_index, const hash_digest& tx_hash,
    const message::transaction& block_tx)
{
    if (dupli_save(txn, tx_hash, block_depth, tx_index))
        return true;
    // Actually add block
    protobuf::Transaction proto_tx = transaction_to_protobuf(block_tx);
    proto_tx.set_is_coinbase(is_coinbase(block_tx));
    // Add parent block to transaction
    protobuf::Transaction_BlockPointer* proto_parent = proto_tx.add_parent();
    proto_parent->set_depth(block_depth);
    proto_parent->set_index(tx_index);
    // Save tx to bdb
    std::ostringstream oss;
    if (!proto_tx.SerializeToOstream(&oss))
        return false;
    readable_data_type key, value;
    key.set(tx_hash);
    value.set(oss.str());
    // Checks for duplicates first
    if (db_txs_->put(txn->get(), key.get(), value.get(), DB_NOOVERWRITE) != 0)
        return false;
    // Coinbase inputs do not spend anything.
    if (!is_coinbase(block_tx))
        for (uint32_t input_index = 0; input_index < block_tx.inputs.size();
            ++input_index)
        {
            const message::transaction_input& input =
                block_tx.inputs[input_index];
            const message::input_point inpoint{tx_hash, input_index};
            if (!mark_spent_outputs(txn, input.previous_output, inpoint))
                return false;
        }
    for (uint32_t output_index = 0; output_index < block_tx.outputs.size();
        ++output_index)
    {
        const message::transaction_output& output =
            block_tx.outputs[output_index];
        if (!add_address(txn, output.output_script, {tx_hash, output_index}))
            return false;
    }
    return true;
}

bool bdb_common::dupli_save(txn_guard_ptr txn, const hash_digest& tx_hash,
    uint32_t block_depth, uint32_t tx_index)
{
    protobuf::Transaction proto_tx = fetch_proto_transaction(txn, tx_hash);
    if (!proto_tx.IsInitialized())
        return false;
    BITCOIN_ASSERT(block_depth == 91842 || block_depth == 91880);
    protobuf::Transaction::BlockPointer* parent = proto_tx.add_parent();
    parent->set_depth(block_depth);
    parent->set_index(tx_index);
    return rewrite_transaction(txn, tx_hash, proto_tx);
}

bool bdb_common::mark_spent_outputs(txn_guard_ptr txn,
    const message::output_point& previous_output,
    const message::input_point& current_input)
{
    readable_data_type spent_key, spend_value;
    spent_key.set(create_spent_key(previous_output));
    spend_value.set(create_spent_key(current_input));
    if (db_spends_->put(txn->get(), spent_key.get(), spend_value.get(),
            DB_NOOVERWRITE) != 0)
        return false;
    return true;
}

bool bdb_common::add_address(txn_guard_ptr txn,
    const script& output_script, const message::output_point& outpoint)
{
    data_chunk raw_address = create_address_key(output_script);
    if (raw_address.empty())
        return true;
    readable_data_type address_key, output_value;
    address_key.set(raw_address);
    output_value.set(create_spent_key(outpoint));
    if (db_address_->put(txn->get(), address_key.get(),
            output_value.get(), 0) != 0)
        return false;
    return true;
}

bool bdb_common::rewrite_transaction(txn_guard_ptr txn,
    const hash_digest& tx_hash, const protobuf::Transaction& replace_proto_tx)
{
    // Now rewrite tx
    // First delete old
    readable_data_type tx_key;
    tx_key.set(tx_hash);
    if (db_txs_->del(txn->get(), tx_key.get(), 0) != 0)
        return false;
    // Save tx to bdb
    std::ostringstream write_oss;
    if (!replace_proto_tx.SerializeToOstream(&write_oss))
        return false;
    readable_data_type tx_data;
    tx_data.set(write_oss.str());
    // Checks for duplicates first
    if (db_txs_->put(txn->get(), tx_key.get(), tx_data.get(),
        DB_NOOVERWRITE) != 0)
    {
        return false;
    }
    return true;
}

template<typename Index, typename ProtoType>
bool proto_read(Db* database, txn_guard_ptr txn,
    const Index& index, ProtoType& proto_object)
{
    readable_data_type key;
    key.set(index);
    writable_data_type data;
    if (database->get(txn->get(), key.get(), data.get(), 0) != 0)
        return false;
    std::stringstream ss;
    data_chunk raw_object(data.data());
    std::copy(raw_object.begin(), raw_object.end(),
        std::ostream_iterator<byte>(ss));
    proto_object.ParseFromIstream(&ss);
    return true;
}

protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
    uint32_t depth)
{
    protobuf::Block proto_block;
    if (!proto_read(db_blocks_, txn, depth, proto_block))
        return protobuf::Block();
    return proto_block;
}

protobuf::Transaction bdb_common::fetch_proto_transaction(
    txn_guard_ptr txn, const hash_digest& tx_hash)
{
    protobuf::Transaction proto_tx;
    if (!proto_read(db_txs_, txn, tx_hash, proto_tx))
        return protobuf::Transaction();
    return proto_tx;
}

protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
    const hash_digest& block_hash)
{
    protobuf::Block proto_block;
    if (!proto_read(db_blocks_hash_, txn, block_hash, proto_block))
        return protobuf::Block();
    return proto_block;
}

bool bdb_common::reconstruct_block(txn_guard_ptr txn,
    const protobuf::Block& proto_block_header,
    message::block& result_block)
{
    result_block = protobuf_to_block_header(proto_block_header);
    for (const std::string& raw_tx_hash: proto_block_header.transactions())
    {
        protobuf::Transaction proto_tx;
        if (!proto_read(db_txs_, txn, raw_tx_hash, proto_tx))
            return false;
        result_block.transactions.push_back(protobuf_to_transaction(proto_tx));
    }
    return true;
}

data_chunk create_address_key(const script& output_script)
{
    payment_address address;
    if (!extract(address, output_script))
        return data_chunk();
    serializer serial;
    serial.write_byte(address.version());
    serial.write_short_hash(address.hash());
    return serial.data();
}

} // namespace libbitcoin

<|endoftext|>


<commit_before>#define SEQAN_PROFILE

#include <iostream>
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/system.h>

using namespace seqan;
using namespace std;

const int blockSize = 1 << 12;
const int repeats = 1 << 17;

char block1[blockSize] = "This a test string";
char block2[blockSize];

template <typename TFile>
void testThroughput(const char *fileName)
{
	TFile myFile;
	typename aRequest<TFile>::Type req1, req2;

	if (!open(myFile, fileName, OPEN_WRONLY | OPEN_CREATE)) {
		cout << "Could not open for writing" << endl;
		return;
	}

	SEQAN_PROTIMESTART(iotime);

	for (unsigned i = 0; i < repeats; ++i)
	{
		waitFor(req1);
		awriteAt(myFile, block1, blockSize,    2*i  * blockSize, req1);
		waitFor(req2);
		awriteAt(myFile, block2, blockSize, (2*i+1) * blockSize, req2);
	}
	waitFor(req1);
	waitFor(req2);

	cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
	cout << " MB/s" << endl;

	close(myFile);
}

int main()
{
	testThroughput< FILE* >("file_speedF.bin");
	testThroughput< File< Sync<> > >("file_speedS.bin");
	testThroughput< File< Async<> > >("file_speedA.bin");
	return 0;
}
<commit_msg>added: Memory Mapped String<commit_after>#define SEQAN_PROFILE
//#define SEQAN_DEBUG

#include <seqan/sequence.h>
#include <seqan/file.h>
#include <iostream>

using namespace seqan;
using namespace std;

const int blockSize = 1 << 12;
const int repeats = 1 << 17;

CharString block1 = "This a test string";
CharString block2;

template <typename TFile>
void testThroughput(const char *fileName)
{
	TFile myFile;
	typename aRequest<TFile>::Type req1, req2;

	if (!open(myFile, fileName, OPEN_WRONLY | OPEN_CREATE)) {
		cout << "Could not open for writing" << endl;
		return;
	}

	SEQAN_PROTIMESTART(iotime);

	awriteAt(myFile, toCString(block1), blockSize, 0 * blockSize, req1);
	awriteAt(myFile, toCString(block2), blockSize, 1 * blockSize, req2);
	for (unsigned i = 1; i < repeats; ++i)
	{
		waitFor(req1);
		awriteAt(myFile, toCString(block1), blockSize,    2*i  * blockSize, req1);
		waitFor(req2);
		awriteAt(myFile, toCString(block2), blockSize, (2*i+1) * blockSize, req2);
	}
	waitFor(req1);
	waitFor(req2);

	cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
	cout << " MB/s" << endl;

	close(myFile);
}

template <typename TFile>
void testExtString(const char *fileName)
{
	String<char, External<ExternalConfig<TFile> > > myString;

	if (!open(myString, fileName, OPEN_WRONLY | OPEN_CREATE)) {
		cout << "Could not open for writing" << endl;
		return;
	}

	SEQAN_PROTIMESTART(iotime);

	for (unsigned i = 0; i < repeats; ++i)
	{
		append(myString, block1);
		append(myString, block2);
	}

	cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
	cout << " MB/s" << endl;
}

template <typename TFile>
void testMMapString(const char *fileName)
{
	String<char, MMap<ExternalConfig<TFile> > > myString;

	if (!open(myString, fileName, OPEN_RDWR | OPEN_CREATE)) {
		cout << "Could not open for writing" << endl;
		return;
	}

	SEQAN_PROTIMESTART(iotime);

	for (unsigned i = 0; i < repeats; ++i)
	{
		append(myString, block1);
		append(myString, block2);
	}

	cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
	cout << " MB/s" << endl;
}

int main()
{
	resize(block1, blockSize);
	resize(block2, blockSize);
	cout << "awrite() using FILE*        ";		testThroughput< FILE* >				("file_speed1.bin");
	cout << "awrite() using sync. File   ";		testThroughput< File< Sync<> > >	("file_speed2.bin");
	cout << "awrite() using async. File  ";		testThroughput< File< Async<> > >	("file_speed3.bin");
	cout << "ExtString using FILE*       ";		testExtString< FILE* >				("file_speed4.bin");
	cout << "ExtString using sync. File  ";		testExtString< File< Sync<> > >		("file_speed5.bin");
	cout << "ExtString using async. File ";		testExtString< File< Async<> > >	("file_speed6.bin");
	cout << "Memory Mapped String        ";		testMMapString< File< Sync<> > >	("file_speed7.bin");
	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shapeattributelayerholder.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:18:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX
#define _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX

#include <attributableshape.hxx>
#include <shapeattributelayer.hxx>

namespace presentation
{
    namespace internal
    {
        /** Holds a ShapeAttributeLayer, together with the associated
            Shape

            Use this class to hold ShapeAttributeLayer objects the
            RAII way. When this object gets deleted, it will
            automatically revoke the attribute layer for the given
            shape (this encapsulates the somewhat clumsy notification
            process that is required for shape and attribute layer
            interaction).
         */
        class ShapeAttributeLayerHolder
        {
        public:
            /** Create a ShapeAttributeLayerHolder instance.

                This constructor creates an empty attribute holder, to
                generate an attribute layer, you have to manually call
                createAttributeLayer().
             */
            ShapeAttributeLayerHolder() :
                mpShape(),
                mpAttributeLayer()
            {
            }

            ~ShapeAttributeLayerHolder()
            {
                reset(); // ensures that the last attribute layer is
                         // correctly deregistered from the shape.
            }

            void reset()
            {
                if( mpShape.get() && mpAttributeLayer.get() )
                    mpShape->revokeAttributeLayer( mpAttributeLayer );
            }

            /** This constructor receives a pointer to the Shape, from
                which attribute layers should be generated. Initially,
                this object does not create an attribute layer, you
                have to manually call createAttributeLayer().

                @param rShape
                Shape for which attribute layers should be generated.
            */
            bool createAttributeLayer( const AttributableShapeSharedPtr& rShape )
            {
                reset();

                mpShape = rShape;

                if( mpShape.get() )
                    mpAttributeLayer = mpShape->createAttributeLayer();

                return mpAttributeLayer.get() != NULL;
            }

            ShapeAttributeLayerSharedPtr get() const
            {
                return mpAttributeLayer;
            }

        private:
            // default: disabled copy/assignment
            ShapeAttributeLayerHolder(const ShapeAttributeLayerHolder&);
            ShapeAttributeLayerHolder& operator=( const ShapeAttributeLayerHolder& );

            AttributableShapeSharedPtr      mpShape;
            ShapeAttributeLayerSharedPtr    mpAttributeLayer;
        };

    }
}

#endif /* _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX */
<commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/04/12 20:40:09 thb 1.3.18.3: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006/03/24 18:23:36 thb 1.3.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/23 17:22:45 thb 1.3.18.1: #i49357# Changed manual noncopyable boiler plate to boost::noncopyable<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shapeattributelayerholder.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 16:01:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX
#define _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX

#include <attributableshape.hxx>
#include <shapeattributelayer.hxx>

#include <boost/utility.hpp>

namespace slideshow
{
    namespace internal
    {
        /** Holds a ShapeAttributeLayer, together with the associated
            Shape

            Use this class to hold ShapeAttributeLayer objects the
            RAII way. When this object gets deleted, it will
            automatically revoke the attribute layer for the given
            shape (this encapsulates the somewhat clumsy notification
            process that is required for shape and attribute layer
            interaction).
         */
        class ShapeAttributeLayerHolder : private boost::noncopyable
        {
        public:
            /** Create a ShapeAttributeLayerHolder instance.

                This constructor creates an empty attribute holder, to
                generate an attribute layer, you have to manually call
                createAttributeLayer().
             */
            ShapeAttributeLayerHolder() :
                mpShape(),
                mpAttributeLayer()
            {
            }

            ~ShapeAttributeLayerHolder()
            {
                reset(); // ensures that the last attribute layer is
                         // correctly deregistered from the shape.
            }

            void reset()
            {
                if( mpShape && mpAttributeLayer )
                    mpShape->revokeAttributeLayer( mpAttributeLayer );
            }

            /** This constructor receives a pointer to the Shape, from
                which attribute layers should be generated. Initially,
                this object does not create an attribute layer, you
                have to manually call createAttributeLayer().

                @param rShape
                Shape for which attribute layers should be generated.
            */
            bool createAttributeLayer( const AttributableShapeSharedPtr& rShape )
            {
                reset();

                mpShape = rShape;

                if( mpShape )
                    mpAttributeLayer = mpShape->createAttributeLayer();

                return mpAttributeLayer;
            }

            ShapeAttributeLayerSharedPtr get() const
            {
                return mpAttributeLayer;
            }

        private:
            AttributableShapeSharedPtr      mpShape;
            ShapeAttributeLayerSharedPtr    mpAttributeLayer;
        };

    }
}

#endif /* _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX */
<|endoftext|>


<commit_before>#ifdef COMPONENT_PARSER_H
#ifndef COMPONENT_PARSER_OPERATION_H
#define COMPONENT_PARSER_OPERATION_H

namespace Operations {
	const Token nullval("null", KEYWORD, CONSTANT);

	Token add(Token, Token);
	Token subtract(Token, Token);
	Token multiply(Token, Token);
	Token divide(Token, Token);
	Token modulo(Token, Token);
	Token mathOperator(String, Token, Token);

	Token compare(String, Token, Token);
	Token logical(String, Token, Token);

	int priority(String);
	int comparePriority(Token, Token);

};

Token Operations::mathOperator(String op, Token a, Token b) {/*
	if (op == "+") return add(a, b);
	if (op == "-") return subtract(a, b);
	if (op == "*") return multiply(a, b);
	if (op == "/") return divide(a, b);
	if (op == "%") return modulo(a, b);
	*/
	return nullval;
}

int Operations::priority(String op) {
	if (op == ".") return 6;
	if (op == "++" || op == "--") return 5;
	if (op == "*" || op == "/" || op == "%")  return 4;
	if (op == "+" || op == "-") return 3;
	if (op.substr(0,2) == "==" || op.substr(0, 2) == "!=" || op[0] == '<' || op[0] == '>') return 2;
	if (op == "!" || op == "&&" || op == "||" || op == "=" || op[1] == '=') return 1;
	return 0;
}

int Operations::comparePriority(Token a, Token b) {
	return priority(a.value()) - priority(b.value());
}

#endif /* COMPONENT_PARSER_OPERATION_H */
#endif /* COMPONENT_PARSER_H */
<commit_msg>Operation Functions<commit_after>#ifdef COMPONENT_PARSER_H
#ifndef COMPONENT_PARSER_OPERATION_H
#define COMPONENT_PARSER_OPERATION_H

namespace Operations {
	const Token nullval("null", KEYWORD, CONSTANT);

	Token add(Token, Token);
	Token subtract(Token, Token);
	Token multiply(Token, Token);
	Token divide(Token, Token);
	Token modulo(Token, Token);
	Token mathOperator(String, Token, Token);

	Token compare(String, Token, Token);
	Token logical(String, Token, Token);

	int priority(String);
	int comparePriority(Token, Token);

};

Token Operations::mathOperator(String op, Token a, Token b) {/*
	if (op == "+") return add(a, b);
	if (op == "-") return subtract(a, b);
	if (op == "*") return multiply(a, b);
	if (op == "/") return divide(a, b);
	if (op == "%") return modulo(a, b);
	*/
	return nullval;
}

int Operations::priority(String op) {
	if (op == ".") return 6;
	if (op == "++" || op == "--") return 5;
	if (op == "*" || op == "/" || op == "%")  return 4;
	if (op == "+" || op == "-") return 3;
	if (op.substr(0,2) == "==" || op.substr(0, 2) == "!=" || op[0] == '<' || op[0] == '>') return 2;
	if (op == "!" || op == "&&" || op == "||" || op == "=" || op[1] == '=') return 1;
	return 0;
}

int Operations::comparePriority(Token a, Token b) {
	return priority(a.value()) - priority(b.value());
}

Token Operations::add(Token t1, Token t2) {
    if(t1.subtype() != t2.subtype() ) return nullToken;
    if(t1.subtype() == NUMBER) {
        long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
        return Lexer::toToken(numberToString(a1 + a2));
    }
    if(t1.subtype() == STRING) {
        String s1 = Lexer::tokenToString(t1),s2 = Lexer::tokenToString(t2);
        return Lexer::toToken(s1 + s2);
    }
}

Token Operations::subtract(Token t1, Token t2) {
    if(t1.subtype() != NUMBER && t2.subtype() != NUMBER) return nullToken;
    long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
    return Lexer::toToken(numberToString(a1 - a2));
}

Token Operations::multiply(Token t1, Token t2) {
    if(t1.subtype() != NUMBER && t2.subtype() != NUMBER) return nullToken;
    long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
    return Lexer::toToken(numberToString(a1 * a2));
}

Token Operations::divide(Token t1, Token t2) {
    if(t1.subtype() != NUMBER && t2.subtype() != NUMBER) return nullToken;
    long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
    return Lexer::toToken(numberToString(a1 / a2));
}

Token Operations::modulo(Token t1, Token t2) {
    if((!t1.value().isInteger()) && (!t2.value().isInteger())) return nullToken;
    long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
    return Lexer::toToken(integerToString(a1 / a2));
}

#endif /* COMPONENT_PARSER_OPERATION_H */
#endif /* COMPONENT_PARSER_H */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fileobj.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-22 10:37:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _FILEOBJ_HXX
#define _FILEOBJ_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _LINKSRC_HXX //autogen
#include <sfx2/linksrc.hxx>
#endif
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif

#ifndef _SVXLINKMGR_HXX
#include "linkmgr.hxx"
#endif

class Graphic;
struct Impl_DownLoadData;
namespace sfx2 { class FileDialogHelper; }

class SvFileObject : public sfx2::SvLinkSource
{
    String              sFileNm;
    String              sFilter;
    String              sReferer;
    Link                aEndEditLink;
    SfxMediumRef        xMed;
    Impl_DownLoadData*  pDownLoadData;
    Window*             pOldParent;

    BYTE nType;

    BOOL bLoadAgain : 1;
    BOOL bSynchron : 1;
    BOOL bLoadError : 1;
    BOOL bWaitForData : 1;
    BOOL bInNewData : 1;
    BOOL bDataReady : 1;
    BOOL bMedUseCache : 1;
    BOOL bNativFormat : 1;
    BOOL bClearMedium : 1;
    BOOL bStateChangeCalled : 1;
    BOOL bInCallDownLoad : 1;

    BOOL GetGraphic_Impl( Graphic&, SvStream* pStream = 0 );
    BOOL LoadFile_Impl();
    void SendStateChg_Impl( LinkState nState );

    DECL_STATIC_LINK( SvFileObject, DelMedium_Impl, SfxMediumRef* );
    DECL_STATIC_LINK( SvFileObject, LoadGrfReady_Impl, void* );
    DECL_STATIC_LINK( SvFileObject, LoadGrfNewData_Impl, void* );
    DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );

protected:
    virtual ~SvFileObject();

public:
    SvFileObject();

    virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
                            const String & rMimeType,
                            BOOL bSynchron = FALSE );

    virtual BOOL    Connect( sfx2::SvBaseLink* );
    virtual void    Edit( Window *, sfx2::SvBaseLink *, const Link& rEndEditHdl );

    // erfrage ob das man direkt auf die Daten zugreifen kann oder ob das
    // erst angestossen werden muss
    virtual BOOL IsPending() const;
    virtual BOOL IsDataComplete() const;

    void CancelTransfers();
    void SetTransferPriority( USHORT nPrio );
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.8.620); FILE MERGED 2008/04/01 15:51:46 thb 1.8.620.3: #i85898# Stripping all external header guards 2008/04/01 12:50:07 thb 1.8.620.2: #i85898# Stripping all external header guards 2008/03/31 14:24:03 rt 1.8.620.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fileobj.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _FILEOBJ_HXX
#define _FILEOBJ_HXX

#include <tools/string.hxx>
#include <sfx2/linksrc.hxx>
#include <sfx2/docfile.hxx>
#include "linkmgr.hxx"

class Graphic;
struct Impl_DownLoadData;
namespace sfx2 { class FileDialogHelper; }

class SvFileObject : public sfx2::SvLinkSource
{
    String              sFileNm;
    String              sFilter;
    String              sReferer;
    Link                aEndEditLink;
    SfxMediumRef        xMed;
    Impl_DownLoadData*  pDownLoadData;
    Window*             pOldParent;

    BYTE nType;

    BOOL bLoadAgain : 1;
    BOOL bSynchron : 1;
    BOOL bLoadError : 1;
    BOOL bWaitForData : 1;
    BOOL bInNewData : 1;
    BOOL bDataReady : 1;
    BOOL bMedUseCache : 1;
    BOOL bNativFormat : 1;
    BOOL bClearMedium : 1;
    BOOL bStateChangeCalled : 1;
    BOOL bInCallDownLoad : 1;

    BOOL GetGraphic_Impl( Graphic&, SvStream* pStream = 0 );
    BOOL LoadFile_Impl();
    void SendStateChg_Impl( LinkState nState );

    DECL_STATIC_LINK( SvFileObject, DelMedium_Impl, SfxMediumRef* );
    DECL_STATIC_LINK( SvFileObject, LoadGrfReady_Impl, void* );
    DECL_STATIC_LINK( SvFileObject, LoadGrfNewData_Impl, void* );
    DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );

protected:
    virtual ~SvFileObject();

public:
    SvFileObject();

    virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
                            const String & rMimeType,
                            BOOL bSynchron = FALSE );

    virtual BOOL    Connect( sfx2::SvBaseLink* );
    virtual void    Edit( Window *, sfx2::SvBaseLink *, const Link& rEndEditHdl );

    // erfrage ob das man direkt auf die Daten zugreifen kann oder ob das
    // erst angestossen werden muss
    virtual BOOL IsPending() const;
    virtual BOOL IsDataComplete() const;

    void CancelTransfers();
    void SetTransferPriority( USHORT nPrio );
};

#endif

<|endoftext|>


<commit_before>#undef DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

//for connection to server
#include "../sockets/SocketW.h"
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;

FILE * CONN = 0;
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper

int main(){

  int server_socket = DDV_Listen(1935);
  int status;
  while (server_socket > 0){
    waitpid((pid_t)-1, &status, WNOHANG);
    CONN = DDV_Accept(server_socket);
    pid_t myid = fork();
    if (myid == 0){
      break;
    }else{
      printf("Spawned new process %i for incoming client\n", (int)myid);
    }
  }
  if (server_socket <= 0){
    return 0;
  }

  unsigned int ts;
  unsigned int fts = 0;
  unsigned int ftst;
  SWUnixSocket ss;

  //first timestamp set
  firsttime = getNowMS();

  #ifdef DEBUG
  fprintf(stderr, "Doing handshake...\n");
  #endif
  if (doHandshake()){
    #ifdef DEBUG
    fprintf(stderr, "Handshake succcess!\n");
    #endif
  }else{
    #ifdef DEBUG
    fprintf(stderr, "Handshake fail!\n");
    #endif
    return 0;
  }
  #ifdef DEBUG
  fprintf(stderr, "Starting processing...\n");
  #endif
  while (!ferror(stdin) && !ferror(stdout)){
    //only parse input from stdin if available or not yet init'ed
    //rightnow = getNowMS();
    if ((!ready4data || (snd_cnt - snd_window_at >= snd_window_size)) && !stopparsing){
      parseChunk();
      fflush(CONN);
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        if (!ss.connect(streamname.c_str())){
          #ifdef DEBUG
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          return 0;
        }
        FLV_Readheader(ss);//read the header, we don't want it
        #ifdef DEBUG
        fprintf(stderr, "Header read, starting to send video data...\n");
        #endif
        inited = true;
      }
      //only send data if previous data has been ACK'ed...
      if (snd_cnt - snd_window_at < snd_window_size){
        if (FLV_GetPacket(ss)){//able to read a full packet?
          ts = FLVbuffer[7] * 256*256*256;
          ts += FLVbuffer[4] * 256*256;
          ts += FLVbuffer[5] * 256;
          ts += FLVbuffer[6];
          if (ts != 0){
            if (fts == 0){fts = ts;ftst = getNowMS();}
            ts -= fts;
            FLVbuffer[7] = ts / (256*256*256);
            FLVbuffer[4] = ts / (256*256);
            FLVbuffer[5] = ts / 256;
            FLVbuffer[6] = ts % 256;
            ts += ftst;
          }else{
            ftst = getNowMS();
            FLVbuffer[7] = ftst / (256*256*256);
            FLVbuffer[4] = ftst / (256*256);
            FLVbuffer[5] = ftst / 256;
            FLVbuffer[6] = ftst % 256;
          }
          SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);
          FLV_Dump();//dump packet and get ready for next
        }
        if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){
          #ifdef DEBUG
          fprintf(stderr, "No more data! :-(  (%s)\n", SWBerr.get_error().c_str());
          #endif
          return 0;//no more input possible! Fail immediately.
        }
      }
    }
    //send ACK if we received a whole window
    if (rec_cnt - rec_window_at > rec_window_size){
      rec_window_at = rec_cnt;
      SendCTL(3, rec_cnt);//send ack (msg 3)
    }
  }
  #ifdef DEBUG
  fprintf(stderr, "User disconnected.\n");
  #endif
  return 0;
}//main
<commit_msg>Nog een poging...<commit_after>#define DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

//for connection to server
#include "../sockets/SocketW.h"
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;

FILE * CONN = 0;
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper

int main(){

  int server_socket = DDV_Listen(1935);
  int status;
  while (server_socket > 0){
    waitpid((pid_t)-1, &status, WNOHANG);
    CONN = DDV_Accept(server_socket);
    pid_t myid = fork();
    if (myid == 0){
      break;
    }else{
      printf("Spawned new process %i for incoming client\n", (int)myid);
    }
  }
  if (server_socket <= 0){
    return 0;
  }

  unsigned int ts;
  unsigned int fts = 0;
  unsigned int ftst;
  SWUnixSocket ss;

  //first timestamp set
  firsttime = getNowMS();

  #ifdef DEBUG
  fprintf(stderr, "Doing handshake...\n");
  #endif
  if (doHandshake()){
    #ifdef DEBUG
    fprintf(stderr, "Handshake succcess!\n");
    #endif
  }else{
    #ifdef DEBUG
    fprintf(stderr, "Handshake fail!\n");
    #endif
    return 0;
  }
  #ifdef DEBUG
  fprintf(stderr, "Starting processing...\n");
  #endif
  while (!ferror(CONN)){
    //only parse input if available or not yet init'ed
    //rightnow = getNowMS();
    if ((!ready4data || (snd_cnt - snd_window_at >= snd_window_size)) && !stopparsing){
      parseChunk();
      fflush(CONN);
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        if (!ss.connect(streamname.c_str())){
          #ifdef DEBUG
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          return 0;
        }
        FLV_Readheader(ss);//read the header, we don't want it
        #ifdef DEBUG
        fprintf(stderr, "Header read, starting to send video data...\n");
        #endif
        inited = true;
      }
      //only send data if previous data has been ACK'ed...
      if (snd_cnt - snd_window_at < snd_window_size){
        if (FLV_GetPacket(ss)){//able to read a full packet?
          ts = FLVbuffer[7] * 256*256*256;
          ts += FLVbuffer[4] * 256*256;
          ts += FLVbuffer[5] * 256;
          ts += FLVbuffer[6];
          if (ts != 0){
            if (fts == 0){fts = ts;ftst = getNowMS();}
            ts -= fts;
            FLVbuffer[7] = ts / (256*256*256);
            FLVbuffer[4] = ts / (256*256);
            FLVbuffer[5] = ts / 256;
            FLVbuffer[6] = ts % 256;
            ts += ftst;
          }else{
            ftst = getNowMS();
            FLVbuffer[7] = ftst / (256*256*256);
            FLVbuffer[4] = ftst / (256*256);
            FLVbuffer[5] = ftst / 256;
            FLVbuffer[6] = ftst % 256;
          }
          SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);
          FLV_Dump();//dump packet and get ready for next
        }
        if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){
          #ifdef DEBUG
          fprintf(stderr, "No more data! :-(  (%s)\n", SWBerr.get_error().c_str());
          #endif
          return 0;//no more input possible! Fail immediately.
        }
      }
    }
    //send ACK if we received a whole window
    if (rec_cnt - rec_window_at > rec_window_size){
      rec_window_at = rec_cnt;
      SendCTL(3, rec_cnt);//send ack (msg 3)
    }
  }
  #ifdef DEBUG
  fprintf(stderr, "User disconnected.\n");
  #endif
  return 0;
}//main
<|endoftext|>


<commit_before>/* Copyright 2014 Andrew Schwartzmeyer
 *
 * Source file for simulated annealing derived algorithm class
 */

#include <cmath>
#include <iostream>

#include "simulated_annealing_algorithm.hpp"

bool SimulatedAnnealing::probability(const parameter energy1,
				     const parameter energy2,
				     const parameter temperature) const {
  int_dist percent(0, 100);
  // mutation probability P(e1, e2, T) = e^(-c(e1 - e2)/T)
  const parameter chance = 100 * // [0, 1] -> [0, 100]
    std::exp(-problem.constant * (energy1 - energy2) / temperature);
  return percent(rg.engine) < chance;
}

const Individual SimulatedAnnealing::solve() const {
  while(true) {
    // random restart
    Individual best = problem.potential();
    // work with "lucky" values
    if (best > problem.filter) {
      // actual simulated-annealing algorithm
      for (long T = problem.iterations; T > 0; --T) {
	// convert temperature to [0, 100]
	const parameter temperature = 100. * parameter(T) / problem.iterations;
	// get neighbor
        const Individual neighbor = mutate(best);
	// keep track of best solution
	if (neighbor > best
	    // SA swaps in bad solutions with this probability
	    || probability(best.fitness, neighbor.fitness, temperature)) {
	  best = neighbor;
	  // terminating condition
	  if (best > problem.goal) return best;
	}
      }
      std::cout << "Exhausted fitness: " << best.fitness << "\n";
    }
  }
}
<commit_msg>Fixed call to SA's probability function (sending normalized fitness)<commit_after>/* Copyright 2014 Andrew Schwartzmeyer
 *
 * Source file for simulated annealing derived algorithm class
 */

#include <cmath>
#include <iostream>

#include "simulated_annealing_algorithm.hpp"

bool SimulatedAnnealing::probability(const parameter energy1,
				     const parameter energy2,
				     const parameter temperature) const {
  int_dist percent(0, 100);
  // mutation probability P(e1, e2, T) = e^(-c(e1 - e2)/T)
  const parameter chance = 100 * // [0, 1] -> [0, 100]
    std::exp(-problem.constant * (energy1 - energy2) / temperature);
  return percent(rg.engine) < chance;
}

const Individual SimulatedAnnealing::solve() const {
  while(true) {
    // random restart
    Individual best = problem.potential();
    // work with "lucky" values
    if (best > problem.filter) {
      // actual simulated-annealing algorithm
      for (long T = problem.iterations; T > 0; --T) {
	// convert temperature to [0, 100]
	const parameter temperature = 100. * parameter(T) / problem.iterations;
	// get neighbor
        const Individual neighbor = mutate(best);
	// keep track of best solution
	if (neighbor > best
	    // SA swaps in bad solutions with this probability
	    || probability(problem.normal(best), problem.normal(neighbor),
			   temperature)) {
	  best = neighbor;
	  // terminating condition
	  if (best > problem.goal) return best;
	}
      }
      std::cout << "Exhausted fitness: " << best.fitness << "\n";
    }
  }
}
<|endoftext|>