<commit_before>#include <iostream>
#include <algorithm>
#include <vector>
#include <complex>

#include <sndfile.hh>

#define kiss_fft_scalar double
#include "kiss_fft.h"

int main()
{
    const int I = 2;
    const int D = 1;
    const int N = 256;
    const int M = I*N/D;
    const int L = N/8;

    kiss_fft_cfg fwd = kiss_fft_alloc(N, 0, NULL, NULL);
    kiss_fft_cfg inv = kiss_fft_alloc(M, 1, NULL, NULL);

    const std::string infilename = "sine_48000_pcm32.wav";
    const std::string outfilename = "orig.wav";
    const std::string resfilename = "res.wav";
    SndfileHandle  infile(infilename);
    SndfileHandle outfile(outfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate());
    SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D);

    std::vector<double> buffer(N);

    std::vector<std::complex<double>> fwd_fft_in_buffer(N);
    std::vector<std::complex<double>> fwd_fft_out_buffer(N);

    std::vector<std::complex<double>> bwd_fft_in_buffer(M);
    std::vector<std::complex<double>> bwd_fft_out_buffer(M);

    /* prepend 2L zeros */
    for (int i=0; i < 2*L; ++i) {
        buffer[i] = 0;
    }

    while (sf_count_t readcount = infile.read(buffer.data() + 2*L, N - 2*L))
    {
        /* Store original samples */
        outfile.write(buffer.data() + 2*L, std::min(static_cast<int>(readcount), N - 2*L));

        /* Create FFT input buffer: 1 block of N samples with 2*L overlap */
        for(int i=0; i < std::min(static_cast<int>(readcount) + 2*L, N); ++i) {
            fwd_fft_in_buffer[i] = std::complex<double>(buffer[i], 0.0);
            std::cout << i << ": " << fwd_fft_in_buffer[i] << "\n";
        }
        std::cout << "\n";

        /* Forward N points FFT */
        kiss_fft(fwd, (kiss_fft_cpx *)fwd_fft_in_buffer.data(), (kiss_fft_cpx *)(fwd_fft_out_buffer.data()));
        for(int i=0; i < N; ++i) {
            std::cout << "FFT: " << i << " " << fwd_fft_out_buffer[i] << "\n";
        }

        /* Create IFFT input buffer */
        for(int i=0; i < N/2; ++i) {
            bwd_fft_in_buffer[i] = static_cast<double>(I/D) * fwd_fft_out_buffer[i];
        }
        for(int i=N/2; i <= M - N/2; ++i) {
            bwd_fft_in_buffer[i] = static_cast<double>(I/D) * std::complex<double>(0.0, 0.0);
        }
        for(int i=M - N/2 + 1; i < M; ++i) {
            bwd_fft_in_buffer[i] = static_cast<double>(I/D) * fwd_fft_out_buffer[i + M/2];
        }

        /* IFFT */
        kiss_fft(inv, (kiss_fft_cpx *)bwd_fft_in_buffer.data(), (kiss_fft_cpx *)(bwd_fft_out_buffer.data()));
        for(int i=0; i < M; ++i) {
            std::cout << "IFFT: " << i << " " << bwd_fft_out_buffer[i] << "\n";
        }

        /* Discard first and last L points and store the rest of the real vector */
        std::vector<double> res(M - 2*L);
        int j = L;
        for(int i=0; i < M - 2*L; ++i) {
            res[i] = bwd_fft_out_buffer[j++].real();
        }
        resfile.write(res.data(), res.size());

        /* Shift vector to the left 2*L times */
        std::rotate(buffer.begin(), buffer.begin() + N - 2*L, buffer.end());
    };

    kiss_fft_free(fwd);
    kiss_fft_free(inv);

    return 0;
}
<commit_msg>Fix the overlap factor after the FFT.<commit_after>#include <iostream>
#include <algorithm>
#include <vector>
#include <complex>

#include <sndfile.hh>

#define kiss_fft_scalar double
#include "kiss_fft.h"

int main()
{
    const int I = 2;
    const int D = 1;
    const int N = 256;
    const int M = I*N/D;
    const int L = N/8;

    kiss_fft_cfg fwd = kiss_fft_alloc(N, 0, NULL, NULL);
    kiss_fft_cfg inv = kiss_fft_alloc(M, 1, NULL, NULL);

    const std::string infilename = "sine_48000_pcm32.wav";
    const std::string outfilename = "orig.wav";
    const std::string resfilename = "res.wav";
    SndfileHandle  infile(infilename);
    SndfileHandle outfile(outfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate());
    SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D);

    std::vector<double> buffer(N);

    std::vector<std::complex<double>> fwd_fft_in_buffer(N);
    std::vector<std::complex<double>> fwd_fft_out_buffer(N);

    std::vector<std::complex<double>> bwd_fft_in_buffer(M);
    std::vector<std::complex<double>> bwd_fft_out_buffer(M);

    /* prepend 2L zeros */
    for (int i=0; i < 2*L; ++i) {
        buffer[i] = 0;
    }

    while (sf_count_t readcount = infile.read(buffer.data() + 2*L, N - 2*L))
    {
        /* Store original samples */
        outfile.write(buffer.data() + 2*L, std::min(static_cast<int>(readcount), N - 2*L));

        /* Create FFT input buffer: 1 block of N samples with 2*L overlap */
        for(int i=0; i < std::min(static_cast<int>(readcount) + 2*L, N); ++i) {
            fwd_fft_in_buffer[i] = std::complex<double>(buffer[i], 0.0);
            std::cout << i << ": " << fwd_fft_in_buffer[i] << "\n";
        }
        std::cout << "\n";

        /* Forward N points FFT */
        kiss_fft(fwd, (kiss_fft_cpx *)fwd_fft_in_buffer.data(), (kiss_fft_cpx *)(fwd_fft_out_buffer.data()));
        for(int i=0; i < N; ++i) {
            std::cout << "FFT: " << i << " " << fwd_fft_out_buffer[i] << "\n";
        }

        /* Create IFFT input buffer */
        for(int i=0; i < N/2; ++i) {
            bwd_fft_in_buffer[i] = static_cast<double>(I/D) * fwd_fft_out_buffer[i];
        }
        for(int i=N/2; i <= M - N/2; ++i) {
            bwd_fft_in_buffer[i] = static_cast<double>(I/D) * std::complex<double>(0.0, 0.0);
        }
        for(int i=M - N/2 + 1; i < M; ++i) {
            bwd_fft_in_buffer[i] = static_cast<double>(I/D) * fwd_fft_out_buffer[i + M/2];
        }

        /* Backward M points IFFT */
        kiss_fft(inv, (kiss_fft_cpx *)bwd_fft_in_buffer.data(), (kiss_fft_cpx *)(bwd_fft_out_buffer.data()));
        for(int i=0; i < M; ++i) {
            std::cout << "IFFT: " << i << " " << bwd_fft_out_buffer[i] << "\n";
        }

        /* Discard first and last L points and store the rest of the real vector */
        std::vector<double> res(M - 2*I/D*L);
        int j = I/D*L;
        for(int i=0; i < M - 2*I/D*L; ++i) {
            res[i] = bwd_fft_out_buffer[j++].real();
        }
        resfile.write(res.data(), res.size());

        /* Shift vector to the left 2*L times */
        std::rotate(buffer.begin(), buffer.begin() + N - 2*L, buffer.end());
    };

    kiss_fft_free(fwd);
    kiss_fft_free(inv);

    return 0;
}
<|endoftext|>


<commit_before>#ifndef __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED
#define __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED

#include "code/ylikuutio/geometry/spherical_terrain_struct.hpp"

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstddef>  // std::size_t
#include <string>   // std::string

namespace yli
{
    namespace geometry
    {
        typedef struct TriangulateQuadsStruct
        {
            TriangulateQuadsStruct()
                : image_width(0), image_height(0), x_step(1), z_step(1), should_ylikuutio_use_real_texture_coordinates(true), sphere_radius(NAN)
            {
                // constructor.
            }
            std::size_t image_width;
            std::size_t image_height;
            std::size_t x_step;
            std::size_t z_step;
            std::string triangulation_type;
            bool should_ylikuutio_use_real_texture_coordinates;
            double sphere_radius;
            yli::geometry::SphericalTerrainStruct spherical_terrain_struct;
        } TriangulateQuadsStruct;
    }
}

#endif
<commit_msg>Split unnecessarily long line into multiple lines.<commit_after>#ifndef __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED
#define __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED

#include "code/ylikuutio/geometry/spherical_terrain_struct.hpp"

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstddef>  // std::size_t
#include <string>   // std::string

namespace yli
{
    namespace geometry
    {
        typedef struct TriangulateQuadsStruct
        {
            TriangulateQuadsStruct()
                : image_width(0),
                image_height(0),
                x_step(1),
                z_step(1),
                should_ylikuutio_use_real_texture_coordinates(true),
                sphere_radius(NAN)
            {
                // constructor.
            }
            std::size_t image_width;
            std::size_t image_height;
            std::size_t x_step;
            std::size_t z_step;
            std::string triangulation_type;
            bool should_ylikuutio_use_real_texture_coordinates;
            double sphere_radius;
            yli::geometry::SphericalTerrainStruct spherical_terrain_struct;
        } TriangulateQuadsStruct;
    }
}

#endif
<|endoftext|>


<commit_before>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_GAME_GAME_HPP
#define RJ_CORE_GAME_GAME_HPP

#include "game_updater.hpp"
#include "game_window.hpp"

namespace rj
{
	class game
	{
		game_window& m_window;

	public:
		game(game_window& window) :
			m_window{window}
		{
			m_window.updater().on_update.add_func([this](dur duration){this->update(duration);});
			m_window.updater().on_render.add_func([this]{this->render();});
		}

		void update(dur duration)
		{

		}

		void render()
		{

		}

		void render_object(const sf::Drawable& object)
		{m_window.draw(object);}
	};
}

#endif // RJ_CORE_GAME_GAME_HPP
<commit_msg>using += operator<commit_after>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_GAME_GAME_HPP
#define RJ_CORE_GAME_GAME_HPP

#include "game_updater.hpp"
#include "game_window.hpp"

namespace rj
{
	class game
	{
		game_window& m_window;

	public:
		game(game_window& window) :
			m_window{window}
		{
			m_window.updater().on_update += [this](dur duration){this->update(duration);};
			m_window.updater().on_render += [this]{this->render();};
		}

		void update(dur duration)
		{

		}

		void render()
		{

		}

		void render_object(const sf::Drawable& object)
		{m_window.draw(object);}
	};
}

#endif // RJ_CORE_GAME_GAME_HPP
<|endoftext|>


<commit_before>/*
 * preprocessor.hpp
 *
 *  Created on: Jun 29, 2015
 *      Author: hugo
 */

#ifndef SRC_PREPROCESSOR_HPP_
#define SRC_PREPROCESSOR_HPP_

#include <cassert>
#include <string>

#include "../../log/easylogging++.h"
#include "mapped_stream.hpp"
#include "splitterbuffer.hpp"

namespace mflash{

template <class IdType>
class EdgeConversor{
	public:
		template <class Splitter>
		static void process (const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter);
};

template <class IdType>
template <class Splitter>
void EdgeConversor<IdType>::process(const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter){
	MappedStream in(file_graph);

	IdType v1 = 		0;
	IdType v2 = 		0;
	bool isQuantity = !edgelist;
	bool isInVertice = 	true;

	const char comment = '#';
	const char comment2 = '%';
	const char end_line = '\n';
	const char end_line2 = '\r';
	//char separator = ' ';
	const char separator2 = '\t';
	const char separator3 = ' ';

	EmptyField value;

/*

	const int64 MEGABYTE = 1024 * 1024;
	const int64 STEP_INFO = 500 * MEGABYTE;
*/

	while(in.has_remain()){
		char b = in.next();
		/*if( (in.current_ptr-in.ptr) % STEP_INFO ==0){
			LOG(INFO)<<"Processed: " << (in.current_ptr-in.ptr) / MEGABYTE << "MB";
		}*/
		//removing comment line
	  if(b == comment || b == comment2){
		while(b != end_line){
		  b = in.next();
		}
		b = in.next();
		//when the line content \n\r
		while( b == end_line || b==end_line2){
			b = in.next();
		}
		in.set_position(in.position()- sizeof(char));
		continue;
	  }
	  if (b == separator || b == separator2 || b == separator3){
		if(!isInVertice && !isQuantity){ //
			splitter.add(v1, v2, &value);
		}else{
			if(isInVertice) isInVertice = false;
			else if(isQuantity) isQuantity = false;
		}
		v2 = 0;
		continue;
	  }
		if (b == end_line || b == end_line2){
			b = in.next();
			//when the line content \n\r
			while( b == end_line || b==end_line2){
				b = in.next();
			}
			in.set_position(in.position()- sizeof(char));

			if(!isQuantity || edgelist){
				splitter.add(v1, v2, &value);
			}
			v1 = 0;
			v2 = 0;
			isInVertice = true;
			isQuantity = !edgelist;
			continue;
		}
		if(b<48 || b > 57){
			LOG(ERROR) << "The character '" << b << "' was not recognized.";
			assert(false);
		}

		if(isInVertice){
			v1 = (v1<< 3) + (v1 << 1) + (0xF & b);
		}else{
			v2 = (v2<< 3) + (v2 << 1) + (0xF & b);
		}
	}
	in.close_stream();
	splitter.flush();
	LOG(INFO)<<"Graph Binarization was succesfully";
}

}

#endif /* SRC_PREPROCESSOR_HPP_ */
<commit_msg>Solving mistake with \r\n<commit_after>/*
 * preprocessor.hpp
 *
 *  Created on: Jun 29, 2015
 *      Author: hugo
 */

#ifndef SRC_PREPROCESSOR_HPP_
#define SRC_PREPROCESSOR_HPP_

#include <cassert>
#include <string>

#include "../../log/easylogging++.h"
#include "mapped_stream.hpp"
#include "splitterbuffer.hpp"

namespace mflash{

template <class IdType>
class EdgeConversor{
	public:
		template <class Splitter>
		static void process (const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter);
};

template <class IdType>
template <class Splitter>
void EdgeConversor<IdType>::process(const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter){
	MappedStream in(file_graph);

	IdType v1 = 		0;
	IdType v2 = 		0;
	bool isQuantity = !edgelist;
	bool isInVertice = 	true;

	const char comment = '#';
	const char comment2 = '%';
	const char end_line = '\n';
	const char end_line2 = '\r';
	//char separator = ' ';
	const char separator2 = '\t';
	const char separator3 = ' ';

	EmptyField value;

/*

	const int64 MEGABYTE = 1024 * 1024;
	const int64 STEP_INFO = 500 * MEGABYTE;
*/

	while(in.has_remain()){
		char b = in.next();
		/*if( (in.current_ptr-in.ptr) % STEP_INFO ==0){
			LOG(INFO)<<"Processed: " << (in.current_ptr-in.ptr) / MEGABYTE << "MB";
		}*/
		//removing comment line
	  if(b == comment || b == comment2){
		while(b != end_line){
		  b = in.next();
		}
		b = in.next();
		//when the line content \n\r
		while( b == end_line || b==end_line2){
			b = in.next();
		}
		in.set_position(in.position()- sizeof(char));
		continue;
	  }
	  if (b == separator || b == separator2 || b == separator3){
		if(!isInVertice && !isQuantity){ //
			splitter.add(v1, v2, &value);
		}else{
			if(isInVertice) isInVertice = false;
			else if(isQuantity) isQuantity = false;
		}
		v2 = 0;
		continue;
	  }
		if (b == end_line || b == end_line2){
			b = in.next();
			//when the line content \r\n
			while( b == end_line || b==end_line2){
				b = in.next();
			}
			in.set_position(in.position()- sizeof(char));

			if(!isQuantity || edgelist){
				splitter.add(v1, v2, &value);
			}
			v1 = 0;
			v2 = 0;
			isInVertice = true;
			isQuantity = !edgelist;
			continue;
		}
		if(b<48 || b > 57){
			LOG(ERROR) << "The character '" << b << "' was not recognized.";
			assert(false);
		}

		if(isInVertice){
			v1 = (v1<< 3) + (v1 << 1) + (0xF & b);
		}else{
			v2 = (v2<< 3) + (v2 << 1) + (0xF & b);
		}
	}
	in.close_stream();
	splitter.flush();
	LOG(INFO)<<"Graph Binarization was succesfully";
}

}

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


<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_UI_BUTTON_HPP
#define RJ_UI_BUTTON_HPP

#include "widget.hpp"
#include <rectojump/global/common.hpp>
#include <rectojump/shared/input.hpp>

#include <mlk/signals_slots/slot.h>
#include <mlk/types/types.h>

namespace rj
{
	namespace ui
	{
		class button : public ui::widget
		{
		protected:
			sf::RectangleShape m_shape;
			sf::Text m_text;
			bool m_hover{false};
			bool m_press{false};

		private:
			sf::RectangleShape m_restore_shape;

		public:
			mlk::slot<> on_clicked;
			mlk::slot<> on_hovered;

			button(const vec2f& size = {0.f, 0.f}, const vec2f& pos = {0.f, 0.f}) :
				m_shape{size}
			{
				m_shape.setPosition(pos);
				this->init_base();
			}

			button(const vec2f& size, const std::string& text, const sf::Font& font, const sf::Color& fontcolor = {}) :
				button{size}
			{
				m_text.setString(text);
				m_text.setFont(font);
				m_text.setColor(fontcolor);
				this->calculate_textpos();
			}

			void update(dur)
			{
				// check states
				if(m_hover) this->on_hover();
				else this->on_hover_end();

				if(m_press) this->on_press();
				else this->on_press_end();

				// collision
				auto bounds(m_shape.getGlobalBounds());
				auto mousebounds(inp::get_mousebounds<true>());

				if(bounds.intersects(mousebounds))
					m_hover = true;
				else m_hover = false;

				if(m_hover)
				{
					if(inp::is_btn_pressed(btn::Left))
						m_press = true;
					else if(inp::was_real_mousepress_left())
						this->on_clicked();
					else m_press = false;
				}
				else m_press = false;
			}

			void setText(const std::string& text) noexcept
			{m_text.setString(text); this->calculate_textpos();}

			void setFont(const sf::Font& font) noexcept
			{m_text.setFont(font); this->calculate_textpos();}

			void setFontColor(const sf::Color& color) noexcept
			{m_text.setColor(color);}

			void setFontSize(mlk::uint size) noexcept
			{m_text.setCharacterSize(size); this->calculate_textpos();}

			void setColor(const sf::Color& color) noexcept
			{m_shape.setFillColor(color); m_restore_shape.setFillColor(color);}

			void setOutlineThickness(float thickness) noexcept
			{m_shape.setOutlineThickness(thickness); m_restore_shape.setOutlineThickness(thickness);}

			void setOutlineColor(const sf::Color& color) noexcept
			{m_shape.setOutlineColor(color); m_restore_shape.setOutlineColor(color);}

			void setPosition(const vec2f& pos) noexcept
			{m_shape.setPosition(pos); m_restore_shape.setPosition(pos); this->calculate_textpos();}

			void setOrigin(const vec2f& pos) noexcept
			{m_shape.setOrigin(pos); m_restore_shape.setOrigin(pos); this->calculate_textpos();}

			void setSize(const vec2f& size) noexcept
			{m_shape.setSize(size); m_restore_shape.setSize(size); this->calculate_textpos();}

			void setTexture(sf::Texture* tx) noexcept
			{m_shape.setTexture(tx); m_restore_shape.setTexture(tx);}

			void move(const vec2f& offset) noexcept
			{m_shape.move(offset); m_restore_shape.move(offset); this->calculate_textpos();}

			void rotate(float angle) noexcept
			{m_shape.rotate(angle); m_restore_shape.rotate(angle); this->calculate_textpos();}

			std::string getText() const noexcept
			{return m_text.getString();}

			const sf::Font* getFont() const noexcept
			{return m_text.getFont();}

			const sf::Color& getFontColor() const noexcept
			{return m_text.getColor();}

			mlk::uint getFontSize() const noexcept
			{return m_text.getCharacterSize();}

			const sf::Color& getColor() const noexcept
			{return m_shape.getFillColor();}

			float getOutlineThickness() const noexcept
			{return m_shape.getOutlineThickness();}

			const sf::Color& getOutlineColor() const noexcept
			{return m_shape.getOutlineColor();}

			const vec2f& getPosition() const noexcept
			{return m_shape.getPosition();}

			const vec2f& getOrigin() const noexcept
			{return m_shape.getOrigin();}

			const vec2f& getSize() const noexcept
			{return m_shape.getSize();}

			const sf::Texture* getTexture() const noexcept
			{return m_shape.getTexture();}

			bool pressed() const noexcept
			{return m_press;}

			bool hover() const noexcept
			{return m_hover;}

		protected:
			virtual void init()
			{
				// init the rect
			}

			void init_base()
			{
				this->init();
				this->create_restore_shape();
			}

			virtual void on_hover()
			{
				// do something on hover
			}

			virtual void on_hover_end()
			{
				if(m_press) return;
				this->restore_origin();
			}

			virtual void on_press()
			{
				// do something on press
			}

			virtual void on_press_end()
			{
				if(m_hover) return;
				this->restore_origin();
			}

			void create_restore_shape() noexcept
			{m_restore_shape = m_shape;}

			void restore_origin() noexcept
			{m_shape = m_restore_shape;}

			virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override
			{
				target.draw(m_shape, states);
				target.draw(m_text, states);
			}

		private:
			void calculate_textpos()
			{
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_text.getGlobalBounds());
				m_text.setOrigin(text_bounds.width / 2.f, text_bounds.height / 2.f);
				m_text.setPosition(shape_bounds.left + shape_bounds.width / 2.f, shape_bounds.top + shape_bounds.height / 2.f);
			}
		};
	}
}

#endif // RJ_UI_BUTTON_HPP
<commit_msg>ui > button: changed the if statements<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_UI_BUTTON_HPP
#define RJ_UI_BUTTON_HPP

#include "widget.hpp"
#include <rectojump/global/common.hpp>
#include <rectojump/shared/input.hpp>

#include <mlk/signals_slots/slot.h>
#include <mlk/types/types.h>

namespace rj
{
	namespace ui
	{
		class button : public ui::widget
		{
		protected:
			sf::RectangleShape m_shape;
			sf::Text m_text;
			bool m_hover{false};
			bool m_press{false};

		private:
			sf::RectangleShape m_restore_shape;

		public:
			mlk::slot<> on_clicked;
			mlk::slot<> on_hovered;

			button(const vec2f& size = {0.f, 0.f}, const vec2f& pos = {0.f, 0.f}) :
				m_shape{size}
			{
				m_shape.setPosition(pos);
				this->init_base();
			}

			button(const vec2f& size, const std::string& text, const sf::Font& font, const sf::Color& fontcolor = {}) :
				button{size}
			{
				m_text.setString(text);
				m_text.setFont(font);
				m_text.setColor(fontcolor);
				this->calculate_textpos();
			}

			void update(dur)
			{
				// check states
				if(m_hover) this->on_hover();
				else this->on_hover_end();

				if(m_press) this->on_press();
				else this->on_press_end();

				// collision
				auto bounds(m_shape.getGlobalBounds());
				auto mousebounds(inp::get_mousebounds<true>());

				if(bounds.intersects(mousebounds))
					m_hover = true;
				else m_hover = false;

				if(m_hover)
				{
					if(inp::is_btn_pressed(btn::Left))
						m_press = true;
					else m_press = false;

					if(inp::was_real_mousepress_left())
						this->on_clicked();
				}
				else m_press = false;
			}

			void setText(const std::string& text) noexcept
			{m_text.setString(text); this->calculate_textpos();}

			void setFont(const sf::Font& font) noexcept
			{m_text.setFont(font); this->calculate_textpos();}

			void setFontColor(const sf::Color& color) noexcept
			{m_text.setColor(color);}

			void setFontSize(mlk::uint size) noexcept
			{m_text.setCharacterSize(size); this->calculate_textpos();}

			void setColor(const sf::Color& color) noexcept
			{m_shape.setFillColor(color); m_restore_shape.setFillColor(color);}

			void setOutlineThickness(float thickness) noexcept
			{m_shape.setOutlineThickness(thickness); m_restore_shape.setOutlineThickness(thickness);}

			void setOutlineColor(const sf::Color& color) noexcept
			{m_shape.setOutlineColor(color); m_restore_shape.setOutlineColor(color);}

			void setPosition(const vec2f& pos) noexcept
			{m_shape.setPosition(pos); m_restore_shape.setPosition(pos); this->calculate_textpos();}

			void setOrigin(const vec2f& pos) noexcept
			{m_shape.setOrigin(pos); m_restore_shape.setOrigin(pos); this->calculate_textpos();}

			void setSize(const vec2f& size) noexcept
			{m_shape.setSize(size); m_restore_shape.setSize(size); this->calculate_textpos();}

			void setTexture(sf::Texture* tx) noexcept
			{m_shape.setTexture(tx); m_restore_shape.setTexture(tx);}

			void move(const vec2f& offset) noexcept
			{m_shape.move(offset); m_restore_shape.move(offset); this->calculate_textpos();}

			void rotate(float angle) noexcept
			{m_shape.rotate(angle); m_restore_shape.rotate(angle); this->calculate_textpos();}

			std::string getText() const noexcept
			{return m_text.getString();}

			const sf::Font* getFont() const noexcept
			{return m_text.getFont();}

			const sf::Color& getFontColor() const noexcept
			{return m_text.getColor();}

			mlk::uint getFontSize() const noexcept
			{return m_text.getCharacterSize();}

			const sf::Color& getColor() const noexcept
			{return m_shape.getFillColor();}

			float getOutlineThickness() const noexcept
			{return m_shape.getOutlineThickness();}

			const sf::Color& getOutlineColor() const noexcept
			{return m_shape.getOutlineColor();}

			const vec2f& getPosition() const noexcept
			{return m_shape.getPosition();}

			const vec2f& getOrigin() const noexcept
			{return m_shape.getOrigin();}

			const vec2f& getSize() const noexcept
			{return m_shape.getSize();}

			const sf::Texture* getTexture() const noexcept
			{return m_shape.getTexture();}

			bool pressed() const noexcept
			{return m_press;}

			bool hover() const noexcept
			{return m_hover;}

		protected:
			virtual void init()
			{
				// init the rect
			}

			void init_base()
			{
				this->init();
				this->create_restore_shape();
			}

			virtual void on_hover()
			{
				// do something on hover
			}

			virtual void on_hover_end()
			{
				if(m_press) return;
				this->restore_origin();
			}

			virtual void on_press()
			{
				// do something on press
			}

			virtual void on_press_end()
			{
				if(m_hover) return;
				this->restore_origin();
			}

			void create_restore_shape() noexcept
			{m_restore_shape = m_shape;}

			void restore_origin() noexcept
			{m_shape = m_restore_shape;}

			virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override
			{
				target.draw(m_shape, states);
				target.draw(m_text, states);
			}

		private:
			void calculate_textpos()
			{
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_text.getGlobalBounds());
				m_text.setOrigin(text_bounds.width / 2.f, text_bounds.height / 2.f);
				m_text.setPosition(shape_bounds.left + shape_bounds.width / 2.f, shape_bounds.top + shape_bounds.height / 2.f);
			}
		};
	}
}

#endif // RJ_UI_BUTTON_HPP
<|endoftext|>


<commit_before>//
// Macro to be invoked before Calibration analysis
// Setup TPC OCDB entries
//
// This is just example macro  - some path are hardwired
//  TO BE MODIFIED BY USERS

void ConfigOCDB(Float_t bfield){
  //
  //
  // import geometry
  //

  printf("SETUP OCBD for PROOF\n");
  TGeoManager::Import("/u/miranov/proof/geometry.root");
  AliGeomManager::LoadGeometry("/u/miranov/proof/geometry.root");
  //
  //
  // Setup magnetic field
  //
  TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));
  //
  //
  //
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/Parameters","local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/ClusterParam","local://$ALICE_ROOT/OCDB");
  //  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/PadTime0","local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/PadTime0","local:///u/miranov/OCDB0");

  AliCDBManager::Instance()->SetSpecificStorage("GRP/GRP/Data","local:///lustre_alpha/alice/alien/alice/data/2008/LHC08d/OCDB/");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/Temperature","local:///lustre_alpha/alice/alien/alice/data/2008/LHC08d/OCDB/");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/Goofie","local:///lustre_alpha/alice/alien/alice/data/2008/LHC08d/OCDB/");

  AliCDBManager::Instance()->SetRun(1);

  AliTPCClusterParam * paramCl = AliTPCcalibDB::Instance()->GetClusterParam();
  AliTPCParam   * paramTPC = AliTPCcalibDB::Instance()->GetParameters();
  paramCl->SetInstance(paramCl);
  //paramTPC->Dump();
  printf("\n\nSET EXB FIELD\t%f\n\n", bfield);
  AliTPCcalibDB::Instance()->SetExBField(bfield);
  //
  //
  //
  printf("END of SETUP OCBD for PROOF\n");
}

void ConfigAlien(){
  //
  // Setup-activate alien
  //

  //myvar=342
  //while [ $myvar -ne 360 ] ; do  echo enable alien on lxb$myvar; lsrun -m lxb$myvar  /u/miranov/.aliensetup;  myvar=$(( $myvar + 1 )) ; echo $myvar ; done
  gSystem->Exec("/u/miranov/.aliensetup >setup.log");
  //ifstream in;
  //in.open("path.txt");

  TString envString;

  gSystem->Setenv("LD_LIBRARY_PATH",envString.Data());
  gSystem->Setenv("GBBOX_ENVFILE","/tmp/xxxxxxx");
  printf("LOAD LIBRARIES start\n\n\n");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libSTAT.so");
  gSystem->Load("libTPCcalib.so");
  //
  gSystem->Load("libXrdClient.so");
  gSystem->Load("libNetx.so");
  printf("LOAD LIBRARIES end\n\n\n");
  TGrid * alien = TGrid::Connect("alien://",0,0,"t");
  if (alien) {
    printf("Alien activated\n");
  }else{
    printf("Alien not activated\n");
  }
}
<commit_msg>THIS IS EXAMPLE MACRO:<commit_after>//
// Macro to Setup OCDB
// This is just example macro
// Responsible: marian.ivanov@cern.ch
// To be used:
// 1. Before invocation of the calibration - in the calibration trains
// 2. To setup calibration viewer.
//
// ConfigOCDB  - setup default and specific data storage
// SetupCustom - user sepcific configuration
//             - Values in local cache of OCDB are overwritten

void SetupCustom(Int_t run);

void ConfigOCDB(Int_t crun=-1){
  //
  printf("SETUP OCBD for TPC\n");
  //
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/Parameters","local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/ClusterParam","local:///u/miranov/OCDB/TPCcosmic2/");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/PadTime0","local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetSpecificStorage("GRP/GRP/Data","local:///lustre/alice/alien/alice/data/2009/OCDB/");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/Temperature","local:///lustre/alice/alien/alice/data/2009/OCDB/");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/Goofie","local:///lustre/alice/alien/alice/data/2009/OCDB/");
  AliCDBManager::Instance()->SetSpecificStorage("TPC/Calib/HighVoltage","local:///lustre/alice/alien/alice/data/2009/OCDB/");
  Int_t run =crun;
  if (run<0) run =0;
  AliCDBManager::Instance()->SetRun(run);
  SetupCustom(run);
}

void SetupCustom(Int_t run){
  //
  //
  // Custom part - to be empty once we are happy with the calibration
  //
  //
  // Setup magnetic field
  //
  AliGRPObject *grp = AliTPCcalibDB::GetGRP(run);
  Float_t current = 0;
  Float_t bz      = 0;
  if (grp){
    current = grp->GetL3Current((AliGRPObject::Stats)0);
    bz = 5*current/30000.;
    printf("Run%d\tL3 current%f\tBz\t%f\n",run,current,bz);
  }
  else{
    printf("Run%d\tL3 current%f\tBz\t%f\n",run,current,bz);
  }
  AliMagF::BMap_t smag = AliMagF::k5kG;
  Double_t bzfac = bz/5;
  TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, bzfac, 1., 10., smag));

  printf("\n\nSET EXB FIELD\t%f\n\n", -bz);
  AliTPCcalibDB::Instance()->SetExBField(-bz);
  //
  //
  // import geometry
  //
  //
  TGeoManager::Import("/u/miranov/proof/geometry.root");
  AliGeomManager::LoadGeometry("/u/miranov/proof/geometry.root");

  AliTPCClusterParam * paramCl = AliTPCcalibDB::Instance()->GetClusterParam();
  AliTPCParam   * paramTPC = AliTPCcalibDB::Instance()->GetParameters();
  paramCl->SetInstance(paramCl);

  //
  // Setup reco param
  //
  AliTPCTransform *transform     = AliTPCcalibDB::Instance()->GetTransform() ;
  AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
  transform->SetCurrentRecoParam(tpcRecoParam);
  tpcRecoParam->SetUseRPHICorrection(kTRUE);
  //
  tpcRecoParam->SetUseRadialCorrection(kFALSE);
  tpcRecoParam->SetUseQuadrantAlignment(kTRUE);
  //
  tpcRecoParam->SetUseSectorAlignment(kFALSE);
  tpcRecoParam->SetUseDriftCorrectionTime(kFALSE);
  tpcRecoParam->SetUseDriftCorrectionGY(kTRUE);
  tpcRecoParam->SetUseGainCorrectionTime(kFALSE);
  tpcRecoParam->SetUseFieldCorrection(kFALSE);
  tpcRecoParam->SetUseExBCorrection(kTRUE);
  //
  //
  //
  TFile fposcor("~/OCDB/calibUnlin.root");
  AliTPCPointCorrection *pcorr = fposcor.Get("correction");
  if (pcorr) pcorr->SetInstance(pcorr);
  //
  //
  //
  printf("END of SETUP OCBD for TPC\n");
}

<|endoftext|>


<commit_before>#ifndef ___INANITY_EXCEPTION_HPP___
#define ___INANITY_EXCEPTION_HPP___

#include "Object.hpp"
#include "String.hpp"
#include "meta/decl.hpp"
#include <ostream>

BEGIN_INANITY

/// Базовый класс исключения.
/** Данный класс используется везде, для предоставления информации
о происходящих ошибках.
Происходящяя ошибка должна обрабатываться соответствующим кодом,
который переводит её в первичное исключение Inanity.
Это первичное исключение может быть перехвачено кодом, решающим
более высокоуровневую задачу; он должен в свою очередь создать
вторичное исключение, и описать в нем, какая ошибка произошла
с его точки зрения. Последующие уровни кода также могут создавать
вторичные исключения, каждый раз описывая проблему все более и
более глобально. Такая схема позволяет легко понять, почему
ошибка произошла, и что сделать для её устранения, а также
легко контролировать возникновение ошибок.
Сообщение, которое задаётся для исключения, должно быть одним
предложением, с большой буквы, без завершающей точки или перевода
строки.
*/
class Exception : public Object
{
protected:
	String message;
	ptr<Exception> innerException;

public:
	/// Создать первичный объект исключения.
	/** Первичный объект исключения является первым исключением,
	возникающем при ошибке.
	\param message Текстовое сообщение об ошибке.
	*/
	Exception(const String& message);

	/// Создать вторичный объект исключения.
	/** Вторичный объект исключения является исключением,
	обертывающим более низкоуровневое исключение,
	и объясняющим с более глобальной точки зрения,
	что означает данная ошибка.
	\param message Текстовое сообщение об ошибке.
	\param innerException Исключение более низкого уровня,
	породившее данное исключение.
	*/
	Exception(const String& message, ptr<Exception> innerException);

	/// Получить текст сообщения об ошибке.
	/** Данный текст включает только сообщение, которое
	относится именно к этому уровню ошибки.
	\return Текст сообщения об ошибке.
	*/
	String GetMessageText() const;

	/// Получить внутреннее (низкоуровневое) исключение
	/** \return Объект внутреннего исключения, или null,
	если данное исключение первичное.
	*/
	ptr<Exception> GetInnerException() const;

	/// Вывести в поток вывода сообщения всего стека исключений.
	/** Позволяет получить полную картину произошедшей ошибки,
	выводя всю информацию по указанной ошибке.
	*/
	virtual void PrintStack(std::ostream& stream) const;

	/// Создать исключение, описывающее ошибку системы.
	/** Ошибка системы определяется специфичным для платформы способом (Windows - GetLastError, Linux - errno). */
	static ptr<Exception> SystemError();
	static ptr<Exception> SystemError(int errorCode);

	META_DECLARE_CLASS(Exception);
};

#ifdef _DEBUG
#define __SLINE2__(x) #x
#define __SLINE3__(x) __SLINE2__(x)
#define __SLINE__ __SLINE3__(__LINE__)
/// Макрос для вызова первичного исключения
#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception(String("[ " __FILE__ ", " __SLINE__ " ] ") + (message)))
/// Макрос для вызова вторичного исключения
#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception(String("[ " __FILE__ ", " __SLINE__ " ] ") + (message), (exception)))
#else
/// Макрос для вызова первичного исключения
#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception((message)))
/// Макрос для вызова вторичного исключения
#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception((message), (exception)))
#endif

END_INANITY

#endif
<commit_msg>BEGIN_TRY, END_TRY macros<commit_after>#ifndef ___INANITY_EXCEPTION_HPP___
#define ___INANITY_EXCEPTION_HPP___

#include "Object.hpp"
#include "String.hpp"
#include "meta/decl.hpp"
#include <ostream>

BEGIN_INANITY

/// Базовый класс исключения.
/** Данный класс используется везде, для предоставления информации
о происходящих ошибках.
Происходящяя ошибка должна обрабатываться соответствующим кодом,
который переводит её в первичное исключение Inanity.
Это первичное исключение может быть перехвачено кодом, решающим
более высокоуровневую задачу; он должен в свою очередь создать
вторичное исключение, и описать в нем, какая ошибка произошла
с его точки зрения. Последующие уровни кода также могут создавать
вторичные исключения, каждый раз описывая проблему все более и
более глобально. Такая схема позволяет легко понять, почему
ошибка произошла, и что сделать для её устранения, а также
легко контролировать возникновение ошибок.
Сообщение, которое задаётся для исключения, должно быть одним
предложением, с большой буквы, без завершающей точки или перевода
строки.
*/
class Exception : public Object
{
protected:
	String message;
	ptr<Exception> innerException;

public:
	/// Создать первичный объект исключения.
	/** Первичный объект исключения является первым исключением,
	возникающем при ошибке.
	\param message Текстовое сообщение об ошибке.
	*/
	Exception(const String& message);

	/// Создать вторичный объект исключения.
	/** Вторичный объект исключения является исключением,
	обертывающим более низкоуровневое исключение,
	и объясняющим с более глобальной точки зрения,
	что означает данная ошибка.
	\param message Текстовое сообщение об ошибке.
	\param innerException Исключение более низкого уровня,
	породившее данное исключение.
	*/
	Exception(const String& message, ptr<Exception> innerException);

	/// Получить текст сообщения об ошибке.
	/** Данный текст включает только сообщение, которое
	относится именно к этому уровню ошибки.
	\return Текст сообщения об ошибке.
	*/
	String GetMessageText() const;

	/// Получить внутреннее (низкоуровневое) исключение
	/** \return Объект внутреннего исключения, или null,
	если данное исключение первичное.
	*/
	ptr<Exception> GetInnerException() const;

	/// Вывести в поток вывода сообщения всего стека исключений.
	/** Позволяет получить полную картину произошедшей ошибки,
	выводя всю информацию по указанной ошибке.
	*/
	virtual void PrintStack(std::ostream& stream) const;

	/// Создать исключение, описывающее ошибку системы.
	/** Ошибка системы определяется специфичным для платформы способом (Windows - GetLastError, Linux - errno). */
	static ptr<Exception> SystemError();
	static ptr<Exception> SystemError(int errorCode);

	META_DECLARE_CLASS(Exception);
};

#ifdef _DEBUG
#define __SLINE2__(x) #x
#define __SLINE3__(x) __SLINE2__(x)
#define __SLINE__ __SLINE3__(__LINE__)
/// Макрос для вызова первичного исключения
#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception(String("[ " __FILE__ ", " __SLINE__ " ] ") + (message)))
/// Макрос для вызова вторичного исключения
#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception(String("[ " __FILE__ ", " __SLINE__ " ] ") + (message), (exception)))
#else
/// Макрос для вызова первичного исключения
#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception((message)))
/// Макрос для вызова вторичного исключения
#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception((message), (exception)))
#endif

#define BEGIN_TRY() try {
#define END_TRY(message) } catch(Exception* exception) { THROW_SECONDARY_EXCEPTION(message, exception); }

END_INANITY

#endif
<|endoftext|>


<commit_before>#include "makeplan.h"

MakePlan::MakePlan()
{
}

void MakePlan::removeOutliers(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)
{
  pcl::RadiusOutlierRemoval<pcl::PointXYZ> outrem;
  // build the filter
  outrem.setInputCloud(cloud_in);
  outrem.setRadiusSearch(0.01);
  outrem.setMinNeighborsInRadius (4);
  // apply filter
  outrem.filter (*cloud_out);
}

bool MakePlan::getAveragePoint(PointCloud::Ptr cloud_in, pcl::PointXYZ &avrPt)
{
  if (!cloud_in->points.size())
  {
    return false;
  }

  pcl::PointXYZ min_dis_point;
  float min_dis = 100.0;
  for (PointCloud::const_iterator it = cloud_in->begin(); it != cloud_in->end(); ++ it)
  {
    float dis = pow(it->x, 2) + pow(it->y, 2);
    if (dis < min_dis)
    {
      min_dis = dis;
      min_dis_point = *it;
    }
  }

  smartOffset(min_dis_point, 0.02);
  avrPt = min_dis_point;
  return true;
}

void MakePlan::smartOffset(pcl::PointXYZ &p_in, float off_val)
{
  float y_off = off_val / sqrt(1 + pow(p_in.x / p_in.y, 2)) * p_in.y / fabs(p_in.y);
  float x_off = p_in.x / p_in.y * y_off;
  p_in.x = p_in.x + x_off;
  p_in.y = p_in.y + y_off;
}

void MakePlan::removeNans(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)
{
  std::vector< int >	index;
  PointCloud::Ptr cloud_filtered_nan (new PointCloud);

  pcl::removeNaNFromPointCloud(*cloud_in, *cloud_filtered_nan, index);

  pcl::PointIndices::Ptr indices_x(new pcl::PointIndices);
  pcl::PointIndices::Ptr indices_xy(new pcl::PointIndices);

  pcl::PassThrough<pcl::PointXYZ> ptfilter; // Initializing with true will allow us to extract the removed indices
  ptfilter.setInputCloud (cloud_filtered_nan);
  ptfilter.setFilterFieldName ("x");
  ptfilter.setFilterLimits (-0.2, 0.2);
  ptfilter.filter (indices_x->indices);

  ptfilter.setIndices (indices_x);
  ptfilter.setFilterFieldName ("y");
  ptfilter.setFilterLimits (-0.2, 0.2);
  ptfilter.filter (indices_xy->indices);

  ptfilter.setIndices (indices_xy);
  ptfilter.setFilterFieldName ("z");
  ptfilter.setFilterLimits (0.5, 2.0);// this method can only be used on source cloud, aka cloud whose frame is camera optical frame
  ptfilter.filter (*cloud_out);
}

bool MakePlan::process(PointCloud::Ptr cloud_in, float a, float b, float c, float d, pcl::PointXYZ &avrPt)
{
  if (!cloud_in->points.size())
  {
    return false;
  }

  PointCloud::Ptr cloud_filtered (new PointCloud);
#ifdef USE_CENTER
  cloud_filtered = cloud_in;
#else
  removeOutliers(cloud_in, cloud_filtered);
#endif
  bool success = getAveragePoint(cloud_filtered, avrPt);
  return success;
}
<commit_msg>shift target pose a bit in -z<commit_after>#include "makeplan.h"

MakePlan::MakePlan()
{
}

void MakePlan::removeOutliers(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)
{
  pcl::RadiusOutlierRemoval<pcl::PointXYZ> outrem;
  // build the filter
  outrem.setInputCloud(cloud_in);
  outrem.setRadiusSearch(0.01);
  outrem.setMinNeighborsInRadius (4);
  // apply filter
  outrem.filter (*cloud_out);
}

bool MakePlan::getAveragePoint(PointCloud::Ptr cloud_in, pcl::PointXYZ &avrPt)
{
  if (!cloud_in->points.size())
  {
    return false;
  }

  pcl::PointXYZ min_dis_point;
  float min_dis = 100.0;
  for (PointCloud::const_iterator it = cloud_in->begin(); it != cloud_in->end(); ++ it)
  {
    float dis = pow(it->x, 2) + pow(it->y, 2);
    if (dis < min_dis)
    {
      min_dis = dis;
      min_dis_point = *it;
    }
  }

  smartOffset(min_dis_point, 0.02);
  avrPt = min_dis_point;
  return true;
}

void MakePlan::smartOffset(pcl::PointXYZ &p_in, float off_val)
{
  float y_off = off_val / sqrt(1 + pow(p_in.x / p_in.y, 2)) * p_in.y / fabs(p_in.y);
  float x_off = p_in.x / p_in.y * y_off;
  p_in.x += x_off;
  p_in.y += y_off;
  float off_z = 0.05; // To solve the detected point is higher than optimal
  p_in.z -= off_z;
}

void MakePlan::removeNans(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)
{
  std::vector< int >	index;
  PointCloud::Ptr cloud_filtered_nan (new PointCloud);

  pcl::removeNaNFromPointCloud(*cloud_in, *cloud_filtered_nan, index);

  pcl::PointIndices::Ptr indices_x(new pcl::PointIndices);
  pcl::PointIndices::Ptr indices_xy(new pcl::PointIndices);

  pcl::PassThrough<pcl::PointXYZ> ptfilter; // Initializing with true will allow us to extract the removed indices
  ptfilter.setInputCloud (cloud_filtered_nan);
  ptfilter.setFilterFieldName ("x");
  ptfilter.setFilterLimits (-0.2, 0.2);
  ptfilter.filter (indices_x->indices);

  ptfilter.setIndices (indices_x);
  ptfilter.setFilterFieldName ("y");
  ptfilter.setFilterLimits (-0.2, 0.2);
  ptfilter.filter (indices_xy->indices);

  ptfilter.setIndices (indices_xy);
  ptfilter.setFilterFieldName ("z");
  ptfilter.setFilterLimits (0.5, 2.0);// this method can only be used on source cloud, aka cloud whose frame is camera optical frame
  ptfilter.filter (*cloud_out);
}

bool MakePlan::process(PointCloud::Ptr cloud_in, float a, float b, float c, float d, pcl::PointXYZ &avrPt)
{
  if (!cloud_in->points.size())
  {
    return false;
  }

  PointCloud::Ptr cloud_filtered (new PointCloud);
#ifdef USE_CENTER
  cloud_filtered = cloud_in;
#else
  removeOutliers(cloud_in, cloud_filtered);
#endif
  bool success = getAveragePoint(cloud_filtered, avrPt);
  return success;
}
<|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 <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

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

#include "base.hh"

namespace Dune {
namespace GDT {
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(std::is_base_of< Stuff::LocalizableFunctionInterface< typename FunctionType::EntityType
                                                                    , typename FunctionType::DomainFieldType
                                                                    , FunctionType::dimDomain
                                                                    , typename FunctionType::RangeFieldType
                                                                    , FunctionType::dimRange
                                                                    , FunctionType::dimRangeCols >
                               , FunctionType >::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits,
                                                 SpaceImp::dimDomain,
                                                 SpaceImp::dimRange,
                                                 SpaceImp::dimRangeCols >,
                                 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

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

#endif // DUNE_GDT_FUNCTIONALS_L2_HH
<commit_msg>[functionals.l2] modernize static checks<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 <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

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

#include "base.hh"

namespace Dune {
namespace GDT {
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

} // 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";

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.
   **/
<commit_msg>[common.color] fixed wrong reset color in highlighString()<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[0m"; //"\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>/*
*******************************************************************************

Copyright (c) 2015, The Curators of the University of Missouri
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.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.

*******************************************************************************
*/

#ifndef GPU_WINDOW_FITLER_ALGORITHM_
#define GPU_WINDOW_FITLER_ALGORITHM_

#include "GpuAlgorithm.hpp"
#include "../kernels/GpuAlgorithmKernels.hpp"

namespace cvt {
namespace gpu {

enum windowRadiusType{
	SQUARE,
	CIRCLE
};

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
class GpuWindowFilterAlgorithm : public GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>
{

	using GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice;

	public:

	 explicit GpuWindowFilterAlgorithm(unsigned int cudaDeviceId, size_t roiDataWidth,
							 size_t roiDataHeight, ssize_t windowRadius);

	 virtual ~GpuWindowFilterAlgorithm();
	 virtual ErrorCode initializeDevice(enum windowRadiusType type);

	 virtual ErrorCode operator()(const cvt::cvTile<InputPixelType>& tile,
													  const cvt::cvTile<OutputPixelType> ** outTile);

	protected:

	ErrorCode allocateAdditionalGpuMemory();
	virtual ErrorCode launchKernel(unsigned bw, unsigned bh);
	void computeRelativeOffsets();
	ErrorCode transferRelativeOffsetsToDevice();
	ErrorCode copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr);

	/**
	 * PROTECTED ATTRIBUTES
	 * */
	ssize_t windowRadius_;
	std::vector<int2> relativeOffsets_;
	int2 *relativeOffsetsGpu_;
	enum windowRadiusType type;
	/***************************
	 *  NOTE: Any class that extends the window filter class can not have an roi that
	 *  is equal to the whole image. You will need a buffer.
	 *
	 **************************/
	size_t roiWidth_;
	cv::Size2i roiSize_;
	size_t bufferWidth_;

}; // END of GpuWindowFilterAlgorithm

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::GpuWindowFilterAlgorithm(
	unsigned int cudaDeviceId, size_t roiDataWidth,
	size_t roiDataHeight, ssize_t windowRadius)
	: cvt::gpu::GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>(
	cudaDeviceId, roiDataWidth + windowRadius * 2, roiDataHeight + windowRadius * 2),
	windowRadius_(windowRadius), roiSize_(roiDataWidth,roiDataHeight), bufferWidth_(windowRadius)
{
	;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::~GpuWindowFilterAlgorithm() {
	////////////////////////////////////////
	// FREE CUDA ARRAYS USED FOR GPU INPUT //
	////////////////////////////////////////

	cudaFree(relativeOffsetsGpu_);

	cudaError cuer3 = cudaGetLastError();
	if(cuer3 == cudaErrorInvalidValue)
		this->lastError = DestructFailcuOutArraycudaErrorInvalidValue;
	else if(cuer3 == cudaErrorInitializationError)
		this->lastError = DestructFailcuOutArraycudaErrorInitializationError;
	else if(cuer3 != cudaSuccess)
		this->lastError = CudaError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::operator()(const cvt::cvTile<InputPixelType>& tile,
													  const cvt::cvTile<OutputPixelType> ** outTile)
{
		//TO-DO Error Check Template Params for Type/Bounds

	const cv::Size2i tileSize = tile.getSize();

	if (tileSize != this->dataSize)
	{
		std::stringstream ss;
		ss << tileSize << " expected of " << this->dataSize << std::endl;
		throw std::runtime_error(ss.str());
	}

	/*
	 *  Copy data down for tile using the parents implementation
	 */
	this->lastError = this->copyTileToDevice(tile);
	if (this->lastError != cvt::Ok)
	{
		throw std::runtime_error("Failed to copy tile to device");
	}

	// Invoke kernel with empirically chosen block size
	unsigned short bW = 16; // 16
	unsigned short bH = 16; // 16

	if ((unsigned int) tile.getROI().x != bufferWidth_) {
		throw std::runtime_error("Buffer size of incoming tile is not equal to the window radius");
	}

	launchKernel(bW, bH);

	this->lastError = this->copyTileFromDevice(outTile);
	if(this->lastError != cvt::Ok) {
		std::runtime_error("Failed copy off tile from device");
	}
	return Ok;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice(enum windowRadiusType type)
{
	/* Initialize additional argument then allow parent to init card */
	this->type = type;
	GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice();

	/* Transfer offsets to card */
	transferRelativeOffsetsToDevice();

	return this->lastError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr)
{

	const size_t bytes = roiSize_.area() * OutputBandCount * sizeof(OutputPixelType);
	std::vector<OutputPixelType> data;
	data.resize(bytes/sizeof(OutputPixelType));

	cudaMemcpyAsync(
			&(data[0]),
			this->gpuOutputData,
			bytes,
			cudaMemcpyDeviceToHost,
			this->stream
			);

	cudaError cuer = cudaGetLastError();
	if(cuer == cudaErrorInvalidValue)
		this->lastError = TileFromDevicecudaErrorInvalidValue;
	else if(cuer == cudaErrorInvalidDevicePointer)
		this->lastError = TileFromDevicecudaErrorInvalidDevicePointer;
	else if(cuer == cudaErrorInvalidMemcpyDirection)
		this->lastError = TileFromDevicecudaErrorInvalidMemcpyDirection;
	else if(cuer != cudaSuccess)
		this->lastError = CudaError;

	/*for(const auto& ele: data)
	{
		std::cout << "data: " << ele << std::endl;

	}*/
	if(cuer == cudaSuccess) {
		(*tilePtr) = new cvTile<OutputPixelType>(&(data[0]), roiSize_, OutputBandCount);
	}
	else
		(*tilePtr) = NULL;

	return this->lastError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::launchKernel(
	__attribute__((unused)) unsigned bw,
	__attribute__((unused)) unsigned bh) {
	return Ok; // NEED TO ADD DEFAULT KERNEL FOR FILTER
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::allocateAdditionalGpuMemory()
{
	computeRelativeOffsets();
	cudaMalloc((void**)&relativeOffsetsGpu_, sizeof(int2) * relativeOffsets_.size());
	cudaError cuer = cudaGetLastError();
	if (cuer != cudaSuccess) {
		throw std::runtime_error("GPU WHS () FAILURE TO ALLOCATE MEMORY FOR RELATIVE COORDS");
	}
	if (cuer == cudaErrorMemoryAllocation)
	{
		this->lastError = InitFailcuOutArrayMemErrorcudaErrorMemoryAllocation;
	}
	return this->lastError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
void GpuWindowFilterAlgorithm<InputPixelType,InputBandCount, OutputPixelType, OutputBandCount>::computeRelativeOffsets()
{
	if (type == CIRCLE) {
		const size_t radius_squared = windowRadius_ * windowRadius_;
		for(ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i){
			size_t i_squared = i * i;
			for(ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j){
				if(i_squared + j * j <= radius_squared)
					relativeOffsets_.push_back(make_int2(i,j));
			}
		}
	}
	else {
		for (ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i) {
			for (ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j) {
				relativeOffsets_.push_back(make_int2(i,j));
			}
		}

	}
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::transferRelativeOffsetsToDevice()
{
	cudaMemcpyAsync(
		relativeOffsetsGpu_,
		relativeOffsets_.data(),
		relativeOffsets_.size() * sizeof(int2),
		cudaMemcpyHostToDevice,
		this->stream
	);

	cudaError cuer = cudaGetLastError();
	if (cuer != cudaSuccess) {
		std::cout << "CUDA ERR = " << cuer << std::endl;
		throw std::runtime_error("GPU WHS () FAILED TO MEMCPY RELATIVE COORDS ON TO DEVICE");
	}

	//cuer = cvt::gpu::load_relative_offsets(this->stream,this->relativeOffsets_.data(), this->relativeOffsets_.size());
	//if (cuer != cudaSuccess) {
	//	std::cout << "CUDA ERR = " << cuer << std::endl;
	//	throw std::runtime_error("GPU WHS TO CONSTANT MEMORY");
	//}

	return this->lastError;
}

} // END of cvt namespace
} // END of gpu namespace

#endif
<commit_msg>Incremental manual reapply of LBP<commit_after>/*
*******************************************************************************

Copyright (c) 2015, The Curators of the University of Missouri
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.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.

*******************************************************************************
*/

#ifndef GPU_WINDOW_FITLER_ALGORITHM_
#define GPU_WINDOW_FITLER_ALGORITHM_

#include "GpuAlgorithm.hpp"
#include "../kernels/GpuAlgorithmKernels.hpp"

namespace cvt {
namespace gpu {

enum windowRadiusType{
	SQUARE,
	CIRCLE,
	SPARSE_RING
};

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
class GpuWindowFilterAlgorithm : public GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>
{

	using GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice;

	public:

	explicit GpuWindowFilterAlgorithm(unsigned int cudaDeviceId, size_t roiDataWidth,
							 		  size_t roiDataHeight, ssize_t windowRadius);

	virtual ~GpuWindowFilterAlgorithm();
	virtual ErrorCode initializeDevice(enum windowRadiusType type);

	virtual ErrorCode operator()(const cvt::cvTile<InputPixelType>& tile,
								 const cvt::cvTile<OutputPixelType> ** outTile);

	protected:

	ErrorCode allocateAdditionalGpuMemory();
	virtual ErrorCode launchKernel(unsigned bw, unsigned bh);
	void computeRelativeOffsets();
	ErrorCode transferRelativeOffsetsToDevice();
	ErrorCode copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr);

	/**
	 * PROTECTED ATTRIBUTES
	 * */
	ssize_t windowRadius_;
	std::vector<int2> relativeOffsets_;
	int2 *relativeOffsetsGpu_;
	enum windowRadiusType type_;
	/***************************
	 *  NOTE: Any class that extends the window filter class can not have an roi that
	 *  is equal to the whole image. You will need a buffer.
	 *
	 **************************/
	size_t roiWidth_;
	cv::Size2i roiSize_;
	size_t bufferWidth_;

}; // END of GpuWindowFilterAlgorithm

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::GpuWindowFilterAlgorithm(
	unsigned int cudaDeviceId, size_t roiDataWidth,
	size_t roiDataHeight, ssize_t windowRadius)
	: cvt::gpu::GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>(
	cudaDeviceId, roiDataWidth + windowRadius * 2, roiDataHeight + windowRadius * 2),
	windowRadius_(windowRadius), roiSize_(roiDataWidth,roiDataHeight), bufferWidth_(windowRadius)
{
	;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::~GpuWindowFilterAlgorithm() {
	////////////////////////////////////////
	// FREE CUDA ARRAYS USED FOR GPU INPUT //
	////////////////////////////////////////

	cudaFree(relativeOffsetsGpu_);

	cudaError cuer3 = cudaGetLastError();
	if(cuer3 == cudaErrorInvalidValue)
		this->lastError = DestructFailcuOutArraycudaErrorInvalidValue;
	else if(cuer3 == cudaErrorInitializationError)
		this->lastError = DestructFailcuOutArraycudaErrorInitializationError;
	else if(cuer3 != cudaSuccess)
		this->lastError = CudaError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::operator()(const cvt::cvTile<InputPixelType>& tile,
													  const cvt::cvTile<OutputPixelType> ** outTile)
{
		//TO-DO Error Check Template Params for Type/Bounds

	const cv::Size2i tileSize = tile.getSize();

	if (tileSize != this->dataSize)
	{
		std::stringstream ss;
		ss << tileSize << " expected of " << this->dataSize << std::endl;
		throw std::runtime_error(ss.str());
	}

	/*
	 *  Copy data down for tile using the parents implementation
	 */
	this->lastError = this->copyTileToDevice(tile);
	if (this->lastError != cvt::Ok)
	{
		throw std::runtime_error("Failed to copy tile to device");
	}

	// Invoke kernel with empirically chosen block size
	unsigned short bW = 16; // 16
	unsigned short bH = 16; // 16

	if ((unsigned int) tile.getROI().x != bufferWidth_) {
		throw std::runtime_error("Buffer size of incoming tile is not equal to the window radius");
	}

	launchKernel(bW, bH);

	this->lastError = this->copyTileFromDevice(outTile);
	if(this->lastError != cvt::Ok) {
		std::runtime_error("Failed copy off tile from device");
	}
	return Ok;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice(enum windowRadiusType type)
{
	/* Initialize additional argument then allow parent to init card */
	type_ = type;
	GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice();

	/* Transfer offsets to card */
	transferRelativeOffsetsToDevice();

	return this->lastError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr)
{

	const size_t bytes = roiSize_.area() * OutputBandCount * sizeof(OutputPixelType);
	std::vector<OutputPixelType> data;
	data.resize(bytes/sizeof(OutputPixelType));

	cudaMemcpyAsync(
			&(data[0]),
			this->gpuOutputData,
			bytes,
			cudaMemcpyDeviceToHost,
			this->stream
			);

	cudaError cuer = cudaGetLastError();
	if(cuer == cudaErrorInvalidValue)
		this->lastError = TileFromDevicecudaErrorInvalidValue;
	else if(cuer == cudaErrorInvalidDevicePointer)
		this->lastError = TileFromDevicecudaErrorInvalidDevicePointer;
	else if(cuer == cudaErrorInvalidMemcpyDirection)
		this->lastError = TileFromDevicecudaErrorInvalidMemcpyDirection;
	else if(cuer != cudaSuccess)
		this->lastError = CudaError;

	/*for(const auto& ele: data)
	{
		std::cout << "data: " << ele << std::endl;

	}*/
	if(cuer == cudaSuccess) {
		(*tilePtr) = new cvTile<OutputPixelType>(&(data[0]), roiSize_, OutputBandCount);
	}
	else
		(*tilePtr) = NULL;

	return this->lastError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::launchKernel(
	__attribute__((unused)) unsigned bw,
	__attribute__((unused)) unsigned bh) {
	return Ok; // NEED TO ADD DEFAULT KERNEL FOR FILTER
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::allocateAdditionalGpuMemory()
{
	computeRelativeOffsets();
	cudaMalloc((void**)&relativeOffsetsGpu_, sizeof(int2) * relativeOffsets_.size());
	cudaError cuer = cudaGetLastError();
	if (cuer != cudaSuccess) {
		throw std::runtime_error("GPU WINDOW FILTER ALGORITHM () FAILURE TO ALLOCATE MEMORY FOR RELATIVE COORDS");
	}
	if (cuer == cudaErrorMemoryAllocation)
	{
		this->lastError = InitFailcuOutArrayMemErrorcudaErrorMemoryAllocation;
	}
	return this->lastError;
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
void GpuWindowFilterAlgorithm<InputPixelType,InputBandCount, OutputPixelType, OutputBandCount>::computeRelativeOffsets()
{
	if (type_ == CIRCLE) {
		const size_t radius_squared = windowRadius_ * windowRadius_;
		for(ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i){
			size_t i_squared = i * i;
			for(ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j){
				if(i_squared + j * j <= radius_squared)
					relativeOffsets_.push_back(make_int2(i,j));
			}
		}
	}
	else if (type_ == SPARSE_RING) {
		//TODO(TYLER): These limits seem suspect...
	    const size_t numOffsets = sizeof(OutputPixelType) * 8;
	    //TODO(Tyler): Remove this debug comment before merging.
	    //std::cout << "computeRelative::numOffsets = " << numOffsets << std::endl;
	    const size_t maxOffsets = (windowRadius_ * 2 + 1) * (windowRadius_ * 2 + 1);

	    if (numOffsets > maxOffsets)
	    {
			throw std::invalid_argument("computeRelativeOffets: output size was larger than maximum neighbors.");
	    }

	    const double angleStep = 2 * M_PI / numOffsets;
	    double currAngle = 0;
	    ssize_t xOffset , yOffset;

	    for (size_t i = 0; i<numOffsets; i++) {
			xOffset = (ssize_t) (round (windowRadius_ * sin (currAngle)));
			yOffset = (ssize_t) (round (windowRadius_ * cos (currAngle)));
			currAngle += angleStep;
			relativeOffsets_.push_back(make_int2(xOffset,yOffset));
	    }
	}
	else {
		for (ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i) {
			for (ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j) {
				relativeOffsets_.push_back(make_int2(i,j));
			}
		}

	}
}

template< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >
ErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::transferRelativeOffsetsToDevice()
{
	cudaMemcpyAsync(
		relativeOffsetsGpu_,
		relativeOffsets_.data(),
		relativeOffsets_.size() * sizeof(int2),
		cudaMemcpyHostToDevice,
		this->stream
	);

	cudaError cuer = cudaGetLastError();
	if (cuer != cudaSuccess) {
		std::cout << "CUDA ERR = " << cuer << std::endl;
		throw std::runtime_error("GPU WHS () FAILED TO MEMCPY RELATIVE COORDS ON TO DEVICE");
	}

	//cuer = cvt::gpu::load_relative_offsets(this->stream,this->relativeOffsets_.data(), this->relativeOffsets_.size());
	//if (cuer != cudaSuccess) {
	//	std::cout << "CUDA ERR = " << cuer << std::endl;
	//	throw std::runtime_error("GPU WHS TO CONSTANT MEMORY");
	//}

	return this->lastError;
}

} // END of cvt namespace
} // END of gpu namespace

#endif
<|endoftext|>