<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "perf_precomp.hpp"

using namespace std;
using namespace testing;
using namespace perf;

//////////////////////////////////////////////////////////////////////
// Blur

DEF_PARAM_TEST(Sz_Type_KernelSz, cv::Size, MatType, int);

PERF_TEST_P(Sz_Type_KernelSz, Blur,
            Combine(GPU_TYPICAL_MAT_SIZES,
                    Values(CV_8UC1, CV_8UC4),
                    Values(3, 5, 7)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;

        TEST_CYCLE() cv::gpu::blur(d_src, dst, cv::Size(ksize, ksize));

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::blur(src, dst, cv::Size(ksize, ksize));

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Sobel

PERF_TEST_P(Sz_Type_KernelSz, Sobel, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::Sobel(d_src, dst, -1, 1, 1, d_buf, ksize);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::Sobel(src, dst, -1, 1, 1, ksize);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Scharr

PERF_TEST_P(Sz_Type, Scharr, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::Scharr(d_src, dst, -1, 1, 0, d_buf);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::Scharr(src, dst, -1, 1, 0);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// GaussianBlur

PERF_TEST_P(Sz_Type_KernelSz, GaussianBlur, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::GaussianBlur(d_src, dst, cv::Size(ksize, ksize), d_buf, 0.5);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::GaussianBlur(src, dst, cv::Size(ksize, ksize), 0.5);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Laplacian

PERF_TEST_P(Sz_Type_KernelSz, Laplacian, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(1, 3)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;

        TEST_CYCLE() cv::gpu::Laplacian(d_src, dst, -1, ksize);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Erode

PERF_TEST_P(Sz_Type, Erode, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::erode(d_src, dst, ker, d_buf);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::erode(src, dst, ker);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Dilate

PERF_TEST_P(Sz_Type, Dilate, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::dilate(d_src, dst, ker, d_buf);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::dilate(src, dst, ker);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// MorphologyEx

CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT)

DEF_PARAM_TEST(Sz_Type_Op, cv::Size, MatType, MorphOp);

PERF_TEST_P(Sz_Type_Op, MorphologyEx, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4), MorphOp::all()))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int morphOp = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf1;
        cv::gpu::GpuMat d_buf2;

        TEST_CYCLE() cv::gpu::morphologyEx(d_src, dst, morphOp, ker, d_buf1, d_buf2);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::morphologyEx(src, dst, morphOp, ker);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Filter2D

PERF_TEST_P(Sz_Type_KernelSz, Filter2D, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(3, 5, 7, 9, 11, 13, 15)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    cv::Mat kernel(ksize, ksize, CV_32FC1);
    declare.in(kernel, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;

        TEST_CYCLE() cv::gpu::filter2D(d_src, dst, -1, kernel);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);

        CPU_SANITY_CHECK(dst);
    }
}
<commit_msg>fixed BoxFilter sanity test (different rounding results)<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "perf_precomp.hpp"

using namespace std;
using namespace testing;
using namespace perf;

//////////////////////////////////////////////////////////////////////
// Blur

DEF_PARAM_TEST(Sz_Type_KernelSz, cv::Size, MatType, int);

PERF_TEST_P(Sz_Type_KernelSz, Blur,
            Combine(GPU_TYPICAL_MAT_SIZES,
                    Values(CV_8UC1, CV_8UC4),
                    Values(3, 5, 7)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;

        TEST_CYCLE() cv::gpu::blur(d_src, dst, cv::Size(ksize, ksize));

        GPU_SANITY_CHECK(dst, 1);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::blur(src, dst, cv::Size(ksize, ksize));

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Sobel

PERF_TEST_P(Sz_Type_KernelSz, Sobel, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::Sobel(d_src, dst, -1, 1, 1, d_buf, ksize);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::Sobel(src, dst, -1, 1, 1, ksize);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Scharr

PERF_TEST_P(Sz_Type, Scharr, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::Scharr(d_src, dst, -1, 1, 0, d_buf);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::Scharr(src, dst, -1, 1, 0);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// GaussianBlur

PERF_TEST_P(Sz_Type_KernelSz, GaussianBlur, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1), Values(3, 5, 7, 9, 11, 13, 15)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::GaussianBlur(d_src, dst, cv::Size(ksize, ksize), d_buf, 0.5);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::GaussianBlur(src, dst, cv::Size(ksize, ksize), 0.5);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Laplacian

PERF_TEST_P(Sz_Type_KernelSz, Laplacian, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(1, 3)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;

        TEST_CYCLE() cv::gpu::Laplacian(d_src, dst, -1, ksize);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Erode

PERF_TEST_P(Sz_Type, Erode, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::erode(d_src, dst, ker, d_buf);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::erode(src, dst, ker);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Dilate

PERF_TEST_P(Sz_Type, Dilate, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf;

        TEST_CYCLE() cv::gpu::dilate(d_src, dst, ker, d_buf);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::dilate(src, dst, ker);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// MorphologyEx

CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT)

DEF_PARAM_TEST(Sz_Type_Op, cv::Size, MatType, MorphOp);

PERF_TEST_P(Sz_Type_Op, MorphologyEx, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4), MorphOp::all()))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int morphOp = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    const cv::Mat ker = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;
        cv::gpu::GpuMat d_buf1;
        cv::gpu::GpuMat d_buf2;

        TEST_CYCLE() cv::gpu::morphologyEx(d_src, dst, morphOp, ker, d_buf1, d_buf2);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::morphologyEx(src, dst, morphOp, ker);

        CPU_SANITY_CHECK(dst);
    }
}

//////////////////////////////////////////////////////////////////////
// Filter2D

PERF_TEST_P(Sz_Type_KernelSz, Filter2D, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4), Values(3, 5, 7, 9, 11, 13, 15)))
{
    declare.time(20.0);

    const cv::Size size = GET_PARAM(0);
    const int type = GET_PARAM(1);
    const int ksize = GET_PARAM(2);

    cv::Mat src(size, type);
    declare.in(src, WARMUP_RNG);

    cv::Mat kernel(ksize, ksize, CV_32FC1);
    declare.in(kernel, WARMUP_RNG);

    if (PERF_RUN_GPU())
    {
        const cv::gpu::GpuMat d_src(src);
        cv::gpu::GpuMat dst;

        TEST_CYCLE() cv::gpu::filter2D(d_src, dst, -1, kernel);

        GPU_SANITY_CHECK(dst);
    }
    else
    {
        cv::Mat dst;

        TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);

        CPU_SANITY_CHECK(dst);
    }
}
<|endoftext|>


<commit_before>#include "Step7.h"

#include <QmitkRenderWindow.h>
#include <QmitkSliceWidget.h>

#include <mitkProperties.h>

#include <mitkSurface.h>

#include <vtkMarchingCubes.h>
#include <vtkSTLWriter.h>

//##Documentation
//## @brief Convert result of region-grower into a surface
//## by means of a VTK filter
Step7::Step7( int argc, char* argv[], QWidget *parent, const char *name )
  : Step6( argc, argv, parent, name )
{
}

void Step7::StartRegionGrowing()
{
  Step6::StartRegionGrowing();

  if(m_ResultImage.IsNotNull())
  {
    m_ResultNode->SetProperty("volumerendering", new mitk::BoolProperty(false));

    vtkMarchingCubes* surfaceCreator = vtkMarchingCubes::New();
    surfaceCreator->SetInput(m_ResultImage->GetVtkImageData());
    surfaceCreator->SetValue(0, 1);

//    vtkSTLWriter* writer = vtkSTLWriter::New();
//    writer->SetInput(surfaceCreator->GetOutput());
//    writer->SetFileName("C:\\lungsOfOrig_volume.stl");
//writer->Write();

    mitk::Surface::Pointer surface = mitk::Surface::New();
    surface->SetVtkPolyData(surfaceCreator->GetOutput());

    mitk::DataTreeNode::Pointer surfaceNode = mitk::DataTreeNode::New();
    surfaceNode->SetData(surface);

    mitk::DataTreePreOrderIterator it(m_Tree);
    it.Add(surfaceNode);

    mitk::RenderWindow::UpdateAllInstances();
  }
}

/**
\example Step7.cpp
*/
<commit_msg>FIX: removed accidentally commited stuff<commit_after>#include "Step7.h"

#include <QmitkRenderWindow.h>
#include <QmitkSliceWidget.h>

#include <mitkProperties.h>

#include <mitkSurface.h>

#include <vtkMarchingCubes.h>
#include <vtkSTLWriter.h>

//##Documentation
//## @brief Convert result of region-grower into a surface
//## by means of a VTK filter
Step7::Step7( int argc, char* argv[], QWidget *parent, const char *name )
  : Step6( argc, argv, parent, name )
{
}

void Step7::StartRegionGrowing()
{
  Step6::StartRegionGrowing();

  if(m_ResultImage.IsNotNull())
  {
    m_ResultNode->SetProperty("volumerendering", new mitk::BoolProperty(false));

    vtkMarchingCubes* surfaceCreator = vtkMarchingCubes::New();
    surfaceCreator->SetInput(m_ResultImage->GetVtkImageData());
    surfaceCreator->SetValue(0, 1);

    mitk::Surface::Pointer surface = mitk::Surface::New();
    surface->SetVtkPolyData(surfaceCreator->GetOutput());

    mitk::DataTreeNode::Pointer surfaceNode = mitk::DataTreeNode::New();
    surfaceNode->SetData(surface);

    mitk::DataTreePreOrderIterator it(m_Tree);
    it.Add(surfaceNode);

    mitk::RenderWindow::UpdateAllInstances();
  }
}

/**
\example Step7.cpp
*/
<|endoftext|>


<commit_before>#include "OneDEnergyFlux.h"
#include "SinglePhaseCommonFluidProperties.h"

template<>
InputParameters validParams<OneDEnergyFlux>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredCoupledVar("area", "Cross-sectional area");
  params.addRequiredCoupledVar("rhoA", "density multiplied by area");
  params.addRequiredCoupledVar("rhouA", "momentum multiplied by area");
  params.addRequiredCoupledVar("u", "velocity");
  params.addRequiredCoupledVar("enthalpy", "enthalpy");
  params.addParam<bool>("is_liquid", true, "True for liquid, false for vapor");
  params.addCoupledVar("alpha", 1., "Volume fraction");
  params.addCoupledVar("alpha_A_liquid", "Volume fraction of liquid");
  params.addRequiredParam<MaterialPropertyName>("pressure", "Pressure");
  params.addRequiredParam<MaterialPropertyName>("dp_darhoA", "Derivative of pressure w.r.t. density");
  params.addRequiredParam<MaterialPropertyName>("dp_darhouA", "Derivative of pressure w.r.t. momentum");
  params.addRequiredParam<MaterialPropertyName>("dp_darhoEA", "Derivative of pressure w.r.t. total energy");
  params.addParam<MaterialPropertyName>("dp_daAL", "Derivative of pressure w.r.t. alpha_A_liquid");

  return params;
}

OneDEnergyFlux::OneDEnergyFlux(const InputParameters & parameters) :
    Kernel(parameters),
    _is_liquid(getParam<bool>("is_liquid")),
    _sign(_is_liquid ? 1. : -1.),
    _rhouA(coupledValue("rhouA")),
    _area(coupledValue("area")),
    _u_vel(coupledValue("u")),
    _enthalpy(coupledValue("enthalpy")),
    _pressure(getMaterialProperty<Real>("pressure")),
    _dp_darhoA(getMaterialProperty<Real>("dp_darhoA")),
    _dp_darhouA(getMaterialProperty<Real>("dp_darhouA")),
    _dp_darhoEA(getMaterialProperty<Real>("dp_darhoEA")),
    _rhoA_var_number(coupled("rhoA")),
    _rhouA_var_number(coupled("rhouA")),
    _has_alpha_A(isCoupled("alpha_A_liquid")),
    _alpha_A_liquid_var_number(_has_alpha_A ? coupled("alpha_A_liquid") : libMesh::invalid_uint),
    _dp_daAL(_has_alpha_A ? &getMaterialProperty<Real>("dp_daAL") : NULL),
    _alpha(coupledValue("alpha"))
{
}

OneDEnergyFlux::~OneDEnergyFlux()
{
}

Real
OneDEnergyFlux::computeQpResidual()
{
  return -_rhouA[_qp] * _enthalpy[_qp] * _grad_test[_i][_qp](0);
}

Real
OneDEnergyFlux::computeQpJacobian()
{
  Real A33 = _u_vel[_qp] * (1. + _alpha[_qp] * _dp_darhoEA[_qp] * _area[_qp]);
  return -A33 * _phi[_j][_qp] * _grad_test[_i][_qp](0);
}

Real
OneDEnergyFlux::computeQpOffDiagJacobian(unsigned int jvar)
{
  if (jvar == _rhoA_var_number)
  {
    Real A31 = _u_vel[_qp] * (_alpha[_qp] * _dp_darhoA[_qp] * _area[_qp] - _enthalpy[_qp]);
    return -A31 * _phi[_j][_qp] * _grad_test[_i][_qp](0);
  }
  else if (jvar == _rhouA_var_number)
  {
    Real A32 = _u_vel[_qp] * _alpha[_qp] * _dp_darhouA[_qp] * _area[_qp] + _enthalpy[_qp];
    return -A32 * _phi[_j][_qp] * _grad_test[_i][_qp](0);
  }
  else if (jvar == _alpha_A_liquid_var_number)
  {
    return -(_u_vel[_qp] * (_sign * _pressure[_qp] + _alpha[_qp] * _area[_qp] * (*_dp_daAL)[_qp])) * _phi[_j][_qp] * _grad_test[_i][_qp](0);
  }
  else
    return 0.;
}
<commit_msg>Removing SinglePhaseCommonFluidProperties<commit_after>#include "OneDEnergyFlux.h"

template<>
InputParameters validParams<OneDEnergyFlux>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredCoupledVar("area", "Cross-sectional area");
  params.addRequiredCoupledVar("rhoA", "density multiplied by area");
  params.addRequiredCoupledVar("rhouA", "momentum multiplied by area");
  params.addRequiredCoupledVar("u", "velocity");
  params.addRequiredCoupledVar("enthalpy", "enthalpy");
  params.addParam<bool>("is_liquid", true, "True for liquid, false for vapor");
  params.addCoupledVar("alpha", 1., "Volume fraction");
  params.addCoupledVar("alpha_A_liquid", "Volume fraction of liquid");
  params.addRequiredParam<MaterialPropertyName>("pressure", "Pressure");
  params.addRequiredParam<MaterialPropertyName>("dp_darhoA", "Derivative of pressure w.r.t. density");
  params.addRequiredParam<MaterialPropertyName>("dp_darhouA", "Derivative of pressure w.r.t. momentum");
  params.addRequiredParam<MaterialPropertyName>("dp_darhoEA", "Derivative of pressure w.r.t. total energy");
  params.addParam<MaterialPropertyName>("dp_daAL", "Derivative of pressure w.r.t. alpha_A_liquid");

  return params;
}

OneDEnergyFlux::OneDEnergyFlux(const InputParameters & parameters) :
    Kernel(parameters),
    _is_liquid(getParam<bool>("is_liquid")),
    _sign(_is_liquid ? 1. : -1.),
    _rhouA(coupledValue("rhouA")),
    _area(coupledValue("area")),
    _u_vel(coupledValue("u")),
    _enthalpy(coupledValue("enthalpy")),
    _pressure(getMaterialProperty<Real>("pressure")),
    _dp_darhoA(getMaterialProperty<Real>("dp_darhoA")),
    _dp_darhouA(getMaterialProperty<Real>("dp_darhouA")),
    _dp_darhoEA(getMaterialProperty<Real>("dp_darhoEA")),
    _rhoA_var_number(coupled("rhoA")),
    _rhouA_var_number(coupled("rhouA")),
    _has_alpha_A(isCoupled("alpha_A_liquid")),
    _alpha_A_liquid_var_number(_has_alpha_A ? coupled("alpha_A_liquid") : libMesh::invalid_uint),
    _dp_daAL(_has_alpha_A ? &getMaterialProperty<Real>("dp_daAL") : NULL),
    _alpha(coupledValue("alpha"))
{
}

OneDEnergyFlux::~OneDEnergyFlux()
{
}

Real
OneDEnergyFlux::computeQpResidual()
{
  return -_rhouA[_qp] * _enthalpy[_qp] * _grad_test[_i][_qp](0);
}

Real
OneDEnergyFlux::computeQpJacobian()
{
  Real A33 = _u_vel[_qp] * (1. + _alpha[_qp] * _dp_darhoEA[_qp] * _area[_qp]);
  return -A33 * _phi[_j][_qp] * _grad_test[_i][_qp](0);
}

Real
OneDEnergyFlux::computeQpOffDiagJacobian(unsigned int jvar)
{
  if (jvar == _rhoA_var_number)
  {
    Real A31 = _u_vel[_qp] * (_alpha[_qp] * _dp_darhoA[_qp] * _area[_qp] - _enthalpy[_qp]);
    return -A31 * _phi[_j][_qp] * _grad_test[_i][_qp](0);
  }
  else if (jvar == _rhouA_var_number)
  {
    Real A32 = _u_vel[_qp] * _alpha[_qp] * _dp_darhouA[_qp] * _area[_qp] + _enthalpy[_qp];
    return -A32 * _phi[_j][_qp] * _grad_test[_i][_qp](0);
  }
  else if (jvar == _alpha_A_liquid_var_number)
  {
    return -(_u_vel[_qp] * (_sign * _pressure[_qp] + _alpha[_qp] * _area[_qp] * (*_dp_daAL)[_qp])) * _phi[_j][_qp] * _grad_test[_i][_qp](0);
  }
  else
    return 0.;
}
<|endoftext|>


<commit_before>#include "serialcli.h"

#include <stdlib.h>
#include <string.h>

#include "control.h"
#include "globals.h"
#include "serialstatemachine.h"

const int MAX_CMD_LEN = 31, MAX_TOKENS = 5;
byte cmd_buf[MAX_CMD_LEN+1];
byte* cmd_tokenv[MAX_TOKENS+1];
int cmd_len;

// States
static SerialState readingCommandState(byte ch);

// Process command stored in cmd_buf and return state to transition to.
static SerialState processCommand();

// Print a brief usage summary to the serial port.
static void printHelp();

// EXTERNAL

SerialState startSerialPrompt() {
    // Reset current command
    cmd_buf[0] = '\0';
    cmd_len = 0;

    Serial.print("> ");
    return { .next = &readingCommandState };
}

// INTERNAL

// State machine
static SerialState readingCommandState(byte ch) {
    switch(ch) {
        // handle backspace
        case 8:
        case 127:
            if(cmd_len > 0) {
                Serial.write(8);
                Serial.write(' ');
                Serial.write(8);
                cmd_len--;
                cmd_buf[cmd_len] = '\0';
            } else {
                // bell
                Serial.write(7);
            }
            break;

        // handle enter
        case 10:
        case 13:
            Serial.println("");
            return processCommand();
            break;

        default:
            // Only accept printable chars.
            if(ch < 0x20) {
                // Bell
                Serial.write(7);
            } else if(cmd_len < MAX_CMD_LEN) {
                // Add character to command buffer
                cmd_buf[cmd_len] = ch;
                cmd_len++;
                cmd_buf[cmd_len] = '\0';

                // Echo character to output
                Serial.write(ch);
            } else {
                // Bell
                Serial.write(7);
            }
            break;
    }

    return { .next = &readingCommandState };
}

static void printHelp() {
    Serial.println("?           - show brief help message");
    Serial.println("p[rint]     - print current address/data bus");
    Serial.println("h[alt]      - toggle halt state");
    Serial.println("c[ycle] [n] - single cycle n times");
    Serial.println("s[tep] [n]  - single step n times");
    Serial.println("r[eset]     - toggle ~RST line");
    Serial.println("");
    Serial.println("Specify decimal numbers with no prefix.");
    Serial.println("Specify hexadecimal numbers with $ prefix.");
}

// MODIFY cmd_buf tokenizing it into space-separated tokens skipping leading
// and trailing spaces. (Spaces are replaced with '\0'.) Update cmd_tokenv as
// pointers into cmd_buf for each token will NULL marking the end of the list.
static void tokenizeCmdBuf() {
    int next_tokenv_idx = 0;
    int ch_idx = 0;

    // Reset token vector
    cmd_tokenv[0] = NULL;

    while((next_tokenv_idx < MAX_TOKENS) && (ch_idx < cmd_len)) {
        // Skip to next non-space char
        for(; (ch_idx < cmd_len) && (cmd_buf[ch_idx] != '\0') &&
              (cmd_buf[ch_idx] == ' '); ++ch_idx) { }

        // Have we reached end of string without finding token?
        if((ch_idx == cmd_len) || (cmd_buf[ch_idx] == '\0')) {
            // yes, exit
            break;
        }

        // Record location of token and advance next_tokenv_idx
        cmd_tokenv[next_tokenv_idx] = &(cmd_buf[ch_idx]);
        ++next_tokenv_idx;

        // Start by assuming we won't find a token next time around
        cmd_tokenv[next_tokenv_idx] = NULL;

        // Advance to first space character or end of buffer
        for(;(ch_idx < cmd_len) && (cmd_buf[ch_idx] != '\0') &&
             (cmd_buf[ch_idx] != ' ')
            ;++ch_idx)
        { }

        // Write '\0' and advance ch_idx
        if(ch_idx < cmd_len) {
            cmd_buf[ch_idx] = '\0';
        }
        ++ch_idx;
    }

    // Reset command buffer length
    cmd_len = 0;

    // Ensure cmd_tokenv is terminated with a NULL come what may.
    cmd_tokenv[MAX_TOKENS] = NULL;
}

// return true if a == b or a == b[0]
static bool strprefixeq(const char* a, const char* b) {
    if((a[0] != '\0') && (a[0] == b[0]) && (a[1] == '\0')) {
        return true;
    }
    return !strcmp(a, b);
}

// Parse s as an integer and write result to l. Return true iff parsing
// succeeds.
bool parseLong(const char* s, long* l) {
    char* end_ptr;
    int base = 10;

    // Are we parsing a hex number?
    if(s[0] == '$') {
        base = 16;
        ++s;
    }

    *l = strtol(s, &end_ptr, base);
    return (s[0] != '\0') && (*end_ptr == '\0');
}

static SerialState processCommand() {
    // Parse cmd_buf into tokens
    tokenizeCmdBuf();

    // Count tokens
    int n_tokens = 0;
    for(; (cmd_tokenv[n_tokens] != NULL) && (n_tokens < MAX_TOKENS)
        ; ++n_tokens) {}

    // Pull out command name
    const char *cmd = reinterpret_cast<const char*>(cmd_tokenv[0]);

    if(n_tokens == 0) {
        // If no command was given, print help
        printHelp();
    } else if(strprefixeq(cmd, "?") && (n_tokens == 1)) {
        // If help command was given, print help
        printHelp();
    } else if(strprefixeq(cmd, "halt") && (n_tokens == 1)) {
        halt = !halt;
        Serial.print("halt ");
        Serial.println(halt ? "on" : "off");
    } else if(strprefixeq(cmd, "print") && (n_tokens == 1)) {
        // print current state
        Serial.print("A: ");
        Serial.print(address_bus, HEX);
        Serial.print(" D: ");
        Serial.print(data_bus, HEX);
        Serial.println("");
    } else if(strprefixeq(cmd, "cycle") && (n_tokens <= 2)) {
        long n=1; // default
        if(n_tokens > 1) {
            const char* arg1 = reinterpret_cast<const char*>(cmd_tokenv[1]);
            if(!parseLong(arg1, &n)) {
                Serial.print("invalid number: ");
                Serial.println(arg1);
            }
        }

        if(processorCanBeStepped()) {
            for(long i=0; i<n; ++i) {
                step_state = SS_CYCLE;
                while(step_state != SS_NONE) {
                    controlLoop();
                }
            }
        } else {
            Serial.println("processor in incorrect state for stepping");
        }
    } else if(strprefixeq(cmd, "step") && (n_tokens <= 2)) {
        long n=1; // default
        if(n_tokens > 1) {
            const char* arg1 = reinterpret_cast<const char*>(cmd_tokenv[1]);
            if(!parseLong(arg1, &n)) {
                Serial.print("invalid number: ");
                Serial.println(arg1);
            }
        }

        if(processorCanBeStepped()) {
            for(long i=0; i<n; ++i) {
                step_state = SS_INST;
                while(step_state != SS_NONE) {
                    controlLoop();
                }
            }
        } else {
            Serial.println("processor in incorrect state for stepping");
        }
    } else if(strprefixeq(cmd, "reset") && (n_tokens == 1)) {
        pull_rst_low = !pull_rst_low;
        Serial.print("~rst ");
        Serial.println(pull_rst_low ? "low" : "high");
    } else {
        Serial.println("unknown command");
        printHelp();
    }

    return startSerialPrompt();
}
<commit_msg>make step aborting more robust<commit_after>#include "serialcli.h"

#include <stdlib.h>
#include <string.h>

#include "control.h"
#include "globals.h"
#include "serialstatemachine.h"

const int MAX_CMD_LEN = 31, MAX_TOKENS = 5;
byte cmd_buf[MAX_CMD_LEN+1];
byte* cmd_tokenv[MAX_TOKENS+1];
int cmd_len;

// States
static SerialState readingCommandState(byte ch);

// Process command stored in cmd_buf and return state to transition to.
static SerialState processCommand();

// Print a brief usage summary to the serial port.
static void printHelp();

// EXTERNAL

SerialState startSerialPrompt() {
    // Reset current command
    cmd_buf[0] = '\0';
    cmd_len = 0;

    Serial.print("> ");
    return { .next = &readingCommandState };
}

// INTERNAL

// State machine
static SerialState readingCommandState(byte ch) {
    switch(ch) {
        // handle backspace
        case 8:
        case 127:
            if(cmd_len > 0) {
                Serial.write(8);
                Serial.write(' ');
                Serial.write(8);
                cmd_len--;
                cmd_buf[cmd_len] = '\0';
            } else {
                // bell
                Serial.write(7);
            }
            break;

        // handle enter
        case 10:
        case 13:
            Serial.println("");
            return processCommand();
            break;

        default:
            // Only accept printable chars.
            if(ch < 0x20) {
                // Bell
                Serial.write(7);
            } else if(cmd_len < MAX_CMD_LEN) {
                // Add character to command buffer
                cmd_buf[cmd_len] = ch;
                cmd_len++;
                cmd_buf[cmd_len] = '\0';

                // Echo character to output
                Serial.write(ch);
            } else {
                // Bell
                Serial.write(7);
            }
            break;
    }

    return { .next = &readingCommandState };
}

static void printHelp() {
    Serial.println("?           - show brief help message");
    Serial.println("p[rint]     - print current address/data bus");
    Serial.println("h[alt]      - toggle halt state");
    Serial.println("c[ycle] [n] - single cycle n times");
    Serial.println("s[tep] [n]  - single step n times");
    Serial.println("r[eset]     - toggle ~RST line");
    Serial.println("");
    Serial.println("Specify decimal numbers with no prefix.");
    Serial.println("Specify hexadecimal numbers with $ prefix.");
}

// MODIFY cmd_buf tokenizing it into space-separated tokens skipping leading
// and trailing spaces. (Spaces are replaced with '\0'.) Update cmd_tokenv as
// pointers into cmd_buf for each token will NULL marking the end of the list.
static void tokenizeCmdBuf() {
    int next_tokenv_idx = 0;
    int ch_idx = 0;

    // Reset token vector
    cmd_tokenv[0] = NULL;

    while((next_tokenv_idx < MAX_TOKENS) && (ch_idx < cmd_len)) {
        // Skip to next non-space char
        for(; (ch_idx < cmd_len) && (cmd_buf[ch_idx] != '\0') &&
              (cmd_buf[ch_idx] == ' '); ++ch_idx) { }

        // Have we reached end of string without finding token?
        if((ch_idx == cmd_len) || (cmd_buf[ch_idx] == '\0')) {
            // yes, exit
            break;
        }

        // Record location of token and advance next_tokenv_idx
        cmd_tokenv[next_tokenv_idx] = &(cmd_buf[ch_idx]);
        ++next_tokenv_idx;

        // Start by assuming we won't find a token next time around
        cmd_tokenv[next_tokenv_idx] = NULL;

        // Advance to first space character or end of buffer
        for(;(ch_idx < cmd_len) && (cmd_buf[ch_idx] != '\0') &&
             (cmd_buf[ch_idx] != ' ')
            ;++ch_idx)
        { }

        // Write '\0' and advance ch_idx
        if(ch_idx < cmd_len) {
            cmd_buf[ch_idx] = '\0';
        }
        ++ch_idx;
    }

    // Reset command buffer length
    cmd_len = 0;

    // Ensure cmd_tokenv is terminated with a NULL come what may.
    cmd_tokenv[MAX_TOKENS] = NULL;
}

// return true if a == b or a == b[0]
static bool strprefixeq(const char* a, const char* b) {
    if((a[0] != '\0') && (a[0] == b[0]) && (a[1] == '\0')) {
        return true;
    }
    return !strcmp(a, b);
}

// Parse s as an integer and write result to l. Return true iff parsing
// succeeds.
bool parseLong(const char* s, long* l) {
    char* end_ptr;
    int base = 10;

    // Are we parsing a hex number?
    if(s[0] == '$') {
        base = 16;
        ++s;
    }

    *l = strtol(s, &end_ptr, base);
    return (s[0] != '\0') && (*end_ptr == '\0');
}

static SerialState processCommand() {
    // Parse cmd_buf into tokens
    tokenizeCmdBuf();

    // Count tokens
    int n_tokens = 0;
    for(; (cmd_tokenv[n_tokens] != NULL) && (n_tokens < MAX_TOKENS)
        ; ++n_tokens) {}

    // Pull out command name
    const char *cmd = reinterpret_cast<const char*>(cmd_tokenv[0]);

    if(n_tokens == 0) {
        // If no command was given, print help
        printHelp();
    } else if(strprefixeq(cmd, "?") && (n_tokens == 1)) {
        // If help command was given, print help
        printHelp();
    } else if(strprefixeq(cmd, "halt") && (n_tokens == 1)) {
        halt = !halt;
        Serial.print("halt ");
        Serial.println(halt ? "on" : "off");
    } else if(strprefixeq(cmd, "print") && (n_tokens == 1)) {
        // print current state
        Serial.print("A: ");
        Serial.print(address_bus, HEX);
        Serial.print(" D: ");
        Serial.print(data_bus, HEX);
        Serial.println("");
    } else if(strprefixeq(cmd, "cycle") && (n_tokens <= 2)) {
        long n=1; // default
        if(n_tokens > 1) {
            const char* arg1 = reinterpret_cast<const char*>(cmd_tokenv[1]);
            if(!parseLong(arg1, &n)) {
                Serial.print("invalid number: ");
                Serial.println(arg1);
            }
        }

        for(long i=0; i<n; ++i) {
            step_state = SS_INST;
            while(step_state != SS_NONE) {
                controlLoop();

                if(!processorCanBeStepped()) {
                    Serial.println("aborting: processor in incorrect state for stepping");
                    step_state = SS_NONE;
                }
            }
        }
    } else if(strprefixeq(cmd, "step") && (n_tokens <= 2)) {
        long n=1; // default
        if(n_tokens > 1) {
            const char* arg1 = reinterpret_cast<const char*>(cmd_tokenv[1]);
            if(!parseLong(arg1, &n)) {
                Serial.print("invalid number: ");
                Serial.println(arg1);
            }
        }

        for(long i=0; i<n; ++i) {
            step_state = SS_INST;
            while(step_state != SS_NONE) {
                controlLoop();

                if(!processorCanBeStepped()) {
                    Serial.println("aborting: processor in incorrect state for stepping");
                    step_state = SS_NONE;
                }
            }
        }
    } else if(strprefixeq(cmd, "reset") && (n_tokens == 1)) {
        pull_rst_low = !pull_rst_low;
        Serial.print("~rst ");
        Serial.println(pull_rst_low ? "low" : "high");
    } else {
        Serial.println("unknown command");
        printHelp();
    }

    return startSerialPrompt();
}
<|endoftext|>


<commit_before>//auto data = stream->getReceivedData();
//PeerMessage msg(data);
#include "IncomingPeersListener.h"
#include "Configuration.h"
#include "utils/TcpAsyncServer.h"
#include "PeerMessage.h"
#include "utils/UpnpPortMapping.h"

mtt::IncomingPeersListener::IncomingPeersListener(std::function<void(std::shared_ptr<TcpAsyncStream>, const uint8_t* hash)> cb)
{
	onNewPeer = cb;
	pool.start(2);

	createListener();

	upnpEnabled = mtt::config::getExternal().connection.upnpPortMapping;
	upnp = std::make_shared<UpnpPortMapping>(pool.io);

	if (upnpEnabled)
	{
		upnp->mapActiveAdapters(mtt::config::getExternal().connection.tcpPort, UpnpPortMapping::PortType::Tcp);
		upnp->mapActiveAdapters(mtt::config::getExternal().connection.udpPort, UpnpPortMapping::PortType::Udp);
	}

	config::registerOnChangeCallback(config::ValueType::Connection, [this](config::ValueType)
		{
			auto& settings = mtt::config::getExternal().connection;

			if (settings.upnpPortMapping != upnpEnabled)
			{
				if (settings.upnpPortMapping)
				{
					upnp->mapActiveAdapters(settings.tcpPort, UpnpPortMapping::PortType::Tcp);
					upnp->mapActiveAdapters(settings.udpPort, UpnpPortMapping::PortType::Udp);
				}
				else
					upnp->unmapAllMappedAdapters(false);
			}
			else if(upnpEnabled)
			{
				if (usedPorts.udp != settings.udpPort)
				{
					upnp->unmapMappedAdapters(usedPorts.udp, UpnpPortMapping::PortType::Udp, false);
					upnp->mapActiveAdapters(settings.udpPort, UpnpPortMapping::PortType::Udp);
				}
				if (usedPorts.tcp != settings.tcpPort)
				{
					upnp->unmapMappedAdapters(usedPorts.udp, UpnpPortMapping::PortType::Tcp, false);
					upnp->mapActiveAdapters(settings.tcpPort, UpnpPortMapping::PortType::Tcp);
				}
			}

			if (usedPorts.tcp != settings.tcpPort)
				createListener();

			usedPorts.tcp = settings.tcpPort;
			usedPorts.udp = settings.udpPort;
			upnpEnabled = settings.upnpPortMapping;
		});

	usedPorts.tcp = mtt::config::getExternal().connection.tcpPort;
	usedPorts.udp = mtt::config::getExternal().connection.udpPort;
}

void mtt::IncomingPeersListener::stop()
{
	upnp->unmapAllMappedAdapters();

	listener->stop();

	std::lock_guard<std::mutex> guard(peersMutex);
	pendingPeers.clear();
}

void mtt::IncomingPeersListener::createListener()
{
	if (listener)
		listener->stop();

	listener = std::make_shared<TcpAsyncServer>(pool.io, mtt::config::getExternal().connection.tcpPort, false);
	listener->acceptCallback = [this](std::shared_ptr<TcpAsyncStream> c)
	{
		auto sPtr = c.get();

		c->onCloseCallback = [sPtr, this](int)
		{
			removePeer(sPtr);
		};
		c->onReceiveCallback = [sPtr, this]()
		{
			auto data = sPtr->getReceivedData();
			PeerMessage msg(data);

			if (msg.id == Handshake)
				addPeer(sPtr, msg.handshake.info);
			else if (msg.messageSize == 0)
				removePeer(sPtr);
		};

		std::lock_guard<std::mutex> guard(peersMutex);
		pendingPeers.push_back(c);
	};

	listener->listen();
}

void mtt::IncomingPeersListener::removePeer(TcpAsyncStream* s)
{
	std::lock_guard<std::mutex> guard(peersMutex);
	for (auto it = pendingPeers.begin(); it != pendingPeers.end(); it++)
	{
		if ((*it).get() == s)
		{
			pendingPeers.erase(it);
			break;
		}
	}
}

void mtt::IncomingPeersListener::addPeer(TcpAsyncStream* s, const uint8_t* hash)
{
	std::lock_guard<std::mutex> guard(peersMutex);
	for (auto it = pendingPeers.begin(); it != pendingPeers.end(); it++)
	{
		if ((*it).get() == s)
		{
			auto ptr = *it;
			std::vector<uint8_t> hashData;
			hashData.assign(hash, hash+20);

			pool.io.post([this, ptr, hashData]()
			{
				onNewPeer(ptr, hashData.data());
			});

			pendingPeers.erase(it);
			break;
		}
	}
}
<commit_msg>handle creation failure of tcp acceptor for listening<commit_after>//auto data = stream->getReceivedData();
//PeerMessage msg(data);
#include "IncomingPeersListener.h"
#include "Configuration.h"
#include "utils/TcpAsyncServer.h"
#include "PeerMessage.h"
#include "utils/UpnpPortMapping.h"

mtt::IncomingPeersListener::IncomingPeersListener(std::function<void(std::shared_ptr<TcpAsyncStream>, const uint8_t* hash)> cb)
{
	onNewPeer = cb;
	pool.start(2);

	createListener();

	upnpEnabled = mtt::config::getExternal().connection.upnpPortMapping;
	upnp = std::make_shared<UpnpPortMapping>(pool.io);

	if (upnpEnabled)
	{
		upnp->mapActiveAdapters(mtt::config::getExternal().connection.tcpPort, UpnpPortMapping::PortType::Tcp);
		upnp->mapActiveAdapters(mtt::config::getExternal().connection.udpPort, UpnpPortMapping::PortType::Udp);
	}

	config::registerOnChangeCallback(config::ValueType::Connection, [this](config::ValueType)
		{
			auto& settings = mtt::config::getExternal().connection;

			if (settings.upnpPortMapping != upnpEnabled)
			{
				if (settings.upnpPortMapping)
				{
					upnp->mapActiveAdapters(settings.tcpPort, UpnpPortMapping::PortType::Tcp);
					upnp->mapActiveAdapters(settings.udpPort, UpnpPortMapping::PortType::Udp);
				}
				else
					upnp->unmapAllMappedAdapters(false);
			}
			else if(upnpEnabled)
			{
				if (usedPorts.udp != settings.udpPort)
				{
					upnp->unmapMappedAdapters(usedPorts.udp, UpnpPortMapping::PortType::Udp, false);
					upnp->mapActiveAdapters(settings.udpPort, UpnpPortMapping::PortType::Udp);
				}
				if (usedPorts.tcp != settings.tcpPort)
				{
					upnp->unmapMappedAdapters(usedPorts.udp, UpnpPortMapping::PortType::Tcp, false);
					upnp->mapActiveAdapters(settings.tcpPort, UpnpPortMapping::PortType::Tcp);
				}
			}

			if (usedPorts.tcp != settings.tcpPort)
				createListener();

			usedPorts.tcp = settings.tcpPort;
			usedPorts.udp = settings.udpPort;
			upnpEnabled = settings.upnpPortMapping;
		});

	usedPorts.tcp = mtt::config::getExternal().connection.tcpPort;
	usedPorts.udp = mtt::config::getExternal().connection.udpPort;
}

void mtt::IncomingPeersListener::stop()
{
	upnp->unmapAllMappedAdapters();

	if (listener)
		listener->stop();

	std::lock_guard<std::mutex> guard(peersMutex);
	pendingPeers.clear();
}

void mtt::IncomingPeersListener::createListener()
{
	if (listener)
		listener->stop();

	try
	{
		listener = std::make_shared<TcpAsyncServer>(pool.io, mtt::config::getExternal().connection.tcpPort, false);
	}
	catch (const boost::system::system_error&)
	{
		listener = nullptr;
		return;
	}

	listener->acceptCallback = [this](std::shared_ptr<TcpAsyncStream> c)
	{
		auto sPtr = c.get();

		c->onCloseCallback = [sPtr, this](int)
		{
			removePeer(sPtr);
		};
		c->onReceiveCallback = [sPtr, this]()
		{
			auto data = sPtr->getReceivedData();
			PeerMessage msg(data);

			if (msg.id == Handshake)
				addPeer(sPtr, msg.handshake.info);
			else if (msg.messageSize == 0)
				removePeer(sPtr);
		};

		std::lock_guard<std::mutex> guard(peersMutex);
		pendingPeers.push_back(c);
	};

	listener->listen();
}

void mtt::IncomingPeersListener::removePeer(TcpAsyncStream* s)
{
	std::lock_guard<std::mutex> guard(peersMutex);
	for (auto it = pendingPeers.begin(); it != pendingPeers.end(); it++)
	{
		if ((*it).get() == s)
		{
			pendingPeers.erase(it);
			break;
		}
	}
}

void mtt::IncomingPeersListener::addPeer(TcpAsyncStream* s, const uint8_t* hash)
{
	std::lock_guard<std::mutex> guard(peersMutex);
	for (auto it = pendingPeers.begin(); it != pendingPeers.end(); it++)
	{
		if ((*it).get() == s)
		{
			auto ptr = *it;
			std::vector<uint8_t> hashData;
			hashData.assign(hash, hash+20);

			pool.io.post([this, ptr, hashData]()
			{
				onNewPeer(ptr, hashData.data());
			});

			pendingPeers.erase(it);
			break;
		}
	}
}
<|endoftext|>


<commit_before>/*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifdef WIN32
#include "stdafx.h"
#endif

#include "sage_media_format_MPEGParser2.h"

// NativeCore.h redefines this and it makes gcc grumpy.
#ifdef _LARGEFILE64_SOURCE
#undef _LARGEFILE64_SOURCE
#endif

#include "NativeCore.h"
#include "TSBuilder.h"
#include "Demuxer.h"
#include "Remuxer.h"

typedef struct {
	REMUXER *pRemuxer;
	int inputFormat;
	int outputFormat;
	int streamFormat;
	int channel;
	DUMP *pfnOutputDump;
	jobject outStream;
	char* pFormat;

	unsigned long bytes_in, bytes_out;

	JNIEnv *env;
	jmethodID outStreamWrite;
	jbyteArray outBuf;
	int outBufSize;
} JavaRemuxer2;

static int OutputDump(void* pContext, void* pData, int nSize)
{
	JavaRemuxer2* jr = (JavaRemuxer2*)pContext;

	OUTPUT_DATA *pOutputData = (OUTPUT_DATA*)pData;
	unsigned char* pBlockData = pOutputData->data_ptr;
	int nBytes = pOutputData->bytes;
	//unsigned long dwUsedBytes;
	//unsigned long dwGroupFlag = pOutputData->group_flag;
	//int nGroupStart = pOutputData->start_offset;

	// This should reduce the number of time a byte array is created to return data.
	if (jr->outBuf == NULL) {
		jr->outBuf = (jbyteArray)jr->env->NewGlobalRef(jr->env->NewByteArray(nBytes));
		jr->outBufSize = nBytes;
	} else
	// When the array isn't exactly the same size as the data being returned,
	// sometimes it will cause the JVM to crash.
	if (jr->outBufSize != nBytes)
	{
		jr->env->DeleteGlobalRef(jr->outBuf);
		jr->outBuf = (jbyteArray)jr->env->NewGlobalRef(jr->env->NewByteArray(nBytes));
		jr->outBufSize = nBytes;
	}

	jr->env->SetByteArrayRegion(jr->outBuf, 0, nBytes, (jbyte*)pBlockData);

	jr->env->CallVoidMethod(jr->outStream, jr->outStreamWrite, jr->outBuf, 0, nBytes);
	jr->bytes_out += nBytes;

	return nBytes;
}

static int AVInfDump(void* pContext, void* pData, int nSize) {
	JavaRemuxer2* jr = (JavaRemuxer2*)pContext;

	// Clear the queue so we can go back to the begining of the stream
	// without accidentally writing data out of order.
	QueueZeroDemux(jr->pRemuxer->demuxer);

	// Allocate a copy since this is locally instantiated.
	jr->pFormat = (char*)malloc(nSize);
	memcpy(jr->pFormat, (char*)pData, nSize);

	return nSize;
}

/*
* Class:     sage_media_format_MPEGParser
* Method:    openRemuxer0
* Signature: (IIIIBSSSSSLjava/io/OutputStream;)J
*/
JNIEXPORT jlong JNICALL Java_sage_media_format_MPEGParser2_openRemuxer0
  (JNIEnv *env, jclass jc, jint inputFormat, jint outputFormat, jint streamFormat, jint subFormat, jbyte tuneStringType, jshort channel, jshort tsid, jshort data1, jshort data2, jshort data3, jobject outputStreamCallback)
{
	TUNE tune = { 0 };

	//3:xx-xx-xx; 2:xx-xx; 1: program; 0:channel
	tune.tune_string_type = tuneStringType;
	if (tuneStringType == 0)
	{
		tune.channel = channel;
	}
	else
	{
		tune.u.unkn.tsid = tsid;
		tune.u.unkn.data1 = data1;
		tune.u.unkn.data2 = data2;
		tune.u.unkn.data3 = data3;
	}

	ConsolidateTuneParam(&tune, streamFormat, subFormat);

	JavaRemuxer2 *jr = (JavaRemuxer2*)malloc(sizeof(JavaRemuxer2));

	jr->inputFormat = inputFormat;
	jr->outputFormat = outputFormat;
	jr->streamFormat = streamFormat;
	jr->channel = channel;
	jr->pFormat = 0;
	jr->outBuf = 0;
	jr->outBufSize = 0;
	jr->outStream = env->NewGlobalRef(outputStreamCallback);
	// This pointer is always used to call the output method which
	// will always be called by the same thread pushing data in.
	jr->env = env;
	// This ID will never change.
	jr->outStreamWrite = env->GetMethodID(env->FindClass("java/io/OutputStream"), "write", "([BII)V");

	jr->pRemuxer = (REMUXER*)OpenRemuxStream(REMUX_STREAM, &tune, inputFormat, outputFormat, NULL, NULL, (DUMP)OutputDump, jr);

	SetupEPGDumpLanguage(jr->pRemuxer, LANGUAGE_CODE("eng"));
	SetDefaultAudioLanguage(jr->pRemuxer, LANGUAGE_CODE("eng"));

	SetupAVInfDump(jr->pRemuxer, (DUMP)AVInfDump, jr);

	return (jlong)jr;
}

/*
* Class:     sage_media_format_MPEGParser2
* Method:    closeRemuxer0
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_sage_media_format_MPEGParser2_closeRemuxer0
  (JNIEnv *env, jclass jc, jlong ptr)
{
	if (!ptr) return;

	JavaRemuxer2* jr = (JavaRemuxer2*)ptr;

	// This pointer is always used to call the output method which
	// will always be called by the same thread pushing data in.
	jr->env = env;

	if (jr->pRemuxer != NULL)
		CloseRemuxStream(jr->pRemuxer);

	if (jr->outBufSize > 0)
		env->DeleteGlobalRef(jr->outBuf);

	env->DeleteGlobalRef(jr->outStream);

	if (jr->pFormat != NULL)
		free(jr->pFormat);

	free(jr);
}

/*
* Class:     sage_media_format_MPEGParser2
* Method:    pushRemuxData0
* Signature: (J[BII)J
*/
JNIEXPORT jlong JNICALL Java_sage_media_format_MPEGParser2_pushRemuxData0
  (JNIEnv *env, jclass jc, jlong ptr, jbyteArray javabuf, jint offset, jint length)
{
	if (!ptr) return -1;
	if (length == 0) return 0;

	JavaRemuxer2* jr = (JavaRemuxer2*)ptr;

	// This pointer is always used to call the output method which
	// will always be called by the same thread pushing data in.
	jr->env = env;

	jbyte* newData = env->GetByteArrayElements(javabuf, NULL);
	unsigned char* pStart = (unsigned char*)(newData + offset);

	// This variable is being passed, but since 188 byte alignment is being done in
	// Java, unless we start to see other byte alignments, I can't think of a good
	// reason to return this value to the JVM.
	int nExpectedBytes2;
	int nUsedBytes = PushRemuxStreamData(jr->pRemuxer, pStart, length, &nExpectedBytes2);

	jr->bytes_in += length;

	env->ReleaseByteArrayElements(javabuf, newData, JNI_ABORT);

	return (jlong)nUsedBytes;
}

/*
* Class:     sage_media_format_MPEGParser2
* Method:    getAvFormat0
* Signature: (J[)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_sage_media_format_MPEGParser2_getAvFormat0
  (JNIEnv *env, jclass jc, jlong ptr)
{
	JavaRemuxer2* jr = (JavaRemuxer2*)ptr;

	return jr->pFormat != NULL ? env->NewStringUTF(jr->pFormat) : NULL;
}<commit_msg>Converted variables to fixed width integer types.<commit_after>/*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifdef WIN32
#include "stdafx.h"
#endif

#include "sage_media_format_MPEGParser2.h"

// NativeCore.h redefines this and it makes gcc grumpy.
#ifdef _LARGEFILE64_SOURCE
#undef _LARGEFILE64_SOURCE
#endif

#include "NativeCore.h"
#include "TSBuilder.h"
#include "Demuxer.h"
#include "Remuxer.h"

typedef struct {
	REMUXER *pRemuxer;
	int32_t inputFormat;
	int32_t outputFormat;
	int32_t streamFormat;
	int32_t channel;
	DUMP *pfnOutputDump;
	jobject outStream;
	char* pFormat;

	uint64_t bytes_in, bytes_out;

	JNIEnv *env;
	jmethodID outStreamWrite;
	jbyteArray outBuf;
	int32_t outBufSize;
} JavaRemuxer2;

static int OutputDump(void* pContext, void* pData, int nSize)
{
	JavaRemuxer2* jr = (JavaRemuxer2*)pContext;

	OUTPUT_DATA *pOutputData = (OUTPUT_DATA*)pData;
	uint8_t* pBlockData = pOutputData->data_ptr;
	int32_t nBytes = pOutputData->bytes;
	//uint64_t dwUsedBytes;
	//uint64_t dwGroupFlag = pOutputData->group_flag;
	//int32_t nGroupStart = pOutputData->start_offset;

	// This should reduce the number of time a byte array is created to return data.
	if (jr->outBuf == NULL) {
		jr->outBuf = (jbyteArray)jr->env->NewGlobalRef(jr->env->NewByteArray(nBytes));
		jr->outBufSize = nBytes;
	} else
	// When the array isn't exactly the same size as the data being returned,
	// sometimes it will cause the JVM to crash.
	if (jr->outBufSize != nBytes)
	{
		jr->env->DeleteGlobalRef(jr->outBuf);
		jr->outBuf = (jbyteArray)jr->env->NewGlobalRef(jr->env->NewByteArray(nBytes));
		jr->outBufSize = nBytes;
	}

	jr->env->SetByteArrayRegion(jr->outBuf, 0, nBytes, (jbyte*)pBlockData);

	jr->env->CallVoidMethod(jr->outStream, jr->outStreamWrite, jr->outBuf, 0, nBytes);
	jr->bytes_out += nBytes;

	return nBytes;
}

static int AVInfDump(void* pContext, void* pData, int nSize) {
	JavaRemuxer2* jr = (JavaRemuxer2*)pContext;

	// Clear the queue so we can go back to the begining of the stream
	// without accidentally writing data out of order.
	QueueZeroDemux(jr->pRemuxer->demuxer);

	// Allocate a copy since this is locally instantiated.
	jr->pFormat = (char*)malloc(nSize);
	memcpy(jr->pFormat, (char*)pData, nSize);

	return nSize;
}

/*
* Class:     sage_media_format_MPEGParser
* Method:    openRemuxer0
* Signature: (IIIIBSSSSSLjava/io/OutputStream;)J
*/
JNIEXPORT jlong JNICALL Java_sage_media_format_MPEGParser2_openRemuxer0
  (JNIEnv *env, jclass jc, jint inputFormat, jint outputFormat, jint streamFormat, jint subFormat, jbyte tuneStringType, jshort channel, jshort tsid, jshort data1, jshort data2, jshort data3, jobject outputStreamCallback)
{
	TUNE tune = { 0 };

	//3:xx-xx-xx; 2:xx-xx; 1: program; 0:channel
	tune.tune_string_type = tuneStringType;
	if (tuneStringType == 0)
	{
		tune.channel = channel;
	}
	else
	{
		tune.u.unkn.tsid = tsid;
		tune.u.unkn.data1 = data1;
		tune.u.unkn.data2 = data2;
		tune.u.unkn.data3 = data3;
	}

	ConsolidateTuneParam(&tune, streamFormat, subFormat);

	JavaRemuxer2 *jr = (JavaRemuxer2*)malloc(sizeof(JavaRemuxer2));

	jr->inputFormat = inputFormat;
	jr->outputFormat = outputFormat;
	jr->streamFormat = streamFormat;
	jr->channel = channel;
	jr->pFormat = 0;
	jr->outBuf = 0;
	jr->outBufSize = 0;
	jr->outStream = env->NewGlobalRef(outputStreamCallback);
	// This pointer is always used to call the output method which
	// will always be called by the same thread pushing data in.
	jr->env = env;
	// This ID will never change.
	jr->outStreamWrite = env->GetMethodID(env->FindClass("java/io/OutputStream"), "write", "([BII)V");

	jr->pRemuxer = (REMUXER*)OpenRemuxStream(REMUX_STREAM, &tune, inputFormat, outputFormat, NULL, NULL, (DUMP)OutputDump, jr);

	SetupEPGDumpLanguage(jr->pRemuxer, LANGUAGE_CODE("eng"));
	SetDefaultAudioLanguage(jr->pRemuxer, LANGUAGE_CODE("eng"));

	SetupAVInfDump(jr->pRemuxer, (DUMP)AVInfDump, jr);

	return (jlong)jr;
}

/*
* Class:     sage_media_format_MPEGParser2
* Method:    closeRemuxer0
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_sage_media_format_MPEGParser2_closeRemuxer0
  (JNIEnv *env, jclass jc, jlong ptr)
{
	if (!ptr) return;

	JavaRemuxer2* jr = (JavaRemuxer2*)ptr;

	// This pointer is always used to call the output method which
	// will always be called by the same thread pushing data in.
	jr->env = env;

	if (jr->pRemuxer != NULL)
		CloseRemuxStream(jr->pRemuxer);

	if (jr->outBufSize > 0)
		env->DeleteGlobalRef(jr->outBuf);

	env->DeleteGlobalRef(jr->outStream);

	if (jr->pFormat != NULL)
		free(jr->pFormat);

	free(jr);
}

/*
* Class:     sage_media_format_MPEGParser2
* Method:    pushRemuxData0
* Signature: (J[BII)J
*/
JNIEXPORT jlong JNICALL Java_sage_media_format_MPEGParser2_pushRemuxData0
  (JNIEnv *env, jclass jc, jlong ptr, jbyteArray javabuf, jint offset, jint length)
{
	if (!ptr) return -1;
	if (length == 0) return 0;

	JavaRemuxer2* jr = (JavaRemuxer2*)ptr;

	// This pointer is always used to call the output method which
	// will always be called by the same thread pushing data in.
	jr->env = env;

	jbyte* newData = env->GetByteArrayElements(javabuf, NULL);
	unsigned char* pStart = (unsigned char*)(newData + offset);

	// This variable is being passed, but since 188 byte alignment is being done in
	// Java, unless we start to see other byte alignments, I can't think of a good
	// reason to return this value to the JVM.
	int nExpectedBytes2;
	int nUsedBytes = PushRemuxStreamData(jr->pRemuxer, pStart, length, &nExpectedBytes2);

	jr->bytes_in += length;

	env->ReleaseByteArrayElements(javabuf, newData, JNI_ABORT);

	return (jlong)nUsedBytes;
}

/*
* Class:     sage_media_format_MPEGParser2
* Method:    getAvFormat0
* Signature: (J[)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_sage_media_format_MPEGParser2_getAvFormat0
  (JNIEnv *env, jclass jc, jlong ptr)
{
	JavaRemuxer2* jr = (JavaRemuxer2*)ptr;

	return jr->pFormat != NULL ? env->NewStringUTF(jr->pFormat) : NULL;
}<|endoftext|>


<commit_before>#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <string>
#include <iostream>
#include <utility>
extern "C" {
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
}

#include <eval.hh>
#include <eval-inline.hh>
#include <util.hh>
#include <store-api.hh>

class filedes {
  int fd;

  void close() noexcept {
    if (fd != -1 && ::close(fd) == -1)
      std::cerr << "error closing file descriptor: " << strerror(errno);
  };

  public:
  filedes() : fd{-1} {};

  filedes(int fd) : fd{fd} {};

  filedes(const filedes &) = delete;

  filedes(filedes && that) : fd{that.fd} {
    that.fd = -1;
  };

  filedes & operator=(const filedes &) & = delete;

  filedes & operator=(filedes && that) & {
    close();
    fd = that.fd;
    that.fd = -1;
    return *this;
  };

  ~filedes() {
    close();
  };

  explicit operator int() {
    return fd;
  };

  explicit operator bool() {
    return fd != -1;
  };

  void set_cloexec() {
    ::fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
  };
};

extern "C" void decrypt( nix::EvalState & state
                       , const nix::Pos & pos
                       , nix::Value ** args
                       , nix::Value & v
                       ) {
  state.forceValue(*args[0]);

  auto needsPass = true;
  auto passString = std::string{};
  if (args[0]->type == nix::tNull)
    needsPass = false;
  else
    passString = state.forceStringNoCtx(*args[0], pos);

  auto name = state.forceStringNoCtx(*args[1], pos);

  auto ctx = nix::PathSet{};
  auto path = state.coerceToPath(pos, *args[2], ctx);
  nix::realiseContext(ctx);

  int pipe_fds[2];
  filedes fds[4];

  if (pipe(pipe_fds) == -1)
    throw nix::SysError("creating pipes");

  fds[0] = filedes{pipe_fds[0]};
  fds[1] = filedes{pipe_fds[1]};

  if (needsPass && pipe(pipe_fds) == -1)
    throw nix::SysError("creating pipes");

  fds[2] = filedes{pipe_fds[0]};
  fds[3] = filedes{pipe_fds[1]};

  fds[0].set_cloexec();
  fds[1].set_cloexec();
  if (needsPass)
    fds[3].set_cloexec();

  auto fourth_arg = needsPass ? std::to_string(static_cast<int>(fds[2])) : "-d";

  const char * argv[] = { "gpg2"
                        , "--batch"
                        , needsPass ? "--passphrase-fd" : "--use-agent"
                        , fourth_arg.c_str()
                        , needsPass ? "-d" : path.c_str()
                        , needsPass ? path.c_str() : NULL
                        , NULL
                        };
  switch (fork()) {
    case -1:
      throw nix::SysError("forking to run gpg2");
    case 0:
      if (dup2(static_cast<int>(fds[1]), STDOUT_FILENO) == -1) {
        perror("duping pipe to stdout");
        _exit(213);
      }
      /* const-correct because execv swears not to modify argv */
      execv(GPG, const_cast<char **>(argv));
      perror("executing gpg");
      _exit(212);
  }

  if (needsPass) {
    nix::writeFull( static_cast<int>(fds[3])
                  , reinterpret_cast<const unsigned char *>(passString.c_str())
                  , passString.size()
                  );

    fds[3] = filedes{};
  }

  fds[1] = filedes{};

  /* nix has no way to stream a file to the store, so just stuff everything
   * into a string */
  auto contents = nix::drainFD(static_cast<int>(fds[0]));

  int status;
  while(wait(&status) == -1);
  if (WIFEXITED(status)) {
    if (WEXITSTATUS(status))
      throw nix::EvalError(boost::format("gpg2 exited with non-zero exit code %1%")
          % WEXITSTATUS(status));
  } else
    throw nix::EvalError(boost::format("gpg2 killed by signal %1%")
        % WTERMSIG(status));

  auto res = nix::store->addTextToStore( name
                                       , contents
                                       , nix::PathSet{}
                                       );

  nix::mkString(v, res, nix::PathSet{res});
}
<commit_msg>decrypt-file: Only set up the second pipe if the passphrase is needed<commit_after>#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <string>
#include <iostream>
#include <utility>
extern "C" {
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
}

#include <eval.hh>
#include <eval-inline.hh>
#include <util.hh>
#include <store-api.hh>

class filedes {
  int fd;

  void close() noexcept {
    if (fd != -1 && ::close(fd) == -1)
      std::cerr << "error closing file descriptor: " << strerror(errno);
  };

  public:
  filedes() : fd{-1} {};

  filedes(int fd) : fd{fd} {};

  filedes(const filedes &) = delete;

  filedes(filedes && that) : fd{that.fd} {
    that.fd = -1;
  };

  filedes & operator=(const filedes &) & = delete;

  filedes & operator=(filedes && that) & {
    close();
    fd = that.fd;
    that.fd = -1;
    return *this;
  };

  ~filedes() {
    close();
  };

  explicit operator int() {
    return fd;
  };

  explicit operator bool() {
    return fd != -1;
  };

  void set_cloexec() {
    ::fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
  };
};

extern "C" void decrypt( nix::EvalState & state
                       , const nix::Pos & pos
                       , nix::Value ** args
                       , nix::Value & v
                       ) {
  state.forceValue(*args[0]);

  auto needsPass = true;
  auto passString = std::string{};
  if (args[0]->type == nix::tNull)
    needsPass = false;
  else
    passString = state.forceStringNoCtx(*args[0], pos);

  auto name = state.forceStringNoCtx(*args[1], pos);

  auto ctx = nix::PathSet{};
  auto path = state.coerceToPath(pos, *args[2], ctx);
  nix::realiseContext(ctx);

  int pipe_fds[2];
  filedes fds[4];

  if (pipe(pipe_fds) == -1)
    throw nix::SysError("creating pipes");

  fds[0] = filedes{pipe_fds[0]};
  fds[1] = filedes{pipe_fds[1]};

  if (needsPass) {
    if (pipe(pipe_fds) == -1)
      throw nix::SysError("creating pipes");

    fds[2] = filedes{pipe_fds[0]};
    fds[3] = filedes{pipe_fds[1]};
  }

  fds[0].set_cloexec();
  fds[1].set_cloexec();
  if (needsPass)
    fds[3].set_cloexec();

  auto fourth_arg = needsPass ? std::to_string(static_cast<int>(fds[2])) : "-d";

  const char * argv[] = { "gpg2"
                        , "--batch"
                        , needsPass ? "--passphrase-fd" : "--use-agent"
                        , fourth_arg.c_str()
                        , needsPass ? "-d" : path.c_str()
                        , needsPass ? path.c_str() : NULL
                        , NULL
                        };
  switch (fork()) {
    case -1:
      throw nix::SysError("forking to run gpg2");
    case 0:
      if (dup2(static_cast<int>(fds[1]), STDOUT_FILENO) == -1) {
        perror("duping pipe to stdout");
        _exit(213);
      }
      /* const-correct because execv swears not to modify argv */
      execv(GPG, const_cast<char **>(argv));
      perror("executing gpg");
      _exit(212);
  }

  if (needsPass) {
    nix::writeFull( static_cast<int>(fds[3])
                  , reinterpret_cast<const unsigned char *>(passString.c_str())
                  , passString.size()
                  );

    fds[3] = filedes{};
  }

  fds[1] = filedes{};

  /* nix has no way to stream a file to the store, so just stuff everything
   * into a string */
  auto contents = nix::drainFD(static_cast<int>(fds[0]));

  int status;
  while(wait(&status) == -1);
  if (WIFEXITED(status)) {
    if (WEXITSTATUS(status))
      throw nix::EvalError(boost::format("gpg2 exited with non-zero exit code %1%")
          % WEXITSTATUS(status));
  } else
    throw nix::EvalError(boost::format("gpg2 killed by signal %1%")
        % WTERMSIG(status));

  auto res = nix::store->addTextToStore( name
                                       , contents
                                       , nix::PathSet{}
                                       );

  nix::mkString(v, res, nix::PathSet{res});
}
<|endoftext|>


<commit_before><commit_msg>Attempt to fix a buildbot.<commit_after><|endoftext|>


<commit_before>#include "src/triangle.h"

// simplest case: will plot either a flat bottom or flat top triangles
enum TriangleType
{
    FLAT_BOTTOM,
    FLAT_TOP
};

// internal triangle renderer based on triangle type
void drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type);

// draw the triangle!
void drawTriangle(const Triangle *t, unsigned char *buffer)
{
    const Vertex *v0, *v1, *v2;

    v0 = &t->vertices[0];
    v1 = &t->vertices[1];
    v2 = &t->vertices[2];

    // sort vertices so that v0 is topmost, then v1, then v2
    if(v0->position.y > v1->position.y)
    {
        v0 = &t->vertices[1];
        v1 = &t->vertices[0];
    }

    if(v0->position.y > v2->position.y)
    {
        v2 = v0;
        v0 = &t->vertices[2];
    }

    // degenerate triangle?
    //if((int)v0->position.y == (int)v2->position.y)
    //    return;

    if(v1->position.y == v2->position.y)
        drawTriangleType(t, v0, v1, v2, buffer, FLAT_BOTTOM);
    else if(v0->position.y == v1->position.y)
        drawTriangleType(t, v2, v1, v0, buffer, FLAT_TOP);
    else
    {
        Vertex v3;

        if(v2->position.y > v1->position.y)
        {
            const Vertex *tmp = v2;
            v2 = v1;
            v1 = tmp;
        }

        v3.position.x = v0->position.x + ((float)(v2->position.y - v0->position.y) / (float)(v1->position.y - v0->position.y)) * (v1->position.x - v0->position.x);
        v3.position.y = v2->position.y;
        v3.position.z = v2->position.z;
        v3.uv.u = v1->uv.u * 0.5;
        v3.uv.v = v1->uv.v * 0.5;

        // more degenerate triangle tests
        //if((int)v0->position.y == (int)v3.position.y)
        //    return;

        //if((int)v0->position.y == (int)v2->position.y)
        //    return;

        drawTriangleType(t, v0, &v3, v2, buffer, FLAT_BOTTOM);

        //if((int)v1->position.y == (int)v3.position.y)
        //    return;

        //if((int)v1->position.y == (int)v2->position.y)
        //    return;

        drawTriangleType(t, v1, &v3, v2, buffer, FLAT_TOP);
    }
}

/*
* Render counter clockwise (v0->v1->v2) for wanted effect.
* v0         v0----v1
* |\         |     /
* | \        |    /
* |  \       |   /
* |   \      |  /
* |    \     | /
* |     \    |/
* v2-----v1  v2
*/
void drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type)
{
    double invDy, dxLeft, dxRight, xLeft, xRight;
    double x, y, yDir = 1;

    if(type == FLAT_BOTTOM)
    {
        invDy  = 1.f / (v2->position.y - v0->position.y);
    }
    else
    {
        invDy  = 1.f / (v0->position.y - v2->position.y);
        yDir = -1;
    }
    dxLeft  = (v2->position.x - v0->position.x) * invDy;
    dxRight = (v1->position.x - v0->position.x) * invDy;
    xLeft  = v0->position.x;
    xRight = xLeft;

    if(!t->texture)
    {
        for(y = v0->position.y; ; y += yDir)
        {
            // to avoid pixel wide gaps, render extra line at the junction between two final points
            if(type == FLAT_TOP && y < v2->position.y)
            {
                //drawLine(xLeft-dxLeft, y, xRight-dxRight, y, t->color, buffer);
                break;
            }
            else if(type == FLAT_BOTTOM && y > v2->position.y)
            {
                drawLine(xLeft-dxLeft, y, xRight-dxRight, y, t->color, buffer);
                break;
            }

            drawLine(xLeft, y, xRight, y, t->color, buffer);
            xLeft += dxLeft;
            xRight += dxRight;

        }
    }
    else
    {
        float texW = t->texture->width - 1;
        float texH = t->texture->height - 1;
        float duLeft =  texW * (v2->uv.u - v0->uv.u) * invDy;
        float dvLeft =  texH * (v2->uv.v - v0->uv.v) * invDy;
        float duRight = texW * (v1->uv.u - v0->uv.u) * invDy;
        float dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;

        float uLeft = texW * v0->uv.u;
        float uRight = uLeft;
        float vLeft = texH * v0->uv.v;
        float vRight = vLeft;
        int startY = v0->position.y;
        int endY = v2->position.y;

        setPalette(t->texture->palette);

        if(type == FLAT_BOTTOM)
            y = startY;
        else
        {
            startY = v2->position.y;
            endY   = v0->position.y;
            y = endY;
        }

        for(; ; y += yDir)
        {
            int startX = xLeft;
            int endX  = xRight;
            float u = uLeft;
            float v = vLeft;
            float du, dv;
            float dx = endX - startX;

            if(dx > 0)
            {
                du = (uRight - uLeft) / dx;
                dv = (vRight - vLeft) / dx;
            }
            else
            {
                du = uRight - uLeft;
                dv = vRight - vLeft;
            }

            for(x = startX; x <= endX; ++x)
            {
                byte pixel = t->texture->data[(int)u + ((int)v << 6)];
                drawPixel(x, y, pixel, buffer);
                u += du;
                v += dv;
            }

            xLeft += dxLeft;
            xRight += dxRight;
            uLeft += duLeft;
            uRight += duRight;
            vLeft += dvLeft;
            vRight += dvRight;

           if(type == FLAT_BOTTOM && y >= endY)
                break;
            else if ( type == FLAT_TOP && y <= startY)
                break;
        }
    }
}
<commit_msg>avoid rendering glitches with textured triangles<commit_after>#include "src/triangle.h"

// simplest case: will plot either a flat bottom or flat top triangles
enum TriangleType
{
    FLAT_BOTTOM,
    FLAT_TOP
};

// internal triangle renderer based on triangle type
void drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type);

// draw the triangle!
void drawTriangle(const Triangle *t, unsigned char *buffer)
{
    const Vertex *v0, *v1, *v2;

    v0 = &t->vertices[0];
    v1 = &t->vertices[1];
    v2 = &t->vertices[2];

    // sort vertices so that v0 is topmost, then v1, then v2
    if(v0->position.y > v1->position.y)
    {
        v0 = &t->vertices[1];
        v1 = &t->vertices[0];
    }

    if(v0->position.y > v2->position.y)
    {
        v2 = v0;
        v0 = &t->vertices[2];
    }

    // degenerate triangle?
    //if((int)v0->position.y == (int)v2->position.y)
    //    return;

    if(v1->position.y == v2->position.y)
        drawTriangleType(t, v0, v1, v2, buffer, FLAT_BOTTOM);
    else if(v0->position.y == v1->position.y)
        drawTriangleType(t, v2, v1, v0, buffer, FLAT_TOP);
    else
    {
        Vertex v3;

        if(v2->position.y > v1->position.y)
        {
            const Vertex *tmp = v2;
            v2 = v1;
            v1 = tmp;
        }

        v3.position.x = v0->position.x + ((float)(v2->position.y - v0->position.y) / (float)(v1->position.y - v0->position.y)) * (v1->position.x - v0->position.x);
        v3.position.y = v2->position.y;
        v3.position.z = v2->position.z;
        v3.uv.u = v1->uv.u * 0.5;
        v3.uv.v = v1->uv.v * 0.5;

        // more degenerate triangle tests
        //if((int)v0->position.y == (int)v3.position.y)
        //    return;

        //if((int)v0->position.y == (int)v2->position.y)
        //    return;

        drawTriangleType(t, v0, &v3, v2, buffer, FLAT_BOTTOM);

        //if((int)v1->position.y == (int)v3.position.y)
        //    return;

        //if((int)v1->position.y == (int)v2->position.y)
        //    return;

        drawTriangleType(t, v1, &v3, v2, buffer, FLAT_TOP);
    }
}

/*
* Render counter clockwise (v0->v1->v2) for wanted effect.
* v0         v0----v1
* |\         |     /
* | \        |    /
* |  \       |   /
* |   \      |  /
* |    \     | /
* |     \    |/
* v2-----v1  v2
*/
void drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type)
{
    double invDy, dxLeft, dxRight, xLeft, xRight;
    double x, y, yDir = 1;

    if(type == FLAT_BOTTOM)
    {
        invDy  = 1.f / (v2->position.y - v0->position.y);
    }
    else
    {
        invDy  = 1.f / (v0->position.y - v2->position.y);
        yDir = -1;
    }
    dxLeft  = (v2->position.x - v0->position.x) * invDy;
    dxRight = (v1->position.x - v0->position.x) * invDy;
    xLeft  = v0->position.x;
    xRight = xLeft;

    if(!t->texture)
    {
        for(y = v0->position.y; ; y += yDir)
        {
            // to avoid pixel wide gaps, render extra line at the junction between two final points
            if(type == FLAT_TOP && y < v2->position.y)
            {
                //drawLine(xLeft-dxLeft, y, xRight-dxRight, y, t->color, buffer);
                break;
            }
            else if(type == FLAT_BOTTOM && y > v2->position.y)
            {
                drawLine(xLeft-dxLeft, y, xRight-dxRight, y, t->color, buffer);
                break;
            }

            drawLine(xLeft, y, xRight, y, t->color, buffer);
            xLeft += dxLeft;
            xRight += dxRight;

        }
    }
    else
    {
        float texW = t->texture->width - 1;
        float texH = t->texture->height - 1;
        float duLeft =  texW * (v2->uv.u - v0->uv.u) * invDy;
        float dvLeft =  texH * (v2->uv.v - v0->uv.v) * invDy;
        float duRight = texW * (v1->uv.u - v0->uv.u) * invDy;
        float dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;

        float uLeft = texW * v0->uv.u;
        float uRight = uLeft;
        float vLeft = texH * v0->uv.v;
        float vRight = vLeft;
        int startY = v0->position.y;
        int endY = v2->position.y;

        setPalette(t->texture->palette);

        if(type == FLAT_BOTTOM)
            y = startY;
        else
        {
            startY = v2->position.y;
            endY   = v0->position.y;
            y = endY;
        }

        for(; ; y += yDir)
        {
            int startX = xLeft;
            int endX  = xRight;
            float u = uLeft;
            float v = vLeft;
            float du, dv;
            float dx = endX - startX;

           if(type == FLAT_BOTTOM && y > v2->position.y)
                break;
            else if ( type == FLAT_TOP && y < v2->position.y)
                break;

            if(dx > 0)
            {
                du = (uRight - uLeft) / dx;
                dv = (vRight - vLeft) / dx;
            }
            else
            {
                du = uRight - uLeft;
                dv = vRight - vLeft;
            }

            for(x = startX; x <= endX; ++x)
            {
                byte pixel = t->texture->data[(int)u + ((int)v << 6)];
                drawPixel(x, y, pixel, buffer);
                u += du;
                v += dv;
            }

            xLeft += dxLeft;
            xRight += dxRight;
            uLeft += duLeft;
            uRight += duRight;
            vLeft += dvLeft;
            vRight += dvRight;
        }
    }
}
<|endoftext|>


<commit_before>#include "SyntaxTree.h"

#include <list>
#include <vector>
#include <sstream>
#include <iostream>
#include <stdexcept>

#include <boost/format.hpp>

#include "template.common.h"
#include "template.cs.h"

using namespace std;

// class Node
// {
// public:
    Node::~Node()
    {
    }

    int Node::getType() { return 0; } //TODO: remove getType() if unnecessary
    int Node::getHash(vector<Node*>* referencingStack) { return 0; }
    string* Node::getParsed(int as) { return 0; }

// };

// class NodeKst : public Node
// {
    // list<Node*>* commands;
    // string* fileName;
    // public:
    NodeKst::NodeKst(list<Node*>* _commands, string* _fileName) : Node()
    {
        commands = _commands;
        fileName = _fileName;
    }

    int NodeKst::getType()
    {
       return CsNodeType::kst;
    }

    int NodeKst::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodeKst::getParsed(int as)
    {
        stringstream parsed;

        parsed << boost::format(TCS_HEADER) % *fileName;
        parsed << TCS_USINGS;

        string namespaceByFileName = fileName->substr(0, fileName->find("."));

        parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;

        list<Node*>::iterator i = commands->begin();
        list<Node*>::iterator end = commands->end();

        string* temp;

        for (; i != end; ++i)
        {
            temp = (*i)->getParsed(CsParseAs::Default);
            temp = indent(temp);
            parsed << *temp;
            parsed << "\n";
        }

        parsed << TCS_NAMESPACE_END;

        parsed << "\n\n";

        return new string(parsed.str());
    }
// };

// class NodeInclude : public Node
// {
//     string* value;
//     public:
    NodeInclude::NodeInclude(string* _value) : Node()
    {
        value = _value;
    }

    int NodeInclude::getType()
    {
       return CsNodeType::include;
    }

    int NodeInclude::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodeInclude::getParsed(int as)
    {
        stringstream parsed;

        parsed << "#include \"";
        parsed << *(value);
        parsed << "\"";

        return new string(parsed.str());
    }
// };

// class NodePacket : public Node
// {
//     string* packetName;
//     list<Node*>* packetMembers;
//     public:
    NodePacket::NodePacket(string* _packetName, list<Node*>* _packetMembers) : Node()
    {
        packetName = _packetName;
        packetMembers = _packetMembers;
    }

    int NodePacket::getType()
    {
       return CsNodeType::packet;
    }

    int NodePacket::getHash(vector<Node*>* referencingStack)
    {
        if (referencingStack == NULL)
        {
            referencingStack = new vector<Node*>();
        }

        referencingStack->push_back(this);

        int packetNameHash = getHashCode(packetName);
        cout << "packetNameHash: " << packetNameHash << "\n";
        // TODO: iterate packet members and get each hash
        // TODO: combine all the hashes

        return 0;
    }

    string* NodePacket::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;
                list<Node*>::iterator i = packetMembers->begin();
                list<Node*>::iterator end = packetMembers->end();
                for (; i != end; ++i)
                {
                    parsed << "\t" << *((*i)->getParsed(CsParseAs::Default));
                }
                parsed << TCS_PACKET_END;
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMember : public Node
// {
//     Node* memberType;
//     Node* memberName;
//     public:
    NodePacketMember::NodePacketMember(Node* _memberType, Node* _memberName) : Node()
    {
        memberType = _memberType;
        memberName = _memberName;
    }

    int NodePacketMember::getType()
    {
       return CsNodeType::packetMember;
    }

    int NodePacketMember::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodePacketMember::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)
                    % *(memberType->getParsed(CsParseAs::Default))
                    % *(memberName->getParsed(CsParseAs::Default));
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberType : public Node
// {
//     int typeType; // one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST
//     string* value; // "int", "bool", ..., "MyPacket", "Skill" or NULL when type is MAP or LIST
//     Node* generic1; // LIST<generic1>
//     Node* generic2; // MAP <generic1, generic2>
//     Node* generic3; // reserved
//     public:
    NodePacketMemberType::NodePacketMemberType(int _type, string* _value) : Node()
    {
        typeType = _type;
        value = _value;
        generic1 = NULL;
        generic2 = NULL;
        generic3 = NULL;
    }

    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1) : Node()
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = NULL;
        generic3 = NULL;
    }

    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2) : Node()
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = NULL;
    }

    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node()
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = _generic3;
    }

    int NodePacketMemberType::getType()
    {
       return CsNodeType::packetMemberType;
    }

    int NodePacketMemberType::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodePacketMemberType::getParsed(int as)
    {
        stringstream parsed;

        switch (typeType) {

            case Rakjin::Krystal::Parser::token::PRIMITIVE_DATA_TYPE:
            parsed << *value;
            break;

            case Rakjin::Krystal::Parser::token::REFERENCE_DATA_TYPE:
            parsed << *value;
            break;

            case Rakjin::Krystal::Parser::token::MAP:
            parsed << "Dictionary";
            parsed << "<" << *(generic1->getParsed(CsParseAs::Default)) << ", " << *(generic2->getParsed(CsParseAs::Default)) << ">";
            break;

            case Rakjin::Krystal::Parser::token::LIST:
            parsed << "List";
            parsed << "<" << *(generic1->getParsed(CsParseAs::Default)) << ">";
            break;

            default:
            throw(runtime_error("Unknown NodePacketMemberType type."));
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberName : public Node
// {
//     string* value;
//     public:
    NodePacketMemberName::NodePacketMemberName(string* _value) : Node()
    {
        value = _value;
    }

    int NodePacketMemberName::getType()
    {
       return CsNodeType::packetMemberName;
    }

    int NodePacketMemberName::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodePacketMemberName::getParsed(int as)
    {
       return value;
    }
// };

<commit_msg>(trivial) change variable name<commit_after>#include "SyntaxTree.h"

#include <list>
#include <vector>
#include <sstream>
#include <iostream>
#include <stdexcept>

#include <boost/format.hpp>

#include "template.common.h"
#include "template.cs.h"

using namespace std;

// class Node
// {
// public:
    Node::~Node()
    {
    }

    int Node::getType() { return 0; } //TODO: remove getType() if unnecessary
    int Node::getHash(vector<Node*>* referencingStack) { return 0; }
    string* Node::getParsed(int as) { return 0; }

// };

// class NodeKst : public Node
// {
    // list<Node*>* commands;
    // string* fileName;
    // public:
    NodeKst::NodeKst(list<Node*>* _commands, string* _fileName) : Node()
    {
        commands = _commands;
        fileName = _fileName;
    }

    int NodeKst::getType()
    {
       return CsNodeType::kst;
    }

    int NodeKst::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodeKst::getParsed(int as)
    {
        stringstream parsed;

        parsed << boost::format(TCS_HEADER) % *fileName;
        parsed << TCS_USINGS;

        string namespaceByFileName = fileName->substr(0, fileName->find("."));

        parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;

        list<Node*>::iterator i = commands->begin();
        list<Node*>::iterator end = commands->end();

        string* temp;

        for (; i != end; ++i)
        {
            temp = (*i)->getParsed(CsParseAs::Default);
            temp = indent(temp);
            parsed << *temp;
            parsed << "\n";
        }

        parsed << TCS_NAMESPACE_END;

        parsed << "\n\n";

        return new string(parsed.str());
    }
// };

// class NodeInclude : public Node
// {
//     string* value;
//     public:
    NodeInclude::NodeInclude(string* _value) : Node()
    {
        value = _value;
    }

    int NodeInclude::getType()
    {
       return CsNodeType::include;
    }

    int NodeInclude::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodeInclude::getParsed(int as)
    {
        stringstream parsed;

        parsed << "#include \"";
        parsed << *(value);
        parsed << "\"";

        return new string(parsed.str());
    }
// };

// class NodePacket : public Node
// {
//     string* packetName;
//     list<Node*>* packetMembers;
//     public:
    NodePacket::NodePacket(string* _packetName, list<Node*>* _packetMembers) : Node()
    {
        packetName = _packetName;
        packetMembers = _packetMembers;
    }

    int NodePacket::getType()
    {
       return CsNodeType::packet;
    }

    int NodePacket::getHash(vector<Node*>* referencingStack)
    {
        if (referencingStack == NULL)
        {
            referencingStack = new vector<Node*>();
        }

        referencingStack->push_back(this);

        int packetHash = getHashCode(packetName);
        cout << "packetHash: " << packetHash << "\n";
        // TODO: iterate packet members and get each hash
        // TODO: combine all the hashes

        return 0;
    }

    string* NodePacket::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;
                list<Node*>::iterator i = packetMembers->begin();
                list<Node*>::iterator end = packetMembers->end();
                for (; i != end; ++i)
                {
                    parsed << "\t" << *((*i)->getParsed(CsParseAs::Default));
                }
                parsed << TCS_PACKET_END;
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMember : public Node
// {
//     Node* memberType;
//     Node* memberName;
//     public:
    NodePacketMember::NodePacketMember(Node* _memberType, Node* _memberName) : Node()
    {
        memberType = _memberType;
        memberName = _memberName;
    }

    int NodePacketMember::getType()
    {
       return CsNodeType::packetMember;
    }

    int NodePacketMember::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodePacketMember::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)
                    % *(memberType->getParsed(CsParseAs::Default))
                    % *(memberName->getParsed(CsParseAs::Default));
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberType : public Node
// {
//     int typeType; // one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST
//     string* value; // "int", "bool", ..., "MyPacket", "Skill" or NULL when type is MAP or LIST
//     Node* generic1; // LIST<generic1>
//     Node* generic2; // MAP <generic1, generic2>
//     Node* generic3; // reserved
//     public:
    NodePacketMemberType::NodePacketMemberType(int _type, string* _value) : Node()
    {
        typeType = _type;
        value = _value;
        generic1 = NULL;
        generic2 = NULL;
        generic3 = NULL;
    }

    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1) : Node()
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = NULL;
        generic3 = NULL;
    }

    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2) : Node()
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = NULL;
    }

    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node()
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = _generic3;
    }

    int NodePacketMemberType::getType()
    {
       return CsNodeType::packetMemberType;
    }

    int NodePacketMemberType::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodePacketMemberType::getParsed(int as)
    {
        stringstream parsed;

        switch (typeType) {

            case Rakjin::Krystal::Parser::token::PRIMITIVE_DATA_TYPE:
            parsed << *value;
            break;

            case Rakjin::Krystal::Parser::token::REFERENCE_DATA_TYPE:
            parsed << *value;
            break;

            case Rakjin::Krystal::Parser::token::MAP:
            parsed << "Dictionary";
            parsed << "<" << *(generic1->getParsed(CsParseAs::Default)) << ", " << *(generic2->getParsed(CsParseAs::Default)) << ">";
            break;

            case Rakjin::Krystal::Parser::token::LIST:
            parsed << "List";
            parsed << "<" << *(generic1->getParsed(CsParseAs::Default)) << ">";
            break;

            default:
            throw(runtime_error("Unknown NodePacketMemberType type."));
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberName : public Node
// {
//     string* value;
//     public:
    NodePacketMemberName::NodePacketMemberName(string* _value) : Node()
    {
        value = _value;
    }

    int NodePacketMemberName::getType()
    {
       return CsNodeType::packetMemberName;
    }

    int NodePacketMemberName::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* NodePacketMemberName::getParsed(int as)
    {
       return value;
    }
// };

<|endoftext|>