<commit_before>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author 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 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.

*/

#include "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>

using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*

struct peer_conn
{
	peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
		, char const* ih)
		: s(ios)
		, read_pos(0)
		, state(handshaking)
		// don't request anything from the last piece
		// to keep things simple
		, pieces(num_pieces - 1)
		, block(0)
		, blocks_per_piece(blocks_pp)
		, info_hash(ih)
		, outstanding_requests(0)
	{
		// build a list of all pieces and request them all!
		for (int i = 0; i < int(pieces.size()); ++i)
			pieces[i] = i;
		std::random_shuffle(pieces.begin(), pieces.end());

		s.async_connect(ep, boost::bind(&peer_conn::on_connect, this, _1));
	}

	stream_socket s;
	char buffer[17*1024];
	int read_pos;

	enum state_t
	{
		handshaking,
		sending_request,
		receiving_message
	};
	int state;
	std::vector<int> pieces;
	int block;
	int blocks_per_piece;
	char const* info_hash;
	int outstanding_requests;

	void on_connect(error_code const& ec)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
			return;
		}

		char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
			"                    " // space for info-hash
			"aaaaaaaaaaaaaaaaaaaa" // peer-id
			"\0\0\0\x01\x02"; // interested
		char* h = (char*)malloc(sizeof(handshake));
		memcpy(h, handshake, sizeof(handshake));
		std::memcpy(h + 28, info_hash, 20);
		std::generate(h + 48, h + 68, &rand);
		boost::asio::async_write(s, libtorrent::asio::buffer(h, sizeof(handshake) - 1)
			, boost::bind(&peer_conn::on_handshake, this, h, _1, _2));
	}

	void on_handshake(char* h, error_code const& ec, size_t bytes_transferred)
	{
		free(h);
		if (ec)
		{
			fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
			return;
		}

		// read handshake
		boost::asio::async_read(s, libtorrent::asio::buffer(buffer, 68)
			, boost::bind(&peer_conn::on_handshake2, this, _1, _2));
	}

	void on_handshake2(error_code const& ec, size_t bytes_transferred)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR READ HANDSHAKE: %s\n", ec.message().c_str());
			return;
		}

		work();
	}

	void write_request()
	{
		if (pieces.empty()) return;

		int piece = pieces.back();

		char msg[] = "\0\0\0\xd\x06"
			"    " // piece
			"    " // offset
			"    "; // length
		char* m = (char*)malloc(sizeof(msg));
		memcpy(m, msg, sizeof(msg));
		char* ptr = m + 5;
		write_uint32(piece, ptr);
		write_uint32(block * 16 * 1024, ptr);
		write_uint32(16 * 1024, ptr);
		error_code ec;
		boost::asio::async_write(s, libtorrent::asio::buffer(m, sizeof(msg) - 1)
			, boost::bind(&peer_conn::on_req_sent, this, m, _1, _2));

		++block;
		if (block == blocks_per_piece)
		{
			block = 0;
			pieces.pop_back();
		}
	}

	void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred)
	{
		free(m);
		if (ec)
		{
			fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
			return;
		}

		++outstanding_requests;

		work();
	}

	void work()
	{
		if (pieces.empty() && outstanding_requests == 0)
		{
			fprintf(stderr, "COMPLETED DOWNLOAD\n");
			return;
		}

		// send requests
		if (outstanding_requests < 20 && !pieces.empty())
		{
			write_request();
			return;
		}

		// read message
		boost::asio::async_read(s, asio::buffer(buffer, 4)
			, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
	}

	void on_msg_length(error_code const& ec, size_t bytes_transferred)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
			return;
		}
		char* ptr = buffer;
		unsigned int length = read_uint32(ptr);
		if (length > sizeof(buffer))
		{
			fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: packet too big\n");
			return;
		}
		boost::asio::async_read(s, asio::buffer(buffer, length)
			, boost::bind(&peer_conn::on_message, this, _1, _2));
	}

	void on_message(error_code const& ec, size_t bytes_transferred)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
			return;
		}
		char* ptr = buffer;
		int msg = read_uint8(ptr);
		if (msg == 7) --outstanding_requests;

		work();
	}
};

int main(int argc, char* argv[])
{
	if (argc < 5)
	{
		fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
		return 1;
	}
	int num_connections = atoi(argv[1]);
	error_code ec;
	address_v4 addr = address_v4::from_string(argv[2], ec);
	if (ec)
	{
		fprintf(stderr, "ERROR RESOLVING %s: %s\n", argv[2], ec.message().c_str());
		return 1;
	}
	int port = atoi(argv[3]);
	tcp::endpoint ep(addr, port);
	torrent_info ti(argv[4], ec);
	if (ec)
	{
		fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
		return 1;
	}
	std::list<peer_conn*> conns;
	io_service ios;
	for (int i = 0; i < num_connections; ++i)
	{
		conns.push_back(new peer_conn(ios, ti.num_pieces(), ti.piece_length() / 16 / 1024
			, ep, (char const*)&ti.info_hash()[0]));
		libtorrent::sleep(1);
		ios.poll_one(ec);
		if (ec)
		{
			fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
			break;
		}
	}

	ios.run(ec);
	if (ec) fprintf(stderr, "ERROR: %s\n", ec.message().c_str());

	return 0;
}

<commit_msg>extend connection test to support uploading as well<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author 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 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.

*/

#include "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/hasher.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
#include <boost/array.hpp>

using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*

void generate_block(boost::uint32_t* buffer, int piece, int start, int length)
{
	boost::uint32_t fill = (piece << 16) | (start / 0x4000);
	for (int i = 0; i < length / 4; ++i)
	{
		buffer[i] = fill;
	}
}

struct peer_conn
{
	peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
		, char const* ih, bool seed_)
		: s(ios)
		, read_pos(0)
		, state(handshaking)
		// don't request anything from the last piece
		// to keep things simple
		, pieces(num_pieces - 1)
		, block(0)
		, blocks_per_piece(blocks_pp)
		, info_hash(ih)
		, outstanding_requests(0)
		, seed(seed_)
	{
		if (!seed_)
		{
			// build a list of all pieces and request them all!
			for (int i = 0; i < int(pieces.size()); ++i)
				pieces[i] = i;
			std::random_shuffle(pieces.begin(), pieces.end());
		}

		s.async_connect(ep, boost::bind(&peer_conn::on_connect, this, _1));
	}

	stream_socket s;
	boost::uint32_t write_buffer[17*1024/4];
	boost::uint32_t buffer[17*1024/4];
	int read_pos;

	enum state_t
	{
		handshaking,
		sending_request,
		receiving_message
	};
	int state;
	std::vector<int> pieces;
	int block;
	int blocks_per_piece;
	char const* info_hash;
	int outstanding_requests;
	// if this is true, this connection is a seed
	bool seed;

	void on_connect(error_code const& ec)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
			return;
		}

		char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
			"                    " // space for info-hash
			"aaaaaaaaaaaaaaaaaaaa" // peer-id
			"\0\0\0\x01\x02"; // interested
		char* h = (char*)malloc(sizeof(handshake));
		memcpy(h, handshake, sizeof(handshake));
		std::memcpy(h + 28, info_hash, 20);
		std::generate(h + 48, h + 68, &rand);
		// for seeds, don't send the interested message
		boost::asio::async_write(s, libtorrent::asio::buffer(h, (sizeof(handshake) - 1) - (seed ? 5 : 0))
			, boost::bind(&peer_conn::on_handshake, this, h, _1, _2));
	}

	void on_handshake(char* h, error_code const& ec, size_t bytes_transferred)
	{
		free(h);
		if (ec)
		{
			fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
			return;
		}

		// read handshake
		boost::asio::async_read(s, libtorrent::asio::buffer((char*)buffer, 68)
			, boost::bind(&peer_conn::on_handshake2, this, _1, _2));
	}

	void on_handshake2(error_code const& ec, size_t bytes_transferred)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR READ HANDSHAKE: %s\n", ec.message().c_str());
			return;
		}

		if (seed)
		{
			write_have_all();
		}
		else
		{
			work_download();
		}
	}

	void write_have_all()
	{
		// have_all and unchoke
		static char msg[] = "\0\0\0\x01\x0e\0\0\0\x01\x01";
		error_code ec;
		boost::asio::async_write(s, libtorrent::asio::buffer(msg, sizeof(msg) - 1)
			, boost::bind(&peer_conn::on_have_all_sent, this, _1, _2));

	}

	void on_have_all_sent(error_code const& ec, size_t bytes_transferred)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR SEND HAVE ALL: %s\n", ec.message().c_str());
			return;
		}

		// read message
		boost::asio::async_read(s, asio::buffer((char*)buffer, 4)
			, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
	}

	void write_request()
	{
		if (pieces.empty()) return;

		int piece = pieces.back();

		char msg[] = "\0\0\0\xd\x06"
			"    " // piece
			"    " // offset
			"    "; // length
		char* m = (char*)malloc(sizeof(msg));
		memcpy(m, msg, sizeof(msg));
		char* ptr = m + 5;
		write_uint32(piece, ptr);
		write_uint32(block * 16 * 1024, ptr);
		write_uint32(16 * 1024, ptr);
		error_code ec;
		boost::asio::async_write(s, libtorrent::asio::buffer(m, sizeof(msg) - 1)
			, boost::bind(&peer_conn::on_req_sent, this, m, _1, _2));

		++block;
		if (block == blocks_per_piece)
		{
			block = 0;
			pieces.pop_back();
		}
	}

	void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred)
	{
		free(m);
		if (ec)
		{
			fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
			return;
		}

		++outstanding_requests;

		work_download();
	}

	void work_download()
	{
		if (pieces.empty() && outstanding_requests == 0)
		{
			fprintf(stderr, "COMPLETED DOWNLOAD\n");
			return;
		}

		// send requests
		if (outstanding_requests < 20 && !pieces.empty())
		{
			write_request();
			return;
		}

		// read message
		boost::asio::async_read(s, asio::buffer((char*)buffer, 4)
			, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
	}

	void on_msg_length(error_code const& ec, size_t bytes_transferred)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
			return;
		}
		char* ptr = (char*)buffer;
		unsigned int length = read_uint32(ptr);
		if (length > sizeof(buffer))
		{
			fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: packet too big\n");
			return;
		}
		boost::asio::async_read(s, asio::buffer((char*)buffer, length)
			, boost::bind(&peer_conn::on_message, this, _1, _2));
	}

	void on_message(error_code const& ec, size_t bytes_transferred)
	{
		if (ec)
		{
			fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
			return;
		}
		char* ptr = (char*)buffer;
		int msg = read_uint8(ptr);

		if (seed)
		{
			if (msg == 6 && bytes_transferred == 13)
			{
				int piece = detail::read_int32(ptr);
				int start = detail::read_int32(ptr);
				int length = detail::read_int32(ptr);
				write_piece(piece, start, length);
			}
			else
			{
				// read another message
				boost::asio::async_read(s, asio::buffer(buffer, 4)
					, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
			}
		}
		else
		{
			if (msg == 7) --outstanding_requests;
			work_download();
		}
	}

	void write_piece(int piece, int start, int length)
	{
		generate_block(write_buffer, piece, start, length);
		static char msg[] = "    \x07"
			"    " // piece
			"    "; // start
		char* ptr = msg;
		write_uint32(9 + length, ptr);
		assert(length == 0x4000);
		assert(*ptr == 7);
		++ptr; // skip message id
		write_uint32(piece, ptr);
		write_uint32(start, ptr);
		boost::array<libtorrent::asio::const_buffer, 2> vec;
		vec[0] = libtorrent::asio::buffer(msg, sizeof(msg)-1);
		vec[1] = libtorrent::asio::buffer(write_buffer, length);
		boost::asio::async_write(s, vec, boost::bind(&peer_conn::on_have_all_sent, this, _1, _2));
	}
};

void print_usage()
{
	fprintf(stderr, "usage: connection_tester command ...\n\n"
		"command is one of:\n"
		"  gen-torrent         generate a test torrent\n"
		"  upload              start an uploader test\n"
		"  download            start a downloader test\n\n"
		"examples:\n\n"
		"connection_tester gen-torrent torrent-name\n"
		"connection_tester upload number-of-connections destination-ip destination-port torrent-file\n"
		"connection_tester download number-of-connections destination-ip destination-port torrent-file\n");
	exit(1);
}

void generate_torrent(std::vector<char>& buf)
{
	file_storage fs;
	// 1 MiB piece size
	const int piece_size = 1024 * 1024;
	// 50 GiB should be enough to not fit in physical RAM
	const int num_pieces = 1 * 1024;
	const size_type total_size = size_type(piece_size) * num_pieces;
	fs.add_file("stress_test_file", total_size);
	libtorrent::create_torrent t(fs, piece_size);

	boost::uint32_t piece[0x4000 / 4];
	for (int i = 0; i < num_pieces; ++i)
	{
		hasher ph;
		for (int j = 0; j < piece_size; j += 0x4000)
		{
			generate_block(piece, i, j, 0x4000);
			ph.update((char*)piece, 0x4000);
		}
		t.set_hash(i, ph.final());
	}

	std::back_insert_iterator<std::vector<char> > out(buf);

	bencode(out, t.generate());
}

int main(int argc, char* argv[])
{
	if (argc <= 1) print_usage();

	bool upload_test = false;
	bool download_test = false;

	if (strcmp(argv[1], "gen-torrent") == 0)
	{
		if (argc != 3) print_usage();

		std::vector<char> tmp;
		generate_torrent(tmp);

		FILE* output = stdout;
		if (strcmp("-", argv[2]) != 0)
			output = fopen(argv[2], "wb+");
		fwrite(&tmp[0], 1, tmp.size(), output);
		if (output != stdout)
			fclose(output);

		return 0;
	}
	else if (strcmp(argv[1], "upload") == 0)
	{
		if (argc != 6) print_usage();
		upload_test = true;
	}
	else if (strcmp(argv[1], "download") == 0)
	{
		if (argc != 6) print_usage();
		download_test = true;
	}

	if (!download_test && !upload_test) print_usage();

	int num_connections = atoi(argv[2]);
	error_code ec;
	address_v4 addr = address_v4::from_string(argv[3], ec);
	if (ec)
	{
		fprintf(stderr, "ERROR RESOLVING %s: %s\n", argv[3], ec.message().c_str());
		return 1;
	}
	int port = atoi(argv[4]);
	tcp::endpoint ep(addr, port);

	torrent_info ti(argv[5], ec);
	if (ec)
	{
		fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
		return 1;
	}

	std::list<peer_conn*> conns;
	io_service ios;
	for (int i = 0; i < num_connections; ++i)
	{
		conns.push_back(new peer_conn(ios, ti.num_pieces(), ti.piece_length() / 16 / 1024
			, ep, (char const*)&ti.info_hash()[0], upload_test));
		libtorrent::sleep(1);
		ios.poll_one(ec);
		if (ec)
		{
			fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
			break;
		}
	}

	ios.run(ec);
	if (ec) fprintf(stderr, "ERROR: %s\n", ec.message().c_str());

	return 0;
}

<|endoftext|>


<commit_before>#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;

map <string ,int> IDcache;
int main(int argc, char const *argv[])
{
	/* code */
	return 0;
}
<commit_msg>update uoj1109<commit_after>#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
using namespace std;

map <string ,int> IDcache;
int main(int argc, char const *argv[])
{
	/* code */
	return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>

using namespace std;

stack<string> lv1;
stack<string> lv2;
stack<string> lv3;

string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
	if(now < temptime) return 0;

	do{

		if(temp.empty()){

		}else{

			switch(templv){
				case 1:
					lv1.push(temp);break;
				case 2:
					lv2.push(temp);break;
				case 3:
					lv3.push(temp);break;
			}
		}
		if(users<usernum)
			cin >>temptime>>templv>>temp;
		users++;
	}while(temptime<=now);

}
int main(int argc, char const *argv[])
{
		int time;
		scanf("%d%d",&usernum,&time);
		for (int i = 0; i < time; ++i)
		{
			read(i);
			cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
		}

	return 0;
}<commit_msg>update uoj2254<commit_after>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>

using namespace std;

stack<string> lv1;
stack<string> lv2;
stack<string> lv3;

string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
	if(now < temptime) return 0;

	do{
		printf("test\n");
		if(temp.empty()){

		}else{

			switch(templv){
				case 1:
					lv1.push(temp);break;
				case 2:
					lv2.push(temp);break;
				case 3:
					lv3.push(temp);break;
			}
		}
		if(users<usernum)
			cin >>temptime>>templv>>temp;
		users++;
	}while(temptime<=now);

}
int main(int argc, char const *argv[])
{
		int time;
		scanf("%d%d",&usernum,&time);
		for (int i = 0; i < time; ++i)
		{
			read(i);
			cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
		}

	return 0;
}<|endoftext|>


<commit_before>#include "convolution2d.hpp"

void convolution2d
(
	const cv::Mat& src,
	cv::Mat& dst,
	const cv::Mat& kernel
)
{
	const int half_size = (kernel.cols / 2);
	for (int y = half_size; y < (src.rows - half_size); y++)
	{
		for (int x = half_size; x < (src.cols - half_size); x++)
		{
			float temp = 0.0f;
			for (int dy = -half_size; dy <= half_size; dy++)
			{
				for (int dx = -half_size; dx <= half_size; dx++)
				{
					temp += src.ptr<uchar>(y+dy)[x+dx] * kernel.ptr<float>(dy+half_size)[dx+half_size];
				}
			}
			dst.ptr<uchar>(y)[x] = (uchar)temp;
		}
	}
}

double launch_convolution2d
(
	const cv::Mat& src,
	cv::Mat& dst,
	const cv::Mat& kernel,
	const int loop_num
)
{
	double f = 1000.0 / cv::getTickFrequency();
	int64 start = 0, end = 0;
	double time = 0.0;
	for (int i = 0; i <= loop_num; i++)
	{
		start = cv::getTickCount();

		convolution2d(src, dst, kernel);

		end = cv::getTickCount();
		time += (i > 0) ? ((end - start) * f) : 0;
	}
	time /= loop_num;

	return time;
}
<commit_msg>refactoring<commit_after>#include "convolution2d.hpp"

void convolution2d
(
	const cv::Mat& src,
	cv::Mat& dst,
	const cv::Mat& kernel
)
{
	const int half_size = (kernel.cols / 2);
	for (int y = half_size; y < (src.rows - half_size); y++)
	{
		for (int x = half_size; x < (src.cols - half_size); x++)
		{
			double sum = 0.0;
			for (int dy = -half_size; dy <= half_size; dy++)
			{
				for (int dx = -half_size; dx <= half_size; dx++)
				{
					sum += (src.ptr<uchar>(y+dy)[x+dx] * kernel.ptr<float>(dy+half_size)[dx+half_size]);
				}
			}
			dst.ptr<uchar>(y)[x] = sum;
		}
	}
}

double launch_convolution2d
(
	const cv::Mat& src,
	cv::Mat& dst,
	const cv::Mat& kernel,
	const int loop_num
)
{
	double f = 1000.0 / cv::getTickFrequency();
	int64 start = 0, end = 0;
	double time = 0.0;
	for (int i = 0; i <= loop_num; i++)
	{
		start = cv::getTickCount();

		convolution2d(src, dst, kernel);

		end = cv::getTickCount();
		time += (i > 0) ? ((end - start) * f) : 0;
	}
	time /= loop_num;

	return time;
}
<|endoftext|>


<commit_before>/*-
 * Copyright (c) 2010 Benjamin Close <Benjamin.Close@clearchain.com>
 * 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 AUTHOR 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 AUTHOR 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.
 */

#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include "GrayCode.h"

using namespace std;

GrayCode::GrayCode(const unsigned iwidth, const unsigned iheight ):
    width(iwidth), height(iheight), totalGrayCodes(0), codedImages(NULL),stage(0),
    decodedColumns(iwidth, iheight), decodedRows(iwidth, iheight)
{
    // Work out how many patterns are needed for the
    // specified rows and columns. Since we are trying to
    // encode a binary sequence, this is: count = log2(x)
    // where x is the width or the height - depending if we
    // are encoding columns or rows. We also have to cater
    // for rounding in c hence we ceil to the next
    // highest value then cast the value to get count;
    this->grayCodeColumnCount = (unsigned)ceil(log2(this->width));
    this->grayCodeRowCount = (unsigned)ceil(log2(this->height));

    // When considering the columns and the rows we also have to consider
    // that the width/height is not an exact factor of 2 (ie 800 pixels).
    // Hence we may have to shift the phase of a binary image so that
    // the binary bands line up correctly.
    this->grayCodeColumnPhase = (unsigned)floor((pow(2.0,this->grayCodeColumnCount)-this->width)/2);
    this->grayCodeRowPhase = (unsigned)floor((pow(2.0,this->grayCodeRowCount)-this->height)/2);

    // Record the total amount of patterns required for
    // both the columns and the rows, we also cater for the inverts and the
    // initial images
    this->totalGrayCodes = ((this->grayCodeColumnCount + this->grayCodeRowCount) * 2) +4;

    // Create the data storage for the patterns.
    this->createStorage();

    // Build the various images required for graycode displaying
    this->buildGrayCodes();

    // zero the decode matrixes
    this->decodedColumns.storeZeros();
    this->decodedRows.storeZeros();
};

GrayCode::~GrayCode()
{
    if( this->codedImages ){
	for( unsigned i = 0; i <  this->totalGrayCodes; i++ )
	    delete this->codedImages[i];

	delete this->codedImages;
    }
}

bool GrayCode::next()
{
    this->stage++;
    if( this->stage >= this->totalGrayCodes){
	this->stage=0;
	return false;
    }

    return true;
}

const unsigned char *GrayCode::generate()
{
    return this->codedImages[this->stage];
}

void GrayCode::buildGrayCodes()
{
    //
    // Build the required gray code images.
    // When building the images we build both the initial image and
    // the image invert to aid in detection
    //

    // The first two images are the most sigificant bit and full black/white
    // this allows us to work out the region the graycodes are projected onto
    // We set the initial pattern here we calculate all inverts below
    unsigned char **codedColumnImages = this->codedImages;
    memset( *codedColumnImages, 255, this->width * this->height );
    codedColumnImages+=2;

    // We start by building the graycoded columns.
    for(unsigned column = 0; column < this->width; column++ ) {
	for ( unsigned imageCount = 0; imageCount < this->grayCodeColumnCount; imageCount++ ){

	    unsigned char *data = codedColumnImages[imageCount*2];

	    //
	    // Work out the value for this column
	    //

	    // Binary encoding. Put basically, a particular column over
	    // grayCodeColumnCount images represents a binary number. What
	    // we do here is work out what bit value that number is for this
	    // particular (imageCount) image. Ie the number for column 0 is
	    // always 0..n  where n is grayCodeColumnCount long. Column 1 always
	    // equates to 1 in binary. Hence in image 0 column 1 is black. In
	    // image grayCodeColumnCount column 1 is white.
	    //
	    // To work what colour (white/black) a column should be in this particular image
	    // we need to work out the bit value for this image. Hence if column =10
	    // which is binary n-4..1010 and we're in the second to last image the
	    // column must be white. To calculate colour we bitshift the column
	    // count (ie the value for the column) by the imagecount we are in.
	    // This shifts the bit we care about down to the least significant
	    // bit. We can simply test it using a bit comparison against 1 to
	    // then see if we need to be white or black.
	    // Now the only issue with this is we work from least significant
	    // bit up to most siginificate bit. This makes decoding the number
	    // harder. Hence instead we shift by grayCodeColumnCount-imageCount.
	    // This then works from most significant bit down to least
	    // significant bit which makes deciding easier.
	    //
	    // We also take into account that the width and the height of an
	    // image is not a power of two. Hence we offset each column/row by the
	    // relevant phase shift to align the graycodes correctly.
	    unsigned char value  = ( toGrayCode(column+this->grayCodeColumnPhase) >> (this->grayCodeColumnCount - imageCount -1)) & 1;

	    // We now update the value of the column to be in the range 0
	    // (black) or 255 (white). As this is what GL expects for a texture
	    value *=255;

	    // Store the value in the image
	    this->setPixel(data,column,0 /* y */, value);

	    // Copy the value down for all rows of the image.
	    // after this the entire column for this image is set
	    for( unsigned row = 1; row < this->height; row++ )
		this->setPixel(data,column,row, value);
	}
    }

    //
    // We now repeat the above setup but focus on the rows not
    // the columns
    //
    unsigned char **codedRowImages= codedColumnImages+(this->grayCodeColumnCount*2);
    memset( *codedRowImages, 255, this->width * this->height );
    codedRowImages+=2;

    for( unsigned row=0; row < this->height; row++){
	for ( unsigned imageCount = 0; imageCount < this->grayCodeRowCount; imageCount++ ){
	    unsigned char *data = codedRowImages[imageCount*2];
	    unsigned char value  = ( toGrayCode(row+this->grayCodeRowPhase) >> (this->grayCodeRowCount - imageCount -1)) & 1;
	    value *=255;
	    this->setPixel(data,0 /* X */,row, value);
	    for( unsigned column = 1; column < this->width; column++ )
		this->setPixel(data,column,row, value);
	}
    }

    //
    // Now create the invert images for each pattern
    //
    for( unsigned count = 0; count < this->totalGrayCodes; count+=2 ){
	    for( unsigned row = 0; row < this->height; row++ ){
		for( unsigned column = 0; column < this->width; column++ ){
		this->codedImages[count+1][row*this->width+column] =
		    this->codedImages[count][row*this->width+column] ? 0 : 255;
	    }
	}
    }
}

/**
 * Create the memory required for all the required gray code images
 */
void GrayCode::createStorage()
{
    this->codedImages = new unsigned char *[this->totalGrayCodes];
    for( unsigned i = 0; i < this->totalGrayCodes; i++ )
	this->codedImages[i] = new unsigned char [this->width * this->height];
}

void GrayCode::setPixel(unsigned char *data, const unsigned x, const unsigned y, const unsigned char colour )
{
    assert(x < this->width && "Column out of bounds" );
    assert(y < this->height && "Row out of bounds");

    data[(y*this->width)+x]= colour;
}

/**
 * Given a camera coo
 */
wcl::Vector GrayCode::getRowCol(const wcl::Vector &input) const
{
    wcl::Vector v(2);

    int col = input[0];
    int row = input[1];

    // Search the row/column matrixes for the input pixel values
    v[0] = this->decodedColumns[col][row];
    v[1] = this->decodedRows[col][row];

    return v;
}

unsigned int GrayCode::fromGrayCode(const unsigned value)
{
    unsigned int temp = value ^ (value>>8);
    temp ^= (temp>>4);
    temp ^= (temp>>2);
    temp ^= (temp>>1);
    return temp;
}

unsigned int GrayCode::toGrayCode(const unsigned value)
{
    return ( value >> 1 ) ^ (value);
}

/**
 * Given the correct amount of images, decode the structured light sequence.
 * Note the images are expected to be in 8 bit grayscale.
 *
 * @param capturedImages the images captured for each structured light sequence
 */
void GrayCode::decode(const unsigned char **capturedImages)
{
    // First we separate the rows from the columns;
    const unsigned char **columnImages = capturedImages;
    const unsigned char **rowImages = capturedImages+ this->grayCodeRowCount;

    // We now begin the process of decoding the images back into the relevant
    // graycodes. The decoding works as follows. When capturing the graycodes
    // we generated both the gray code image and the image invert. By looking
    // at the difference between these two images we find what the bit is at
    // each pixel of the imagepair. For pixels that are not part of the
    // projected image they get assigned a bit value of zero. Ie all undetected
    // pixels are 0.
    for(unsigned columnCount = 0; columnCount < this->grayCodeColumnCount; columnCount++){

	// Obtain pointers to the gray code image and the image invert
	const unsigned char *gray    = columnImages[ columnCount ];
	const unsigned char *invgray = columnImages[ columnCount + 1];

	// Now decode each pixel of the image pair.
	for( unsigned y = 0; y < this->height; y++ ){
	    for( unsigned x = 0; x < this->width; x++ ){

		unsigned offset = (this->width * y) + x;

		// Find the bit value for this pixel in the image
		bool bitvalue = gray[offset] >= invgray[offset];

		// Store the value of this bit in decoded matrix at the correct
		// location. The columnCount indicates the significance of the
		// bit in the number.
		int bit = this->grayCodeColumnCount - columnCount - 1;
		if( bitvalue ){
		    int value = (int)this->decodedColumns[x][y];
		    value |= 1 << bit;
		    this->decodedColumns[x][y] = value;
		}
	    }
	}
    }

    // Repeat for rows
    for(unsigned rowCount = 0; rowCount < this->grayCodeRowCount; rowCount++){

	// Obtain pointers to the gray code image and the image invert
	const unsigned char *gray    = rowImages[ rowCount ];
	const unsigned char *invgray = rowImages[ rowCount + 1];

	// Now decode each pixel of the image pair.
	for( unsigned y = 0; y < this->height; y++ ){
	    for( unsigned x = 0; x < this->width; x++ ){

		unsigned offset = (this->width * y) + x;
		bool bitvalue = gray[offset] >= invgray[offset];
		int bit = this->grayCodeRowCount - rowCount - 1;
		if( bitvalue ){
		    int value = (int)this->decodedRows[x][y];
		    value |= 1 << bit;
		    this->decodedRows[x][y] = value;
		}
	    }
	}
    }

    // Each stored value in the matrixes are gray coded still. We now
    // convert the values back to binary. At the same time we filter to make
    // sure the values are within range of what they should be (ie width or
    // height of the original graycode)
    for(unsigned y; y < this->height; y++ ){
	for(unsigned x; x < this->width; x++){
	    this->decodedRows[x][y] = fromGrayCode((unsigned) this->decodedRows[x][y]);
	    this->decodedColumns[x][y] = fromGrayCode((unsigned) this->decodedColumns[x][y]);
	    if( this->decodedRows[x][y] > this->height )
		this->decodedRows[x][y] = 0.0;
	    if( this->decodedColumns[x][y] > this->width )
		this->decodedRows[x][y] = 0.0;
	}
    }
}

unsigned GrayCode::getRequiredImageCount() const
{
    return this->totalGrayCodes;
}

void GrayCode::reset()
{
    this->decodedColumns.storeZeros();
    this->decodedRows.storeZeros();
}

const unsigned char *GrayCode::getDebugImage()
{
    static unsigned char *buffer = new unsigned char[this->width*this->height];

    // Display the values of the detection in the rgb image
    for(unsigned y = 0; y < this->height; y++ ){
	for(unsigned x = 0; x < this->width; x++){
	    this->setPixel(buffer, x, y, (int)((this->decodedColumns[x][y] /
						(float)this->width)) * 255.0);
	}
    }

    return buffer;
}
<commit_msg>Turn off graycode conversion to aid in debugging. For now we simply use raw binary<commit_after>/*-
 * Copyright (c) 2010 Benjamin Close <Benjamin.Close@clearchain.com>
 * 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 AUTHOR 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 AUTHOR 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.
 */

#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include "GrayCode.h"

using namespace std;

GrayCode::GrayCode(const unsigned iwidth, const unsigned iheight ):
    width(iwidth), height(iheight), totalGrayCodes(0), codedImages(NULL),stage(0),
    decodedColumns(iwidth, iheight), decodedRows(iwidth, iheight)
{
    // Work out how many patterns are needed for the
    // specified rows and columns. Since we are trying to
    // encode a binary sequence, this is: count = log2(x)
    // where x is the width or the height - depending if we
    // are encoding columns or rows. We also have to cater
    // for rounding in c hence we ceil to the next
    // highest value then cast the value to get count;
    this->grayCodeColumnCount = (unsigned)ceil(log2(this->width));
    this->grayCodeRowCount = (unsigned)ceil(log2(this->height));

    // When considering the columns and the rows we also have to consider
    // that the width/height is not an exact factor of 2 (ie 800 pixels).
    // Hence we may have to shift the phase of a binary image so that
    // the binary bands line up correctly.
    this->grayCodeColumnPhase = (unsigned)floor((pow(2.0,this->grayCodeColumnCount)-this->width)/2);
    this->grayCodeRowPhase = (unsigned)floor((pow(2.0,this->grayCodeRowCount)-this->height)/2);

    // Record the total amount of patterns required for
    // both the columns and the rows, we also cater for the inverts and the
    // initial images
    this->totalGrayCodes = ((this->grayCodeColumnCount + this->grayCodeRowCount) * 2) +4;

    // Create the data storage for the patterns.
    this->createStorage();

    // Build the various images required for graycode displaying
    this->buildGrayCodes();

    // zero the decode matrixes
    this->decodedColumns.storeZeros();
    this->decodedRows.storeZeros();
};

GrayCode::~GrayCode()
{
    if( this->codedImages ){
	for( unsigned i = 0; i <  this->totalGrayCodes; i++ )
	    delete this->codedImages[i];

	delete this->codedImages;
    }
}

bool GrayCode::next()
{
    this->stage++;
    if( this->stage >= this->totalGrayCodes){
	this->stage=0;
	return false;
    }

    return true;
}

const unsigned char *GrayCode::generate()
{
    return this->codedImages[this->stage];
}

void GrayCode::buildGrayCodes()
{
    //
    // Build the required gray code images.
    // When building the images we build both the initial image and
    // the image invert to aid in detection
    //

    // The first two images are the most sigificant bit and full black/white
    // this allows us to work out the region the graycodes are projected onto
    // We set the initial pattern here we calculate all inverts below
    unsigned char **codedColumnImages = this->codedImages;
    memset( *codedColumnImages, 255, this->width * this->height );
    codedColumnImages+=2;

    // We start by building the graycoded columns.
    for(unsigned column = 0; column < this->width; column++ ) {
	for ( unsigned imageCount = 0; imageCount < this->grayCodeColumnCount; imageCount++ ){

	    unsigned char *data = codedColumnImages[imageCount*2];

	    //
	    // Work out the value for this column
	    //

	    // Binary encoding. Put basically, a particular column over
	    // grayCodeColumnCount images represents a binary number. What
	    // we do here is work out what bit value that number is for this
	    // particular (imageCount) image. Ie the number for column 0 is
	    // always 0..n  where n is grayCodeColumnCount long. Column 1 always
	    // equates to 1 in binary. Hence in image 0 column 1 is black. In
	    // image grayCodeColumnCount column 1 is white.
	    //
	    // To work what colour (white/black) a column should be in this particular image
	    // we need to work out the bit value for this image. Hence if column =10
	    // which is binary n-4..1010 and we're in the second to last image the
	    // column must be white. To calculate colour we bitshift the column
	    // count (ie the value for the column) by the imagecount we are in.
	    // This shifts the bit we care about down to the least significant
	    // bit. We can simply test it using a bit comparison against 1 to
	    // then see if we need to be white or black.
	    // Now the only issue with this is we work from least significant
	    // bit up to most siginificate bit. This makes decoding the number
	    // harder. Hence instead we shift by grayCodeColumnCount-imageCount.
	    // This then works from most significant bit down to least
	    // significant bit which makes deciding easier.
	    //
	    // We also take into account that the width and the height of an
	    // image is not a power of two. Hence we offset each column/row by the
	    // relevant phase shift to align the graycodes correctly.
	    //unsigned char value  = (column+this->grayCodeColumnPhase) >> (this->grayCodeColumnCount - imageCount -1) & 1;
	    unsigned char value  = ((column) >> (this->grayCodeColumnCount - imageCount -1)) & 1;

	    // We now update the value of the column to be in the range 0
	    // (black) or 255 (white). As this is what GL expects for a texture
	    value *=255;

	    // Store the value in the image
	    this->setPixel(data,column,0 /* y */, value);

	    // Copy the value down for all rows of the image.
	    // after this the entire column for this image is set
	    for( unsigned row = 1; row < this->height; row++ )
		this->setPixel(data,column,row, value);
	}
    }

    //
    // We now repeat the above setup but focus on the rows not
    // the columns
    //
    unsigned char **codedRowImages= codedColumnImages+(this->grayCodeColumnCount*2);
    memset( *codedRowImages, 255, this->width * this->height );
    codedRowImages+=2;

    for( unsigned row=0; row < this->height; row++){
	for ( unsigned imageCount = 0; imageCount < this->grayCodeRowCount; imageCount++ ){
	    unsigned char *data = codedRowImages[imageCount*2];
	    //unsigned char value  = (toGrayCode(row+this->grayCodeRowPhase)) >> (this->grayCodeRowCount - imageCount -1) & 1;
	    //unsigned char value  = (toGrayCode(row)) >> (this->grayCodeRowCount - imageCount -1) & 1;
	    unsigned char value  = (row) >> (this->grayCodeRowCount - imageCount -1) & 1;
	    value *=255;
	    this->setPixel(data,0 /* X */,row, value);
	    for( unsigned column = 1; column < this->width; column++ )
		this->setPixel(data,column,row, value);
	}
    }

    //
    // Now create the invert images for each pattern
    //
    for( unsigned count = 0; count < this->totalGrayCodes; count+=2 ){
	    for( unsigned row = 0; row < this->height; row++ ){
		for( unsigned column = 0; column < this->width; column++ ){
		this->codedImages[count+1][row*this->width+column] =
		    this->codedImages[count][row*this->width+column] ? 0 : 255;
	    }
	}
    }
}

/**
 * Create the memory required for all the required gray code images
 */
void GrayCode::createStorage()
{
    this->codedImages = new unsigned char *[this->totalGrayCodes];
    for( unsigned i = 0; i < this->totalGrayCodes; i++ )
	this->codedImages[i] = new unsigned char [this->width * this->height];
}

void GrayCode::setPixel(unsigned char *data, const unsigned x, const unsigned y, const unsigned char colour )
{
    assert(x < this->width && "Column out of bounds" );
    assert(y < this->height && "Row out of bounds");

    data[(y*this->width)+x]= colour;
}

/**
 * Given a camera coo
 */
wcl::Vector GrayCode::getRowCol(const wcl::Vector &input) const
{
    wcl::Vector v(2);

    int col = input[0];
    int row = input[1];

    // Search the row/column matrixes for the input pixel values
    v[0] = this->decodedColumns[col][row];
    v[1] = this->decodedRows[col][row];

    return v;
}

unsigned int GrayCode::fromGrayCode(const unsigned value)
{
    unsigned int temp = value ^ (value>>8);
    temp ^= (temp>>4);
    temp ^= (temp>>2);
    temp ^= (temp>>1);
    return temp;
}

unsigned int GrayCode::toGrayCode(const unsigned value)
{
    return ( value >> 1 ) ^ (value);
}

/**
 * Given the correct amount of images, decode the structured light sequence.
 * Note the images are expected to be in 8 bit grayscale.
 *
 * @param capturedImages the images captured for each structured light sequence
 */
void GrayCode::decode(const unsigned char **capturedImages)
{
    // First we separate the rows from the columns;
    const unsigned char **columnImages = capturedImages;
    const unsigned char **rowImages = capturedImages+ this->grayCodeRowCount;

    // We now begin the process of decoding the images back into the relevant
    // graycodes. The decoding works as follows. When capturing the graycodes
    // we generated both the gray code image and the image invert. By looking
    // at the difference between these two images we find what the bit is at
    // each pixel of the imagepair. For pixels that are not part of the
    // projected image they get assigned a bit value of zero. Ie all undetected
    // pixels are 0.
    for(unsigned columnCount = 0; columnCount < this->grayCodeColumnCount; columnCount++){

	// Obtain pointers to the gray code image and the image invert
	const unsigned char *gray    = columnImages[ columnCount ];
	const unsigned char *invgray = columnImages[ columnCount + 1];

	// Now decode each pixel of the image pair.
	for( unsigned y = 0; y < this->height; y++ ){
	    for( unsigned x = 0; x < this->width; x++ ){

		unsigned offset = (this->width * y) + x;

		// Find the bit value for this pixel in the image
		bool bitvalue = gray[offset] >= invgray[offset];

		// Store the value of this bit in decoded matrix at the correct
		// location. The columnCount indicates the significance of the
		// bit in the number.
		int bit = this->grayCodeColumnCount - columnCount - 1;
		if( bitvalue ){
		    int value = (int)this->decodedColumns[x][y];
		    value |= 1 << bit;
		    this->decodedColumns[x][y] = value;
		}
	    }
	}
    }

    // Repeat for rows
    for(unsigned rowCount = 0; rowCount < this->grayCodeRowCount; rowCount++){

	// Obtain pointers to the gray code image and the image invert
	const unsigned char *gray    = rowImages[ rowCount ];
	const unsigned char *invgray = rowImages[ rowCount + 1];

	// Now decode each pixel of the image pair.
	for( unsigned y = 0; y < this->height; y++ ){
	    for( unsigned x = 0; x < this->width; x++ ){

		unsigned offset = (this->width * y) + x;
		bool bitvalue = gray[offset] >= invgray[offset];
		int bit = this->grayCodeRowCount - rowCount - 1;
		if( bitvalue ){
		    int value = (int)this->decodedRows[x][y];
		    value |= 1 << bit;
		    this->decodedRows[x][y] = value;
		}
	    }
	}
    }
    // Each stored value in the matrixes are gray coded still. We now
    // convert the values back to binary. At the same time we filter to make
    // sure the values are within range of what they should be (ie width or
    // height of the original graycode)
    for(unsigned y; y < this->height; y++ ){
	for(unsigned x; x < this->width; x++){
	    //this->decodedRows[x][y] = fromGrayCode((unsigned) this->decodedRows[x][y]);
	    //this->decodedColumns[x][y] = fromGrayCode((unsigned) this->decodedColumns[x][y]);
	    if( this->decodedRows[x][y] > this->height )
		this->decodedRows[x][y] = 0.0;
	    if( this->decodedColumns[x][y] > this->width )
		this->decodedRows[x][y] = 0.0;
	}
    }
}

unsigned GrayCode::getRequiredImageCount() const
{
    return this->totalGrayCodes;
}

void GrayCode::reset()
{
    this->decodedColumns.storeZeros();
    this->decodedRows.storeZeros();
}

const unsigned char *GrayCode::getDebugImage()
{
    static unsigned char *buffer = new unsigned char[this->width*this->height];

    // Display the values of the detection in the rgb image
    for(unsigned y = 0; y < this->height; y++ ){
	for(unsigned x = 0; x < this->width; x++){
	    this->setPixel(buffer, x, y, (int)((this->decodedColumns[x][y] /
						(float)this->width)) * 255.0);
	}
    }

    return buffer;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * @file     prngcl_example_pi.cpp
 * @author   Vadim Demchik <vadimdi@yahoo.com>
 * @version  1.1.1
 *
 * @brief    [PRNGCL library]
 *           Pseudo-random number generators for HGPU package
 *           example PI calculation
 *
 *
 * @section  LICENSE
 *
 * Copyright (c) 2014 Vadim Demchik
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *    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 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.
 *
 *****************************************************************************/

#include "prngcl_example_pi.h"
#include "../hgpucl/hgpucl.h"

void
HGPU_GPU_example_pi(int argc, char** argv){
    double result = 0.0;

    HGPU_parameter** parameters_all = HGPU_parameters_get_all(argc,argv);     // get all parameters from commandline, .ini-file and environment (may be empty)
    HGPU_GPU_context* context = HGPU_GPU_context_select_auto(parameters_all); // create new context according to parameters

    printf("********************************************************\n");
    printf(" PRNGCL library v.%u.%u.%u\n",PRNGCL_VERSION_MAJOR,PRNGCL_VERSION_MINOR,PRNGCL_VERSION_MICRO);
    printf(" HGPU core v.%u.%u.%u\n",HGPUCL_VERSION_MAJOR,HGPUCL_VERSION_MINOR,HGPUCL_VERSION_MICRO);
    printf(" Copyright (c) 2014, Vadim Demchik\n\n");
    printf(" [EXAMPLE]:\n");
    printf(" Pi calculation with PRNGCL library\n\n");
    printf("********************************************************\n\n");

    HGPU_GPU_context_print_used_hardware(context); // print using hardware

    const HGPU_PRNG_description* prng_descr = NULL;
          HGPU_precision         precision  = HGPU_precision_single; // precision to be used
          unsigned int           randseries = 0;                     // serial number of sequence (0=random, other=determined)
          unsigned int           instances  = HGPU_GPU_device_get_max_memory_width(context->device); // number of PRNG instances
          unsigned int           samples_per_stream = 1024;          // number of PRNs per stream
          unsigned int           passes     = 1000;                  // number of passes for pi calculation

    HGPU_PRNG_set_default_precision(precision);        // set precision
    HGPU_PRNG_set_default_randseries(randseries);      // set randseries
    HGPU_PRNG_set_default_instances(instances);        // set instances
    HGPU_PRNG_set_default_samples(samples_per_stream); // set samples (if instances=0 then [autoselection] and samples should be whole number of desired PRNs)

    HGPU_parameter** parameters = HGPU_parameters_get_all(argc,argv);
    HGPU_PRNG_set_default_with_parameters(parameters);
//    HGPU_PRNG_default = HGPU_PRNG_description_get_with_name("MRG32K3A"); // PRNG to be used
    prng_descr = HGPU_PRNG_description_get_with_parameters(parameters);

    HGPU_PRNG* prng = HGPU_PRNG_new(prng_descr); // create new PRNG instance

    unsigned int prng_id = HGPU_PRNG_init(context,prng); // PRNG initialization

    char* example_src = HGPU_io_file_read_with_path(HGPU_io_path_root,EXAMPLE_SRC); // get .cl-source of example
    char options[HGPU_GPU_MAX_OPTIONS_LENGTH];
    int  j2 = sprintf_s(options,HGPU_GPU_MAX_OPTIONS_LENGTH,"-I %s%s",HGPU_io_path_root,PRNGCL_ROOT_PATH);
    if (prng->parameters->precision==HGPU_precision_double) j2 += sprintf_s(options+j2,HGPU_GPU_MAX_OPTIONS_LENGTH-j2," -D PRNG_PRECISION=2");

    cl_program prg = HGPU_GPU_program_with_options_new(example_src,options,context); // compile opencl program

    // allocated memory objects
    size_t pi_acceptance_size = HGPU_GPU_context_buffer_size_align(context,prng->parameters->instances); // align buffer size
    cl_float* pi_acceptance = (cl_float*) calloc(pi_acceptance_size,sizeof(cl_float));
    if (!pi_acceptance)
        HGPU_error_message(HGPU_ERROR_NO_MEMORY,"could not allocate memory for randoms"); // chech if buffer is allocated

    unsigned int PRNG_randoms_id = prng->parameters->id_buffer_randoms; // get randoms buffer id

    // buffer OpenCL initialization
    unsigned int pi_acceptance_id = HGPU_GPU_context_buffer_init(context,pi_acceptance,HGPU_GPU_buffer_type_io,pi_acceptance_size,sizeof(cl_float));
    HGPU_GPU_context_buffer_set_name(context,pi_acceptance_id,(char*) "PI_Acceptance"); // [optional]: set name to buffer for profiling/debugging

    unsigned int kernel_pi_calculate_id = HGPU_GPU_MAX_KERNELS;
    const size_t global_size[]  = {prng->parameters->instances}; // execution domain
    if ((pi_acceptance_id<HGPU_GPU_MAX_BUFFERS) && (PRNG_randoms_id<HGPU_GPU_MAX_BUFFERS) && (prng->prng->production_kernel)) {
        // bind buffers and number of samples (PRNs) per stream to the kernel
        kernel_pi_calculate_id = HGPU_GPU_context_kernel_init(context,prg,"calculate_pi",1,global_size,NULL); // prepare kernel
                     HGPU_GPU_context_kernel_bind_buffer(context,kernel_pi_calculate_id,PRNG_randoms_id);     // bind buffer with randoms
                     HGPU_GPU_context_kernel_bind_buffer(context,kernel_pi_calculate_id,pi_acceptance_id);    // bind buffer for results
                     HGPU_GPU_context_kernel_bind_constant(context,kernel_pi_calculate_id,&samples_per_stream,sizeof(unsigned int)); // bind samples_per_stream
    }

    for (unsigned int i=0; i<passes; i++) {
        HGPU_PRNG_produce(context,prng_id);  // produce PRNs into randoms array
        HGPU_GPU_context_kernel_run(context,kernel_pi_calculate_id); // run pi calculation kernel
    }

    cl_float* results_ptr = (cl_float*) HGPU_GPU_context_buffer_get_mapped(context,pi_acceptance_id);

    for (unsigned int i=0; i<prng->parameters->instances; i++)
        result += results_ptr[i];

    double prns_used = (4.0*((double) passes)*((double) prng->parameters->instances)*((double) prng->parameters->samples));
        printf("\nPRNG: %s\n",prng->prng->name);
        printf("PRNG instances: %u\n",prng->parameters->instances);
        printf("PRNG samples:   %u\n",prng->parameters->samples);
        printf("passes:         %u\n",passes);
        printf("PRNs used:      %e\n\n",prns_used);

        printf("PI = %f\n\n",4.0*result/(prns_used/2.0));

    // release pi_acceptance buffer for example
    if (pi_acceptance_id<HGPU_GPU_MAX_BUFFERS)
        HGPU_GPU_context_buffer_release(context,pi_acceptance_id);

    HGPU_PRNG_and_buffers_free(context,prng);    // release PRNG instance

    free(example_src);
    HGPU_GPU_context_delete(&context);           // release context
}
<commit_msg>example: pi calculation<commit_after>/******************************************************************************
 * @file     prngcl_example_pi.cpp
 * @author   Vadim Demchik <vadimdi@yahoo.com>
 * @version  1.1.1
 *
 * @brief    [PRNGCL library]
 *           Pseudo-random number generators for HGPU package
 *           example PI calculation
 *
 *
 * @section  LICENSE
 *
 * Copyright (c) 2014 Vadim Demchik
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *    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 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.
 *
 *****************************************************************************/

#include "prngcl_example_pi.h"
#include "../hgpucl/hgpucl.h"

void
HGPU_GPU_example_pi(int argc, char** argv){
    double result = 0.0;

    HGPU_parameter** parameters_all = HGPU_parameters_get_all(argc,argv);     // get all parameters from commandline, .ini-file and environment (may be empty)
    HGPU_GPU_context* context = HGPU_GPU_context_select_auto(parameters_all); // create new context according to parameters

    printf("********************************************************\n");
    printf(" PRNGCL library v.%u.%u.%u\n",PRNGCL_VERSION_MAJOR,PRNGCL_VERSION_MINOR,PRNGCL_VERSION_MICRO);
    printf(" HGPU core v.%u.%u.%u\n",HGPUCL_VERSION_MAJOR,HGPUCL_VERSION_MINOR,HGPUCL_VERSION_MICRO);
    printf(" Copyright (c) 2014, Vadim Demchik\n\n");
    printf(" [EXAMPLE]:\n");
    printf(" Pi calculation with PRNGCL library\n\n");
    printf("********************************************************\n\n");

    HGPU_GPU_context_print_used_hardware(context); // print using hardware

    const HGPU_PRNG_description* prng_descr = NULL;
          HGPU_precision         precision  = HGPU_precision_single; // precision to be used
          unsigned int           randseries = 0;                     // serial number of sequence (0=random, other=determined)
          unsigned int           instances  = HGPU_GPU_device_get_max_memory_width(context->device); // number of PRNG instances
          unsigned int           samples_per_stream = 1024;          // number of PRNs per stream
          unsigned int           passes     = 1000;                  // number of passes for pi calculation

    HGPU_PRNG_set_default_precision(precision);        // set precision
    HGPU_PRNG_set_default_randseries(randseries);      // set randseries
    HGPU_PRNG_set_default_instances(instances);        // set instances
    HGPU_PRNG_set_default_samples(samples_per_stream); // set samples (if instances=0 then [autoselection] and samples should be whole number of desired PRNs)

    HGPU_PRNG_set_default_with_parameters(parameters_all);
//    HGPU_PRNG_default = HGPU_PRNG_description_get_with_name("MRG32K3A"); // or manually set PRNG to be used
    prng_descr = HGPU_PRNG_description_get_with_parameters(parameters_all);

    HGPU_PRNG* prng = HGPU_PRNG_new(prng_descr); // create new PRNG instance

    unsigned int prng_id = HGPU_PRNG_init(context,prng); // PRNG initialization

    char* example_src = HGPU_io_file_read_with_path(HGPU_io_path_root,EXAMPLE_SRC); // get .cl-source of example
    char options[HGPU_GPU_MAX_OPTIONS_LENGTH];
    int  j2 = sprintf_s(options,HGPU_GPU_MAX_OPTIONS_LENGTH,"-I %s%s",HGPU_io_path_root,PRNGCL_ROOT_PATH);
    if (prng->parameters->precision==HGPU_precision_double) j2 += sprintf_s(options+j2,HGPU_GPU_MAX_OPTIONS_LENGTH-j2," -D PRNG_PRECISION=2");

    cl_program prg = HGPU_GPU_program_with_options_new(example_src,options,context); // compile opencl program

    // allocated memory objects
    size_t pi_acceptance_size = HGPU_GPU_context_buffer_size_align(context,prng->parameters->instances); // align buffer size
    cl_float* pi_acceptance = (cl_float*) calloc(pi_acceptance_size,sizeof(cl_float));
    if (!pi_acceptance)
        HGPU_error_message(HGPU_ERROR_NO_MEMORY,"could not allocate memory for randoms"); // chech if buffer is allocated

    unsigned int PRNG_randoms_id = prng->parameters->id_buffer_randoms; // get randoms buffer id

    // buffer OpenCL initialization
    unsigned int pi_acceptance_id = HGPU_GPU_context_buffer_init(context,pi_acceptance,HGPU_GPU_buffer_type_io,pi_acceptance_size,sizeof(cl_float));
    HGPU_GPU_context_buffer_set_name(context,pi_acceptance_id,(char*) "PI_Acceptance"); // [optional]: set name to buffer for profiling/debugging

    unsigned int kernel_pi_calculate_id = HGPU_GPU_MAX_KERNELS;
    const size_t global_size[]  = {prng->parameters->instances}; // execution domain
    if ((pi_acceptance_id<HGPU_GPU_MAX_BUFFERS) && (PRNG_randoms_id<HGPU_GPU_MAX_BUFFERS) && (prng->prng->production_kernel)) {
        // bind buffers and number of samples (PRNs) per stream to the kernel
        kernel_pi_calculate_id = HGPU_GPU_context_kernel_init(context,prg,"calculate_pi",1,global_size,NULL); // prepare kernel
                     HGPU_GPU_context_kernel_bind_buffer(context,kernel_pi_calculate_id,PRNG_randoms_id);     // bind buffer with randoms
                     HGPU_GPU_context_kernel_bind_buffer(context,kernel_pi_calculate_id,pi_acceptance_id);    // bind buffer for results
                     HGPU_GPU_context_kernel_bind_constant(context,kernel_pi_calculate_id,&samples_per_stream,sizeof(unsigned int)); // bind samples_per_stream
    }

    for (unsigned int i=0; i<passes; i++) {
        HGPU_PRNG_produce(context,prng_id);  // produce PRNs into randoms array
        HGPU_GPU_context_kernel_run(context,kernel_pi_calculate_id); // run pi calculation kernel
    }

    cl_float* results_ptr = (cl_float*) HGPU_GPU_context_buffer_get_mapped(context,pi_acceptance_id);

    for (unsigned int i=0; i<prng->parameters->instances; i++)
        result += results_ptr[i];

    double prns_used = (4.0*((double) passes)*((double) prng->parameters->instances)*((double) prng->parameters->samples));
        printf("\nPRNG: %s\n",prng->prng->name);
        printf("PRNG instances: %u\n",prng->parameters->instances);
        printf("PRNG samples:   %u\n",prng->parameters->samples);
        printf("passes:         %u\n",passes);
        printf("PRNs used:      %e\n\n",prns_used);

        printf("PI = %f\n\n",4.0*result/(prns_used/2.0));

    // release pi_acceptance buffer for example
    if (pi_acceptance_id<HGPU_GPU_MAX_BUFFERS)
        HGPU_GPU_context_buffer_release(context,pi_acceptance_id);

    HGPU_parameters_delete(&parameters_all);  // free parameters
    HGPU_PRNG_and_buffers_free(context,prng); // release PRNG instance

    free(example_src);
    HGPU_GPU_context_delete(&context);        // release context
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "32a928e"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Grimtoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID " 490c191"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("2GiveCoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-RC5"
#define BUILD_DATE __DATE__ ", " __TIME__

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
//#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID ""
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Ticked version forward to RC5.1<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("2GiveCoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-RC5.1"
#define BUILD_DATE __DATE__ ", " __TIME__

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
//#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID ""
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>#include <silicium/async_process.hpp>
#include <silicium/observable/spawn_coroutine.hpp>
#include <silicium/observable/spawn_observable.hpp>
#include <silicium/observable/transform.hpp>
#include <silicium/observable/ref.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>

namespace
{
	template <class CharSink>
	void begin_reading_output(boost::asio::io_service &io, CharSink &&destination, Si::file_handle &&file)
	{
		Si::spawn_coroutine([&io, destination, &file](Si::spawn_context yield)
		{
			Si::process_output output_reader(Si::make_unique<Si::process_output::stream>(io, file.handle));
			file.release();
			for (;;)
			{
				auto piece = yield.get_one(Si::ref(output_reader));
				assert(piece);
				if (piece->is_error())
				{
					break;
				}
				Si::memory_range data = piece->get();
				if (data.empty())
				{
					break;
				}
				Si::append(destination, data);
			}
		});
	}

	struct process_output
	{
		int exit_code;
		std::string output, error;
	};

	process_output run_process(Si::async_process_parameters parameters)
	{
		Si::pipe standard_input = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::make_pipe().get());
		Si::pipe standard_output = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::make_pipe().get());
		Si::pipe standard_error = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::make_pipe().get());

		Si::async_process process = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::launch_process(parameters, standard_input.read.handle, standard_output.write.handle, standard_error.write.handle).get());
		standard_input.read.close();
		standard_output.write.close();
		standard_error.write.close();

		boost::asio::io_service io;

		process_output result;

		begin_reading_output(io, Si::make_container_sink(result.output), std::move(standard_output.read));
		begin_reading_output(io, Si::make_container_sink(result.error), std::move(standard_error.read));

		io.run();

		result.exit_code = process.wait_for_exit().get();
		return result;
	}
}

#ifndef _WIN32
BOOST_AUTO_TEST_CASE(async_process_unix_which)
{
	Si::async_process_parameters parameters;
	parameters.executable = "/usr/bin/which";
	parameters.arguments.emplace_back("which");
	parameters.current_path = boost::filesystem::current_path();

	process_output result = run_process(parameters);

	BOOST_CHECK_EQUAL("/usr/bin/which\n", result.output);
	BOOST_CHECK_EQUAL("", result.error);
	BOOST_CHECK_EQUAL(0, result.exit_code);
}
#endif

#ifdef _WIN32
BOOST_AUTO_TEST_CASE(async_process_win32_where)
{
	Si::async_process_parameters parameters;
	parameters.executable = L"C:\\Windows\\System32\\where.exe";
	parameters.current_path = boost::filesystem::current_path();

	process_output result = run_process(parameters);

	std::size_t const windows7whereHelpSize = 1830;
	BOOST_CHECK_EQUAL(windows7whereHelpSize, result.output.size());
	BOOST_CHECK_EQUAL("", result.error);
	BOOST_CHECK_EQUAL(2, result.exit_code);
}
#endif

BOOST_AUTO_TEST_CASE(async_process_executable_not_found)
{
	Si::async_process_parameters parameters;
	parameters.executable = "does-not-exist";
	parameters.current_path = boost::filesystem::current_path();

	BOOST_CHECK_EXCEPTION(run_process(parameters), boost::system::system_error, [](boost::system::system_error const &ex)
	{
		return ex.code() == boost::system::errc::no_such_file_or_directory;
	});
}
<commit_msg>the previous commit broke the tests<commit_after>#include <silicium/async_process.hpp>
#include <silicium/observable/spawn_coroutine.hpp>
#include <silicium/observable/spawn_observable.hpp>
#include <silicium/observable/transform.hpp>
#include <silicium/observable/ref.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>

namespace
{
	template <class CharSink>
	void begin_reading_output(boost::asio::io_service &io, CharSink &&destination, Si::file_handle &&file)
	{
		Si::spawn_coroutine([&io, destination, &file](Si::spawn_context yield)
		{
			Si::process_output output_reader(Si::make_unique<Si::process_output::stream>(io, file.handle));
			file.release();
			for (;;)
			{
				auto piece = yield.get_one(Si::ref(output_reader));
				assert(piece);
				if (piece->is_error())
				{
					break;
				}
				Si::memory_range data = piece->get();
				if (data.empty())
				{
					break;
				}
				Si::append(destination, data);
			}
		});
	}

	struct process_output
	{
		int exit_code;
		std::string output, error;
	};

	process_output run_process(Si::async_process_parameters parameters)
	{
		Si::pipe standard_input = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::make_pipe().get());
		Si::pipe standard_output = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::make_pipe().get());
		Si::pipe standard_error = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::make_pipe().get());

		Si::async_process process = SILICIUM_MOVE_IF_COMPILER_LACKS_RVALUE_QUALIFIERS(Si::launch_process(parameters, standard_input.read.handle, standard_output.write.handle, standard_error.write.handle).get());
		standard_input.read.close();
		standard_output.write.close();
		standard_error.write.close();

		boost::asio::io_service io;

		process_output result;

		begin_reading_output(io, Si::make_container_sink(result.output), std::move(standard_output.read));
		begin_reading_output(io, Si::make_container_sink(result.error), std::move(standard_error.read));

		io.run();

		result.exit_code = process.wait_for_exit().get();
		return result;
	}
}

#ifndef _WIN32
BOOST_AUTO_TEST_CASE(async_process_unix_which)
{
	Si::async_process_parameters parameters;
	parameters.executable = *Si::absolute_path::create("/usr/bin/which");
	parameters.arguments.emplace_back("which");
	parameters.current_path = Si::get_current_working_directory();

	process_output result = run_process(parameters);

	BOOST_CHECK_EQUAL("/usr/bin/which\n", result.output);
	BOOST_CHECK_EQUAL("", result.error);
	BOOST_CHECK_EQUAL(0, result.exit_code);
}
#endif

#ifdef _WIN32
BOOST_AUTO_TEST_CASE(async_process_win32_where)
{
	Si::async_process_parameters parameters;
	parameters.executable = L"C:\\Windows\\System32\\where.exe";
	parameters.current_path = boost::filesystem::current_path();

	process_output result = run_process(parameters);

	std::size_t const windows7whereHelpSize = 1830;
	BOOST_CHECK_EQUAL(windows7whereHelpSize, result.output.size());
	BOOST_CHECK_EQUAL("", result.error);
	BOOST_CHECK_EQUAL(2, result.exit_code);
}
#endif

namespace
{
	Si::absolute_path const arbitrary_root_dir = *Si::absolute_path::create(
#ifdef _WIN32
		L"C:\\"
#else
		"/"
#endif
	);
}

BOOST_AUTO_TEST_CASE(async_process_executable_not_found)
{
	Si::async_process_parameters parameters;
	parameters.executable = arbitrary_root_dir / "does-not-exist";
	parameters.current_path = Si::get_current_working_directory();

	BOOST_CHECK_EXCEPTION(run_process(parameters), boost::system::system_error, [](boost::system::system_error const &ex)
	{
		return ex.code() == boost::system::errc::no_such_file_or_directory;
	});
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2017 IBM.
 */

#ifndef _CACHELINE_HH
#define _CACHELINE_HH

#include <cstddef>

namespace seastar {

// Platform-dependent cache line size for alignment and padding purposes.
static constexpr size_t cache_line_size =
#if defined(__x86_64__) || defined(__i386__)
    64;
#elif defined(__s390x__) || defined(__zarch__)
    256;
#elif defined(__PPC64__)
    128;
#else
#error "cache_line_size not defined for this architecture"
#endif

}

#endif // _CACHELINE_HH
<commit_msg>cacheline: define cache line for ARM<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2017 IBM.
 */

#ifndef _CACHELINE_HH
#define _CACHELINE_HH

#include <cstddef>

namespace seastar {

// Platform-dependent cache line size for alignment and padding purposes.
static constexpr size_t cache_line_size =
#if defined(__x86_64__) || defined(__i386__)
    64;
#elif defined(__s390x__) || defined(__zarch__)
    256;
#elif defined(__PPC64__)
    128;
#elif defined(__aarch64__)
    128; // from Linux, may vary among different microarchitetures?
#else
#error "cache_line_size not defined for this architecture"
#endif

}

#endif // _CACHELINE_HH
<|endoftext|>