<commit_before>#include <string>
#include <mutex>
#include <queue>
#include <vector>
#include <cstdint>
#include <iostream>
#include <pthread.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>

typedef enum
{
	extract_image,
	extract_audio,
	upscale_image,
	render_video
} work_t;

typedef struct
{
	uint64_t id;
	std::string *working_dir;
	std::string *command;
	std::mutex *work_lock;
	std::queue<uint64_t> *deps;
	work_t type;
	bool done;
} work_unit_t;

void create_thread(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
{
	int rc = pthread_create(thread, attr, start_routine, arg);
	if (rc)
	{
		std::cerr << "Could not create thread." << std::endl;
		exit(1);
	}
}

bool valid(const std::string &file)
{
	std::vector<std::string> extensions = {"mp4", "mkv", "m4v", "avi"};
	for (auto itr = extensions.begin(); itr != extensions.end(); itr++)
	{
		if (file.size() >= itr -> size() && file.compare(file.size() - itr -> size(), itr -> size(), *itr) == 0) { return true; }
	}
	return false;
}

bool valid(const char *file)
{
	std::string temp = std::string(file);
	return valid(temp);
}

bool isext(const char *file, const char *ext)
{
	size_t file_len = strlen(file);
	size_t ext_len = strlen(ext);
	if (file_len < ext_len) { return false; }
	if (strcmp((const char *) file + file_len - ext_len, ext))
	{
		return false;
	}
	return true;
}

bool dir_exists(const char *path)
{
	DIR *dir = opendir(path);
	if (dir)
	{
		closedir(dir);
		return true;
	}
	else if (errno == ENOENT)
	{
		return false;
	}
	else
	{
		std::cerr << std::strerror(errno) << std::endl;
		exit(errno);
	}
}

void create_dir_tree(const char *base_path, const char *data_path)
{
	std::string ptemp = base_path;
	std::vector<std::string> to_create = {"/images", "/out", "/images/original", "/images/upscaled"};
	ptemp += "/";
	ptemp += data_path;
	if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
	{
		if (errno != EEXIST)
		{
			std::cerr << std::strerror(errno) << std::endl;
			exit(errno);
		}
	}
	for (auto itr = to_create.begin(); itr != to_create.end(); itr++)
	{
		ptemp = base_path;
		ptemp += "/";
		ptemp += data_path;
		ptemp += *itr;
		if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
		{
			if (errno != EEXIST)
			{
				std::cerr << std::strerror(errno) << std::endl;
				exit(errno);
			}
		}
	}
}

void make_work(std::vector<work_unit_t *> *work, DIR *dir, const char *base_path)
{
	dirent *dp = NULL;
	struct stat st;
	std::vector<std::string> dirs;
	std::vector<std::string> files;
	//bool match_dir;
	std::string dtemp;
	std::string ftemp;
	std::string ptemp;
	std::string data_dir;
	std::string original_image_dir;
	std::string upscaled_image_dir;
	std::string output_dir;
	bool orig_img;
	bool upscale_img;
	bool video;
	bool audio;
	work_unit_t *wtemp;
	uint64_t orig_img_id;
	uint64_t audio_id;
	uint64_t upscale_img_id;
	DIR *dptemp;
	while (dir)
	{
		dp = readdir(dir);
		if (dp != NULL)
		{
			ptemp = base_path;
			ptemp += "/";
			ptemp += dp -> d_name;
			if (lstat(ptemp.c_str(), &st) == 0)
			{
				if (S_ISDIR(st.st_mode))
				{
					dirs.push_back(std::string(dp -> d_name));
				}
				else
				{
					files.push_back(std::string(dp -> d_name));
				}
			}
			else
			{
				std::cerr << std::strerror(errno) << std::endl;
				closedir(dir);
				exit(errno);
			}
		}
		else
		{
			closedir(dir); //ensure that this gets called - errors from lstat or readdir may cause this to fail
			break;
		}
	}
	//if (dp) { delete dp; }
	for (auto fitr = files.begin(); fitr != files.end(); fitr++)
	{
		if (valid(*fitr))
		{
			create_dir_tree(base_path, fitr -> substr(0, fitr -> find_last_of(".")).c_str());
			data_dir = base_path;
			data_dir += "/";
			data_dir += fitr -> substr(0, fitr -> find_last_of("."));
			original_image_dir = data_dir;
			original_image_dir += "/images/original";
			upscaled_image_dir = data_dir;
			upscaled_image_dir += "/images/upscaled";
			output_dir = data_dir;
			output_dir += "/out";
			orig_img = false;
			upscale_img = false;
			video = false;
			audio = false;
			//check for existing extracted images
			dptemp = opendir(original_image_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (isext(dp -> d_name, "png"))
					{
						orig_img = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			//check for any upscaled images
			dptemp = opendir(upscaled_image_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (isext(dp -> d_name, "png"))
					{
						upscale_img = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			//check for video
			dptemp = opendir(output_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (valid(dp -> d_name))
					{
						video = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			dptemp = opendir(data_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (strcmp("audio", dp -> d_name) == 0)
					{
						audio = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			if (!orig_img && !video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				orig_img_id = wtemp -> id;
				wtemp -> working_dir = new std::string(original_image_dir);
				wtemp -> command = new std::string("ffmpeg -i ../../");
				*(wtemp -> command) += *fitr;
				*(wtemp -> command) += " %05d.png";
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = extract_image;
				wtemp -> done = false;
				work -> push_back(wtemp);
			}
			if (!upscale_img && !video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				upscale_img_id = wtemp -> id;
				wtemp -> working_dir = new std::string(original_image_dir);
				wtemp -> command = new std::string("for f in *; do waifu2x -i $f -o ../upscaled/$f; done");
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = upscale_image;
				wtemp -> done = false;
				if (!orig_img)
				{
					wtemp -> deps -> push(orig_img_id);
				}
				work -> push_back(wtemp);
			}
			if (!audio && !video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				audio_id = wtemp -> id;
				wtemp -> working_dir = new std::string(data_dir);
				wtemp -> command = new std::string("ffmpeg -i ../");
				*(wtemp -> command) += *fitr;
				*(wtemp -> command) += " -vn -acodec copy audio.ext";
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = extract_audio;
				wtemp -> done = false;
				work -> push_back(wtemp);
			}
			if (!video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				wtemp -> working_dir = new std::string(output_dir);
				wtemp -> command = new std::string("ffmpeg -framerate 30 -i ../images/upscaled/%05d.png -i ../audio.ext -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -pix_fmt yuv420p");
				*(wtemp -> command) += *fitr;
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = render_video;
				wtemp -> done = false;
				if (!orig_img)
				{
					wtemp -> deps -> push(orig_img_id);
				}
				if (!upscale_img)
				{
					wtemp -> deps -> push(upscale_img_id);
				}
				if (!audio)
				{
					wtemp -> deps -> push(audio_id);
				}
				work -> push_back(wtemp);
			}
		}
	}
	/* a miracle happens */
	for (auto ditr = dirs.begin(); ditr != dirs.end(); ditr++)
	{
		if (ditr -> compare(".") && ditr -> compare(".."))
		{
			ptemp = base_path;
			ptemp += "/";
			ptemp += *ditr;
			dptemp = opendir(ptemp.c_str());
			make_work(work, dptemp, ptemp.c_str());
		}
	}
	//if (dp) { delete dp; }
}

void do_work(std::vector<work_unit_t *> *work, std::mutex *vector_lock)
{
	for (auto itr = work -> begin(); itr != work -> end(); itr++)
	{
		std::cout << *((*itr) -> command);
	}
}

int main(int argc, char** argv)
{
	std::vector<work_unit_t*> work;
	std::mutex vector_lock;
	size_t buf_size = 1024;
	char* buf = new char[buf_size];
	if (argc > 1)
	{
		strcpy(buf, argv[1]);
	}
	else if (getcwd(buf, buf_size) == NULL)
	{
		std::cerr << std::strerror(errno) << std::endl;
		return errno;
	}
	DIR *dir = opendir(buf);
	make_work(&work, dir, buf);
	do_work(&work, &vector_lock);
	delete[] buf;
	return 0;
}
<commit_msg>fixed quotes<commit_after>#include <string>
#include <mutex>
#include <queue>
#include <vector>
#include <cstdint>
#include <iostream>
#include <pthread.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>

typedef enum
{
	extract_image,
	extract_audio,
	upscale_image,
	render_video
} work_t;

typedef struct
{
	uint64_t id;
	std::string *working_dir;
	std::string *command;
	std::mutex *work_lock;
	std::queue<uint64_t> *deps;
	work_t type;
	bool done;
} work_unit_t;

void create_thread(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
{
	int rc = pthread_create(thread, attr, start_routine, arg);
	if (rc)
	{
		std::cerr << "Could not create thread." << std::endl;
		exit(1);
	}
}

bool valid(const std::string &file)
{
	std::vector<std::string> extensions = {"mp4", "mkv", "m4v", "avi"};
	for (auto itr = extensions.begin(); itr != extensions.end(); itr++)
	{
		if (file.size() >= itr -> size() && file.compare(file.size() - itr -> size(), itr -> size(), *itr) == 0) { return true; }
	}
	return false;
}

bool valid(const char *file)
{
	std::string temp = std::string(file);
	return valid(temp);
}

bool isext(const char *file, const char *ext)
{
	size_t file_len = strlen(file);
	size_t ext_len = strlen(ext);
	if (file_len < ext_len) { return false; }
	if (strcmp((const char *) file + file_len - ext_len, ext))
	{
		return false;
	}
	return true;
}

bool dir_exists(const char *path)
{
	DIR *dir = opendir(path);
	if (dir)
	{
		closedir(dir);
		return true;
	}
	else if (errno == ENOENT)
	{
		return false;
	}
	else
	{
		std::cerr << std::strerror(errno) << std::endl;
		exit(errno);
	}
}

void create_dir_tree(const char *base_path, const char *data_path)
{
	std::string ptemp = base_path;
	std::vector<std::string> to_create = {"/images", "/out", "/images/original", "/images/upscaled"};
	ptemp += "/";
	ptemp += data_path;
	if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
	{
		if (errno != EEXIST)
		{
			std::cerr << std::strerror(errno) << std::endl;
			exit(errno);
		}
	}
	for (auto itr = to_create.begin(); itr != to_create.end(); itr++)
	{
		ptemp = base_path;
		ptemp += "/";
		ptemp += data_path;
		ptemp += *itr;
		if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
		{
			if (errno != EEXIST)
			{
				std::cerr << std::strerror(errno) << std::endl;
				exit(errno);
			}
		}
	}
}

void make_work(std::vector<work_unit_t *> *work, DIR *dir, const char *base_path)
{
	dirent *dp = NULL;
	struct stat st;
	std::vector<std::string> dirs;
	std::vector<std::string> files;
	//bool match_dir;
	std::string dtemp;
	std::string ftemp;
	std::string ptemp;
	std::string data_dir;
	std::string original_image_dir;
	std::string upscaled_image_dir;
	std::string output_dir;
	bool orig_img;
	bool upscale_img;
	bool video;
	bool audio;
	work_unit_t *wtemp;
	uint64_t orig_img_id;
	uint64_t audio_id;
	uint64_t upscale_img_id;
	DIR *dptemp;
	while (dir)
	{
		dp = readdir(dir);
		if (dp != NULL)
		{
			ptemp = base_path;
			ptemp += "/";
			ptemp += dp -> d_name;
			if (lstat(ptemp.c_str(), &st) == 0)
			{
				if (S_ISDIR(st.st_mode))
				{
					dirs.push_back(std::string(dp -> d_name));
				}
				else
				{
					files.push_back(std::string(dp -> d_name));
				}
			}
			else
			{
				std::cerr << std::strerror(errno) << std::endl;
				closedir(dir);
				exit(errno);
			}
		}
		else
		{
			closedir(dir); //ensure that this gets called - errors from lstat or readdir may cause this to fail
			break;
		}
	}
	//if (dp) { delete dp; }
	for (auto fitr = files.begin(); fitr != files.end(); fitr++)
	{
		if (valid(*fitr))
		{
			create_dir_tree(base_path, fitr -> substr(0, fitr -> find_last_of(".")).c_str());
			data_dir = base_path;
			data_dir += "/";
			data_dir += fitr -> substr(0, fitr -> find_last_of("."));
			original_image_dir = data_dir;
			original_image_dir += "/images/original";
			upscaled_image_dir = data_dir;
			upscaled_image_dir += "/images/upscaled";
			output_dir = data_dir;
			output_dir += "/out";
			orig_img = false;
			upscale_img = false;
			video = false;
			audio = false;
			//check for existing extracted images
			dptemp = opendir(original_image_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (isext(dp -> d_name, "png"))
					{
						orig_img = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			//check for any upscaled images
			dptemp = opendir(upscaled_image_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (isext(dp -> d_name, "png"))
					{
						upscale_img = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			//check for video
			dptemp = opendir(output_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (valid(dp -> d_name))
					{
						video = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			dptemp = opendir(data_dir.c_str());
			while (dptemp)
			{
				dp = readdir(dptemp);
				if (dp != NULL)
				{
					if (strcmp("audio", dp -> d_name) == 0)
					{
						audio = true;
						closedir(dptemp);
						break;
					}
				}
				else
				{
					closedir(dptemp);
					break;
				}
			}
			if (!orig_img && !video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				orig_img_id = wtemp -> id;
				wtemp -> working_dir = new std::string(original_image_dir);
				wtemp -> command = new std::string("ffmpeg -i \"../../");
				*(wtemp -> command) += *fitr;
				*(wtemp -> command) += "\" %05d.png";
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = extract_image;
				wtemp -> done = false;
				work -> push_back(wtemp);
			}
			if (!upscale_img && !video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				upscale_img_id = wtemp -> id;
				wtemp -> working_dir = new std::string(original_image_dir);
				wtemp -> command = new std::string("for f in *; do waifu2x -i $f -o ../upscaled/$f; done");
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = upscale_image;
				wtemp -> done = false;
				if (!orig_img)
				{
					wtemp -> deps -> push(orig_img_id);
				}
				work -> push_back(wtemp);
			}
			if (!audio && !video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				audio_id = wtemp -> id;
				wtemp -> working_dir = new std::string(data_dir);
				wtemp -> command = new std::string("ffmpeg -i \"../");
				*(wtemp -> command) += *fitr;
				*(wtemp -> command) += "\" -vn -acodec copy audio.ext";
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = extract_audio;
				wtemp -> done = false;
				work -> push_back(wtemp);
			}
			if (!video)
			{
				wtemp = new work_unit_t;
				wtemp -> id = work -> size();
				wtemp -> working_dir = new std::string(output_dir);
				wtemp -> command = new std::string("ffmpeg -framerate 30 -i ../images/upscaled/%05d.png -i ../audio.ext -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -pix_fmt yuv420p \"");
				*(wtemp -> command) += *fitr;
				*(wtemp -> command) += "\"";
				wtemp -> work_lock = new std::mutex;
				wtemp -> deps = new std::queue<uint64_t>;
				wtemp -> type = render_video;
				wtemp -> done = false;
				if (!orig_img)
				{
					wtemp -> deps -> push(orig_img_id);
				}
				if (!upscale_img)
				{
					wtemp -> deps -> push(upscale_img_id);
				}
				if (!audio)
				{
					wtemp -> deps -> push(audio_id);
				}
				work -> push_back(wtemp);
			}
		}
	}
	/* a miracle happens */
	for (auto ditr = dirs.begin(); ditr != dirs.end(); ditr++)
	{
		if (ditr -> compare(".") && ditr -> compare(".."))
		{
			ptemp = base_path;
			ptemp += "/";
			ptemp += *ditr;
			dptemp = opendir(ptemp.c_str());
			make_work(work, dptemp, ptemp.c_str());
		}
	}
	//if (dp) { delete dp; }
}

void do_work(std::vector<work_unit_t *> *work, std::mutex *vector_lock)
{
	for (auto itr = work -> begin(); itr != work -> end(); itr++)
	{
		std::cout << *((*itr) -> command);
	}
}

int main(int argc, char** argv)
{
	std::vector<work_unit_t*> work;
	std::mutex vector_lock;
	size_t buf_size = 1024;
	char* buf = new char[buf_size];
	if (argc > 1)
	{
		strcpy(buf, argv[1]);
	}
	else if (getcwd(buf, buf_size) == NULL)
	{
		std::cerr << std::strerror(errno) << std::endl;
		return errno;
	}
	DIR *dir = opendir(buf);
	make_work(&work, dir, buf);
	do_work(&work, &vector_lock);
	delete[] buf;
	return 0;
}
<|endoftext|>


<commit_before>#include <itomp_cio_planner/visualization/new_viz_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/contact/ground_manager.h>
#include <ros/node_handle.h>
#include <boost/lexical_cast.hpp>

using namespace std;

namespace itomp_cio_planner
{

NewVizManager::NewVizManager()
{
}

NewVizManager::~NewVizManager()
{
}

void NewVizManager::initialize(const ItompRobotModelConstPtr& robot_model)
{
	ros::NodeHandle node_handle;
	vis_marker_array_publisher_ = node_handle.advertise<
			visualization_msgs::MarkerArray>(
			"itomp_planner/visualization_marker_array", 10);
	vis_marker_publisher_ = node_handle.advertise<visualization_msgs::Marker>(
			"itomp_planner/visualization_marker", 10);

	robot_model_ = robot_model;
	reference_frame_ = robot_model->getReferenceFrame();

	colors_.resize(8);
	for (int i = 0; i < 8; ++i)
	{
		colors_[i].a = 1.0;
		colors_[i].b = (i % 2 == 0) ? 0.0 : 1.0;
		colors_[i].g = ((i / 2) % 2 == 0) ? 0.0 : 1.0;
		colors_[i].r = ((i / 4) % 2 == 0) ? 0.0 : 1.0;
	}
}

void NewVizManager::setPlanningGroup(
		const ItompPlanningGroupConstPtr& planning_group)
{
	planning_group_ = planning_group;

	const multimap<string, string>& endeffector_names =
			PlanningParameters::getInstance()->getGroupEndeffectorNames();
	std::pair<multimap<string, string>::const_iterator,
			multimap<string, string>::const_iterator> ret =
			endeffector_names.equal_range(planning_group_->name_);
	endeffector_rbdl_indices_.clear();
	for (multimap<string, string>::const_iterator it = ret.first;
			it != ret.second; ++it)
	{
		string endeffector_name = it->second;
		unsigned int rbdl_link_index =
				robot_model_->getRBDLRobotModel().GetBodyId(
						endeffector_name.c_str());
		endeffector_rbdl_indices_.push_back(rbdl_link_index);
	}
}

void NewVizManager::renderOneTime()
{
	//renderGround();
	//renderEnvironment(); // rendered in move_itomp
}

void NewVizManager::renderEnvironment()
{
	string environment_file =
			PlanningParameters::getInstance()->getEnvironmentModel();
	if (environment_file.empty())
		return;

	vector<double> environment_position =
			PlanningParameters::getInstance()->getEnvironmentModelPosition();
	double scale =
			PlanningParameters::getInstance()->getEnvironmentModelScale();
	environment_position.resize(3, 0);

	visualization_msgs::MarkerArray ma;
	visualization_msgs::Marker msg;
	msg.header.frame_id = reference_frame_;
	msg.header.stamp = ros::Time::now();
	msg.ns = "environment";
	msg.type = visualization_msgs::Marker::MESH_RESOURCE;
	msg.action = visualization_msgs::Marker::ADD;
	msg.scale.x = scale;
	msg.scale.y = scale;
	msg.scale.z = scale;
	msg.id = 0;
	msg.pose.position.x = environment_position[0];
	msg.pose.position.y = environment_position[1];
	msg.pose.position.z = environment_position[2];
	/*
	 msg.pose.orientation.x = sqrt(0.5);
	 msg.pose.orientation.y = 0.0;
	 msg.pose.orientation.z = 0.0;
	 msg.pose.orientation.w = sqrt(0.5);
	 */
	msg.pose.orientation.x = 0.0;
	msg.pose.orientation.y = 0.0;
	msg.pose.orientation.z = 0.0;
	msg.pose.orientation.w = 1.0;
	msg.color.a = 1.0;
	msg.color.r = 0.5;
	msg.color.g = 0.5;
	msg.color.b = 0.5;
	msg.mesh_resource = environment_file;
	ma.markers.push_back(msg);
	vis_marker_array_publisher_.publish(ma);
}

void NewVizManager::renderGround()
{
}

void NewVizManager::animateEndeffectors(
		const FullTrajectoryConstPtr& full_trajectory,
		const std::vector<RigidBodyDynamics::Model>& models, bool is_best)
{
	const double scale_keyframe = 0.03;
	const double scale_line = 0.005;
	geometry_msgs::Point point;

	visualization_msgs::Marker msg;
	msg.header.frame_id = reference_frame_;
	msg.header.stamp = ros::Time::now();
	msg.ns = is_best ? "itomp_best_ee" : "itomp_ee";
	msg.action = visualization_msgs::Marker::ADD;
	msg.pose.orientation.w = 1.0;

	// render keyframe endeffectors
	msg.type = visualization_msgs::Marker::SPHERE_LIST;
	msg.scale.x = scale_keyframe;
	msg.scale.y = scale_keyframe;
	msg.scale.z = scale_keyframe;
	msg.points.resize(0);

	msg.color = is_best ? colors_[GREEN] : colors_[BLUE];

	msg.id = 0;
	for (int i = full_trajectory->getKeyframeStartIndex();
			i < full_trajectory->getNumPoints();
			i += full_trajectory->getNumKeyframeIntervalPoints())
	{
		for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
		{
			int rbdl_index = endeffector_rbdl_indices_[j];

			Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
			point.x = endeffector_pos(0);
			point.y = endeffector_pos(1);
			point.z = endeffector_pos(2);
			msg.points.push_back(point);
		}
	}
	vis_marker_publisher_.publish(msg);

	// render endeffector path
	msg.type = visualization_msgs::Marker::LINE_STRIP;
	msg.scale.x = scale_line;
	msg.scale.y = scale_line;
	msg.scale.z = scale_line;
	msg.color = is_best ? colors_[GREEN] : colors_[BLUE];

	for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
	{
		++msg.id;
		msg.points.resize(0);

		int rbdl_index = endeffector_rbdl_indices_[j];
		for (int i = 0; i < full_trajectory->getNumPoints(); ++i)
		{
			Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
			point.x = endeffector_pos(0);
			point.y = endeffector_pos(1);
			point.z = endeffector_pos(2);
			msg.points.push_back(point);
		}

		vis_marker_publisher_.publish(msg);
	}
}

void NewVizManager::animatePath(const FullTrajectoryConstPtr& full_trajectory,
		const robot_state::RobotStatePtr& robot_state, bool is_best)
{
	if (!is_best)
		return;

	geometry_msgs::Point point;

	visualization_msgs::MarkerArray ma;
	std::vector<std::string> link_names =
			robot_model_->getMoveitRobotModel()->getLinkModelNames();
	std_msgs::ColorRGBA color = colors_[WHITE];
	color.a = 0.1;
	ros::Duration dur(100.0);

	for (int point = full_trajectory->getKeyframeStartIndex();
			point < full_trajectory->getNumPoints();
			point += full_trajectory->getNumKeyframeIntervalPoints())
	{
		ma.markers.clear();
		const Eigen::MatrixXd mat = full_trajectory->getTrajectory(
				Trajectory::TRAJECTORY_TYPE_POSITION).row(point);
		robot_state->setVariablePositions(mat.data());
		std::string ns = "kf_" + boost::lexical_cast<std::string>(point);
		robot_state->getRobotMarkers(ma, link_names, color, ns, dur);
		vis_marker_array_publisher_.publish(ma);
	}
}

void NewVizManager::animateContactForces(
		const FullTrajectoryConstPtr& full_trajectory,
		const std::vector<std::vector<ContactVariables> >& contact_variables,
		bool is_best, bool keyframe_only)
{
	const double scale_line = 0.005;
	const double scale_keyframe = 0.03;
	geometry_msgs::Point point_from, point_to;

	visualization_msgs::Marker msg, msg2, msg3, msg4;
	msg.header.frame_id = reference_frame_;
	msg.header.stamp = ros::Time::now();
	msg.ns = is_best ? "itomp_best_cf" : "itomp_cf";
	msg.action = visualization_msgs::Marker::ADD;
	msg.pose.orientation.w = 1.0;

	msg.type = visualization_msgs::Marker::LINE_LIST;
	msg.scale.x = scale_line;
	msg.scale.y = scale_line;
	msg.scale.z = scale_line;
	msg.color = is_best ? colors_[YELLOW] : colors_[MAGENTA];

	msg.id = 0;
	msg.points.resize(0);

	msg2 = msg;
	msg2.ns = is_best ? "itomp_best_cp" : "itomp_cp";
	msg2.type = visualization_msgs::Marker::SPHERE_LIST;
	msg2.scale.x = scale_keyframe;
	msg2.scale.y = scale_keyframe;
	msg2.scale.z = scale_keyframe;

	// inactive
	msg3 = msg;
	msg3.id = 0;
	msg3.color = is_best ? colors_[RED] : colors_[MAGENTA];
	msg3.ns = is_best ? "itomp_best_cf_ia" : "itomp_cf_ia";
	msg4 = msg2;
	msg4.id = 0;
	msg4.color = is_best ? colors_[RED] : colors_[MAGENTA];
	msg4.ns = is_best ? "itomp_best_cp_ia" : "itomp_cp_ia";

	int begin, end, step;
	if (keyframe_only)
	{
		begin = full_trajectory->getKeyframeStartIndex();
		end = full_trajectory->getNumPoints();
		step = full_trajectory->getNumKeyframeIntervalPoints();
	}
	else
	{
		begin = 0;
		end = full_trajectory->getNumPoints();
		step = 1;
	}

	int num_contacts = contact_variables[0].size();
	for (int point = begin; point < end; point += step)
	{
		for (int i = 0; i < num_contacts; ++i)
		{
			double contact_v = contact_variables[point][i].getVariable();

			for (int c = 0; c < NUM_ENDEFFECTOR_CONTACT_POINTS; ++c)
			{
				Eigen::Vector3d point_position =
						contact_variables[point][i].projected_point_positions_[c];

				Eigen::Vector3d contact_force =
						contact_variables[point][i].getPointForce(c);
				contact_force *= contact_v;

				point_from.x = point_position(0);
				point_from.y = point_position(1);
				point_from.z = point_position(2);

				point_to.x = contact_force(0) * 0.001 + point_from.x;
				point_to.y = contact_force(1) * 0.001 + point_from.y;
				point_to.z = contact_force(2) * 0.001 + point_from.z;

				const double k1 = 0.01; //10.0;
				const double k2 = 3; //3.0;
				double contact_variable = contact_v;

				if (contact_variable > 0.0)
				{
					msg.points.push_back(point_from);
					msg.points.push_back(point_to);
					msg2.points.push_back(point_from);
				}
				else
				{
					msg3.points.push_back(point_from);
					msg3.points.push_back(point_to);
					msg4.points.push_back(point_from);
				}
			}

		}
	}
	vis_marker_publisher_.publish(msg);
	vis_marker_publisher_.publish(msg2);
	vis_marker_publisher_.publish(msg3);
	vis_marker_publisher_.publish(msg4);
}

}
<commit_msg>update viz manager<commit_after>#include <itomp_cio_planner/visualization/new_viz_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/contact/ground_manager.h>
#include <ros/node_handle.h>
#include <boost/lexical_cast.hpp>

using namespace std;

namespace itomp_cio_planner
{

NewVizManager::NewVizManager()
{
}

NewVizManager::~NewVizManager()
{
}

void NewVizManager::initialize(const ItompRobotModelConstPtr& robot_model)
{
	ros::NodeHandle node_handle;
	vis_marker_array_publisher_ = node_handle.advertise<
			visualization_msgs::MarkerArray>(
			"itomp_planner/visualization_marker_array", 10);
	vis_marker_publisher_ = node_handle.advertise<visualization_msgs::Marker>(
			"itomp_planner/visualization_marker", 10);

	robot_model_ = robot_model;
	reference_frame_ = robot_model->getReferenceFrame();

	colors_.resize(8);
	for (int i = 0; i < 8; ++i)
	{
		colors_[i].a = 1.0;
		colors_[i].b = (i % 2 == 0) ? 0.0 : 1.0;
		colors_[i].g = ((i / 2) % 2 == 0) ? 0.0 : 1.0;
		colors_[i].r = ((i / 4) % 2 == 0) ? 0.0 : 1.0;
	}
}

void NewVizManager::setPlanningGroup(
		const ItompPlanningGroupConstPtr& planning_group)
{
	planning_group_ = planning_group;

	const multimap<string, string>& endeffector_names =
			PlanningParameters::getInstance()->getGroupEndeffectorNames();
	std::pair<multimap<string, string>::const_iterator,
			multimap<string, string>::const_iterator> ret =
			endeffector_names.equal_range(planning_group_->name_);
	endeffector_rbdl_indices_.clear();
	for (multimap<string, string>::const_iterator it = ret.first;
			it != ret.second; ++it)
	{
		string endeffector_name = it->second;
		unsigned int rbdl_link_index =
				robot_model_->getRBDLRobotModel().GetBodyId(
						endeffector_name.c_str());
		endeffector_rbdl_indices_.push_back(rbdl_link_index);
	}
}

void NewVizManager::renderOneTime()
{
	//renderGround();
	//renderEnvironment(); // rendered in move_itomp
}

void NewVizManager::renderEnvironment()
{
	string environment_file =
			PlanningParameters::getInstance()->getEnvironmentModel();
	if (environment_file.empty())
		return;

	vector<double> environment_position =
			PlanningParameters::getInstance()->getEnvironmentModelPosition();
	double scale =
			PlanningParameters::getInstance()->getEnvironmentModelScale();
	environment_position.resize(3, 0);

	visualization_msgs::MarkerArray ma;
	visualization_msgs::Marker msg;
	msg.header.frame_id = reference_frame_;
	msg.header.stamp = ros::Time::now();
	msg.ns = "environment";
	msg.type = visualization_msgs::Marker::MESH_RESOURCE;
	msg.action = visualization_msgs::Marker::ADD;
	msg.scale.x = scale;
	msg.scale.y = scale;
	msg.scale.z = scale;
	msg.id = 0;
	msg.pose.position.x = environment_position[0];
	msg.pose.position.y = environment_position[1];
	msg.pose.position.z = environment_position[2];
	/*
	 msg.pose.orientation.x = sqrt(0.5);
	 msg.pose.orientation.y = 0.0;
	 msg.pose.orientation.z = 0.0;
	 msg.pose.orientation.w = sqrt(0.5);
	 */
	msg.pose.orientation.x = 0.0;
	msg.pose.orientation.y = 0.0;
	msg.pose.orientation.z = 0.0;
	msg.pose.orientation.w = 1.0;
	msg.color.a = 1.0;
	msg.color.r = 0.5;
	msg.color.g = 0.5;
	msg.color.b = 0.5;
	msg.mesh_resource = environment_file;
	ma.markers.push_back(msg);
	vis_marker_array_publisher_.publish(ma);
}

void NewVizManager::renderGround()
{
}

void NewVizManager::animateEndeffectors(
		const FullTrajectoryConstPtr& full_trajectory,
		const std::vector<RigidBodyDynamics::Model>& models, bool is_best)
{
	const double scale_keyframe = 0.03;
	const double scale_line = 0.005;
	geometry_msgs::Point point;

	visualization_msgs::Marker msg;
	msg.header.frame_id = reference_frame_;
	msg.header.stamp = ros::Time::now();
	msg.ns = is_best ? "itomp_best_ee" : "itomp_ee";
	msg.action = visualization_msgs::Marker::ADD;
	msg.pose.orientation.w = 1.0;

	// render keyframe endeffectors
	msg.type = visualization_msgs::Marker::SPHERE_LIST;
	msg.scale.x = scale_keyframe;
	msg.scale.y = scale_keyframe;
	msg.scale.z = scale_keyframe;
	msg.points.resize(0);

	msg.color = is_best ? colors_[GREEN] : colors_[BLUE];

	msg.id = 0;
	for (int i = full_trajectory->getKeyframeStartIndex();
			i < full_trajectory->getNumPoints();
			i += full_trajectory->getNumKeyframeIntervalPoints())
	{
		for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
		{
			int rbdl_index = endeffector_rbdl_indices_[j];

			Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
			point.x = endeffector_pos(0);
			point.y = endeffector_pos(1);
			point.z = endeffector_pos(2);
			msg.points.push_back(point);
		}
	}
	vis_marker_publisher_.publish(msg);

	// render endeffector path
	msg.type = visualization_msgs::Marker::LINE_STRIP;
	msg.scale.x = scale_line;
	msg.scale.y = scale_line;
	msg.scale.z = scale_line;
	msg.color = is_best ? colors_[GREEN] : colors_[BLUE];

	for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
	{
		++msg.id;
		msg.points.resize(0);

		int rbdl_index = endeffector_rbdl_indices_[j];
		for (int i = 0; i < full_trajectory->getNumPoints(); ++i)
		{
			Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
			point.x = endeffector_pos(0);
			point.y = endeffector_pos(1);
			point.z = endeffector_pos(2);
			msg.points.push_back(point);
		}

		vis_marker_publisher_.publish(msg);
	}
}

void NewVizManager::animatePath(const FullTrajectoryConstPtr& full_trajectory,
		const robot_state::RobotStatePtr& robot_state, bool is_best)
{
	if (!is_best)
		return;

	geometry_msgs::Point point;

	visualization_msgs::MarkerArray ma;
	std::vector<std::string> link_names =
			robot_model_->getMoveitRobotModel()->getLinkModelNames();
	std_msgs::ColorRGBA color = colors_[WHITE];
	color.a = 0.1;
	ros::Duration dur(3600.0);

	for (int point = full_trajectory->getKeyframeStartIndex();
			point < full_trajectory->getNumPoints();
			point += full_trajectory->getNumKeyframeIntervalPoints())
	{
		ma.markers.clear();
		const Eigen::MatrixXd mat = full_trajectory->getTrajectory(
				Trajectory::TRAJECTORY_TYPE_POSITION).row(point);
		robot_state->setVariablePositions(mat.data());
		std::string ns = "kf_" + boost::lexical_cast<std::string>(point);
		robot_state->getRobotMarkers(ma, link_names, color, ns, dur);
		vis_marker_array_publisher_.publish(ma);
	}
}

void NewVizManager::animateContactForces(
		const FullTrajectoryConstPtr& full_trajectory,
		const std::vector<std::vector<ContactVariables> >& contact_variables,
		bool is_best, bool keyframe_only)
{
	const double scale_line = 0.005;
	const double scale_keyframe = 0.03;
	geometry_msgs::Point point_from, point_to;

	visualization_msgs::Marker msg, msg2, msg3, msg4;
	msg.header.frame_id = reference_frame_;
	msg.header.stamp = ros::Time::now();
	msg.ns = is_best ? "itomp_best_cf" : "itomp_cf";
	msg.action = visualization_msgs::Marker::ADD;
	msg.pose.orientation.w = 1.0;

	msg.type = visualization_msgs::Marker::LINE_LIST;
	msg.scale.x = scale_line;
	msg.scale.y = scale_line;
	msg.scale.z = scale_line;
	msg.color = is_best ? colors_[YELLOW] : colors_[MAGENTA];

	msg.id = 0;
	msg.points.resize(0);

	msg2 = msg;
	msg2.ns = is_best ? "itomp_best_cp" : "itomp_cp";
	msg2.type = visualization_msgs::Marker::SPHERE_LIST;
	msg2.scale.x = scale_keyframe;
	msg2.scale.y = scale_keyframe;
	msg2.scale.z = scale_keyframe;

	// inactive
	msg3 = msg;
	msg3.id = 0;
	msg3.color = is_best ? colors_[RED] : colors_[MAGENTA];
	msg3.ns = is_best ? "itomp_best_cf_ia" : "itomp_cf_ia";
	msg4 = msg2;
	msg4.id = 0;
	msg4.color = is_best ? colors_[RED] : colors_[MAGENTA];
	msg4.ns = is_best ? "itomp_best_cp_ia" : "itomp_cp_ia";

	int begin, end, step;
	if (keyframe_only)
	{
		begin = full_trajectory->getKeyframeStartIndex();
		end = full_trajectory->getNumPoints();
		step = full_trajectory->getNumKeyframeIntervalPoints();
	}
	else
	{
		begin = 0;
		end = full_trajectory->getNumPoints();
		step = 1;
	}

	int num_contacts = contact_variables[0].size();
	for (int point = begin; point < end; point += step)
	{
		for (int i = 0; i < num_contacts; ++i)
		{
			double contact_v = contact_variables[point][i].getVariable();

			for (int c = 0; c < NUM_ENDEFFECTOR_CONTACT_POINTS; ++c)
			{
				Eigen::Vector3d point_position =
						contact_variables[point][i].projected_point_positions_[c];

				Eigen::Vector3d contact_force =
						contact_variables[point][i].getPointForce(c);
				contact_force *= contact_v;

				point_from.x = point_position(0);
				point_from.y = point_position(1);
				point_from.z = point_position(2);

				point_to.x = contact_force(0) * 0.001 + point_from.x;
				point_to.y = contact_force(1) * 0.001 + point_from.y;
				point_to.z = contact_force(2) * 0.001 + point_from.z;

				const double k1 = 0.01; //10.0;
				const double k2 = 3; //3.0;
				double contact_variable = contact_v;

				if (contact_variable > 0.0)
				{
					msg.points.push_back(point_from);
					msg.points.push_back(point_to);
					msg2.points.push_back(point_from);
				}
				else
				{
					msg3.points.push_back(point_from);
					msg3.points.push_back(point_to);
					msg4.points.push_back(point_from);
				}
			}

		}
	}
	vis_marker_publisher_.publish(msg);
	vis_marker_publisher_.publish(msg2);
	vis_marker_publisher_.publish(msg3);
	vis_marker_publisher_.publish(msg4);
}

}
<|endoftext|>


<commit_before>#include <BWAPI.h>
#include <BWAPI/Client.h>

#include <iostream>
#include <thread>
#include <chrono>
#include <string>

using namespace BWAPI;

void drawStats();
void drawBullets();
void drawVisibilityData();
void showPlayers();
void showForces();
bool show_bullets;
bool show_visibility_data;

void reconnect()
{
  while(!BWAPIClient.connect())
  {
    std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });
  }
}

int main(int argc, const char* argv[])
{
  std::cout << "Connecting..." << std::endl;;
  reconnect();
  while(true)
  {
    std::cout << "waiting to enter match" << std::endl;
    while ( !Broodwar->isInGame() )
    {
      BWAPI::BWAPIClient.update();
      if (!BWAPI::BWAPIClient.isConnected())
      {
        std::cout << "Reconnecting..." << std::endl;;
        reconnect();
      }
    }
    std::cout << "starting match!" << std::endl;
    Broodwar->sendText("Hello world!");
    Broodwar << "The map is " << Broodwar->mapName() << ", a " << Broodwar->getStartLocations().size() << " player map" << std::endl;
    // Enable some cheat flags
    Broodwar->enableFlag(Flag::UserInput);
    // Uncomment to enable complete map information
    //Broodwar->enableFlag(Flag::CompleteMapInformation);

    show_bullets=false;
    show_visibility_data=false;

    if (Broodwar->isReplay())
    {
      Broodwar << "The following players are in this replay:" << std::endl;;
      Playerset players = Broodwar->getPlayers();
      for(auto p : players)
      {
        if ( !p->getUnits().empty() && !p->isNeutral() )
          Broodwar << p->getName() << ", playing as " << p->getRace() << std::endl;
      }
    }
    else
    {
      if (Broodwar->enemy())
        Broodwar << "The match up is " << Broodwar->self()->getRace() << " vs " << Broodwar->enemy()->getRace() << std::endl;

      //send each worker to the mineral field that is closest to it
      Unitset units    = Broodwar->self()->getUnits();
      Unitset minerals  = Broodwar->getMinerals();
      for ( auto &u : units )
      {
        if ( u->getType().isWorker() )
        {
          Unit closestMineral = nullptr;

          for (auto &m : minerals)
          {
            if ( !closestMineral || u->getDistance(m) < u->getDistance(closestMineral))
              closestMineral = m;
          }
          if ( closestMineral )
            u->rightClick(closestMineral);
        }
        else if ( u->getType().isResourceDepot() )
        {
          //if this is a center, tell it to build the appropiate type of worker
          u->train(Broodwar->self()->getRace().getWorker());
        }
      }
    }
    while(Broodwar->isInGame())
    {
      for(auto &e : Broodwar->getEvents())
      {
        switch(e.getType())
        {
          case EventType::MatchEnd:
            if (e.isWinner())
              Broodwar << "I won the game" << std::endl;
            else
              Broodwar << "I lost the game" << std::endl;
            break;
          case EventType::SendText:
            if (e.getText()=="/show bullets")
            {
              show_bullets=!show_bullets;
            } else if (e.getText()=="/show players")
            {
              showPlayers();
            } else if (e.getText()=="/show forces")
            {
              showForces();
            } else if (e.getText()=="/show visibility")
            {
              show_visibility_data=!show_visibility_data;
            }
            else
            {
              Broodwar << "You typed \"" << e.getText() << "\"!" << std::endl;
            }
            break;
          case EventType::ReceiveText:
            Broodwar << e.getPlayer()->getName() << " said \"" << e.getText() << "\"" << std::endl;
            break;
          case EventType::PlayerLeft:
            Broodwar << e.getPlayer()->getName() << " left the game." << std::endl;
            break;
          case EventType::NukeDetect:
            if (e.getPosition()!=Positions::Unknown)
            {
              Broodwar->drawCircleMap(e.getPosition(), 40, Colors::Red, true);
              Broodwar << "Nuclear Launch Detected at " << e.getPosition() << std::endl;
            }
            else
              Broodwar << "Nuclear Launch Detected" << std::endl;
            break;
          case EventType::UnitCreate:
            if (!Broodwar->isReplay())
              Broodwar << "A " << e.getUnit()->getType() << " [" << e.getUnit() << "] has been created at " << e.getUnit()->getPosition() << std::endl;
            else
            {
              // if we are in a replay, then we will print out the build order
              // (just of the buildings, not the units).
              if (e.getUnit()->getType().isBuilding() && e.getUnit()->getPlayer()->isNeutral()==false)
              {
                int seconds=Broodwar->getFrameCount()/24;
                int minutes=seconds/60;
                seconds%=60;
                Broodwar->sendText("%.2d:%.2d: %s creates a %s", minutes, seconds, e.getUnit()->getPlayer()->getName().c_str(), e.getUnit()->getType().c_str());
              }
            }
            break;
          case EventType::UnitDestroy:
            if (!Broodwar->isReplay())
              Broodwar->sendText("A %s [%p] has been destroyed at (%d,%d)",e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
            break;
          case EventType::UnitMorph:
            if (!Broodwar->isReplay())
              Broodwar->sendText("A %s [%p] has been morphed at (%d,%d)",e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
            else
            {
              // if we are in a replay, then we will print out the build order
              // (just of the buildings, not the units).
              if (e.getUnit()->getType().isBuilding() && e.getUnit()->getPlayer()->isNeutral()==false)
              {
                int seconds=Broodwar->getFrameCount()/24;
                int minutes=seconds/60;
                seconds%=60;
                Broodwar->sendText("%.2d:%.2d: %s morphs a %s" ,minutes, seconds, e.getUnit()->getPlayer()->getName().c_str(), e.getUnit()->getType().c_str());
              }
            }
            break;
          case EventType::UnitShow:
            if (!Broodwar->isReplay())
              Broodwar->sendText("A %s [%p] has been spotted at (%d,%d)", e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
            break;
          case EventType::UnitHide:
            if (!Broodwar->isReplay())
              Broodwar->sendText("A %s [%p] was last seen at (%d,%d)", e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
            break;
          case EventType::UnitRenegade:
            if (!Broodwar->isReplay())
              Broodwar->sendText("A %s [%p] is now owned by %s", e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPlayer()->getName().c_str());
            break;
          case EventType::SaveGame:
            Broodwar->sendText("The game was saved to \"%s\".", e.getText().c_str());
            break;
        }
      }

      if (show_bullets)
        drawBullets();

      if (show_visibility_data)
        drawVisibilityData();

      drawStats();
      Broodwar->drawTextScreen(300,0,"FPS: %f",Broodwar->getAverageFPS());

      BWAPI::BWAPIClient.update();
      if (!BWAPI::BWAPIClient.isConnected())
      {
        std::cout << "Reconnecting..." << std::endl;
        reconnect();
      }
    }
    std::cout << "Game ended" << std::endl;
  }
  std::cout << "Press ENTER to continue..." << std::endl;
  std::cin.ignore();
  return 0;
}

void drawStats()
{
  int line = 0;
  Broodwar->drawTextScreen(5, 0, "I have %d units:", Broodwar->self()->allUnitCount() );
  for (auto& unitType : UnitTypes::allUnitTypes())
  {
    int count = Broodwar->self()->allUnitCount(unitType);
    if ( count )
    {
      Broodwar->drawTextScreen(5, 16*line, "- %d %s%c", count, unitType.c_str(), count == 1 ? ' ' : 's');
      ++line;
    }
  }
}

void drawBullets()
{
  for (auto &b : Broodwar->getBullets())
  {
    Position p = b->getPosition();
    double velocityX = b->getVelocityX();
    double velocityY = b->getVelocityY();
    Broodwar->drawLineMap(p, p + Position((int)velocityX, (int)velocityY), b->getPlayer() == Broodwar->self() ? Colors::Green : Colors::Red);
    Broodwar->drawTextMap(p, "%c%s", b->getPlayer() == Broodwar->self() ? Text::Green : Text::Red, b->getType().c_str());
  }
}

void drawVisibilityData()
{
  int wid = Broodwar->mapHeight(), hgt = Broodwar->mapWidth();
  for ( int x = 0; x < wid; ++x )
    for ( int y = 0; y < hgt; ++y )
    {
      if ( Broodwar->isExplored(x, y) )
        Broodwar->drawDotMap(x*32+16, y*32+16, Broodwar->isVisible(x, y) ? Colors::Green : Colors::Blue);
      else
        Broodwar->drawDotMap(x*32+16, y*32+16, Colors::Red);
    }
}

void showPlayers()
{
  Playerset players = Broodwar->getPlayers();
  for(auto p : players)
    Broodwar << "Player [" << p->getID() << "]: " << p->getName() << " is in force: " << p->getForce()->getName() << std::endl;
}

void showForces()
{
  Forceset forces=Broodwar->getForces();
  for(auto f : forces)
  {
    Playerset players = f->getPlayers();
    Broodwar << "Force " << f->getName() << " has the following players:" << std::endl;
    for(auto p : players)
      Broodwar << "  - Player [" << p->getID() << "]: " << p->getName() << std::endl;
  }
}
<commit_msg>Dispatch all events to KBot.<commit_after>#include <BWAPI.h>
#include <BWAPI/Client.h>

#include <iostream>
#include <thread>
#include <chrono>
#include <string>

#include "KBot.h"

using namespace BWAPI;

static void busy_wait_connect()
{
  while(!BWAPIClient.connect())
  {
    std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });
  }
}

int main(int argc, const char** argv)
{
  std::cout << "Connecting..." << std::endl;
  busy_wait_connect();
  while(true)
  {
    std::cout << "waiting to enter match" << std::endl;
    while ( !Broodwar->isInGame() )
    {
      BWAPI::BWAPIClient.update();
      if (!BWAPI::BWAPIClient.isConnected())
      {
        std::cout << "Reconnecting..." << std::endl;;
        busy_wait_connect();
      }
    }

    // if (Broodwar->isReplay()) // TODO: Handle here?

    std::cout << "starting match!" << std::endl;
    KBot::KBot bot;

    while(Broodwar->isInGame())
    {
      for(auto &e : Broodwar->getEvents())
      {
        switch(e.getType())
        {
            case EventType::MatchStart:
                bot.onStart();
                break;
          case EventType::MatchEnd:
              bot.onEnd(e.isWinner());
            break;
          case EventType::MatchFrame:
              bot.onFrame();
              break;
          case EventType::MenuFrame:
              bot.onFrame(); // TODO: skip these?
              break;
          case EventType::SendText:
              bot.onSendText(e.getText());
            break;
          case EventType::ReceiveText:
              bot.onReceiveText(e.getPlayer(), e.getText());
            break;
          case EventType::PlayerLeft:
              bot.onPlayerLeft(e.getPlayer());
            break;
          case EventType::NukeDetect:
              bot.onNukeDetect(e.getPosition());
            break;
          case EventType::UnitDiscover:
              bot.onUnitDiscover(e.getUnit());
              break;
          case EventType::UnitEvade:
                  bot.onUnitEvade(e.getUnit());
                  break;
          case EventType::UnitShow:
              bot.onUnitShow(e.getUnit());
              break;
          case EventType::UnitHide:
              bot.onUnitHide(e.getUnit());
              break;
          case EventType::UnitCreate:
              bot.onUnitCreate(e.getUnit());
            break;
          case EventType::UnitDestroy:
              bot.onUnitDestroy(e.getUnit());
            break;
          case EventType::UnitMorph:
              bot.onUnitMorph(e.getUnit());
            break;
          case EventType::UnitRenegade:
              bot.onUnitRenegade(e.getUnit());
            break;
          case EventType::SaveGame:
              bot.onSaveGame(e.getText());
            break;
          case EventType::UnitComplete:
              bot.onUnitComplete(e.getUnit());
              break;
        }
      }

      BWAPI::BWAPIClient.update();
      if (!BWAPI::BWAPIClient.isConnected())
      {
        std::cout << "Reconnecting..." << std::endl;
        busy_wait_connect();
      }
    }
    std::cout << "Game ended" << std::endl;
  }
  std::cout << "Press ENTER to continue..." << std::endl;
  std::cin.ignore();

  return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include "flesch-index_config.h"
#include "flesch-index.hpp"

int main (int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stdout,"%s Version %d.%d.%d\n",
                    argv[0], flesch_index_VERSION_MAJOR,
                    flesch_index_VERSION_MINOR, flesch_index_VERSION_PATCH);

        fprintf(stdout,"Usage: %s [FILEIN]\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    std::string filename = argv[1];

    fi::Flesch_Index fi = fi::Flesch_Index(filename);
    fi.Read();
    exit(EXIT_SUCCESS);
}
<commit_msg>Updated main to run updated in flesch-index.cxx<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include "flesch-index_config.h"
#include "flesch-index.hpp"

int main (int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stdout,"%s Version %d.%d.%d\n",
                    argv[0], flesch_index_VERSION_MAJOR,
                    flesch_index_VERSION_MINOR, flesch_index_VERSION_PATCH);

        fprintf(stdout,"Usage: %s [FILEIN]\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    std::string filename = argv[1];

    fi::Flesch_Index fi = fi::Flesch_Index(filename);
    fi.Read();
    fi.Analyze();
    fi.Print();
    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#ifndef BFC_DEAD_LOOPS_VISITOR_HPP
#define BFC_DEAD_LOOPS_VISITOR_HPP

namespace bfc {
namespace ast {

class dead_loops_visitor : public opt_seq_base_visitor {

public:

    status visit(loop &node) {
        // test if previous node make this a dead loop
        test_dead_loop_visitor v;
        node prev_node = opt_seq.back();
        if (prev_node.accept(v) == CONTINUE) {
            // no-op to remove this loop from the sequence
            return CONTINUE;
        }
        // else optimize inner sequence
        return opt_seq_base_visitor::handle_loop(node);
    }

    status visit(const loop &node) {
        // test if previous node make this a dead loop
        test_dead_loop_visitor v;
        node prev_node = opt_seq.back();
        if (prev_node.accept(v) == CONTINUE) {
            // no-op to remove this loop from the sequence
            return CONTINUE;
        }
        // else optimize inner sequence
        return opt_seq_base_visitor::handle_loop(node);
    }

private:

    class test_dead_loop_visitor : public visitor {

        public:
            status visit(set &node) {
                return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
            }
            status visit(const set &node) {
                return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
            }

            // Loops only terminate when the current cell reaches 0
            // Thus loops following loops are dead
            status visit(loop &node) { return CONTINUE; }
            status visit(const loop &node) { return CONTINUE; }

    };

};

}
}

#endif /* !BFC_DEAD_LOOPS_VISITOR_HPP */
<commit_msg>Dead loop visitor now account for dead starting loops<commit_after>#ifndef BFC_DEAD_LOOPS_VISITOR_HPP
#define BFC_DEAD_LOOPS_VISITOR_HPP

namespace bfc {
namespace ast {

class dead_loops_visitor : public opt_seq_base_visitor {

public:

    dead_loops_visitor(void) : maybeProgramStart(true) {}

    status visit(loop &node) {
        // test if this is the first node of a program sequence
        if (maybeProgramStart && opt_seq.empty()) {
            // cells init to 0 on start, this loop is dead
            return CONTINUE;
        }
        // mark that we are past the start of the program
        maybeProgramStart = false;
        // test if previous node makes this a dead loop
        test_dead_loop_visitor v;
        node prev_node = opt_seq.back();
        if (prev_node.accept(v) == CONTINUE) {
            // no-op to remove this loop from the sequence
            return CONTINUE;
        }
        // else optimize inner sequence
        return opt_seq_base_visitor::handle_loop(node);
    }

    status visit(const loop &node) {
        // test if this is the first node of a program sequence
        if (maybeProgramStart && opt_seq.empty()) {
            // cells init to 0 on start, this loop is dead
            return CONTINUE;
        }
        // mark that we are past the start of the program
        maybeProgramStart = false;
        // test if previous node makes this a dead loop
        test_dead_loop_visitor v;
        node prev_node = opt_seq.back();
        if (prev_node.accept(v) == CONTINUE) {
            // no-op to remove this loop from the sequence
            return CONTINUE;
        }
        // else optimize inner sequence
        return opt_seq_base_visitor::handle_loop(node);
    }

private:

    bool maybeProgramStart;

    class test_dead_loop_visitor : public visitor {

        public:
            status visit(set &node) {
                return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
            }
            status visit(const set &node) {
                return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
            }

            // Loops only terminate when the current cell reaches 0
            // Thus loops following loops are dead
            status visit(loop &node) { return CONTINUE; }
            status visit(const loop &node) { return CONTINUE; }

    };

};

}
}

#endif /* !BFC_DEAD_LOOPS_VISITOR_HPP */
<|endoftext|>


<commit_before>/*
* Runtime CPU detection for ARM
* (C) 2009,2010,2013,2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/cpuid.h>

#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)

#if defined(BOTAN_TARGET_OS_IS_IOS)
  #include <sys/types.h>
  #include <sys/sysctl.h>

#else
  #include <botan/internal/os_utils.h>

#endif

#endif

namespace Botan {

#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)

#if defined(BOTAN_TARGET_OS_IS_IOS)

namespace {

uint64_t flags_by_ios_machine_type(const std::string& machine)
   {
   /*
   * This relies on a map of known machine names to features. This
   * will quickly grow out of date as new products are introduced, but
   * is apparently the best we can do for iOS.
   */

   struct version_info {
      std::string name;
      size_t min_version_neon;
      size_t min_version_armv8;
      };

   static const version_info min_versions[] = {
      { "iPhone", 2, 6 },
      { "iPad", 1, 4 },
      { "iPod", 4, 7 },
      { "AppleTV", 2, 5 },
   };

   if(machine.size() < 3)
      return 0;

   auto comma = machine.find(',');

   // Simulator, or something we don't know about
   if(comma == std::string::npos)
      return 0;

   std::string product = machine.substr(0, comma);

   size_t version = 0;
   size_t place = 1;
   while(product.size() > 1 && ::isdigit(product.back()))
      {
      const size_t digit = product.back() - '0';
      version += digit * place;
      place *= 10;
      product.pop_back();
      }

   if(version == 0)
      return 0;

   for(const version_info& info : min_versions)
      {
      if(info.name != product)
         continue;

      if(version >= info.min_version_armv8)
         {
         return CPUID::CPUID_ARM_AES_BIT |
                CPUID::CPUID_ARM_PMULL_BIT |
                CPUID::CPUID_ARM_SHA1_BIT |
                CPUID::CPUID_ARM_SHA2_BIT |
                CPUID::CPUID_ARM_NEON_BIT;
         }

      if(version >= info.min_version_neon)
         return CPUID::CPUID_ARM_NEON_BIT;
      }

   // Some other product we don't know about
   return 0;
   }

}

#endif

uint64_t CPUID::CPUID_Data::detect_cpu_features(size_t* cache_line_size)
   {
   BOTAN_UNUSED(cache_line_size);

   uint64_t detected_features = 0;

#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
   /*
   * On systems with getauxval these bits should normally be defined
   * in bits/auxv.h but some buggy? glibc installs seem to miss them.
   * These following values are all fixed, for the Linux ELF format,
   * so we just hardcode them in ARM_hwcap_bit enum.
   */

   enum ARM_hwcap_bit {
#if defined(BOTAN_TARGET_ARCH_IS_ARM32)
      NEON_bit  = (1 << 12),
      AES_bit   = (1 << 0),
      PMULL_bit = (1 << 1),
      SHA1_bit  = (1 << 2),
      SHA2_bit  = (1 << 3),

      ARCH_hwcap_neon   = 16, // AT_HWCAP
      ARCH_hwcap_crypto = 26, // AT_HWCAP2
#elif defined(BOTAN_TARGET_ARCH_IS_ARM64)
      NEON_bit  = (1 << 1),
      AES_bit   = (1 << 3),
      PMULL_bit = (1 << 4),
      SHA1_bit  = (1 << 5),
      SHA2_bit  = (1 << 6),
      SHA3_bit  = (1 << 17),
      SM3_bit  = (1 << 18),
      SM4_bit  = (1 << 19),
      SHA2_512_bit  = (1 << 21),
      SVE_bit = (1 << 22),

      ARCH_hwcap_neon   = 16, // AT_HWCAP
      ARCH_hwcap_crypto = 16, // AT_HWCAP
#endif
   };

#if defined(AT_DCACHEBSIZE)
   // Exists only on Linux
   const unsigned long dcache_line = ::getauxval(AT_DCACHEBSIZE);

   // plausibility check
   if(dcache_line == 32 || dcache_line == 64 || dcache_line == 128)
      *cache_line_size = static_cast<size_t>(dcache_line);
#endif

   const unsigned long hwcap_neon = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_neon);
   if(hwcap_neon & ARM_hwcap_bit::NEON_bit)
      detected_features |= CPUID::CPUID_ARM_NEON_BIT;

   /*
   On aarch64 this ends up calling getauxval twice with AT_HWCAP
   It doesn't seem worth optimizing this out, since getauxval is
   just reading a field in the ELF header.
   */
   const unsigned long hwcap_crypto = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_crypto);
   if(hwcap_crypto & ARM_hwcap_bit::AES_bit)
      detected_features |= CPUID::CPUID_ARM_AES_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::PMULL_bit)
      detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SHA1_bit)
      detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SHA2_bit)
      detected_features |= CPUID::CPUID_ARM_SHA2_BIT;

#if defined(BOTAN_TARGET_ARCH_IS_ARM64)
   if(hwcap_crypto & ARM_hwcap_bit::SHA3_bit)
      detected_features |= CPUID::CPUID_ARM_SHA3_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SM3_bit)
      detected_features |= CPUID::CPUID_ARM_SM3_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SM4_bit)
      detected_features |= CPUID::CPUID_ARM_SM4_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SHA2_512_bit)
      detected_features |= CPUID::CPUID_ARM_SHA2_512_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SVE_bit)
      detected_features |= CPUID::CPUID_ARM_SVE_BIT;
#endif

#elif defined(BOTAN_TARGET_OS_IS_IOS)

   char machine[64] = { 0 };
   size_t size = sizeof(machine) - 1;
   ::sysctlbyname("hw.machine", machine, &size, nullptr, 0);

   detected_features = flags_by_ios_machine_type(machine);
   // No way to detect cache line size on iOS?

#elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_ARCH_IS_ARM64)

   /*
   No getauxval API available, fall back on probe functions. We only
   bother with Aarch64 here to simplify the code and because going to
   extreme contortions to support detect NEON on devices that probably
   don't support it doesn't seem worthwhile.

   NEON registers v0-v7 are caller saved in Aarch64
   */

   auto neon_probe  = []() noexcept -> int { asm("and v0.16b, v0.16b, v0.16b"); return 1; };
   auto aes_probe   = []() noexcept -> int { asm(".word 0x4e284800"); return 1; };
   auto pmull_probe = []() noexcept -> int { asm(".word 0x0ee0e000"); return 1; };
   auto sha1_probe  = []() noexcept -> int { asm(".word 0x5e280800"); return 1; };
   auto sha2_probe  = []() noexcept -> int { asm(".word 0x5e282800"); return 1; };

   // Only bother running the crypto detection if we found NEON

   if(OS::run_cpu_instruction_probe(neon_probe) == 1)
      {
      detected_features |= CPUID::CPUID_ARM_NEON_BIT;

      if(OS::run_cpu_instruction_probe(aes_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_AES_BIT;
      if(OS::run_cpu_instruction_probe(pmull_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
      if(OS::run_cpu_instruction_probe(sha1_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
      if(OS::run_cpu_instruction_probe(sha2_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_SHA2_BIT;
      }

#endif

   return detected_features;
   }

#endif

}
<commit_msg>cpu arm: Dead code as the symbol was never defined.<commit_after>/*
* Runtime CPU detection for ARM
* (C) 2009,2010,2013,2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/cpuid.h>

#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)

#if defined(BOTAN_TARGET_OS_IS_IOS)
  #include <sys/types.h>
  #include <sys/sysctl.h>

#else
  #include <botan/internal/os_utils.h>

#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
  #include <sys/auxv.h>
#endif

#endif

#endif

namespace Botan {

#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)

#if defined(BOTAN_TARGET_OS_IS_IOS)

namespace {

uint64_t flags_by_ios_machine_type(const std::string& machine)
   {
   /*
   * This relies on a map of known machine names to features. This
   * will quickly grow out of date as new products are introduced, but
   * is apparently the best we can do for iOS.
   */

   struct version_info {
      std::string name;
      size_t min_version_neon;
      size_t min_version_armv8;
      };

   static const version_info min_versions[] = {
      { "iPhone", 2, 6 },
      { "iPad", 1, 4 },
      { "iPod", 4, 7 },
      { "AppleTV", 2, 5 },
   };

   if(machine.size() < 3)
      return 0;

   auto comma = machine.find(',');

   // Simulator, or something we don't know about
   if(comma == std::string::npos)
      return 0;

   std::string product = machine.substr(0, comma);

   size_t version = 0;
   size_t place = 1;
   while(product.size() > 1 && ::isdigit(product.back()))
      {
      const size_t digit = product.back() - '0';
      version += digit * place;
      place *= 10;
      product.pop_back();
      }

   if(version == 0)
      return 0;

   for(const version_info& info : min_versions)
      {
      if(info.name != product)
         continue;

      if(version >= info.min_version_armv8)
         {
         return CPUID::CPUID_ARM_AES_BIT |
                CPUID::CPUID_ARM_PMULL_BIT |
                CPUID::CPUID_ARM_SHA1_BIT |
                CPUID::CPUID_ARM_SHA2_BIT |
                CPUID::CPUID_ARM_NEON_BIT;
         }

      if(version >= info.min_version_neon)
         return CPUID::CPUID_ARM_NEON_BIT;
      }

   // Some other product we don't know about
   return 0;
   }

}

#endif

uint64_t CPUID::CPUID_Data::detect_cpu_features(size_t* cache_line_size)
   {
   BOTAN_UNUSED(cache_line_size);

   uint64_t detected_features = 0;

#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
   /*
   * On systems with getauxval these bits should normally be defined
   * in bits/auxv.h but some buggy? glibc installs seem to miss them.
   * These following values are all fixed, for the Linux ELF format,
   * so we just hardcode them in ARM_hwcap_bit enum.
   */

   enum ARM_hwcap_bit {
#if defined(BOTAN_TARGET_ARCH_IS_ARM32)
      NEON_bit  = (1 << 12),
      AES_bit   = (1 << 0),
      PMULL_bit = (1 << 1),
      SHA1_bit  = (1 << 2),
      SHA2_bit  = (1 << 3),

      ARCH_hwcap_neon   = 16, // AT_HWCAP
      ARCH_hwcap_crypto = 26, // AT_HWCAP2
#elif defined(BOTAN_TARGET_ARCH_IS_ARM64)
      NEON_bit  = (1 << 1),
      AES_bit   = (1 << 3),
      PMULL_bit = (1 << 4),
      SHA1_bit  = (1 << 5),
      SHA2_bit  = (1 << 6),
      SHA3_bit  = (1 << 17),
      SM3_bit  = (1 << 18),
      SM4_bit  = (1 << 19),
      SHA2_512_bit  = (1 << 21),
      SVE_bit = (1 << 22),

      ARCH_hwcap_neon   = 16, // AT_HWCAP
      ARCH_hwcap_crypto = 16, // AT_HWCAP
#endif
   };

#if defined(AT_DCACHEBSIZE)
   // Exists only on Linux
   const unsigned long dcache_line = OS::get_auxval(AT_DCACHEBSIZE);

   // plausibility check
   if(dcache_line == 32 || dcache_line == 64 || dcache_line == 128)
      *cache_line_size = static_cast<size_t>(dcache_line);
#endif

   const unsigned long hwcap_neon = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_neon);
   if(hwcap_neon & ARM_hwcap_bit::NEON_bit)
      detected_features |= CPUID::CPUID_ARM_NEON_BIT;

   /*
   On aarch64 this ends up calling getauxval twice with AT_HWCAP
   It doesn't seem worth optimizing this out, since getauxval is
   just reading a field in the ELF header.
   */
   const unsigned long hwcap_crypto = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_crypto);
   if(hwcap_crypto & ARM_hwcap_bit::AES_bit)
      detected_features |= CPUID::CPUID_ARM_AES_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::PMULL_bit)
      detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SHA1_bit)
      detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SHA2_bit)
      detected_features |= CPUID::CPUID_ARM_SHA2_BIT;

#if defined(BOTAN_TARGET_ARCH_IS_ARM64)
   if(hwcap_crypto & ARM_hwcap_bit::SHA3_bit)
      detected_features |= CPUID::CPUID_ARM_SHA3_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SM3_bit)
      detected_features |= CPUID::CPUID_ARM_SM3_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SM4_bit)
      detected_features |= CPUID::CPUID_ARM_SM4_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SHA2_512_bit)
      detected_features |= CPUID::CPUID_ARM_SHA2_512_BIT;
   if(hwcap_crypto & ARM_hwcap_bit::SVE_bit)
      detected_features |= CPUID::CPUID_ARM_SVE_BIT;
#endif

#elif defined(BOTAN_TARGET_OS_IS_IOS)

   char machine[64] = { 0 };
   size_t size = sizeof(machine) - 1;
   ::sysctlbyname("hw.machine", machine, &size, nullptr, 0);

   detected_features = flags_by_ios_machine_type(machine);
   // No way to detect cache line size on iOS?

#elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_ARCH_IS_ARM64)

   /*
   No getauxval API available, fall back on probe functions. We only
   bother with Aarch64 here to simplify the code and because going to
   extreme contortions to support detect NEON on devices that probably
   don't support it doesn't seem worthwhile.

   NEON registers v0-v7 are caller saved in Aarch64
   */

   auto neon_probe  = []() noexcept -> int { asm("and v0.16b, v0.16b, v0.16b"); return 1; };
   auto aes_probe   = []() noexcept -> int { asm(".word 0x4e284800"); return 1; };
   auto pmull_probe = []() noexcept -> int { asm(".word 0x0ee0e000"); return 1; };
   auto sha1_probe  = []() noexcept -> int { asm(".word 0x5e280800"); return 1; };
   auto sha2_probe  = []() noexcept -> int { asm(".word 0x5e282800"); return 1; };

   // Only bother running the crypto detection if we found NEON

   if(OS::run_cpu_instruction_probe(neon_probe) == 1)
      {
      detected_features |= CPUID::CPUID_ARM_NEON_BIT;

      if(OS::run_cpu_instruction_probe(aes_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_AES_BIT;
      if(OS::run_cpu_instruction_probe(pmull_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
      if(OS::run_cpu_instruction_probe(sha1_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
      if(OS::run_cpu_instruction_probe(sha2_probe) == 1)
         detected_features |= CPUID::CPUID_ARM_SHA2_BIT;
      }

#endif

   return detected_features;
   }

#endif

}
<|endoftext|>


<commit_before>/*
 * DISTRHO Plugin Framework (DPF)
 * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "ApplicationPrivateData.hpp"
#include "../Window.hpp"

#include "pugl.hpp"

#include <ctime>

START_NAMESPACE_DGL

typedef std::list<DGL_NAMESPACE::Window*>::reverse_iterator WindowListReverseIterator;

// --------------------------------------------------------------------------------------------------------------------

Application::PrivateData::PrivateData(const bool standalone)
    : world(puglNewWorld(standalone ? PUGL_PROGRAM : PUGL_MODULE,
                         standalone ? PUGL_WORLD_THREADS : 0x0)),
      isStandalone(standalone),
      isQuitting(false),
      isStarting(true),
      visibleWindows(0),
      windows(),
      idleCallbacks()
{
    DISTRHO_SAFE_ASSERT_RETURN(world != nullptr,);

    puglSetWorldHandle(world, this);

    // FIXME
    static int wc_count = 0;
    char classNameBuf[256];
    std::srand((std::time(NULL)));
    std::snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d-%d-%p",
                  DISTRHO_MACRO_AS_STRING(DGL_NAMESPACE), std::rand(), ++wc_count, this);
    classNameBuf[sizeof(classNameBuf)-1] = '\0';
    d_stderr("--------------------------------------------------------------- className is %s", classNameBuf);

    puglSetClassName(world, classNameBuf);
#ifdef HAVE_X11
    sofdFileDialogSetup(world);
#endif
}

Application::PrivateData::~PrivateData()
{
    DISTRHO_SAFE_ASSERT(isStarting || isQuitting);
    DISTRHO_SAFE_ASSERT(visibleWindows == 0);

    windows.clear();
    idleCallbacks.clear();

    if (world != nullptr)
        puglFreeWorld(world);
}

// --------------------------------------------------------------------------------------------------------------------

void Application::PrivateData::oneWindowShown() noexcept
{
    if (++visibleWindows == 1)
    {
        isQuitting = false;
        isStarting = false;
    }
}

void Application::PrivateData::oneWindowClosed() noexcept
{
    DISTRHO_SAFE_ASSERT_RETURN(visibleWindows != 0,);

    if (--visibleWindows == 0)
        isQuitting = true;
}

// --------------------------------------------------------------------------------------------------------------------

void Application::PrivateData::idle(const uint timeoutInMs)
{
    if (world != nullptr)
    {
        const double timeoutInSeconds = timeoutInMs != 0
                                      ? static_cast<double>(timeoutInMs) / 1000.0
                                      : 0.0;

        puglUpdate(world, timeoutInSeconds);
    }

    for (std::list<IdleCallback*>::iterator it = idleCallbacks.begin(), ite = idleCallbacks.end(); it != ite; ++it)
    {
        IdleCallback* const idleCallback(*it);
        idleCallback->idleCallback();
    }
}

void Application::PrivateData::quit()
{
    DISTRHO_SAFE_ASSERT_RETURN(isStandalone,);

    isQuitting = true;

#ifndef DPF_TEST_APPLICATION_CPP
    for (WindowListReverseIterator rit = windows.rbegin(), rite = windows.rend(); rit != rite; ++rit)
    {
        DGL_NAMESPACE::Window* const window(*rit);
        window->close();
    }
#endif
}

// --------------------------------------------------------------------------------------------------------------------

END_NAMESPACE_DGL
<commit_msg>testing<commit_after>/*
 * DISTRHO Plugin Framework (DPF)
 * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "ApplicationPrivateData.hpp"
#include "../Window.hpp"

#include "pugl.hpp"

#include <ctime>

START_NAMESPACE_DGL

typedef std::list<DGL_NAMESPACE::Window*>::reverse_iterator WindowListReverseIterator;

// --------------------------------------------------------------------------------------------------------------------

Application::PrivateData::PrivateData(const bool standalone)
    : world(puglNewWorld(standalone ? PUGL_PROGRAM : PUGL_MODULE,
                         standalone ? PUGL_WORLD_THREADS : 0x0)),
      isStandalone(standalone),
      isQuitting(false),
      isStarting(true),
      visibleWindows(0),
      windows(),
      idleCallbacks()
{
    DISTRHO_SAFE_ASSERT_RETURN(world != nullptr,);

    puglSetWorldHandle(world, this);

    // FIXME
    static int wc_count = 0;
    char classNameBuf[256];
    std::srand((std::time(NULL)));
    std::snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d-%d-%p",
                  "TESTING", std::rand(), ++wc_count, this);
    // DISTRHO_MACRO_AS_STRING(DGL_NAMESPACE)
    classNameBuf[sizeof(classNameBuf)-1] = '\0';
    d_stderr("--------------------------------------------------------------- className is %s", classNameBuf);

    puglSetClassName(world, classNameBuf);
#ifdef HAVE_X11
    sofdFileDialogSetup(world);
#endif
}

Application::PrivateData::~PrivateData()
{
    DISTRHO_SAFE_ASSERT(isStarting || isQuitting);
    DISTRHO_SAFE_ASSERT(visibleWindows == 0);

    windows.clear();
    idleCallbacks.clear();

    if (world != nullptr)
        puglFreeWorld(world);
}

// --------------------------------------------------------------------------------------------------------------------

void Application::PrivateData::oneWindowShown() noexcept
{
    if (++visibleWindows == 1)
    {
        isQuitting = false;
        isStarting = false;
    }
}

void Application::PrivateData::oneWindowClosed() noexcept
{
    DISTRHO_SAFE_ASSERT_RETURN(visibleWindows != 0,);

    if (--visibleWindows == 0)
        isQuitting = true;
}

// --------------------------------------------------------------------------------------------------------------------

void Application::PrivateData::idle(const uint timeoutInMs)
{
    if (world != nullptr)
    {
        const double timeoutInSeconds = timeoutInMs != 0
                                      ? static_cast<double>(timeoutInMs) / 1000.0
                                      : 0.0;

        puglUpdate(world, timeoutInSeconds);
    }

    for (std::list<IdleCallback*>::iterator it = idleCallbacks.begin(), ite = idleCallbacks.end(); it != ite; ++it)
    {
        IdleCallback* const idleCallback(*it);
        idleCallback->idleCallback();
    }
}

void Application::PrivateData::quit()
{
    DISTRHO_SAFE_ASSERT_RETURN(isStandalone,);

    isQuitting = true;

#ifndef DPF_TEST_APPLICATION_CPP
    for (WindowListReverseIterator rit = windows.rbegin(), rite = windows.rend(); rit != rite; ++rit)
    {
        DGL_NAMESPACE::Window* const window(*rit);
        window->close();
    }
#endif
}

// --------------------------------------------------------------------------------------------------------------------

END_NAMESPACE_DGL
<|endoftext|>