<commit_before>// generate transforms with normally distributed noise
// added to the parameters, in order to test the effectiveness
// of the diffusion transform algorithm

#include "boost/program_options.hpp"
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>

#include "itkCenteredAffineTransform.h"

#include "Dirs.hpp"
#include "IOHelpers.hpp"
#include "Stack.hpp"
#include "HiResStackBuilder.hpp"
#include "StackTransforms.hpp"
#include "StackIOHelpers.hpp"

namespace po = boost::program_options;
using namespace boost::filesystem;
using namespace boost;

typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
typedef itk::CenteredAffineTransform< double, 2 > TransformType;

po::variables_map parse_arguments(int argc, char *argv[]);

int main(int argc, char *argv[]) {
  po::variables_map vm = parse_arguments(argc, argv);

	// set directories
  Dirs::SetDataSet( "dummy" );
  Dirs::SetOutputDirName( vm["outputDir"].as<string>() );

  // initialise random number generator
  boost::mt19937 rng;
  rng.seed(static_cast<unsigned int>(std::time(0)));
  boost::normal_distribution<> nd(0.0, 1.0);
  boost::variate_generator<boost::mt19937&,
                            boost::normal_distribution<> > varGen(rng, nd);

  // construct transform output paths
  string transformsDir = Dirs::HiResTransformsDir() + "CenteredAffineTransform/";
  create_directories( transformsDir );
  vector< string > paths = constructPaths(transformsDir, Dirs::ImageList());

  // initialise stack with correct spacings, sizes etc
  HiResStackBuilder<StackType> builder;
  shared_ptr<StackType> stack = builder.getStack();
  StackTransforms::InitializeToCommonCentre< StackType >( *stack );

  // convert to CenteredAffineTransform
  StackTransforms::InitializeFromCurrentTransforms< StackType, TransformType >( *stack );

  // initialise centre of rotation
  TransformType::CenterType center;
  center[0] = getSpacings<2>("LoRes")[0] * (double)getSize()[0] / 2.0;
  center[1] = getSpacings<2>("LoRes")[1] * (double)getSize()[1] / 2.0;

  // create identity transforms with added noise
  for(unsigned int slice_number=0; slice_number<stack->GetSize(); ++slice_number)
  {
    // extract transform
    StackType::TransformType::Pointer transform = stack->GetTransform(slice_number);

    // set centre of rotation
    StackTransforms::MoveCenter(static_cast< StackTransforms::LinearTransformType* >( transform.GetPointer() ), center);

    // add noise, scaled by parameter type
    StackType::TransformType::ParametersType parameters = transform->GetParameters();
    StackType::TransformType::ParametersType scalings(8);
    scalings[0] = scalings[1] = scalings[2] = scalings[3] = 0.02; // matrix params
    scalings[4] = scalings[5] = 0;                                // rotation params
    scalings[6] = scalings[7] = 100;                              // translation params

    for(unsigned int i=0; i<8; ++i)
    {
      parameters[i] += varGen() * scalings[i];
    }

    transform->SetParameters(parameters);

    // write transform
    writeTransform(transform, paths[slice_number]);
  }

  Save(*stack, Dirs::HiResTransformsDir() + "CenteredAffineTransform/");

  stack->updateVolumes();
  writeImage< StackType::VolumeType >(stack->GetVolume(), "/Users/Matt/Desktop/stack.mha");

  return EXIT_SUCCESS;
}

po::variables_map parse_arguments(int argc, char *argv[])
{
  // Declare the supported options.
  po::options_description opts("Options");
  opts.add_options()
      ("help,h", "produce help message")
      ("outputDir", po::value<string>(), "directory to source transforms and place results")
  ;

  po::positional_options_description p;
  p.add("outputDir", 1);

  // parse command line
  po::variables_map vm;
	try
	{
  po::store(po::command_line_parser(argc, argv)
            .options(opts)
            .positional(p)
            .run(),
            vm);
	}
	catch (std::exception& e)
	{
	  cerr << "caught command-line parsing error" << endl;
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
  po::notify(vm);

  // if help is specified, or positional args aren't present
  if (vm.count("help") || !vm.count("outputDir")) {
    cerr << "Usage: "
      << argv[0] << " [--outputDir=]my_dir"
      << endl << endl;
    cerr << opts << "\n";
    exit(EXIT_FAILURE);
  }

  return vm;
}
<commit_msg>GenerateNoisyTransforms adds translation and rotation<commit_after>// generate transforms with normally distributed noise
// added to the parameters, in order to test the effectiveness
// of the diffusion transform algorithm

#define _USE_MATH_DEFINES
#include <cmath>

#include "boost/program_options.hpp"
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>

#include "itkCenteredAffineTransform.h"

#include "Dirs.hpp"
#include "IOHelpers.hpp"
#include "Stack.hpp"
#include "HiResStackBuilder.hpp"
#include "StackTransforms.hpp"
#include "StackIOHelpers.hpp"

namespace po = boost::program_options;
using namespace boost::filesystem;
using namespace boost;

typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
typedef itk::CenteredAffineTransform< double, 2 > TransformType;

po::variables_map parse_arguments(int argc, char *argv[]);

template <typename T>
vector<T> sinspace(T a, T b, size_t N);

int main(int argc, char *argv[]) {
  po::variables_map vm = parse_arguments(argc, argv);

	// set directories
  Dirs::SetDataSet( "dummy" );
  Dirs::SetOutputDirName( vm["outputDir"].as<string>() );

  // initialise random number generator
  boost::mt19937 rng;
  rng.seed(static_cast<unsigned int>(std::time(0)));
  boost::normal_distribution<> nd(0.0, 1.0);
  boost::variate_generator<boost::mt19937&,
                            boost::normal_distribution<> > varGen(rng, nd);

  // construct transform output paths
  string transformsDir = Dirs::HiResTransformsDir() + "CenteredAffineTransform/";
  create_directories( transformsDir );
  vector< string > paths = constructPaths(transformsDir, Dirs::ImageList());

  // initialise stack with correct spacings, sizes etc
  HiResStackBuilder<StackType> builder;
  shared_ptr<StackType> stack = builder.getStack();
  StackTransforms::InitializeToCommonCentre< StackType >( *stack );

  // convert to CenteredAffineTransform
  StackTransforms::InitializeFromCurrentTransforms< StackType, TransformType >( *stack );

  // initialise centre of rotation
  TransformType::CenterType center;
  center[0] = getSpacings<2>("LoRes")[0] * (double)getSize()[0] / 2.0;
  center[1] = getSpacings<2>("LoRes")[1] * (double)getSize()[1] / 2.0;

  vector<double> sine = sinspace(0.0, 2 * M_PI, stack->GetSize());

  // create identity transforms with added noise
  for(unsigned int slice_number=0; slice_number<stack->GetSize(); ++slice_number)
  {
    // extract transform
    StackType::TransformType::Pointer transform = stack->GetTransform(slice_number);

    // set centre of rotation
    StackTransforms::MoveCenter(static_cast< StackTransforms::LinearTransformType* >( transform.GetPointer() ), center);

    // add noise, scaled by parameter type
    StackType::TransformType::ParametersType parameters = transform->GetParameters();
    StackType::TransformType::ParametersType scalings(8);
    scalings[0] = scalings[1] = scalings[2] = scalings[3] = 0.02; // matrix params
    scalings[4] = scalings[5] = 0;                                // rotation params
    scalings[6] = scalings[7] = 100;                              // translation params

    for(unsigned int i=0; i<8; ++i)
    {
      parameters[i] += varGen() * scalings[i];
    }

    if(vm.count("rotation"))
    {
      double angle = sine[slice_number];
      parameters[0] += cos(angle) - 1;
      parameters[1] -= sin(angle);
      parameters[2] += sin(angle);
      parameters[3] += cos(angle) - 1;
    }

    if(vm.count("translation"))
    {
      parameters[6] += 20 * scalings[6] * sine[slice_number];
      parameters[7] += 20 * scalings[7] * sine[slice_number];
    }

    transform->SetParameters(parameters);

    // write transform
    writeTransform(transform, paths[slice_number]);
  }

  Save(*stack, Dirs::HiResTransformsDir() + "CenteredAffineTransform/");

  stack->updateVolumes();
  writeImage< StackType::VolumeType >(stack->GetVolume(), "/Users/Matt/Desktop/stack.mha");

  return EXIT_SUCCESS;
}

po::variables_map parse_arguments(int argc, char *argv[])
{
  // Declare the supported options.
  po::options_description opts("Options");
  opts.add_options()
      ("help,h", "produce help message")
      ("outputDir", po::value<string>(), "directory to source transforms and place results")
      ("translation,t", po::value<bool>()->zero_tokens(), "add translational sinusoidal signal")
      ("rotation,r",    po::value<bool>()->zero_tokens(), "add rotational sinusoidal signal")
  ;

  po::positional_options_description p;
  p.add("outputDir", 1);

  // parse command line
  po::variables_map vm;
	try
	{
  po::store(po::command_line_parser(argc, argv)
            .options(opts)
            .positional(p)
            .run(),
            vm);
	}
	catch (std::exception& e)
	{
	  cerr << "caught command-line parsing error" << endl;
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
  po::notify(vm);

  // if help is specified, or positional args aren't present
  if (vm.count("help") || !vm.count("outputDir")) {
    cerr << "Usage: "
      << argv[0] << " [--outputDir=]my_dir [OPTIONS]"
      << endl << endl;
    cerr << opts << "\n";
    exit(EXIT_FAILURE);
  }

  return vm;
}

template <typename T = double>
vector<T> linspace(T a, T b, size_t N) {
  T h = (b - a) / static_cast<T>(N-1);
  vector<T> xs(N);
  typename vector<T>::iterator x;
  T val;
  for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
    *x = val;
  return xs;
}

template <typename T = double>
vector<T> sinspace(T a, T b, size_t N) {
  vector<T> line = linspace(a, b, N);
  vector<T> sine(line.size());
  for(unsigned int i=0; i<sine.size(); ++i)
  {
    sine[i] = sin(line[i]);
  }
  return sine;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <chrono>
#include <arm_neon.h>
#include <stdlib.h>
#include <inttypes.h>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex m ;
std::condition_variable cv ;
std::chrono::high_resolution_clock::time_point mid ;
std::chrono::high_resolution_clock::time_point reset ;

int32x4_t va;
int32_t a ;
int32_t * ptr;
int32_t n = 2500;
int64_t size = sizeof(a)*n;
//int32_t mm = n-4;

void inline boost_song()
{
    using namespace std::chrono ;

    //int i{0} ;
    while( true )
    {
        std::unique_lock<std::mutex> lk{m} ;
        cv.wait( lk ) ;

        while( high_resolution_clock::now() < mid )
        {
            int32_t var[4] = { *(ptr), *(ptr + 2), *(ptr + 3), *(ptr + 4) };
            va = vld1q_s32(var);
            //i++;
        }
        //if(i==mm) i=0;
        std::this_thread::sleep_until( reset ) ;
    }
}

int init_memory(void){
    ptr = (int32_t *)malloc(size);
    if( ptr == NULL ){
        std::cout << "Malloc Error\n";
        return -1;
    }
    for(int i=0; i<=n; i++){
        ptr[i] = i;
    }
    return 0;
}

void square_am_signal(float time, float frequency)
{
    using namespace std::chrono ;

    std::cout << "Playing / " << time << " seconds / " << frequency << " Hz\n" ;

    seconds const sec{1} ;
    nanoseconds const nsec{ sec } ;
    using rep = nanoseconds::rep ;
    auto nsec_per_sec = nsec.count() ;

    nanoseconds const period( static_cast<rep>( nsec_per_sec / frequency) ) ;

    auto start = high_resolution_clock::now() ;
    auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ;

    while (high_resolution_clock::now() < end)
    {
        mid = start + period / 2 ;
        reset = start + period ;
        cv.notify_all() ;
        std::this_thread::sleep_until( reset ) ;
        start = reset;
    }
}

int main(){
    init_memory();
    for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i )
    {
        std::thread t( boost_song ) ;
        t.detach() ;
    }
    while (1)
    {
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.790, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 3136);
        square_am_signal(0.790, 3136);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2093);
    }
    free(ptr);
}
<commit_msg>add signal handler<commit_after>#include <iostream>
#include <iomanip>
#include <chrono>
#include <arm_neon.h>
#include <stdlib.h>
#include <inttypes.h>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex m ;
std::condition_variable cv ;
std::chrono::high_resolution_clock::time_point mid ;
std::chrono::high_resolution_clock::time_point reset ;

int32x4_t va;
int32_t a ;
int32_t * ptr;
int32_t n = 2500;
int64_t size = sizeof(a)*n;
static int sig{1};
//int32_t mm = n-4;

void sig_handler(int sign) {
    free(ptr);
    exit(-1);
}

void inline boost_song() {
    using namespace std::chrono ;

    //int i{0} ;
    while( true ) {
        std::unique_lock<std::mutex> lk{m} ;
        cv.wait( lk ) ;

        while( high_resolution_clock::now() < mid ) {
            int32_t var[4] = { *(ptr), *(ptr + 2), *(ptr + 3), *(ptr + 4) };
            va = vld1q_s32(var);
            //i++;
        }
        //if(i==mm) i=0;
        std::this_thread::sleep_until( reset ) ;
    }
}

int init_memory(void) {
    ptr = (int32_t *)malloc(size);
    if( ptr == NULL ){
        std::cout << "Malloc Error\n";
        return -1;
    }
    for(int i=0; i<=n; i++){
        ptr[i] = i;
    }
    return 0;
}

void square_am_signal(float time, float frequency) {
    using namespace std::chrono ;

    std::cout << "Playing / " << time << " seconds / " << frequency << " Hz\n" ;

    seconds const sec{1} ;
    nanoseconds const nsec{ sec } ;
    using rep = nanoseconds::rep ;
    auto nsec_per_sec = nsec.count() ;

    nanoseconds const period( static_cast<rep>( nsec_per_sec / frequency) ) ;

    auto start = high_resolution_clock::now() ;
    auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ;

    while (high_resolution_clock::now() < end) {
        mid = start + period / 2 ;
        reset = start + period ;
        cv.notify_all() ;
        std::this_thread::sleep_until( reset ) ;
        start = reset;
    }
}

int main(){
    signal(SIGINT, sig_handler);

    init_memory();
    for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) {
        std::thread t( boost_song ) ;
        t.detach() ;
    }
    while (1) {
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.790, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 3136);
        square_am_signal(0.790, 3136);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2093);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2349);
        square_am_signal(0.400, 2673);
        square_am_signal(0.400, 2349);
        square_am_signal(0.790, 2093);
    }
    free(ptr);
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <string>

#include <itkImage.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkLabelImageGaussianInterpolateImageFunction.h>
#include <itkBSplineInterpolateImageFunction.h>
#include <itkResampleImageFilter.h>
#include <itkVersorRigid3DTransform.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <itkTestingComparisonImageFilter.h>

#include "itkLabelImageGenericInterpolateImageFunction.h"
#include "itkLabelSelectionAdaptor.h"

/* This demo is a torture test for interpolators: it takes an input label map,
 * rotates it one full turn in ten steps, and writes the result */

template <class ImageType>
void
RotateNTimes(typename ImageType::Pointer input,
    typename itk::InterpolateImageFunction<ImageType,double>* interpolator,
    unsigned int number_of_rotations, std::string outputFilename) {
	typedef itk::VersorRigid3DTransform<double> TransformType;
	typedef itk::ResampleImageFilter<ImageType,ImageType> ResampleFilterType;
	TransformType::AxisType axis;
	axis[0]=0;
	axis[1]=1;
	axis[2]=0;
	TransformType::InputPointType center;
	center[0] = 144;
	center[1] = 86;
	center[2] = 101;
	TransformType::Pointer rot = TransformType::New();
	rot->SetCenter(center);
	rot->SetRotation(axis,2.*M_PI/number_of_rotations);

	typename ResampleFilterType::Pointer rs = ResampleFilterType::New();
	rs->SetInput( input );
	rs->SetReferenceImage( input );
	rs->SetUseReferenceImage(true);
	rs->SetTransform(rot);
	//interp->SetSigma(0.3); // Used for the gaussian interpolator
	rs->SetInterpolator(interpolator);
	typename ImageType::Pointer out ;
	for (unsigned i = 0; i<number_of_rotations; ++i) {
		rs->SetReferenceImage( input );
		rs->SetUseReferenceImage(true);
		rs->Update();
		out = rs->GetOutput();
		out->DisconnectPipeline();
		rs->SetInput(out);
		rs->SetTransform(rot);
	}
  typedef itk::Testing::ComparisonImageFilter<ImageType,ImageType> ComparisonFilterType;
  typename ComparisonFilterType::Pointer compare = ComparisonFilterType::New();
  compare->SetValidInput( input );
  compare->SetTestInput( out );
  compare->Update();
  std::cout << "Pixels with differences: " << std::setw(8) << compare->GetNumberOfPixelsWithDifferences() <<
    " ( " << std::fixed << std::setprecision(2) << static_cast<double>(compare->GetNumberOfPixelsWithDifferences()) /
    input->GetLargestPossibleRegion().GetNumberOfPixels() * 100.<<
    "% )" << std::endl;
	typedef  itk::ImageFileWriter< ImageType  > WriterType;
	typename WriterType::Pointer writer = WriterType::New();
	writer->SetUseCompression(true);
	writer->SetInput( out );
	writer->SetFileName(outputFilename);
	writer->Write();
}

// The BSpline interpolator has more arguments than other interpolators, so we set the additional parameter to the default value
using namespace std;
template<class TImage,typename TCoordRep> class BSplineInterpolator : public itk::BSplineInterpolateImageFunction<TImage,TCoordRep> {};

int main(int argc, char *argv[])
{
	string outputFilename = "resampled.mha";
	string inputFilename = "../Source/classification.mha";

	typedef unsigned char     PixelType;
	const   unsigned int    Dimension = 3;
	typedef itk::Image< PixelType, Dimension >  ImageType;

	typedef itk::ImageFileReader<ImageType> ReaderType;
	ReaderType::Pointer r = ReaderType::New();
	r->SetFileName(inputFilename);
	r->Update();

	const unsigned number_of_rotations=3;

  std::cout << "Nearest neighbor interpolator...                        " << std::flush;
	typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> NNInterpolatorType;
	NNInterpolatorType::Pointer nn_interp = NNInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), nn_interp, number_of_rotations, "nearest.mha");

  std::cout << "Linear interpolator...                                  " << std::flush;
	typedef itk::LinearInterpolateImageFunction<ImageType,double> LInterpolatorType;
	LInterpolatorType::Pointer l_interp = LInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), l_interp, number_of_rotations, "linear.mha");

  std::cout << "Label Gaussian interpolator type...                     " << std::flush;
	typedef itk::LabelImageGaussianInterpolateImageFunction<ImageType,double> LGInterpolatorType;
	LGInterpolatorType::Pointer lg_interp = LGInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), lg_interp, number_of_rotations, "label_gaussian.mha");

  std::cout << "Generic label interpolator with nearest neighbor...     " << std::flush;
	typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::NearestNeighborInterpolateImageFunction> GNNInterpolatorType;
	GNNInterpolatorType::Pointer gnn_interp = GNNInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), gnn_interp, number_of_rotations, "gl_nearest.mha");

  std::cout << "Generic label interpolator with linear interpolation... " << std::flush;
	typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::LinearInterpolateImageFunction> GLInterpolatorType;
	GLInterpolatorType::Pointer gl_interp = GLInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), gl_interp, number_of_rotations, "gl_linear.mha");

  std::cout << "Generic label interpolator with B-Spline...             " << std::flush;
	typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,BSplineInterpolator> GBSInterpolatorType;
	GBSInterpolatorType::Pointer gbs_interp = GBSInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), gbs_interp, number_of_rotations, "gl_bspline.mha");

	return EXIT_SUCCESS;
}
<commit_msg>stopwatch<commit_after>#include <iostream>
#include <iomanip>
#include <string>

#include <itkImage.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkLabelImageGaussianInterpolateImageFunction.h>
#include <itkBSplineInterpolateImageFunction.h>
#include <itkResampleImageFilter.h>
#include <itkVersorRigid3DTransform.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <itkTestingComparisonImageFilter.h>
#include <itkTimeProbe.h>

#include "itkLabelImageGenericInterpolateImageFunction.h"
#include "itkLabelSelectionAdaptor.h"

/* This demo is a torture test for interpolators: it takes an input label map,
 * rotates it one full turn in ten steps, and writes the result */

template <class ImageType>
void
RotateNTimes(typename ImageType::Pointer input,
    typename itk::InterpolateImageFunction<ImageType,double>* interpolator,
    unsigned int number_of_rotations, std::string outputFilename) {
	typedef itk::VersorRigid3DTransform<double> TransformType;
	typedef itk::ResampleImageFilter<ImageType,ImageType> ResampleFilterType;
	TransformType::AxisType axis;
	axis[0]=0;
	axis[1]=1;
	axis[2]=0;
	TransformType::InputPointType center;
	center[0] = 144;
	center[1] = 86;
	center[2] = 101;
	TransformType::Pointer rot = TransformType::New();
	rot->SetCenter(center);
	rot->SetRotation(axis,2.*M_PI/number_of_rotations);

	typename ResampleFilterType::Pointer rs = ResampleFilterType::New();
	rs->SetInput( input );
	rs->SetReferenceImage( input );
	rs->SetUseReferenceImage(true);
	rs->SetTransform(rot);
	//interp->SetSigma(0.3); // Used for the gaussian interpolator
	rs->SetInterpolator(interpolator);
	typename ImageType::Pointer out ;
  itk::TimeProbe timer; timer.Start();
	for (unsigned i = 0; i<number_of_rotations; ++i) {
		rs->SetReferenceImage( input );
		rs->SetUseReferenceImage(true);
		rs->Update();
		out = rs->GetOutput();
		out->DisconnectPipeline();
		rs->SetInput(out);
		rs->SetTransform(rot);
	}
  timer.Stop();
  typedef itk::Testing::ComparisonImageFilter<ImageType,ImageType> ComparisonFilterType;
  typename ComparisonFilterType::Pointer compare = ComparisonFilterType::New();
  compare->SetValidInput( input );
  compare->SetTestInput( out );
  compare->Update();
  std::cout << "Pixels with differences: " << std::setw(8) << compare->GetNumberOfPixelsWithDifferences() <<
    " ( " << std::fixed << std::setprecision(2) << static_cast<double>(compare->GetNumberOfPixelsWithDifferences()) /
    input->GetLargestPossibleRegion().GetNumberOfPixels() * 100.<<
    "% ) in " << timer.GetTotal() << "s" << std::endl;
	typedef  itk::ImageFileWriter< ImageType  > WriterType;
	typename WriterType::Pointer writer = WriterType::New();
	writer->SetUseCompression(true);
	writer->SetInput( out );
	writer->SetFileName(outputFilename);
	writer->Write();
}

// The BSpline interpolator has more arguments than other interpolators, so we set the additional parameter to the default value
using namespace std;
template<class TImage,typename TCoordRep> class BSplineInterpolator : public itk::BSplineInterpolateImageFunction<TImage,TCoordRep> {};

int main(int argc, char *argv[])
{
	string outputFilename = "resampled.mha";
	string inputFilename = "../Source/classification.mha";

	typedef unsigned char     PixelType;
	const   unsigned int    Dimension = 3;
	typedef itk::Image< PixelType, Dimension >  ImageType;

	typedef itk::ImageFileReader<ImageType> ReaderType;
	ReaderType::Pointer r = ReaderType::New();
	r->SetFileName(inputFilename);
	r->Update();

	const unsigned number_of_rotations=3;

  std::cout << "Nearest neighbor interpolator...                        " << std::flush;
	typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> NNInterpolatorType;
	NNInterpolatorType::Pointer nn_interp = NNInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), nn_interp, number_of_rotations, "nearest.mha");

  std::cout << "Linear interpolator...                                  " << std::flush;
	typedef itk::LinearInterpolateImageFunction<ImageType,double> LInterpolatorType;
	LInterpolatorType::Pointer l_interp = LInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), l_interp, number_of_rotations, "linear.mha");

  std::cout << "Label Gaussian interpolator type...                     " << std::flush;
	typedef itk::LabelImageGaussianInterpolateImageFunction<ImageType,double> LGInterpolatorType;
	LGInterpolatorType::Pointer lg_interp = LGInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), lg_interp, number_of_rotations, "label_gaussian.mha");

  std::cout << "Generic label interpolator with nearest neighbor...     " << std::flush;
	typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::NearestNeighborInterpolateImageFunction> GNNInterpolatorType;
	GNNInterpolatorType::Pointer gnn_interp = GNNInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), gnn_interp, number_of_rotations, "gl_nearest.mha");

  std::cout << "Generic label interpolator with linear interpolation... " << std::flush;
	typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::LinearInterpolateImageFunction> GLInterpolatorType;
	GLInterpolatorType::Pointer gl_interp = GLInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), gl_interp, number_of_rotations, "gl_linear.mha");

  std::cout << "Generic label interpolator with B-Spline...             " << std::flush;
	typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,BSplineInterpolator> GBSInterpolatorType;
	GBSInterpolatorType::Pointer gbs_interp = GBSInterpolatorType::New();
  RotateNTimes<ImageType>(r->GetOutput(), gbs_interp, number_of_rotations, "gl_bspline.mha");

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// @(#)root/reflex:$Id$
// Author: Pere Mato 2006

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "Reflex/PluginService.h"
#include "Reflex/SharedLibrary.h"
#include "Reflex/Reflex.h"
#include "PluginFactoryMap.h"

#include <vector>

using namespace Reflex;
using namespace std;

//_______________________________________________________________________________
//
//                 The Plugin Service
//
//  This classes have been developed to enhance Reflex with plugin capabilities.
//  The main goals have been:
//
//  - Simplification of the code. Replace existing factories
//  - Compatibility with other plugins and dictionary systems since they are based
//    also on roopmap files
//  - Dependent exclusively on Reflex
//  - Possible replacement for the SEAL plugin manager that could be of interest
//    for CORAL, POOL, COOL, etc.
//
//
//  Using the package
//
//  There is not predefined model on what a plugin/component can be. Any class
//  can be a plugin. The plugin factory is declared in the user code with the exact
//  signature of the constructor and the type returned (base class or interface) by
//  the factory.
//
// Begin_Html
/*
//

//  class MyClass : public ICommon {
//    MyClass(int, ISvc*);
//    ...
//  };
//
//  PLUGINSVC_FACTORY(MyClass,ICommon*(int,ISvc*));
//  PLUGINSVC_FACTORY_WITH_ID(MyClass, 666, ICommon*(int,ISvc*));
//

*/
// End_Html
//
//
//  Implementation
//
//  The rootmap file, which is a text file containing the association between the
//  plugins and the libraries that implements them, is generated automatically at
//  build time with the help of the genmap utility program. This program loads each
//  library and discovers what plugins it contains. The plugin can be easily
//  instantiated in the user code by using the class name or an ID class with strong
//  type checking on the constructor arguments. An ID class can be any class that
//  defined operator==() and ostream& operator<<(). The library containing the plugin
//  will be loaded if needed. The classes are almost standalone with an exclusive
//  dependency on Reflex.
//
// Begin_Html
/*
//

//  ISvc* svc = ...
//  ICommon* myc;
//  myc = PluginSvc::create<ICommon*>(MyClass,10, svc);
//  // or PluginSvc::createWithId<ICommon*>(666,10, svc);
//  if ( myc ) {
//    myc->doSomething();
//  }
//

*/
// End_Html

//-------------------------------------------------------------------------------
void* Reflex::PluginService::Create( const string & name,
                                       const Type & ret,
                                       const vector<ValueObject> & arg) {
//-------------------------------------------------------------------------------
// Create a Plugin. Pass ownership of created object (i.e. returned value) to caller.
   static Object dummy;
   vector<void*> argv;
   vector<Type>  argt;
   for ( vector<ValueObject>::const_iterator i = arg.begin(); i != arg.end(); i++ ){
      argv.push_back(i->Address());
      argt.push_back(Type(i->TypeOf(),0));  // Ignore argument CV qualifiers
   }
   Type signature = FunctionTypeBuilder(ret, argt);
   string factoryname = FactoryName(name);
   //---Look first is the member exists ----
   if( ! Instance().fFactories.FunctionMemberByName(factoryname) ) {
      string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + factoryname;

      int rett = Instance().LoadFactoryLib(mapname);
      if ( ! rett ) {
         if ( Debug() ) cout << "PluginService: Could not load library associated to plugin " << name << endl;
         return 0;
      }
   }
   Member m = Instance().fFactories.FunctionMemberByName(FactoryName(name), signature);
   if ( !m ) {
      if ( Debug() > 1 ) cout << "PluginService: Could not find factory for " << name << " with signature " << signature.Name() << endl;
      return 0;
   }
   else {
      Object rett = m.TypeOf().ReturnType().Construct();
      m.Invoke(dummy, &rett, argv);
      return rett.Address();
   }
}

//-------------------------------------------------------------------------------
void* Reflex::PluginService::CreateWithId(const Any& id,
                                                std::string (*str)(const Any&),
                                                bool(*cmp)(const Any&, const Any&),
                                                const Type& ret,
                                                const vector<ValueObject>& arg) {
//-------------------------------------------------------------------------------
// Create plugin with Id.
   static Object dummy;
   vector<void*> argv;
   vector<Type>  argt;
   for ( vector<ValueObject>::const_iterator i = arg.begin(); i != arg.end(); i++ ){
      argv.push_back(i->Address());
      argt.push_back(Type(i->TypeOf(),0));  // Ignore argument CV qualifiers
   }
   Type signature = FunctionTypeBuilder(ret, argt);

   string factoryname = FactoryName(str(id));

   if( ! Instance().fFactories.FunctionMemberByName(factoryname) ) {
      string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + factoryname;
      int rett = Instance().LoadFactoryLib(mapname);
      if ( ! rett ) {
         if ( Debug() ) cout << "PluginSvc: Could not load library associated to plugin with ID" << str(id) << endl;
         return 0;
      }
   }

   //--- loop over members
   Member m;
   for (Member_Iterator it = Instance().fFactories.FunctionMember_Begin();
        it != Instance().fFactories.FunctionMember_End(); ++it ) {
      if (it->Properties().HasProperty("id")) {
         if ( cmp(it->Properties().PropertyValue("id"),id) ) {
            if (signature.IsEquivalentTo(it->TypeOf())) {
               m = *it;
               break;
            }
         }
      }
   }

   if ( !m ) {
      if ( Debug() > 1 ) cout << "PluginService: Could not find factory for " << str(id) << " with signature " << signature.Name() << endl;
      return 0;
   }
   else {
      Object rett = m.TypeOf().ReturnType().Construct();
      m.Invoke(dummy, &rett, argv);
      return rett.Address();
   }
}

//-------------------------------------------------------------------------------
string Reflex::PluginService::FactoryName(const string& name) {
//-------------------------------------------------------------------------------
// Create a factory name out of the parameter given.
   static string chars(":<> *&, ");
   string::size_type pos1 = name.find_first_not_of(' ');
   string::size_type pos2 = name.find_last_not_of(' ');
   string res = name.substr(pos1 == string::npos ? 0 : pos1,
                            pos2 == string::npos ? name.length() - 1 : pos2 - pos1 + 1);
   for ( string::iterator i = res.begin(); i != res.end(); i++ )
      if ( chars.find(*i) != string::npos ) *i = '_';
   return res;
}

//-------------------------------------------------------------------------------
Reflex::PluginService::PluginService() : fDebugLevel(0) {
//-------------------------------------------------------------------------------
// Constructor.
   NamespaceBuilder(PLUGINSVC_FACTORY_NS);
   fFactories = Scope::ByName(PLUGINSVC_FACTORY_NS);
   fFactoryMap = new PluginFactoryMap();
}

//-------------------------------------------------------------------------------
Reflex::PluginService::~PluginService() {
//-------------------------------------------------------------------------------
// Destructor.
   delete fFactoryMap;
}

//-------------------------------------------------------------------------------
PluginService& Reflex::PluginService::Instance() {
//-------------------------------------------------------------------------------
// Get singleton.
   static PluginService s_instance;
   return s_instance;
}

//-------------------------------------------------------------------------------
int Reflex::PluginService::Debug() {
//-------------------------------------------------------------------------------
// Get debug level.
   return Instance().fDebugLevel;
}

//-------------------------------------------------------------------------------
void Reflex::PluginService::SetDebug(int l) {
//-------------------------------------------------------------------------------
// Set debug level.
   PluginFactoryMap::SetDebug(l);
   Instance().fDebugLevel = l;
}

//-------------------------------------------------------------------------------
int Reflex::PluginService::LoadFactoryLib(const string& name) {
//-------------------------------------------------------------------------------
// Load libraries needed for a plugin to instantiate.
   list<string> libs = Instance().fFactoryMap->GetLibraries(name);
   for ( list<string>::reverse_iterator i = libs.rbegin(); i != libs.rend(); i++ ) {
      SharedLibrary sl(*i);
      if ( sl.Load() ) {
         if ( Debug() ) cout << "PluginService: Loaded library  " << *i << endl;
      }
      else {
         if ( Debug() ) cout << "PluginService: Error loading library " << *i <<
                           endl << sl.Error() <<  endl;
         return 0;
      }
   }
   return 1;
}

<commit_msg>Fix issue with PluginService::Create() returning address of ptr instead of ptr. Should help the POOL nightlies.<commit_after>// @(#)root/reflex:$Id$
// Author: Pere Mato 2006

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "Reflex/PluginService.h"
#include "Reflex/SharedLibrary.h"
#include "Reflex/Reflex.h"
#include "PluginFactoryMap.h"

#include <vector>

using namespace Reflex;
using namespace std;

//_______________________________________________________________________________
//
//                 The Plugin Service
//
//  This classes have been developed to enhance Reflex with plugin capabilities.
//  The main goals have been:
//
//  - Simplification of the code. Replace existing factories
//  - Compatibility with other plugins and dictionary systems since they are based
//    also on roopmap files
//  - Dependent exclusively on Reflex
//  - Possible replacement for the SEAL plugin manager that could be of interest
//    for CORAL, POOL, COOL, etc.
//
//
//  Using the package
//
//  There is not predefined model on what a plugin/component can be. Any class
//  can be a plugin. The plugin factory is declared in the user code with the exact
//  signature of the constructor and the type returned (base class or interface) by
//  the factory.
//
// Begin_Html
/*
//

//  class MyClass : public ICommon {
//    MyClass(int, ISvc*);
//    ...
//  };
//
//  PLUGINSVC_FACTORY(MyClass,ICommon*(int,ISvc*));
//  PLUGINSVC_FACTORY_WITH_ID(MyClass, 666, ICommon*(int,ISvc*));
//

*/
// End_Html
//
//
//  Implementation
//
//  The rootmap file, which is a text file containing the association between the
//  plugins and the libraries that implements them, is generated automatically at
//  build time with the help of the genmap utility program. This program loads each
//  library and discovers what plugins it contains. The plugin can be easily
//  instantiated in the user code by using the class name or an ID class with strong
//  type checking on the constructor arguments. An ID class can be any class that
//  defined operator==() and ostream& operator<<(). The library containing the plugin
//  will be loaded if needed. The classes are almost standalone with an exclusive
//  dependency on Reflex.
//
// Begin_Html
/*
//

//  ISvc* svc = ...
//  ICommon* myc;
//  myc = PluginSvc::create<ICommon*>(MyClass,10, svc);
//  // or PluginSvc::createWithId<ICommon*>(666,10, svc);
//  if ( myc ) {
//    myc->doSomething();
//  }
//

*/
// End_Html

//-------------------------------------------------------------------------------
void* Reflex::PluginService::Create( const string & name,
                                       const Type & ret,
                                       const vector<ValueObject> & arg) {
//-------------------------------------------------------------------------------
// Create a Plugin. Pass ownership of created object (i.e. returned value) to caller,
// UNLESS it's a pointer or a reference - then it's up to the plugin creator function
// and the caller to define the ownership.

   static Object dummy;
   vector<void*> argv;
   vector<Type>  argt;
   for ( vector<ValueObject>::const_iterator i = arg.begin(); i != arg.end(); i++ ){
      argv.push_back(i->Address());
      argt.push_back(Type(i->TypeOf(),0));  // Ignore argument CV qualifiers
   }
   Type signature = FunctionTypeBuilder(ret, argt);
   string factoryname = FactoryName(name);
   //---Look first is the member exists ----
   if( ! Instance().fFactories.FunctionMemberByName(factoryname) ) {
      string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + factoryname;

      int rett = Instance().LoadFactoryLib(mapname);
      if ( ! rett ) {
         if ( Debug() ) cout << "PluginService: Could not load library associated to plugin " << name << endl;
         return 0;
      }
   }
   Member m = Instance().fFactories.FunctionMemberByName(FactoryName(name), signature);
   if ( !m ) {
      if ( Debug() > 1 ) cout << "PluginService: Could not find factory for " << name << " with signature " << signature.Name() << endl;
      return 0;
   }
   else {
      Type retType = m.TypeOf().ReturnType();
      if (retType.IsPointer() || retType.IsReference()) {
         void* ret = 0;
         m.Invoke(dummy, ret, argv);
         return ret;
      } else {
         Object rett = retType.Construct();
         m.Invoke(dummy, &rett, argv);
         return rett.Address();
      }
   }
   // to make compilers happy - we should never get here:
   return 0;
}

//-------------------------------------------------------------------------------
void* Reflex::PluginService::CreateWithId(const Any& id,
                                                std::string (*str)(const Any&),
                                                bool(*cmp)(const Any&, const Any&),
                                                const Type& ret,
                                                const vector<ValueObject>& arg) {
//-------------------------------------------------------------------------------
// Create plugin with Id.
   static Object dummy;
   vector<void*> argv;
   vector<Type>  argt;
   for ( vector<ValueObject>::const_iterator i = arg.begin(); i != arg.end(); i++ ){
      argv.push_back(i->Address());
      argt.push_back(Type(i->TypeOf(),0));  // Ignore argument CV qualifiers
   }
   Type signature = FunctionTypeBuilder(ret, argt);

   string factoryname = FactoryName(str(id));

   if( ! Instance().fFactories.FunctionMemberByName(factoryname) ) {
      string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + factoryname;
      int rett = Instance().LoadFactoryLib(mapname);
      if ( ! rett ) {
         if ( Debug() ) cout << "PluginSvc: Could not load library associated to plugin with ID" << str(id) << endl;
         return 0;
      }
   }

   //--- loop over members
   Member m;
   for (Member_Iterator it = Instance().fFactories.FunctionMember_Begin();
        it != Instance().fFactories.FunctionMember_End(); ++it ) {
      if (it->Properties().HasProperty("id")) {
         if ( cmp(it->Properties().PropertyValue("id"),id) ) {
            if (signature.IsEquivalentTo(it->TypeOf())) {
               m = *it;
               break;
            }
         }
      }
   }

   if ( !m ) {
      if ( Debug() > 1 ) cout << "PluginService: Could not find factory for " << str(id) << " with signature " << signature.Name() << endl;
      return 0;
   }
   else {
      Type retType = m.TypeOf().ReturnType();
      if (retType.IsPointer() || retType.IsReference()) {
         void* ret = 0;
         m.Invoke(dummy, ret, argv);
         return ret;
      } else {
         Object rett = retType.Construct();
         m.Invoke(dummy, &rett, argv);
         return rett.Address();
      }
   }
}

//-------------------------------------------------------------------------------
string Reflex::PluginService::FactoryName(const string& name) {
//-------------------------------------------------------------------------------
// Create a factory name out of the parameter given.
   static string chars(":<> *&, ");
   string::size_type pos1 = name.find_first_not_of(' ');
   string::size_type pos2 = name.find_last_not_of(' ');
   string res = name.substr(pos1 == string::npos ? 0 : pos1,
                            pos2 == string::npos ? name.length() - 1 : pos2 - pos1 + 1);
   for ( string::iterator i = res.begin(); i != res.end(); i++ )
      if ( chars.find(*i) != string::npos ) *i = '_';
   return res;
}

//-------------------------------------------------------------------------------
Reflex::PluginService::PluginService() : fDebugLevel(0) {
//-------------------------------------------------------------------------------
// Constructor.
   NamespaceBuilder(PLUGINSVC_FACTORY_NS);
   fFactories = Scope::ByName(PLUGINSVC_FACTORY_NS);
   fFactoryMap = new PluginFactoryMap();
}

//-------------------------------------------------------------------------------
Reflex::PluginService::~PluginService() {
//-------------------------------------------------------------------------------
// Destructor.
   delete fFactoryMap;
}

//-------------------------------------------------------------------------------
PluginService& Reflex::PluginService::Instance() {
//-------------------------------------------------------------------------------
// Get singleton.
   static PluginService s_instance;
   return s_instance;
}

//-------------------------------------------------------------------------------
int Reflex::PluginService::Debug() {
//-------------------------------------------------------------------------------
// Get debug level.
   return Instance().fDebugLevel;
}

//-------------------------------------------------------------------------------
void Reflex::PluginService::SetDebug(int l) {
//-------------------------------------------------------------------------------
// Set debug level.
   PluginFactoryMap::SetDebug(l);
   Instance().fDebugLevel = l;
}

//-------------------------------------------------------------------------------
int Reflex::PluginService::LoadFactoryLib(const string& name) {
//-------------------------------------------------------------------------------
// Load libraries needed for a plugin to instantiate.
   list<string> libs = Instance().fFactoryMap->GetLibraries(name);
   for ( list<string>::reverse_iterator i = libs.rbegin(); i != libs.rend(); i++ ) {
      SharedLibrary sl(*i);
      if ( sl.Load() ) {
         if ( Debug() ) cout << "PluginService: Loaded library  " << *i << endl;
      }
      else {
         if ( Debug() ) cout << "PluginService: Error loading library " << *i <<
                           endl << sl.Error() <<  endl;
         return 0;
      }
   }
   return 1;
}

<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_L2_HH
#define DUNE_GDT_FUNCTIONALS_L2_HH

#include <type_traits>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/localfunctional/codim0.hh>
#include <dune/gdt/localfunctional/codim1.hh>
#include <dune/gdt/localfunctional/integrals.hh>
#include <dune/gdt/localevaluation/product.hh>
#include <dune/gdt/assembler/system.hh>

#include "base.hh"
#include "default.hh"

namespace Dune {
namespace GDT {

/**
 * \todo Unit tests are missing for this class.
 */
template <class FunctionType, class Space,
          class Vector   = typename Stuff::LA::Container<typename Space::RangeFieldType>::VectorType,
          class GridView = typename Space::GridViewType, class Field = typename Space::RangeFieldType>
class L2VolumeVectorFunctional : public VectorFunctionalDefault<Vector, Space, GridView, Field>
{
  typedef VectorFunctionalDefault<Vector, Space, GridView, Field> BaseType;

public:
  template <class... Args>
  explicit L2VolumeVectorFunctional(const FunctionType& function, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_l2_functional_(function)
  {
    this->add(local_l2_functional_);
  }

  template <class... Args>
  explicit L2VolumeVectorFunctional(const size_t over_integrate, const FunctionType& function, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_l2_functional_(over_integrate, function)
  {
    this->add(local_l2_functional_);
  }

private:
  const LocalVolumeIntegralFunctional<LocalEvaluation::Product<FunctionType>> local_l2_functional_;
}; // class L2VolumeVectorFunctional

namespace Functionals {

// forwards
template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType,
          class LocalEvaluationType                                              = LocalEvaluation::Product<FunctionType>>
class L2Volume;

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType>
class L2Face;

namespace internal {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType>
class L2VolumeTraits
{
  static_assert(Stuff::is_localizable_function<FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(is_space<SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Volume<FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2VolumeTraits

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2FaceTraits
{
  static_assert(Stuff::is_localizable_function<FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(is_space<SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Face<FunctionType, VectorImp, SpaceImp, GridViewImp> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2FaceTraits

} // namespace internal

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType>
class L2Volume : public Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp,
                                                                          GridViewImp, LocalEvaluationType>>,
                 public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp,
                                                            LocalEvaluationType>> FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;
  typedef LocalFunctional::Codim0Integral<LocalEvaluationType> LocalFunctionalType;
  typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType> Traits;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw)
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc)
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc,
           const LocalFunctionalType localFunctional)
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(localFunctional)
    , local_assembler_(local_functional_)
  {
    setup();
  }
  virtual void assemble() override final
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup()
  {
    this->add(local_assembler_, this->vector());
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Volume

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2Face : public Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>,
               public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>
      FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;
  typedef LocalFunctional::Codim1Integral<LocalEvaluation::Product<FunctionType>> LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp> Traits;

  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw,
         const Stuff::Grid::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new Stuff::Grid::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc,
         const Stuff::Grid::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new Stuff::Grid::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  virtual void assemble() override final
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup(const Stuff::Grid::ApplyOn::WhichIntersection<GridViewType>* which_intersections)
  {
    this->add(local_assembler_, this->vector(), which_intersections);
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Face

template <class F, class V, class S, class GV>
std::unique_ptr<L2Volume<F, V, S, GV>> make_l2_volume(const F& function, V& vector, const S& space, const GV& grid_view)
{
  return Stuff::Common::make_unique<L2Volume<F, V, S, GV>>(function, vector, space, grid_view);
}

template <class F, class V, class S>
std::unique_ptr<L2Volume<F, V, S>> make_l2_volume(const F& function, V& vector, const S& space)
{
  return Stuff::Common::make_unique<L2Volume<F, V, S>>(function, vector, space);
}

template <class F, class V, class S>
std::unique_ptr<L2Face<F, V, S>>
make_l2_face(const F& function, V& vector, const S& space,
             const Stuff::Grid::ApplyOn::WhichIntersection<typename S::GridViewType>* which_intersections =
                 new Stuff::Grid::ApplyOn::AllIntersections<typename S::GridViewType>())
{
  return Stuff::Common::make_unique<L2Face<F, V, S>>(function, vector, space, which_intersections);
}

} // namespace Functionals
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_L2_HH
<commit_msg>[functionals.l2] add make_l2_volume_vector_functional<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_L2_HH
#define DUNE_GDT_FUNCTIONALS_L2_HH

#include <type_traits>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/localfunctional/codim0.hh>
#include <dune/gdt/localfunctional/codim1.hh>
#include <dune/gdt/localfunctional/integrals.hh>
#include <dune/gdt/localevaluation/product.hh>
#include <dune/gdt/assembler/system.hh>

#include "base.hh"
#include "default.hh"

namespace Dune {
namespace GDT {

/**
 * \todo Unit tests are missing for this class.
 */
template <class FunctionType, class Space,
          class Vector   = typename Stuff::LA::Container<typename Space::RangeFieldType>::VectorType,
          class GridView = typename Space::GridViewType, class Field = typename Space::RangeFieldType>
class L2VolumeVectorFunctional : public VectorFunctionalDefault<Vector, Space, GridView, Field>
{
  typedef VectorFunctionalDefault<Vector, Space, GridView, Field> BaseType;

public:
  template <class... Args>
  explicit L2VolumeVectorFunctional(const FunctionType& function, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_l2_functional_(function)
  {
    this->add(local_l2_functional_);
  }

  template <class... Args>
  explicit L2VolumeVectorFunctional(const size_t over_integrate, const FunctionType& function, Args&&... args)
    : BaseType(std::forward<Args>(args)...)
    , local_l2_functional_(over_integrate, function)
  {
    this->add(local_l2_functional_);
  }

private:
  const LocalVolumeIntegralFunctional<LocalEvaluation::Product<FunctionType>> local_l2_functional_;
}; // class L2VolumeVectorFunctional

template <class VectorType, class FunctionType, class SpaceType>
typename std::enable_if<Stuff::LA::is_vector<VectorType>::value && Stuff::is_localizable_function<FunctionType>::value
                            && is_space<SpaceType>::value,
                        std::unique_ptr<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType>>>::type
make_l2_volume_vector_functional(const FunctionType& function, const SpaceType& space, const size_t over_integrate = 0)
{
  return DSC::make_unique<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType>>(
      over_integrate, function, space);
}

template <class VectorType, class FunctionType, class SpaceType, class GridViewType>
typename std::
    enable_if<Stuff::LA::is_vector<VectorType>::value && Stuff::is_localizable_function<FunctionType>::value
                  && is_space<SpaceType>::value
                  && !std::is_integral<GridViewType>::value // needed for disambiguation with above specialization
              ,
              std::unique_ptr<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType, GridViewType>>>::type
    make_l2_volume_vector_functional(const FunctionType& function, const SpaceType& space,
                                     const GridViewType& grid_view, const size_t over_integrate = 0)
{
  return DSC::make_unique<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType, GridViewType>>(
      over_integrate, function, space, grid_view);
}

template <class FunctionType, class VectorType, class SpaceType>
typename std::enable_if<Stuff::is_localizable_function<FunctionType>::value && Stuff::LA::is_vector<VectorType>::value
                            && is_space<SpaceType>::value,
                        std::unique_ptr<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType>>>::type
make_l2_volume_vector_functional(const FunctionType& function, VectorType& vector, const SpaceType& space,
                                 const size_t over_integrate = 0)
{
  return DSC::make_unique<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType>>(
      over_integrate, function, vector, space);
}

template <class FunctionType, class VectorType, class SpaceType, class GridViewType>
typename std::
    enable_if<Stuff::is_localizable_function<FunctionType>::value && Stuff::LA::is_vector<VectorType>::value
                  && is_space<SpaceType>::value
                  && !std::is_integral<GridViewType>::value // needed for disambiguation with above specialization
              ,
              std::unique_ptr<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType, GridViewType>>>::type
    make_l2_volume_vector_functional(const FunctionType& function, VectorType& vector, const SpaceType& space,
                                     const GridViewType& grid_view, const size_t over_integrate = 0)
{
  return DSC::make_unique<L2VolumeVectorFunctional<FunctionType, SpaceType, VectorType, GridViewType>>(
      over_integrate, function, vector, space, grid_view);
}

namespace Functionals {

// forwards
template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType,
          class LocalEvaluationType                                              = LocalEvaluation::Product<FunctionType>>
class L2Volume;

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType>
class L2Face;

namespace internal {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType>
class L2VolumeTraits
{
  static_assert(Stuff::is_localizable_function<FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(is_space<SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Volume<FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2VolumeTraits

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2FaceTraits
{
  static_assert(Stuff::is_localizable_function<FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(is_space<SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Face<FunctionType, VectorImp, SpaceImp, GridViewImp> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2FaceTraits

} // namespace internal

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType>
class L2Volume : public Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp,
                                                                          GridViewImp, LocalEvaluationType>>,
                 public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp,
                                                            LocalEvaluationType>> FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;
  typedef LocalFunctional::Codim0Integral<LocalEvaluationType> LocalFunctionalType;
  typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType> Traits;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw)
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc)
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc,
           const LocalFunctionalType localFunctional)
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(localFunctional)
    , local_assembler_(local_functional_)
  {
    setup();
  }
  virtual void assemble() override final
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup()
  {
    this->add(local_assembler_, this->vector());
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Volume

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2Face : public Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>,
               public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>
      FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;
  typedef LocalFunctional::Codim1Integral<LocalEvaluation::Product<FunctionType>> LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp> Traits;

  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw,
         const Stuff::Grid::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new Stuff::Grid::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc,
         const Stuff::Grid::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new Stuff::Grid::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  virtual void assemble() override final
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup(const Stuff::Grid::ApplyOn::WhichIntersection<GridViewType>* which_intersections)
  {
    this->add(local_assembler_, this->vector(), which_intersections);
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Face

template <class F, class V, class S, class GV>
std::unique_ptr<L2Volume<F, V, S, GV>> make_l2_volume(const F& function, V& vector, const S& space, const GV& grid_view)
{
  return Stuff::Common::make_unique<L2Volume<F, V, S, GV>>(function, vector, space, grid_view);
}

template <class F, class V, class S>
std::unique_ptr<L2Volume<F, V, S>> make_l2_volume(const F& function, V& vector, const S& space)
{
  return Stuff::Common::make_unique<L2Volume<F, V, S>>(function, vector, space);
}

template <class F, class V, class S>
std::unique_ptr<L2Face<F, V, S>>
make_l2_face(const F& function, V& vector, const S& space,
             const Stuff::Grid::ApplyOn::WhichIntersection<typename S::GridViewType>* which_intersections =
                 new Stuff::Grid::ApplyOn::AllIntersections<typename S::GridViewType>())
{
  return Stuff::Common::make_unique<L2Face<F, V, S>>(function, vector, space, which_intersections);
}

} // namespace Functionals
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_L2_HH
<|endoftext|>


<commit_before>#ifndef DUNE_COMMON_COLOR_HH
#define DUNE_COMMON_COLOR_HH

#include <sstream>
#include <assert.h>
#include <iostream>

#ifdef __GNUC__
 #include <cxxabi.h>
#endif
#include <string>

#include <dune/stuff/common/string.hh>

namespace Dune {
namespace Stuff {
namespace Common {

/**
 * @brief namespace to define color constants that can be
 * used to print colored text in an output stream.
 *
 * * \todo this could go into libdune-stuff
 * @warning Some color codes might be unsupported by your terminal.
 */
struct Colors {

#define DS_CONST_CHAR const constexpr char*

// foreground colors
static DS_CONST_CHAR black = "\033[30m";
static DS_CONST_CHAR red = "\033[31m";
static DS_CONST_CHAR green = "\033[32m";
static DS_CONST_CHAR brown = "\033[33m";
static DS_CONST_CHAR blue = "\033[34m";
static DS_CONST_CHAR purple = "\033[35m";
static DS_CONST_CHAR cyan = "\033[36m";
static DS_CONST_CHAR lightgray = "\033[37m";
// light foreground colors
static DS_CONST_CHAR darkgray = "\033[1;30m";
static DS_CONST_CHAR lightred = "\033[1;31m";
static DS_CONST_CHAR lightgreen = "\033[1;32m";
static DS_CONST_CHAR yellow = "\033[1;33m";
static DS_CONST_CHAR lightblue = "\033[1;34m";
static DS_CONST_CHAR lightpurple = "\033[1;35m";
static DS_CONST_CHAR lightcyan = "\033[1;36m";
static DS_CONST_CHAR white = "\033[1;37m";

// background colors
static DS_CONST_CHAR bblack = "\033[40m";
static DS_CONST_CHAR bred = "\033[41m";
static DS_CONST_CHAR bgreen = "\033[42m";
static DS_CONST_CHAR bbrown = "\033[43m";
static DS_CONST_CHAR bblue = "\033[44m";
static DS_CONST_CHAR bpurple = "\033[45m";
static DS_CONST_CHAR bcyan = "\033[46m";
static DS_CONST_CHAR blightgray = "\033[47m";
// light background colors
static DS_CONST_CHAR bdarkgray = "\033[1;40m";
static DS_CONST_CHAR blightred = "\033[1;41m";
static DS_CONST_CHAR blightgreen = "\033[1;42m";
static DS_CONST_CHAR byellow = "\033[1;43m";
static DS_CONST_CHAR blightblue = "\033[1;44m";
static DS_CONST_CHAR blightpurple = "\033[1;45m";
static DS_CONST_CHAR blightcyan = "\033[1;46m";
static DS_CONST_CHAR bwhite = "\033[1;47m";
};
// modifiers
struct StreamModifiers {
static DS_CONST_CHAR normal = "\033[0m";
static DS_CONST_CHAR bold = "\033[1m";
static DS_CONST_CHAR italic = "\033[2m";
static DS_CONST_CHAR underline = "\033[4m";
static DS_CONST_CHAR blink = "\033[5m";
static DS_CONST_CHAR reverse = "\033[7m";
static DS_CONST_CHAR enditalic = "\033[22m";
static DS_CONST_CHAR endunderline = "\033[24m";
static DS_CONST_CHAR endblink = "\033[25m";
static DS_CONST_CHAR endreverse = "\033[27m";
#undef DS_CONST_CHAR
};
/**
 * @brief Chooses a color from a 256 color map for a foreground color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string color(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

/**
 * @brief Chooses a color from a 256 color map for a background color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string backcolor(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

// maybe you want to choose your own color
int templateColorChooser(int i) {
  return i % 256;
}

/**
 * @brief Highlights templates depending on the "template"-level.
 *
 * @param str The string containing the template string
 * @param maxlevel The maximal template-level the string is reduced to.
 * @returns A colored template string.
 */
std::string highlightTemplate(std::string str, int maxlevel = 10000) {
  if (maxlevel < 0)
    maxlevel = 0;
  int startindex = 0;
  int level = 0;
  for (size_t i = 0; i < str.size(); i++)
  {
    if (str[i] == '<')
    {
      level++;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(i, dummy);
      i += dummy.size();
      if (level == maxlevel)
        startindex = i + 1;
    } else if (str[i] == '>') {
      level--;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(++i, dummy);
      if (level + 1 == maxlevel)
      {
        int size = i - startindex - 1;
        str.erase(startindex, size);
        i = startindex + 1;
      }
      i += dummy.size();
    }
  }
  str += "\033[38;5;0m";
  return str;
} // highlightTemplate

/**
 * @brief A simple function highlighting a whole string in a specified foreground color.
 *
 * @param str The string you want to highlight.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightString(std::string str, int colornr = 0) {
  return "\033[38;5;" + toString(colornr % 256) + "m" + str + "\033[38;5;0m";
}

/**
 * @brief Highlights a substring of another string in a specified color.
 *
 * @param str The string where you want to highlight substrings.
 * @param substr The sub string you want to highlight in str.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {
  int index = str.find(substr, 0);

  while ( index != int(std::string::npos) )
  {
    std::string dummy = "\033[38;5;" + toString(colornr % 256) + "m";
    std::string dummy2 = "\033[38;5;0m";
    str.insert(index, dummy);
    str.insert(index + substr.size() + dummy.size(), dummy2);
    index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );
  }
  return str;
} // highlightSearchString

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // end of DUNE_COMMON_COLOR_HH

/** Copyright (c) 2012, Stefan Girke
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions 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.
   *
   * 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 COPYRIGHT OWNER 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<commit_msg>[common.color] added highlightString() which takes Colors::color<commit_after>#ifndef DUNE_COMMON_COLOR_HH
#define DUNE_COMMON_COLOR_HH

#include <sstream>
#include <assert.h>
#include <iostream>

#ifdef __GNUC__
 #include <cxxabi.h>
#endif
#include <string>

#include <dune/stuff/common/string.hh>

namespace Dune {
namespace Stuff {
namespace Common {

/**
 * @brief namespace to define color constants that can be
 * used to print colored text in an output stream.
 *
 * * \todo this could go into libdune-stuff
 * @warning Some color codes might be unsupported by your terminal.
 */
struct Colors {

#define DS_CONST_CHAR const constexpr char*

// foreground colors
static DS_CONST_CHAR black = "\033[30m";
static DS_CONST_CHAR red = "\033[31m";
static DS_CONST_CHAR green = "\033[32m";
static DS_CONST_CHAR brown = "\033[33m";
static DS_CONST_CHAR blue = "\033[34m";
static DS_CONST_CHAR purple = "\033[35m";
static DS_CONST_CHAR cyan = "\033[36m";
static DS_CONST_CHAR lightgray = "\033[37m";
// light foreground colors
static DS_CONST_CHAR darkgray = "\033[1;30m";
static DS_CONST_CHAR lightred = "\033[1;31m";
static DS_CONST_CHAR lightgreen = "\033[1;32m";
static DS_CONST_CHAR yellow = "\033[1;33m";
static DS_CONST_CHAR lightblue = "\033[1;34m";
static DS_CONST_CHAR lightpurple = "\033[1;35m";
static DS_CONST_CHAR lightcyan = "\033[1;36m";
static DS_CONST_CHAR white = "\033[1;37m";

// background colors
static DS_CONST_CHAR bblack = "\033[40m";
static DS_CONST_CHAR bred = "\033[41m";
static DS_CONST_CHAR bgreen = "\033[42m";
static DS_CONST_CHAR bbrown = "\033[43m";
static DS_CONST_CHAR bblue = "\033[44m";
static DS_CONST_CHAR bpurple = "\033[45m";
static DS_CONST_CHAR bcyan = "\033[46m";
static DS_CONST_CHAR blightgray = "\033[47m";
// light background colors
static DS_CONST_CHAR bdarkgray = "\033[1;40m";
static DS_CONST_CHAR blightred = "\033[1;41m";
static DS_CONST_CHAR blightgreen = "\033[1;42m";
static DS_CONST_CHAR byellow = "\033[1;43m";
static DS_CONST_CHAR blightblue = "\033[1;44m";
static DS_CONST_CHAR blightpurple = "\033[1;45m";
static DS_CONST_CHAR blightcyan = "\033[1;46m";
static DS_CONST_CHAR bwhite = "\033[1;47m";
};
// modifiers
struct StreamModifiers {
static DS_CONST_CHAR normal = "\033[0m";
static DS_CONST_CHAR bold = "\033[1m";
static DS_CONST_CHAR italic = "\033[2m";
static DS_CONST_CHAR underline = "\033[4m";
static DS_CONST_CHAR blink = "\033[5m";
static DS_CONST_CHAR reverse = "\033[7m";
static DS_CONST_CHAR enditalic = "\033[22m";
static DS_CONST_CHAR endunderline = "\033[24m";
static DS_CONST_CHAR endblink = "\033[25m";
static DS_CONST_CHAR endreverse = "\033[27m";
#undef DS_CONST_CHAR
};
/**
 * @brief Chooses a color from a 256 color map for a foreground color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string color(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

/**
 * @brief Chooses a color from a 256 color map for a background color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string backcolor(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

// maybe you want to choose your own color
int templateColorChooser(int i) {
  return i % 256;
}

/**
 * @brief Highlights templates depending on the "template"-level.
 *
 * @param str The string containing the template string
 * @param maxlevel The maximal template-level the string is reduced to.
 * @returns A colored template string.
 */
std::string highlightTemplate(std::string str, int maxlevel = 10000) {
  if (maxlevel < 0)
    maxlevel = 0;
  int startindex = 0;
  int level = 0;
  for (size_t i = 0; i < str.size(); i++)
  {
    if (str[i] == '<')
    {
      level++;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(i, dummy);
      i += dummy.size();
      if (level == maxlevel)
        startindex = i + 1;
    } else if (str[i] == '>') {
      level--;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(++i, dummy);
      if (level + 1 == maxlevel)
      {
        int size = i - startindex - 1;
        str.erase(startindex, size);
        i = startindex + 1;
      }
      i += dummy.size();
    }
  }
  str += "\033[38;5;0m";
  return str;
} // highlightTemplate

/**
 * @brief A simple function highlighting a whole string in a specified foreground color.
 *
 * @param str The string you want to highlight.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightString(std::string str, int colornr = 0) {
  return "\033[38;5;" + toString(colornr % 256) + "m" + str + "\033[38;5;0m";

std::string highlightString(const std::string string, const std::string color = Colors::red)
{
  return color + string + "\033[0m";
}

/**
 * @brief Highlights a substring of another string in a specified color.
 *
 * @param str The string where you want to highlight substrings.
 * @param substr The sub string you want to highlight in str.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {
  int index = str.find(substr, 0);

  while ( index != int(std::string::npos) )
  {
    std::string dummy = "\033[38;5;" + toString(colornr % 256) + "m";
    std::string dummy2 = "\033[38;5;0m";
    str.insert(index, dummy);
    str.insert(index + substr.size() + dummy.size(), dummy2);
    index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );
  }
  return str;
} // highlightSearchString

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // end of DUNE_COMMON_COLOR_HH

/** Copyright (c) 2012, Stefan Girke
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions 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.
   *
   * 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 COPYRIGHT OWNER 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<|endoftext|>


<commit_before>/*
 * ####                                                ####
 * ####                                                ####
 * ####                                                ####      ##
 * ####                                                ####    ####
 * ####  ############  ############  ####  ##########  ####  ####
 * ####  ####    ####  ####    ####  ####  ####        ########
 * ####  ####    ####  ####    ####  ####  ####        ########
 * ####  ####    ####  ####    ####  ####  ####        ####  ####
 * ####  ####    ####  ####    ####  ####  ####        ####    ####
 * ####  ############  ############  ####  ##########  ####      ####
 *                             ####                                ####
 * ################################                                  ####
 *            __      __              __              __      __       ####
 *   |  |    |  |    [__)    |_/     (__     |__|    |  |    [__)        ####
 *   |/\|    |__|    |  \    |  \    .__)    |  |    |__|    |             ##
 *
 *
 * DU-INO Arduino Library - Interface Widget Library
 * Aaron Mavrinac <aaron@logick.ca>
 */

#include "du-ino_widgets.h"

DUINO_Widget::DUINO_Widget()
  : click_callback_(NULL)
  , double_click_callback_(NULL)
  , scroll_callback_(NULL)
{
}

void DUINO_Widget::on_click()
{
  if(click_callback_)
  {
    click_callback_();
  }
}

void DUINO_Widget::on_double_click()
{
  if(double_click_callback_)
  {
    double_click_callback_();
  }
}

void DUINO_Widget::on_scroll(int delta)
{
  if(scroll_callback_ && delta)
  {
    scroll_callback_(delta);
  }
}

void DUINO_Widget::attach_click_callback(void (*callback)())
{
  click_callback_ = callback;
}

void DUINO_Widget::attach_double_click_callback(void (*callback)())
{
  double_click_callback_ = callback;
}

void DUINO_Widget::attach_scroll_callback(void (*callback)(int))
{
  scroll_callback_ = callback;
}

void DUINO_Widget::draw_invert(uint8_t x, uint8_t y, uint8_t width, uint8_t height, InvertStyle style)
{
  switch(style)
  {
    case Full:
      Display.fill_rect(x, y, width, height, DUINO_SH1106::Inverse);
      break;
    case Box:
      Display.draw_vline(x, y, height, DUINO_SH1106::Inverse);
      Display.draw_vline(x + width - 1, y, height, DUINO_SH1106::Inverse);
      Display.draw_hline(x + 1, y, width - 2, DUINO_SH1106::Inverse);
      Display.draw_hline(x + 1, y + height - 1, width - 2, DUINO_SH1106::Inverse);
      break;
    case DottedBox:
      for(uint8_t i = 0; i < width; i += 2)
      {
        Display.draw_pixel(x + i, y, DUINO_SH1106::Inverse);
        Display.draw_pixel(x + i, y + height - 1, DUINO_SH1106::Inverse);
      }
      for(uint8_t i = 2; i < height - 2; i += 2)
      {
        Display.draw_pixel(x, y + i, DUINO_SH1106::Inverse);
        Display.draw_pixel(x + width - 1, y + i, DUINO_SH1106::Inverse);
      }
      break;
    case Corners:
      Display.draw_vline(x, y, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x + 1, y, DUINO_SH1106::Inverse);
      Display.draw_vline(x + width - 1, y, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x + width - 2, y, DUINO_SH1106::Inverse);
      Display.draw_vline(x, y + height - 2, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x, y + height - 1, DUINO_SH1106::Inverse);
      Display.draw_vline(x + width - 1, y + height - 2, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x + width - 2, y + height - 1, DUINO_SH1106::Inverse);
      break;
    }
}

DUINO_DisplayWidget::DUINO_DisplayWidget(uint8_t x, uint8_t y, uint8_t width, uint8_t height,
    DUINO_Widget::InvertStyle style)
  : x_(x)
  , y_(y)
  , width_(width)
  , height_(height)
  , style_(style)
  , inverted_(false)
{
}

void DUINO_DisplayWidget::display()
{
  Display.display(x_, x_ + width_, y_ / 8, (y_ + width_) / 8);
}

void DUINO_DisplayWidget::invert(bool update_display)
{
  draw_invert(x_, y_, width_, height_, style_);

  if (update_display)
  {
    display();
  }

  inverted_ = !inverted_;
}
<commit_msg>Fix corner invert style.<commit_after>/*
 * ####                                                ####
 * ####                                                ####
 * ####                                                ####      ##
 * ####                                                ####    ####
 * ####  ############  ############  ####  ##########  ####  ####
 * ####  ####    ####  ####    ####  ####  ####        ########
 * ####  ####    ####  ####    ####  ####  ####        ########
 * ####  ####    ####  ####    ####  ####  ####        ####  ####
 * ####  ####    ####  ####    ####  ####  ####        ####    ####
 * ####  ############  ############  ####  ##########  ####      ####
 *                             ####                                ####
 * ################################                                  ####
 *            __      __              __              __      __       ####
 *   |  |    |  |    [__)    |_/     (__     |__|    |  |    [__)        ####
 *   |/\|    |__|    |  \    |  \    .__)    |  |    |__|    |             ##
 *
 *
 * DU-INO Arduino Library - Interface Widget Library
 * Aaron Mavrinac <aaron@logick.ca>
 */

#include "du-ino_widgets.h"

DUINO_Widget::DUINO_Widget()
  : click_callback_(NULL)
  , double_click_callback_(NULL)
  , scroll_callback_(NULL)
{
}

void DUINO_Widget::on_click()
{
  if(click_callback_)
  {
    click_callback_();
  }
}

void DUINO_Widget::on_double_click()
{
  if(double_click_callback_)
  {
    double_click_callback_();
  }
}

void DUINO_Widget::on_scroll(int delta)
{
  if(scroll_callback_ && delta)
  {
    scroll_callback_(delta);
  }
}

void DUINO_Widget::attach_click_callback(void (*callback)())
{
  click_callback_ = callback;
}

void DUINO_Widget::attach_double_click_callback(void (*callback)())
{
  double_click_callback_ = callback;
}

void DUINO_Widget::attach_scroll_callback(void (*callback)(int))
{
  scroll_callback_ = callback;
}

void DUINO_Widget::draw_invert(uint8_t x, uint8_t y, uint8_t width, uint8_t height, InvertStyle style)
{
  switch(style)
  {
    case Full:
      Display.fill_rect(x, y, width, height, DUINO_SH1106::Inverse);
      break;
    case Box:
      Display.draw_vline(x, y, height, DUINO_SH1106::Inverse);
      Display.draw_vline(x + width - 1, y, height, DUINO_SH1106::Inverse);
      Display.draw_hline(x + 1, y, width - 2, DUINO_SH1106::Inverse);
      Display.draw_hline(x + 1, y + height - 1, width - 2, DUINO_SH1106::Inverse);
      break;
    case DottedBox:
      for(uint8_t i = 0; i < width; i += 2)
      {
        Display.draw_pixel(x + i, y, DUINO_SH1106::Inverse);
        Display.draw_pixel(x + i, y + height - 1, DUINO_SH1106::Inverse);
      }
      for(uint8_t i = 2; i < height - 2; i += 2)
      {
        Display.draw_pixel(x, y + i, DUINO_SH1106::Inverse);
        Display.draw_pixel(x + width - 1, y + i, DUINO_SH1106::Inverse);
      }
      break;
    case Corners:
      Display.draw_vline(x, y, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x + 1, y, DUINO_SH1106::Inverse);
      Display.draw_vline(x + width - 1, y, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x + width - 2, y, DUINO_SH1106::Inverse);
      Display.draw_vline(x, y + height - 2, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x + 1, y + height - 1, DUINO_SH1106::Inverse);
      Display.draw_vline(x + width - 1, y + height - 2, 2, DUINO_SH1106::Inverse);
      Display.draw_pixel(x + width - 2, y + height - 1, DUINO_SH1106::Inverse);
      break;
    }
}

DUINO_DisplayWidget::DUINO_DisplayWidget(uint8_t x, uint8_t y, uint8_t width, uint8_t height,
    DUINO_Widget::InvertStyle style)
  : x_(x)
  , y_(y)
  , width_(width)
  , height_(height)
  , style_(style)
  , inverted_(false)
{
}

void DUINO_DisplayWidget::display()
{
  Display.display(x_, x_ + width_, y_ / 8, (y_ + width_) / 8);
}

void DUINO_DisplayWidget::invert(bool update_display)
{
  draw_invert(x_, y_, width_, height_, style_);

  if (update_display)
  {
    display();
  }

  inverted_ = !inverted_;
}
<|endoftext|>


<commit_before>

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include "Effekseer.InstanceGlobal.h"

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer
{
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
InstanceGlobal::InstanceGlobal()
	: m_instanceCount	( 0 )
	, m_updatedFrame	( 0 )
	, m_rootContainer	( NULL )
{

}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
InstanceGlobal::~InstanceGlobal()
{

}

void InstanceGlobal::SetSeed(int32_t seed)
{
	m_seed = seed;
}

float InstanceGlobal::GetRand()
{
	const int a = 1103515245;
	const int c = 12345;
	const int m = 2147483647;

	m_seed = (m_seed * a + c) & m;
	m_seed = m_seed % 0x7fff;

	return (float) m_seed / (float) (0x7fff - 1);
}

float InstanceGlobal::GetRand(float min_, float max_)
{
	return GetRand() * (max_ - min_) + min_;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::AddUpdatedFrame( float frame )
{
	m_updatedFrame += frame;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::IncInstanceCount()
{
	m_instanceCount++;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::DecInstanceCount()
{
	m_instanceCount--;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
int InstanceGlobal::GetInstanceCount()
{
	return m_instanceCount;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
float InstanceGlobal::GetUpdatedFrame()
{
	return m_updatedFrame;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
InstanceContainer* InstanceGlobal::GetRootContainer() const
{
	return m_rootContainer;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::SetRootContainer( InstanceContainer* container )
{
	m_rootContainer = container;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
const Vector3D& InstanceGlobal::GetTargetLocation() const
{
	return m_targetLocation;
}

void InstanceGlobal::SetTargetLocation( const Vector3D& location )
{
	m_targetLocation = location;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------<commit_msg>Fixed random<commit_after>

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include "Effekseer.InstanceGlobal.h"

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer
{
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
InstanceGlobal::InstanceGlobal()
	: m_instanceCount	( 0 )
	, m_updatedFrame	( 0 )
	, m_rootContainer	( NULL )
{

}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
InstanceGlobal::~InstanceGlobal()
{

}

void InstanceGlobal::SetSeed(int32_t seed)
{
	m_seed = seed;
}

float InstanceGlobal::GetRand()
{
	const int a = 1103515245;
	const int c = 12345;
	const int m = 2147483647;

	m_seed = (m_seed * a + c) & m;
	auto ret = m_seed % 0x7fff;

	return (float)ret / (float) (0x7fff - 1);
}

float InstanceGlobal::GetRand(float min_, float max_)
{
	return GetRand() * (max_ - min_) + min_;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::AddUpdatedFrame( float frame )
{
	m_updatedFrame += frame;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::IncInstanceCount()
{
	m_instanceCount++;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::DecInstanceCount()
{
	m_instanceCount--;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
int InstanceGlobal::GetInstanceCount()
{
	return m_instanceCount;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
float InstanceGlobal::GetUpdatedFrame()
{
	return m_updatedFrame;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
InstanceContainer* InstanceGlobal::GetRootContainer() const
{
	return m_rootContainer;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InstanceGlobal::SetRootContainer( InstanceContainer* container )
{
	m_rootContainer = container;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
const Vector3D& InstanceGlobal::GetTargetLocation() const
{
	return m_targetLocation;
}

void InstanceGlobal::SetTargetLocation( const Vector3D& location )
{
	m_targetLocation = location;
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------<|endoftext|>