<commit_before>//
// mc.cpp
//
// manage c++ code
//
// Created by Daniel Kozitza
//

#include <iostream>
#include <cstdlib>
#include <string.h>
#include <csignal>
#include "tools.hpp"

using namespace tools;

string         Args;
vector<string> Argv;
string         VfnmakeSystemCall = "vfnmake";

int help_message() {
	cout << "\nmc is a tool for managing c++ source code.\n\n";
	cout << "Usage:\n\n   mc command [arguments]\n\n";
	cout << "Commands:\n\n";
	cout << "   help     - Show this help message\n";
	cout << "   makefile - Creates a make file by calling vfnmake <arguments>\n";
	cout << "   build    - Calls vfnmake <arguments> then make\n";
	cout << "   rebuild  - Calls make clean, vfnmake <arguments>, then make\n";
	cout << "   run      - Calls vfnmake, make, then ./program <arguments>\n";
	cout << "   doc      - Parses .cpp files adding documentation and\n";
	cout << "              prompting the user for function descriptions\n";
	// TODO:
	//cout << "   mkreadme - Make a README.md file from ./program <arguments>.\n";
	//cout << "              arguments is `help` by default.\n";
	cout << "   dec      - Ensures that all the functions listed in the given\n";
	cout << "              source files are declared properly.\n";
	cout << "   env      - Displays the variables read from vfnmake.conf\n";
	cout << "\n";
	return EXIT_FAILURE;
}

void makefile() {
	cout << "mc: calling `" << VfnmakeSystemCall << "`.\n";
	require(system(VfnmakeSystemCall.c_str()));
}

void build() {
	makefile();
	require(system("make"));
}

void rebuild() {
	require(system("make clean"));
	build();
}

void run() {
	build();

	unordered_map<string, string> vfnconf;
	require(get_vfnmake_conf(vfnconf));

	string named_prog_call = "./";
	named_prog_call += vfnconf["name"];
	named_prog_call += Args;
	cout << "mc: calling `" << named_prog_call << "`.\n";
	require(system(named_prog_call.c_str()));
}

void doc() {
	vector<string> fnames = Argv;

	if (fnames.size() == 0) {
		// get .cpp file names by recursing through vfnconf["src_directory"]
		cout << "mc: automatic source file detection is under construction.\n";
	}
	for (int fn_i = 0; fn_i < fnames.size(); fn_i++) {
		cout << "mc: adding documentation to `" << fnames[fn_i] << "`.\n";
		if (fnames.size() > 1)
			cout << "mc: file " << fn_i+1 << " of " << fnames.size() << ".\n";
		add_documentation(fnames[fn_i]);
		//for (const auto file_name : Argv)
		//	cout << file_name << "\n";// " << item.second << endl;
	}
}

void dec() {
	vector<string> fnames = Argv;

	if (fnames.size() == 0) {
		cout << "mc: automatic source file detection is under construction.\n";
	}

	map<string, vector<string>> scopedecs;
	// vector of all user defined includes found in fnames
	vector<string> includes;

	for (int fn_i = 0; fn_i < fnames.size(); fn_i++) {
		cout << "mc: getting function declarations from `";
		cout << fnames[fn_i] << "`.\n";
		if (fnames.size() > 1)
			cout << "mc: file " << fn_i+1 << " of " << fnames.size() << ".\n";

		vector<string> funcdefs;
		get_func_defs(funcdefs, fnames[fn_i]);

		form_scoped_declarations(scopedecs, funcdefs);

		get_includes(includes, fnames[fn_i]);
	}

	//do this for each namespace found?
	for (const auto nsname : scopedecs) {

		cout << "mc::dec: searching for namespace definition called `";
		cout << nsname.first << "`.\n";

		// now scopedecs is pupulated with all the scoped declarations found in
		// the files fnames. Search for the header file by first checking the
		// user defined includes in the source files for the namespace definition.
		bool found_header_fname = false;
		string header_fname;

		// TODO: should try the src dir from all source files given
		string src_dir = fnames[0];
		replace_first(src_dir, R"([^/]+$)", "");

		for (const auto inc : includes) {
			string str_re = "^namespace " + nsname.first + "\\W";
			cout << "mc::dec: trying regex `" << str_re << "` in file `";
			cout << src_dir << inc << "`.\n";
			// TODO: make sure str_re is properly escaped
			if (find_in_file(str_re, src_dir + inc)) {
				cout << "	found the header file!\n";
				found_header_fname = true;
				header_fname = src_dir + inc;
				break;
			}
		}

		// TODO: finish all these methods of searching for the header_fname

		//if (!found_header_fname) {
		//	// here try to replace the extention of fnames with hpp then h
		//}

		//if (!found_header_fname) {
		//	// here try to replace the extention and move up one dir
		//}
		//
		//if (!found_header_fname) {
		//	// here try to look in the fnames files themselves
		//}
		//
		//if (!found_header_fname) {
		//	// here check every file found in the src dir
		//}
		//
		cout << "mc::dec: new_declarations:\n\n";
		for (const auto item : nsname.second)
			cout << item << endl;

		cout << endl;

		require(
			found_header_fname,
			"mc::dec: could not find namespace `" + nsname.first + "`.");

		update_namespace(nsname.first, nsname.second, header_fname);
	}
}

void env() {
	unordered_map<string, string> vfnconf;
	require(get_vfnmake_conf(vfnconf));

	cout << "\nvfnmake.conf:\n\n";
	for (const auto item : vfnconf) {
		cout << item.first << ": " << item.second << "\n";
	}
	cout << "\n";
}

int main(int argc, char *argv[]) {

	signal(SIGINT, signals_callback_handler);

	commands cmds;
	cmds.handle("help", help_message, "displays this message"},
		{"makefile", makefile},
		{"build", build},
		{"rebuild", rebuild},
		{"run", run},
		{"doc", doc},
		{"dec", dec},
		{"env", env}};

	if (argc < 2)
		return help_message();

	for (int i = 2; i < argc; i++) {
		Argv.push_back(string(argv[i]));
		Args.append(string(" ").append(argv[i]));
	}

	if (
		VfnmakeSystemCall += Args; makefile();

	// make map of ints and use switch instead of if-else
	map<string, const int> commands = {
		{"help", 0},
		{"makefile", 1},
		{"build", 2},
		{"rebuild", 3},
		{"run", 4},
		{"doc", 5},
		{"dec", 6},
		{"env", 7}};

	switch (commands[string(argv[1])]) {
	case 0: help_message();
		break;
	case 1: VfnmakeSystemCall += Args; makefile();
		break;
	case 2: build();
		break;
	case 3: rebuild();
		break;
	case 4: run();
		break;
	case 5: doc();
		break;
	case 6: dec();
		break;
	case 7: env();
		break;
	default:
		// didn't recognize command!
		for (int i = 1; i < argc; i++) {
			cout << "mc: unrecognized command: `" << argv[i] << "`.\n";
		}
		return help_message();
	}

//	if (!strcmp(argv[1], "help")) {
//		help_message();
//	}
//	else if (!strcmp(argv[1], "makefile")) {
//		VfnmakeSystemCall += Args;
//		makefile();
//	}
//	else if (!strcmp(argv[1], "build")) {
//		build();
//	}
//	else if (!strcmp(argv[1], "rebuild")) {
//		rebuild();
//	}
//	else if (!strcmp(argv[1], "run")) {
//		run();
//	}
//	else if (!strcmp(argv[1], "doc")) {
//		doc();
//	}
//	else if (!strcmp(argv[1], "dec")) {
//		dec();
//	}
//	else if (!strcmp(argv[1], "env")) {
//		env();
//	}
//	else {
//		// didn't recognize command!
//		for (int i = 1; i < argc; i++) {
//			cout << "mc: unrecognized command: `" << argv[i] << "`.\n";
//		}
//		return help_message();
//	}

	return 0;
}
<commit_msg>messing around<commit_after>//
// mc.cpp
//
// manage c++ code
//
// Created by Daniel Kozitza
//

#include <iostream>
#include <cstdlib>
#include <string.h>
#include <csignal>
#include "tools.hpp"

using namespace tools;

string         Args;
vector<string> Argv;
string         VfnmakeSystemCall = "vfnmake";

int help_message() {
	cout << "\nmc is a tool for managing c++ source code.\n\n";
	cout << "Usage:\n\n   mc command [arguments]\n\n";
	cout << "Commands:\n\n";
	cout << "   help     - Show this help message\n";
	cout << "   makefile - Creates a make file by calling vfnmake <arguments>\n";
	cout << "   build    - Calls vfnmake <arguments> then make\n";
	cout << "   rebuild  - Calls make clean, vfnmake <arguments>, then make\n";
	cout << "   run      - Calls vfnmake, make, then ./program <arguments>\n";
	cout << "   doc      - Parses .cpp files adding documentation and\n";
	cout << "              prompting the user for function descriptions\n";
	// TODO:
	//cout << "   mkreadme - Make a README.md file from ./program <arguments>.\n";
	//cout << "              arguments is `help` by default.\n";
	cout << "   dec      - Ensures that all the functions listed in the given\n";
	cout << "              source files are declared properly.\n";
	cout << "   env      - Displays the variables read from vfnmake.conf\n";
	cout << "\n";
	return EXIT_FAILURE;
}

void makefile() {
	cout << "mc: calling `" << VfnmakeSystemCall << "`.\n";
	require(system(VfnmakeSystemCall.c_str()));
}

void build() {
	makefile();
	require(system("make"));
}

void rebuild() {
	require(system("make clean"));
	build();
}

void run() {
	build();

	unordered_map<string, string> vfnconf;
	require(get_vfnmake_conf(vfnconf));

	string named_prog_call = "./";
	named_prog_call += vfnconf["name"];
	named_prog_call += Args;
	cout << "mc: calling `" << named_prog_call << "`.\n";
	require(system(named_prog_call.c_str()));
}

void doc() {
	vector<string> fnames = Argv;

	if (fnames.size() == 0) {
		// get .cpp file names by recursing through vfnconf["src_directory"]
		cout << "mc: automatic source file detection is under construction.\n";
	}
	for (int fn_i = 0; fn_i < fnames.size(); fn_i++) {
		cout << "mc: adding documentation to `" << fnames[fn_i] << "`.\n";
		if (fnames.size() > 1)
			cout << "mc: file " << fn_i+1 << " of " << fnames.size() << ".\n";
		add_documentation(fnames[fn_i]);
		//for (const auto file_name : Argv)
		//	cout << file_name << "\n";// " << item.second << endl;
	}
}

void dec() {
	vector<string> fnames = Argv;

	if (fnames.size() == 0) {
		cout << "mc: automatic source file detection is under construction.\n";
	}

	map<string, vector<string>> scopedecs;
	// vector of all user defined includes found in fnames
	vector<string> includes;

	for (int fn_i = 0; fn_i < fnames.size(); fn_i++) {
		cout << "mc: getting function declarations from `";
		cout << fnames[fn_i] << "`.\n";
		if (fnames.size() > 1)
			cout << "mc: file " << fn_i+1 << " of " << fnames.size() << ".\n";

		vector<string> funcdefs;
		get_func_defs(funcdefs, fnames[fn_i]);

		form_scoped_declarations(scopedecs, funcdefs);

		get_includes(includes, fnames[fn_i]);
	}

	//do this for each namespace found?
	for (const auto nsname : scopedecs) {

		cout << "mc::dec: searching for namespace definition called `";
		cout << nsname.first << "`.\n";

		// now scopedecs is pupulated with all the scoped declarations found in
		// the files fnames. Search for the header file by first checking the
		// user defined includes in the source files for the namespace definition.
		bool found_header_fname = false;
		string header_fname;

		// TODO: should try the src dir from all source files given
		string src_dir = fnames[0];
		replace_first(src_dir, R"([^/]+$)", "");

		for (const auto inc : includes) {
			string str_re = "^namespace " + nsname.first + "\\W";
			cout << "mc::dec: trying regex `" << str_re << "` in file `";
			cout << src_dir << inc << "`.\n";
			// TODO: make sure str_re is properly escaped
			if (find_in_file(str_re, src_dir + inc)) {
				cout << "	found the header file!\n";
				found_header_fname = true;
				header_fname = src_dir + inc;
				break;
			}
		}

		// TODO: finish all these methods of searching for the header_fname

		//if (!found_header_fname) {
		//	// here try to replace the extention of fnames with hpp then h
		//}

		//if (!found_header_fname) {
		//	// here try to replace the extention and move up one dir
		//}
		//
		//if (!found_header_fname) {
		//	// here try to look in the fnames files themselves
		//}
		//
		//if (!found_header_fname) {
		//	// here check every file found in the src dir
		//}
		//
		cout << "mc::dec: new_declarations:\n\n";
		for (const auto item : nsname.second)
			cout << item << endl;

		cout << endl;

		require(
			found_header_fname,
			"mc::dec: could not find namespace `" + nsname.first + "`.");

		update_namespace(nsname.first, nsname.second, header_fname);
	}
}

void env() {
	unordered_map<string, string> vfnconf;
	require(get_vfnmake_conf(vfnconf));

	cout << "\nvfnmake.conf:\n\n";
	for (const auto item : vfnconf) {
		cout << item.first << ": " << item.second << "\n";
	}
	cout << "\n";
}

int main(int argc, char *argv[]) {

	signal(SIGINT, signals_callback_handler);

	commands cmds;
	cmds.handle(
			"help",
			help_message,
			"displays this message",
			"USAGE: mc help [command]");
},
		{"makefile", makefile},
		{"build", build},
		{"rebuild", rebuild},
		{"run", run},
		{"doc", doc},
		{"dec", dec},
		{"env", env}};

	if (argc < 2)
		return help_message();

	for (int i = 2; i < argc; i++) {
		Argv.push_back(string(argv[i]));
		Args.append(string(" ").append(argv[i]));
	}

	if (
		VfnmakeSystemCall += Args; makefile();

	// make map of ints and use switch instead of if-else
	map<string, const int> commands = {
		{"help", 0},
		{"makefile", 1},
		{"build", 2},
		{"rebuild", 3},
		{"run", 4},
		{"doc", 5},
		{"dec", 6},
		{"env", 7}};

	switch (commands[string(argv[1])]) {
	case 0: help_message();
		break;
	case 1: VfnmakeSystemCall += Args; makefile();
		break;
	case 2: build();
		break;
	case 3: rebuild();
		break;
	case 4: run();
		break;
	case 5: doc();
		break;
	case 6: dec();
		break;
	case 7: env();
		break;
	default:
		// didn't recognize command!
		for (int i = 1; i < argc; i++) {
			cout << "mc: unrecognized command: `" << argv[i] << "`.\n";
		}
		return help_message();
	}

//	if (!strcmp(argv[1], "help")) {
//		help_message();
//	}
//	else if (!strcmp(argv[1], "makefile")) {
//		VfnmakeSystemCall += Args;
//		makefile();
//	}
//	else if (!strcmp(argv[1], "build")) {
//		build();
//	}
//	else if (!strcmp(argv[1], "rebuild")) {
//		rebuild();
//	}
//	else if (!strcmp(argv[1], "run")) {
//		run();
//	}
//	else if (!strcmp(argv[1], "doc")) {
//		doc();
//	}
//	else if (!strcmp(argv[1], "dec")) {
//		dec();
//	}
//	else if (!strcmp(argv[1], "env")) {
//		env();
//	}
//	else {
//		// didn't recognize command!
//		for (int i = 1; i < argc; i++) {
//			cout << "mc: unrecognized command: `" << argv[i] << "`.\n";
//		}
//		return help_message();
//	}

	return 0;
}
<|endoftext|>


<commit_before>class diddy
{
	public:

	// stub
	static int systemMillisecs() {
		return 0;
	}

	// stub
	static int flushKeys() {
		return 0;
	}
}<commit_msg>Added code for Flushkeys and millisecs for GLFW Target<commit_after>#include <time.h>

class diddy
{
	public:

	// only accurate to 1 second
	static int systemMillisecs() {
		time_t seconds;
		seconds = time (NULL);
		return seconds * 1000;
	}

	static void flushKeys() {
		for( int i=0;i<512;++i ){
			app->input->keyStates[i]&=0x100;
		}
	}
};
<|endoftext|>


<commit_before>//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// This test is intended to create a situation in which multiple events
// (breakpoints, watchpoints, crashes, and signal generation/delivery) happen
// from multiple threads. The test expects the debugger to set a breakpoint on
// the main thread (before any worker threads are spawned) and modify variables
// which control the number of threads that are spawned for each action.

#include <atomic>
#include <vector>
using namespace std;

#include <pthread.h>

#include <signal.h>
#include <sys/types.h>
#include <unistd.h>

// Note that although hogging the CPU while waiting for a variable to change
// would be terrible in production code, it's great for testing since it
// avoids a lot of messy context switching to get multiple threads synchronized.
#define do_nothing()

#define pseudo_barrier_wait(bar) \
    --bar;                       \
    while (bar > 0)              \
        do_nothing();

#define pseudo_barrier_init(bar, count) (bar = count)

typedef std::vector<std::pair<unsigned, void*(*)(void*)> > action_counts;
typedef std::vector<pthread_t> thread_vector;

std::atomic_int g_barrier;
int g_breakpoint = 0;
int g_sigusr1_count = 0;
std::atomic_int g_watchme;

struct action_args {
  int delay;
};

// Perform any extra actions required by thread 'input' arg
void do_action_args(void *input) {
    if (input) {
      action_args *args = static_cast<action_args*>(input);
      sleep(args->delay);
    }
}

void *
breakpoint_func (void *input)
{
    // Wait until all threads are running
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    // Do something
    g_breakpoint++;       // Set breakpoint here
    return 0;
}

void *
signal_func (void *input) {
    // Wait until all threads are running
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    // Send a user-defined signal to the current process
    //kill(getpid(), SIGUSR1);
    // Send a user-defined signal to the current thread
    pthread_kill(pthread_self(), SIGUSR1);

    return 0;
}

void *
watchpoint_func (void *input) {
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    g_watchme += 1;     // watchpoint triggers here
    return 0;
}

void *
crash_func (void *input) {
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    int *a = 0;
    *a = 5; // crash happens here
    return 0;
}

void sigusr1_handler(int sig) {
    if (sig == SIGUSR1)
        g_sigusr1_count += 1; // Break here in signal handler
}

/// Register a simple function for to handle signal
void register_signal_handler(int signal, void (*handler)(int))
{
    sigset_t empty_sigset;
    sigemptyset(&empty_sigset);

    struct sigaction action;
    action.sa_sigaction = 0;
    action.sa_mask = empty_sigset;
    action.sa_flags = 0;
    action.sa_handler = handler;
    sigaction(SIGUSR1, &action, 0);
}

void start_threads(thread_vector& threads,
                   action_counts& actions,
                   void* args = 0) {
    action_counts::iterator b = actions.begin(), e = actions.end();
    for(action_counts::iterator i = b; i != e; ++i) {
        for(unsigned count = 0; count < i->first; ++count) {
            pthread_t t;
            pthread_create(&t, 0, i->second, args);
            threads.push_back(t);
        }
    }
}

int dotest()
{
    g_watchme = 0;

    // Actions are triggered immediately after the thread is spawned
    unsigned num_breakpoint_threads = 1;
    unsigned num_watchpoint_threads = 0;
    unsigned num_signal_threads = 1;
    unsigned num_crash_threads = 0;

    // Actions below are triggered after a 1-second delay
    unsigned num_delay_breakpoint_threads = 0;
    unsigned num_delay_watchpoint_threads = 0;
    unsigned num_delay_signal_threads = 0;
    unsigned num_delay_crash_threads = 0;

    register_signal_handler(SIGUSR1, sigusr1_handler); // Break here and adjust num_[breakpoint|watchpoint|signal|crash]_threads

    unsigned total_threads = num_breakpoint_threads \
                             + num_watchpoint_threads \
                             + num_signal_threads \
                             + num_crash_threads \
                             + num_delay_breakpoint_threads \
                             + num_delay_watchpoint_threads \
                             + num_delay_signal_threads \
                             + num_delay_crash_threads;

    // Don't let either thread do anything until they're both ready.
    pseudo_barrier_init(g_barrier, total_threads);

    action_counts actions;
    actions.push_back(std::make_pair(num_breakpoint_threads, breakpoint_func));
    actions.push_back(std::make_pair(num_watchpoint_threads, watchpoint_func));
    actions.push_back(std::make_pair(num_signal_threads, signal_func));
    actions.push_back(std::make_pair(num_crash_threads, crash_func));

    action_counts delay_actions;
    actions.push_back(std::make_pair(num_delay_breakpoint_threads, breakpoint_func));
    actions.push_back(std::make_pair(num_delay_watchpoint_threads, watchpoint_func));
    actions.push_back(std::make_pair(num_delay_signal_threads, signal_func));
    actions.push_back(std::make_pair(num_delay_crash_threads, crash_func));

    // Create threads that handle instant actions
    thread_vector threads;
    start_threads(threads, actions);

    // Create threads that handle delayed actions
    action_args delay_arg;
    delay_arg.delay = 1;
    start_threads(threads, delay_actions, &delay_arg);

    // Join all threads
    typedef std::vector<pthread_t>::iterator thread_iterator;
    for(thread_iterator t = threads.begin(); t != threads.end(); ++t)
        pthread_join(*t, 0);

    return 0;
}

int main ()
{
    dotest();
    return 0; // Break here and verify one thread is active.
}

<commit_msg>TestConcurrentEvents - delay threads not working<commit_after>//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// This test is intended to create a situation in which multiple events
// (breakpoints, watchpoints, crashes, and signal generation/delivery) happen
// from multiple threads. The test expects the debugger to set a breakpoint on
// the main thread (before any worker threads are spawned) and modify variables
// which control the number of threads that are spawned for each action.

#include <atomic>
#include <vector>
using namespace std;

#include <pthread.h>

#include <signal.h>
#include <sys/types.h>
#include <unistd.h>

// Note that although hogging the CPU while waiting for a variable to change
// would be terrible in production code, it's great for testing since it
// avoids a lot of messy context switching to get multiple threads synchronized.
#define do_nothing()

#define pseudo_barrier_wait(bar) \
    --bar;                       \
    while (bar > 0)              \
        do_nothing();

#define pseudo_barrier_init(bar, count) (bar = count)

typedef std::vector<std::pair<unsigned, void*(*)(void*)> > action_counts;
typedef std::vector<pthread_t> thread_vector;

std::atomic_int g_barrier;
int g_breakpoint = 0;
int g_sigusr1_count = 0;
std::atomic_int g_watchme;

struct action_args {
  int delay;
};

// Perform any extra actions required by thread 'input' arg
void do_action_args(void *input) {
    if (input) {
      action_args *args = static_cast<action_args*>(input);
      sleep(args->delay);
    }
}

void *
breakpoint_func (void *input)
{
    // Wait until all threads are running
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    // Do something
    g_breakpoint++;       // Set breakpoint here
    return 0;
}

void *
signal_func (void *input) {
    // Wait until all threads are running
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    // Send a user-defined signal to the current process
    //kill(getpid(), SIGUSR1);
    // Send a user-defined signal to the current thread
    pthread_kill(pthread_self(), SIGUSR1);

    return 0;
}

void *
watchpoint_func (void *input) {
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    g_watchme += 1;     // watchpoint triggers here
    return 0;
}

void *
crash_func (void *input) {
    pseudo_barrier_wait(g_barrier);
    do_action_args(input);

    int *a = 0;
    *a = 5; // crash happens here
    return 0;
}

void sigusr1_handler(int sig) {
    if (sig == SIGUSR1)
        g_sigusr1_count += 1; // Break here in signal handler
}

/// Register a simple function for to handle signal
void register_signal_handler(int signal, void (*handler)(int))
{
    sigset_t empty_sigset;
    sigemptyset(&empty_sigset);

    struct sigaction action;
    action.sa_sigaction = 0;
    action.sa_mask = empty_sigset;
    action.sa_flags = 0;
    action.sa_handler = handler;
    sigaction(SIGUSR1, &action, 0);
}

void start_threads(thread_vector& threads,
                   action_counts& actions,
                   void* args = 0) {
    action_counts::iterator b = actions.begin(), e = actions.end();
    for(action_counts::iterator i = b; i != e; ++i) {
        for(unsigned count = 0; count < i->first; ++count) {
            pthread_t t;
            pthread_create(&t, 0, i->second, args);
            threads.push_back(t);
        }
    }
}

int dotest()
{
    g_watchme = 0;

    // Actions are triggered immediately after the thread is spawned
    unsigned num_breakpoint_threads = 1;
    unsigned num_watchpoint_threads = 0;
    unsigned num_signal_threads = 1;
    unsigned num_crash_threads = 0;

    // Actions below are triggered after a 1-second delay
    unsigned num_delay_breakpoint_threads = 0;
    unsigned num_delay_watchpoint_threads = 0;
    unsigned num_delay_signal_threads = 0;
    unsigned num_delay_crash_threads = 0;

    register_signal_handler(SIGUSR1, sigusr1_handler); // Break here and adjust num_[breakpoint|watchpoint|signal|crash]_threads

    unsigned total_threads = num_breakpoint_threads \
                             + num_watchpoint_threads \
                             + num_signal_threads \
                             + num_crash_threads \
                             + num_delay_breakpoint_threads \
                             + num_delay_watchpoint_threads \
                             + num_delay_signal_threads \
                             + num_delay_crash_threads;

    // Don't let either thread do anything until they're both ready.
    pseudo_barrier_init(g_barrier, total_threads);

    action_counts actions;
    actions.push_back(std::make_pair(num_breakpoint_threads, breakpoint_func));
    actions.push_back(std::make_pair(num_watchpoint_threads, watchpoint_func));
    actions.push_back(std::make_pair(num_signal_threads, signal_func));
    actions.push_back(std::make_pair(num_crash_threads, crash_func));

    action_counts delay_actions;
    delay_actions.push_back(std::make_pair(num_delay_breakpoint_threads, breakpoint_func));
    delay_actions.push_back(std::make_pair(num_delay_watchpoint_threads, watchpoint_func));
    delay_actions.push_back(std::make_pair(num_delay_signal_threads, signal_func));
    delay_actions.push_back(std::make_pair(num_delay_crash_threads, crash_func));

    // Create threads that handle instant actions
    thread_vector threads;
    start_threads(threads, actions);

    // Create threads that handle delayed actions
    action_args delay_arg;
    delay_arg.delay = 1;
    start_threads(threads, delay_actions, &delay_arg);

    // Join all threads
    typedef std::vector<pthread_t>::iterator thread_iterator;
    for(thread_iterator t = threads.begin(); t != threads.end(); ++t)
        pthread_join(*t, 0);

    return 0;
}

int main ()
{
    dotest();
    return 0; // Break here and verify one thread is active.
}

<|endoftext|>


<commit_before>#include "NewRefereeModule.hpp"

#include <Network.hpp>
#include <multicast.hpp>
#include <Utils.hpp>
#include <unistd.h>
#include <QMutexLocker>
#include <QUdpSocket>
#include <stdexcept>

namespace NewRefereeModuleEnums {
std::string stringFromStage(Stage s) {
    switch (s) {
        case NORMAL_FIRST_HALF_PRE:
            return "Normal First Half Prep";
        case NORMAL_FIRST_HALF:
            return "Normal First Half";
        case NORMAL_HALF_TIME:
            return "Normal Half Time";
        case NORMAL_SECOND_HALF_PRE:
            return "Normal Second Half Prep";
        case NORMAL_SECOND_HALF:
            return "Normal Second Half";
        case EXTRA_TIME_BREAK:
            return "Extra Time Break";
        case EXTRA_FIRST_HALF_PRE:
            return "Extra First Half Prep";
        case EXTRA_FIRST_HALF:
            return "Extra First Half";
        case EXTRA_HALF_TIME:
            return "Extra Half Time";
        case EXTRA_SECOND_HALF_PRE:
            return "Extra Second Half Prep";
        case EXTRA_SECOND_HALF:
            return "Extra Second Half";
        case PENALTY_SHOOTOUT_BREAK:
            return "Penalty Shootout Break";
        case PENALTY_SHOOTOUT:
            return "Penalty Shootout";
        case POST_GAME:
            return "Post Game";
        default:
            return "";
    }
}

std::string stringFromCommand(Command c) {
    switch (c) {
        case HALT:
            return "Halt";
        case STOP:
            return "Stop";
        case NORMAL_START:
            return "Normal Start";
        case FORCE_START:
            return "Force Start";
        case PREPARE_KICKOFF_YELLOW:
            return "Yellow Kickoff Prep";
        case PREPARE_KICKOFF_BLUE:
            return "Blue Kickoff Prep";
        case PREPARE_PENALTY_YELLOW:
            return "Yellow Penalty Prep";
        case PREPARE_PENALTY_BLUE:
            return "Blue Penalty Prep";
        case DIRECT_FREE_YELLOW:
            return "Direct Yellow Free Kick";
        case DIRECT_FREE_BLUE:
            return "Direct Blue Free Kick";
        case INDIRECT_FREE_YELLOW:
            return "Indirect Yellow Free Kick";
        case INDIRECT_FREE_BLUE:
            return "Indirect Blue Free Kick";
        case TIMEOUT_YELLOW:
            return "Timeout Yellow";
        case TIMEOUT_BLUE:
            return "Timeout Blue";
        case GOAL_YELLOW:
            return "Goal Yellow";
        case GOAL_BLUE:
            return "Goal Blue";
        case BALL_PLACEMENT_YELLOW:
            return "Ball Placement Yellow";
        case BALL_PLACEMENT_BLUE:
            return "Ball Placement Blue";
        default:
            return "";
    }
}
}

using namespace std;
using namespace NewRefereeModuleEnums;

/// Distance in meters that the ball must travel for a kick to be detected
static const float KickThreshold = 0.150f;

/// How many milliseconds the ball must be more than KickThreshold meters away
/// from its position when the referee indicated Ready for us to detect the ball
/// as having been kicked.
static const int KickVerifyTime_ms = 250;

NewRefereeModule::NewRefereeModule(SystemState& state)
    : stage(NORMAL_FIRST_HALF_PRE),
      command(HALT),
      _running(false),
      _state(state) {}

NewRefereeModule::~NewRefereeModule() { this->stop(); }

void NewRefereeModule::stop() {
    _running = false;
    wait();
}

void NewRefereeModule::getPackets(std::vector<NewRefereePacket*>& packets) {
    _mutex.lock();
    packets = _packets;
    _packets.clear();
    _mutex.unlock();
}

void NewRefereeModule::run() {
    QUdpSocket socket;

    if (!socket.bind(ProtobufRefereePort, QUdpSocket::ShareAddress)) {
        throw runtime_error("Can't bind to shared referee port");
    }

    multicast_add(&socket, RefereeAddress);

    _packets.reserve(4);

    _running = true;
    while (_running) {
        if (!_useExternalRef) continue;

        char buf[65536];

        if (!socket.waitForReadyRead(500)) {
            continue;
        }

        QHostAddress host;
        quint16 port = 0;
        qint64 size = socket.readDatagram(buf, sizeof(buf), &host, &port);
        if (size < 1) {
            fprintf(stderr, "NewRefereeModule: %s/n",
                    (const char*)socket.errorString().toLatin1());
            ::usleep(100000);
            continue;
        }

        NewRefereePacket* packet = new NewRefereePacket;
        packet->receivedTime = RJ::timestamp();
        this->received_time = packet->receivedTime;
        if (!packet->wrapper.ParseFromArray(buf, size)) {
            fprintf(stderr,
                    "NewRefereeModule: got bad packet of %d bytes from %s:%d\n",
                    (int)size, (const char*)host.toString().toLatin1(), port);
            fprintf(stderr, "Packet: %s\n", buf);
            fprintf(stderr, "Address: %s\n", RefereeAddress);
            continue;
        }

        _mutex.lock();
        _packets.push_back(packet);

        stage = (Stage)packet->wrapper.stage();
        command = (Command)packet->wrapper.command();
        sent_time = packet->wrapper.packet_timestamp();
        stage_time_left = packet->wrapper.stage_time_left();
        command_counter = packet->wrapper.command_counter();
        command_timestamp = packet->wrapper.command_timestamp();
        yellow_info.ParseRefboxPacket(packet->wrapper.yellow());
        blue_info.ParseRefboxPacket(packet->wrapper.blue());
        ballPlacementx = packet->wrapper.designated_position().x();
        ballPlacementy = packet->wrapper.designated_position().y();

        _mutex.unlock();
    }
}

void NewRefereeModule::spinKickWatcher() {
    if (_state.ball.valid) {
        /// Only run the kick detector when the ball is visible
        switch (_kickDetectState) {
            case WaitForReady:
                /// Never kicked and not ready for a restart
                break;

            case CapturePosition:
                // Do this in the processing thread
                _readyBallPos = _state.ball.pos;
                _kickDetectState = WaitForKick;
                break;

            case WaitForKick:
                if (!_state.ball.pos.nearPoint(_readyBallPos, KickThreshold)) {
                    // The ball appears to have moved
                    _kickTime = QTime::currentTime();
                    _kickDetectState = VerifyKick;
                }
                break;

            case VerifyKick:
                if (_state.ball.pos.nearPoint(_readyBallPos, KickThreshold)) {
                    // The ball is back where it was.  There was probably a
                    // vision error.
                    _kickDetectState = WaitForKick;
                } else if (_kickTime.msecsTo(QTime::currentTime()) >=
                           KickVerifyTime_ms) {
                    // The ball has been far enough away for enough time, so
                    // call this a kick.
                    _kickDetectState = Kicked;
                }
                break;

            case Kicked:
                // Stay here until the referee puts us back in Ready
                break;
        }
    }
}

void NewRefereeModule::updateGameState(bool blueTeam) {
    _state.gameState.ourScore = blueTeam ? blue_info.score : yellow_info.score;
    _state.gameState.theirScore =
        blueTeam ? yellow_info.score : blue_info.score;
    using namespace NewRefereeModuleEnums;
    switch (stage) {
        case Stage::NORMAL_FIRST_HALF_PRE:
            _state.gameState.period = GameState::FirstHalf;
            break;
        case Stage::NORMAL_FIRST_HALF:
            _state.gameState.period = GameState::FirstHalf;
            break;
        case Stage::NORMAL_HALF_TIME:
            _state.gameState.period = GameState::Halftime;
            break;
        case Stage::NORMAL_SECOND_HALF_PRE:
            _state.gameState.period = GameState::SecondHalf;
            break;
        case Stage::NORMAL_SECOND_HALF:
            _state.gameState.period = GameState::SecondHalf;
            break;
        case Stage::EXTRA_TIME_BREAK:
            _state.gameState.period = GameState::FirstHalf;
            break;
        case Stage::EXTRA_FIRST_HALF_PRE:
            _state.gameState.period = GameState::Overtime1;
            break;
        case Stage::EXTRA_FIRST_HALF:
            _state.gameState.period = GameState::Overtime1;
            break;
        case Stage::EXTRA_HALF_TIME:
            _state.gameState.period = GameState::Halftime;
            break;
        case Stage::EXTRA_SECOND_HALF_PRE:
            _state.gameState.period = GameState::Overtime2;
            break;
        case Stage::EXTRA_SECOND_HALF:
            _state.gameState.period = GameState::Overtime2;
            break;
        case Stage::PENALTY_SHOOTOUT_BREAK:
            _state.gameState.period = GameState::PenaltyShootout;
            break;
        case Stage::PENALTY_SHOOTOUT:
            _state.gameState.period = GameState::PenaltyShootout;
            break;
        case Stage::POST_GAME:
            _state.gameState.period = GameState::Overtime2;
            break;
    }
    switch (command) {
        case Command::HALT:
            _state.gameState.state = GameState::Halt;
            break;
        case Command::STOP:
            _state.gameState.state = GameState::Stop;
            break;
        case Command::NORMAL_START:
            ready();
            break;
        case Command::FORCE_START:
            _state.gameState.state = GameState::Playing;
            _state.gameState.ourRestart = false;
            _state.gameState.restart = GameState::None;
            break;
        case Command::PREPARE_KICKOFF_YELLOW:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Kickoff;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::PREPARE_KICKOFF_BLUE:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Kickoff;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::PREPARE_PENALTY_YELLOW:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Penalty;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::PREPARE_PENALTY_BLUE:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Penalty;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::DIRECT_FREE_YELLOW:
            ready();
            _state.gameState.restart = GameState::Direct;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::DIRECT_FREE_BLUE:
            ready();
            _state.gameState.restart = GameState::Direct;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::INDIRECT_FREE_YELLOW:
            ready();
            _state.gameState.restart = GameState::Indirect;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::INDIRECT_FREE_BLUE:
            ready();
            _state.gameState.restart = GameState::Indirect;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::TIMEOUT_YELLOW:
            _state.gameState.state = GameState::Halt;
            break;
        case Command::TIMEOUT_BLUE:
            _state.gameState.state = GameState::Halt;
            break;
        case Command::GOAL_YELLOW:
            break;
        case Command::GOAL_BLUE:
            break;
        case Command::BALL_PLACEMENT_YELLOW:
            _state.gameState.state = GameState::Stop;
            _state.gameState.restart = GameState::Placement;
            _state.gameState.ourRestart = !blueTeam;
            _state.gameState.setBallPlacementPoint(ballPlacementx,
                                                   ballPlacementy);
            break;
        case Command::BALL_PLACEMENT_BLUE:
            _state.gameState.state = GameState::Stop;
            _state.gameState.restart = GameState::Placement;
            _state.gameState.ourRestart = blueTeam;
            _state.gameState.setBallPlacementPoint(ballPlacementx,
                                                   ballPlacementy);
            break;
    }

    if (command != prev_command)
        std::cout << "REFEREE: Command = " << stringFromCommand(command)
                  << std::endl;
    prev_command = command;
    if (stage != prev_stage)
        std::cout << "REFEREE: Stage = " << stringFromStage(stage) << std::endl;
    prev_stage = stage;

    if (_state.gameState.state == GameState::Ready && kicked()) {
        _state.gameState.state = GameState::Playing;
    }
    _state.gameState.OurInfo = blueTeam ? blue_info : yellow_info;
    _state.gameState.TheirInfo = blueTeam ? yellow_info : blue_info;
}

void NewRefereeModule::ready() {
    if (_state.gameState.state == GameState::Stop ||
        _state.gameState.state == GameState::Setup) {
        _state.gameState.state = GameState::Ready;
        _kickDetectState = CapturePosition;
    }
}
<commit_msg>Update command and stage only when they change<commit_after>#include "NewRefereeModule.hpp"

#include <Network.hpp>
#include <multicast.hpp>
#include <Utils.hpp>
#include <unistd.h>
#include <QMutexLocker>
#include <QUdpSocket>
#include <stdexcept>

namespace NewRefereeModuleEnums {
std::string stringFromStage(Stage s) {
    switch (s) {
        case NORMAL_FIRST_HALF_PRE:
            return "Normal First Half Prep";
        case NORMAL_FIRST_HALF:
            return "Normal First Half";
        case NORMAL_HALF_TIME:
            return "Normal Half Time";
        case NORMAL_SECOND_HALF_PRE:
            return "Normal Second Half Prep";
        case NORMAL_SECOND_HALF:
            return "Normal Second Half";
        case EXTRA_TIME_BREAK:
            return "Extra Time Break";
        case EXTRA_FIRST_HALF_PRE:
            return "Extra First Half Prep";
        case EXTRA_FIRST_HALF:
            return "Extra First Half";
        case EXTRA_HALF_TIME:
            return "Extra Half Time";
        case EXTRA_SECOND_HALF_PRE:
            return "Extra Second Half Prep";
        case EXTRA_SECOND_HALF:
            return "Extra Second Half";
        case PENALTY_SHOOTOUT_BREAK:
            return "Penalty Shootout Break";
        case PENALTY_SHOOTOUT:
            return "Penalty Shootout";
        case POST_GAME:
            return "Post Game";
        default:
            return "";
    }
}

std::string stringFromCommand(Command c) {
    switch (c) {
        case HALT:
            return "Halt";
        case STOP:
            return "Stop";
        case NORMAL_START:
            return "Normal Start";
        case FORCE_START:
            return "Force Start";
        case PREPARE_KICKOFF_YELLOW:
            return "Yellow Kickoff Prep";
        case PREPARE_KICKOFF_BLUE:
            return "Blue Kickoff Prep";
        case PREPARE_PENALTY_YELLOW:
            return "Yellow Penalty Prep";
        case PREPARE_PENALTY_BLUE:
            return "Blue Penalty Prep";
        case DIRECT_FREE_YELLOW:
            return "Direct Yellow Free Kick";
        case DIRECT_FREE_BLUE:
            return "Direct Blue Free Kick";
        case INDIRECT_FREE_YELLOW:
            return "Indirect Yellow Free Kick";
        case INDIRECT_FREE_BLUE:
            return "Indirect Blue Free Kick";
        case TIMEOUT_YELLOW:
            return "Timeout Yellow";
        case TIMEOUT_BLUE:
            return "Timeout Blue";
        case GOAL_YELLOW:
            return "Goal Yellow";
        case GOAL_BLUE:
            return "Goal Blue";
        case BALL_PLACEMENT_YELLOW:
            return "Ball Placement Yellow";
        case BALL_PLACEMENT_BLUE:
            return "Ball Placement Blue";
        default:
            return "";
    }
}
}

using namespace std;
using namespace NewRefereeModuleEnums;

/// Distance in meters that the ball must travel for a kick to be detected
static const float KickThreshold = 0.150f;

/// How many milliseconds the ball must be more than KickThreshold meters away
/// from its position when the referee indicated Ready for us to detect the ball
/// as having been kicked.
static const int KickVerifyTime_ms = 250;

NewRefereeModule::NewRefereeModule(SystemState& state)
    : stage(NORMAL_FIRST_HALF_PRE),
      command(HALT),
      _running(false),
      _state(state) {}

NewRefereeModule::~NewRefereeModule() { this->stop(); }

void NewRefereeModule::stop() {
    _running = false;
    wait();
}

void NewRefereeModule::getPackets(std::vector<NewRefereePacket*>& packets) {
    _mutex.lock();
    packets = _packets;
    _packets.clear();
    _mutex.unlock();
}

void NewRefereeModule::run() {
    QUdpSocket socket;

    if (!socket.bind(ProtobufRefereePort, QUdpSocket::ShareAddress)) {
        throw runtime_error("Can't bind to shared referee port");
    }

    multicast_add(&socket, RefereeAddress);

    _packets.reserve(4);

    _running = true;
    while (_running) {
        if (!_useExternalRef) continue;

        char buf[65536];

        if (!socket.waitForReadyRead(500)) {
            continue;
        }

        QHostAddress host;
        quint16 port = 0;
        qint64 size = socket.readDatagram(buf, sizeof(buf), &host, &port);
        if (size < 1) {
            fprintf(stderr, "NewRefereeModule: %s/n",
                    (const char*)socket.errorString().toLatin1());
            ::usleep(100000);
            continue;
        }

        NewRefereePacket* packet = new NewRefereePacket;
        packet->receivedTime = RJ::timestamp();
        this->received_time = packet->receivedTime;
        if (!packet->wrapper.ParseFromArray(buf, size)) {
            fprintf(stderr,
                    "NewRefereeModule: got bad packet of %d bytes from %s:%d\n",
                    (int)size, (const char*)host.toString().toLatin1(), port);
            fprintf(stderr, "Packet: %s\n", buf);
            fprintf(stderr, "Address: %s\n", RefereeAddress);
            continue;
        }

        _mutex.lock();
        _packets.push_back(packet);

        stage = (Stage)packet->wrapper.stage();
        command = (Command)packet->wrapper.command();
        sent_time = packet->wrapper.packet_timestamp();
        stage_time_left = packet->wrapper.stage_time_left();
        command_counter = packet->wrapper.command_counter();
        command_timestamp = packet->wrapper.command_timestamp();
        yellow_info.ParseRefboxPacket(packet->wrapper.yellow());
        blue_info.ParseRefboxPacket(packet->wrapper.blue());
        ballPlacementx = packet->wrapper.designated_position().x();
        ballPlacementy = packet->wrapper.designated_position().y();

        _mutex.unlock();
    }
}

void NewRefereeModule::spinKickWatcher() {
    if (_state.ball.valid) {
        /// Only run the kick detector when the ball is visible
        switch (_kickDetectState) {
            case WaitForReady:
                /// Never kicked and not ready for a restart
                break;

            case CapturePosition:
                // Do this in the processing thread
                _readyBallPos = _state.ball.pos;
                _kickDetectState = WaitForKick;
                break;

            case WaitForKick:
                if (!_state.ball.pos.nearPoint(_readyBallPos, KickThreshold)) {
                    // The ball appears to have moved
                    _kickTime = QTime::currentTime();
                    _kickDetectState = VerifyKick;
                }
                break;

            case VerifyKick:
                if (_state.ball.pos.nearPoint(_readyBallPos, KickThreshold)) {
                    // The ball is back where it was.  There was probably a
                    // vision error.
                    _kickDetectState = WaitForKick;
                } else if (_kickTime.msecsTo(QTime::currentTime()) >=
                           KickVerifyTime_ms) {
                    // The ball has been far enough away for enough time, so
                    // call this a kick.
                    _kickDetectState = Kicked;
                }
                break;

            case Kicked:
                // Stay here until the referee puts us back in Ready
                break;
        }
    }
}

void NewRefereeModule::updateGameState(bool blueTeam) {
    _state.gameState.ourScore = blueTeam ? blue_info.score : yellow_info.score;
    _state.gameState.theirScore =
        blueTeam ? yellow_info.score : blue_info.score;
    using namespace NewRefereeModuleEnums;
    switch (stage) {
        case Stage::NORMAL_FIRST_HALF_PRE:
            _state.gameState.period = GameState::FirstHalf;
            break;
        case Stage::NORMAL_FIRST_HALF:
            _state.gameState.period = GameState::FirstHalf;
            break;
        case Stage::NORMAL_HALF_TIME:
            _state.gameState.period = GameState::Halftime;
            break;
        case Stage::NORMAL_SECOND_HALF_PRE:
            _state.gameState.period = GameState::SecondHalf;
            break;
        case Stage::NORMAL_SECOND_HALF:
            _state.gameState.period = GameState::SecondHalf;
            break;
        case Stage::EXTRA_TIME_BREAK:
            _state.gameState.period = GameState::FirstHalf;
            break;
        case Stage::EXTRA_FIRST_HALF_PRE:
            _state.gameState.period = GameState::Overtime1;
            break;
        case Stage::EXTRA_FIRST_HALF:
            _state.gameState.period = GameState::Overtime1;
            break;
        case Stage::EXTRA_HALF_TIME:
            _state.gameState.period = GameState::Halftime;
            break;
        case Stage::EXTRA_SECOND_HALF_PRE:
            _state.gameState.period = GameState::Overtime2;
            break;
        case Stage::EXTRA_SECOND_HALF:
            _state.gameState.period = GameState::Overtime2;
            break;
        case Stage::PENALTY_SHOOTOUT_BREAK:
            _state.gameState.period = GameState::PenaltyShootout;
            break;
        case Stage::PENALTY_SHOOTOUT:
            _state.gameState.period = GameState::PenaltyShootout;
            break;
        case Stage::POST_GAME:
            _state.gameState.period = GameState::Overtime2;
            break;
    }
    switch (command) {
        case Command::HALT:
            _state.gameState.state = GameState::Halt;
            break;
        case Command::STOP:
            _state.gameState.state = GameState::Stop;
            break;
        case Command::NORMAL_START:
            ready();
            break;
        case Command::FORCE_START:
            _state.gameState.state = GameState::Playing;
            _state.gameState.ourRestart = false;
            _state.gameState.restart = GameState::None;
            break;
        case Command::PREPARE_KICKOFF_YELLOW:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Kickoff;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::PREPARE_KICKOFF_BLUE:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Kickoff;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::PREPARE_PENALTY_YELLOW:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Penalty;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::PREPARE_PENALTY_BLUE:
            _state.gameState.state = GameState::Setup;
            _state.gameState.restart = GameState::Penalty;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::DIRECT_FREE_YELLOW:
            ready();
            _state.gameState.restart = GameState::Direct;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::DIRECT_FREE_BLUE:
            ready();
            _state.gameState.restart = GameState::Direct;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::INDIRECT_FREE_YELLOW:
            ready();
            _state.gameState.restart = GameState::Indirect;
            _state.gameState.ourRestart = !blueTeam;
            break;
        case Command::INDIRECT_FREE_BLUE:
            ready();
            _state.gameState.restart = GameState::Indirect;
            _state.gameState.ourRestart = blueTeam;
            break;
        case Command::TIMEOUT_YELLOW:
            _state.gameState.state = GameState::Halt;
            break;
        case Command::TIMEOUT_BLUE:
            _state.gameState.state = GameState::Halt;
            break;
        case Command::GOAL_YELLOW:
            break;
        case Command::GOAL_BLUE:
            break;
        case Command::BALL_PLACEMENT_YELLOW:
            _state.gameState.state = GameState::Stop;
            _state.gameState.restart = GameState::Placement;
            _state.gameState.ourRestart = !blueTeam;
            _state.gameState.setBallPlacementPoint(ballPlacementx,
                                                   ballPlacementy);
            break;
        case Command::BALL_PLACEMENT_BLUE:
            _state.gameState.state = GameState::Stop;
            _state.gameState.restart = GameState::Placement;
            _state.gameState.ourRestart = blueTeam;
            _state.gameState.setBallPlacementPoint(ballPlacementx,
                                                   ballPlacementy);
            break;
    }

    if (command != prev_command){
        std::cout << "REFEREE: Command = " << stringFromCommand(command)<< std::endl;
        prev_command = command;
    }

    if (stage != prev_stage){
        std::cout << "REFEREE: Stage = " << stringFromStage(stage) << std::endl;
        prev_stage = stage;
    }

    if (_state.gameState.state == GameState::Ready && kicked()) {
        _state.gameState.state = GameState::Playing;
    }

    _state.gameState.OurInfo = blueTeam ? blue_info : yellow_info;
    _state.gameState.TheirInfo = blueTeam ? yellow_info : blue_info;
}

void NewRefereeModule::ready() {
    if (_state.gameState.state == GameState::Stop ||
        _state.gameState.state == GameState::Setup) {
        _state.gameState.state = GameState::Ready;
        _kickDetectState = CapturePosition;
    }
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   uga@ee.ed.ac.uk                                                       *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
//  *   (at your option) any later version.                                   *
 ***************************************************************************/
#include "propertiesdialog.h"

PropertiesDialog::PropertiesDialog(QWidget *parent,RecipeDB *db):QWidget(parent)
{

    // Store pointer to database
    database=db;

    // Initialize internal variables
    propertyList=new IngredientPropertyList;

    // Design dialog

    layout = new QGridLayout( this, 1, 1, 0, 0);
    QSpacerItem* spacer_left = new QSpacerItem( 10,10, QSizePolicy::Fixed, QSizePolicy::Minimum );
    layout->addMultiCell( spacer_left, 1,4,0,0 );
    QSpacerItem* spacer_top = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
    layout->addMultiCell(spacer_top,0,0,1,4);

    propertyListView=new KListView (this);
    layout->addMultiCellWidget (propertyListView,1,4,1,6);
    propertyListView->addColumn("Id");
    propertyListView->addColumn("Property");
    propertyListView->addColumn("Units");

    // Populate UI with data
    reloadPropertyList();

}

PropertiesDialog::~PropertiesDialog()
{
}

void PropertiesDialog::createNewProperty(void)
{
ElementList list;
database->loadUnits(&list);
CreatePropertyDialog* propertyDialog=new CreatePropertyDialog(&list);

if ( propertyDialog->exec() == QDialog::Accepted ) {
   QString name = propertyDialog->newPropertyName();
   QString units= propertyDialog->newUnitsName();
   int perUnits= 1;
   if (!((name.isNull()) || (units.isNull()))) // Make sure none of the fields are empty
      database->addProperty(name, units);
}
delete propertyDialog;

reloadPropertyList();
}

void PropertiesDialog::reloadPropertyList(void)
{
propertyList->clear(); // Empty list
propertyListView->clear(); // Clear the view
database->loadProperties(propertyList);

//Populate this data into the KListView
	for ( IngredientProperty *prop =propertyList->getFirst(); prop; prop =propertyList->getNext() )
	{
	QListViewItem *it= new QListViewItem(propertyListView,QString::number(prop->id),prop->name,prop->units+QString("/")+prop->perUnit.name );

	}

}
<commit_msg>Properties do not include "per_units" now.<commit_after>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   uga@ee.ed.ac.uk                                                       *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
//  *   (at your option) any later version.                                   *
 ***************************************************************************/
#include "propertiesdialog.h"

PropertiesDialog::PropertiesDialog(QWidget *parent,RecipeDB *db):QWidget(parent)
{

    // Store pointer to database
    database=db;

    // Initialize internal variables
    propertyList=new IngredientPropertyList;

    // Design dialog

    layout = new QGridLayout( this, 1, 1, 0, 0);
    QSpacerItem* spacer_left = new QSpacerItem( 10,10, QSizePolicy::Fixed, QSizePolicy::Minimum );
    layout->addMultiCell( spacer_left, 1,4,0,0 );
    QSpacerItem* spacer_top = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
    layout->addMultiCell(spacer_top,0,0,1,4);

    propertyListView=new KListView (this);
    layout->addMultiCellWidget (propertyListView,1,4,1,6);
    propertyListView->addColumn("Id");
    propertyListView->addColumn("Property");
    propertyListView->addColumn("Units");

    // Populate UI with data
    reloadPropertyList();

}

PropertiesDialog::~PropertiesDialog()
{
}

void PropertiesDialog::createNewProperty(void)
{
ElementList list;
database->loadUnits(&list);
CreatePropertyDialog* propertyDialog=new CreatePropertyDialog(&list);

if ( propertyDialog->exec() == QDialog::Accepted ) {
   QString name = propertyDialog->newPropertyName();
   QString units= propertyDialog->newUnitsName();
   int perUnits= 1;
   if (!((name.isNull()) || (units.isNull()))) // Make sure none of the fields are empty
      database->addProperty(name, units);
}
delete propertyDialog;

reloadPropertyList();
}

void PropertiesDialog::reloadPropertyList(void)
{
propertyList->clear(); // Empty list
propertyListView->clear(); // Clear the view
database->loadProperties(propertyList);

//Populate this data into the KListView
	for ( IngredientProperty *prop =propertyList->getFirst(); prop; prop =propertyList->getNext() )
	{
	QListViewItem *it= new QListViewItem(propertyListView,QString::number(prop->id),prop->name,prop->units);

	}

}
<|endoftext|>


<commit_before>/*
 * simple_tree.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: programmer
 */

#include "../system/discursive_system.h"
#include "./initial_agents.h"

#include "repository_access.h"
#include <Magick++.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../model/surrogate_tree_node.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"

using namespace Magick;
int debugLevel;

// display our command usage
void display_usage( void )
{
	std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n";
	usage_string += "where option can be any of the following";
	usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n";
	usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n";
	usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n";
	usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
	usage_string += "\n-i option - interactive mode (asks you questions) \n";
	usage_string += "\n-d option - debug level, defaults to 1\n";
	usage_string += "\n-O option - output file name, defaults to tree.jpg\n";
	usage_string += "\n-m option - output the creation of the current tree one step at a time via many .jpgs in sequence\n";
	usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-R and -r option -output the creation of the current tree one revision at a time via many .jpgs in sequence\n";
	usage_string += "\n-------------- -R also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-W option - spatial displacement scaling width level, defaults to .9\n";
	usage_string += "\n-H option - spatial displacement scaling height level, defaults to .85\n";

	DiscursivePrint("%s",usage_string.c_str());
    DiscursiveError("Copyright Discursive Labs LLC, 2010");
}

int main(int argc, char **argv)
{
	// set the debug level
	SetDiscursiveDebugLevel(0);

	// agentName equates to the passed command line parameter argument string
	char *agentName = NULL;

	// type of agent to use, ie command line options or interactive
	int agentType = 0;

	// scaling factors to use for spatial displacement
	double scaleHeight = 0.85;
	double scaleWidth = 0.9;

	// our filename for output file
	std::string fileName = "tree.jpg";

	// should we make many jpgs?
	int manyJpgs = 0;

	// options for many jpgs
	int jpgStep = 1;
	int jpgStart = 3;
	int jpgStop = 10000;

	// should we output a jpg per revision?
	int revJpgs = 0;

	// options for jpg per revison
	int revStep = 1;
	int revStart = 2;
	int revStop = 10000;

	// our option string
	static const char *optString = "g:G:S:C:H:W:O:m:R:ridh?";

	// loop over our command options in the normal unix way

	int opt;
	opt = getopt( argc, argv, optString );
	while( opt != -1 ) {
		switch( opt ) {
			case 'g':
				agentName = optarg;
				agentType = 1;
				break;
			case 'G':
				agentName = optarg;
				agentType = 2;
				break;
			case 'S':
				agentName = optarg;
				agentType = 3;
				break;
			case 'C':
				agentName = optarg;
				agentType = 4;
				break;
			case 'W':
				scaleWidth = atof(optarg);
				break;
			case 'm':
				manyJpgs = 1;
				sscanf("%d:%d:%d",optarg,jpgStart,jpgStop,jpgStep);
				if(jpgStart < 3)
				{
					jpgStart = 3;
				}
				break;
			case 'R':
				revJpgs = 1;
				sscanf("%d:%d:%d",optarg,revStart,revStop,revStep);
				if(revStart < 3)
				{
					revStart = 3;
				}
				break;
			case 'r':
				revJpgs = 1;
				revStart = 3;
				revStop = 100000;
				revStep = 1;
				break;
			case 'H':
				scaleHeight = atof(optarg);
				break;
			case 'O':
				fileName = optarg;
				break;
			case 'd':
				// set the debug level
				SetDiscursiveDebugLevel(1);
				break;
			case 'i':
				// set the interactivity level
				agentType = 5;
				break;
			case 'h':   /* fall-through is intentional */
			case '?':
				display_usage();
				break;
			default:
				DiscursiveError("bad cli, bad!");
				break;
		}
		// get the next Command Line option
		opt = getopt( argc, argv, optString );
	}

	// Tree Generation pipeline
	// create an abstract method for repository access
	RepositoryAccess* git;

	// let an interactive or command line agent create the repository access type
	switch(agentType)
	{
		case 5:
			git = interactive_agent();
			break;
		case 1:
		case 2:
		case 3:
		case 4:
			printf("%s\n",agentName);
			git = noninteractive_agent(agentType, agentName);
			break;
		case 0:
			display_usage();
			break;
        default:
            /* You won't actually get here. */
        	DiscursiveError("an impossibility occured in error processing");
            break;
	}

    // set our repository single or manyjpg options
	git->snapshotJpgs = manyJpgs;
	git->jpgIndex = 1000;
	git->scaleHeight = scaleHeight;
	git->scaleWidth = scaleWidth;
	git->fileName = (char*)fileName.c_str();
	git->globalInserts = 0;
	git->localInserts = 0;
	git->insertTarget = 0;
	git->revJpgs = revJpgs;
	git->globalRevs = 0;
	git->localRevs = 0;
	git->revTarget = 0;
	git->currentTreeSize = 0;
	git->logGenerated = 0;

	// retrieve our source tree
	git->source = git->retrieve();

	// output tree info
	DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str());
	DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts);

	// create loop step variables generically for any jpg looping type
	double loopStart = 0;
	double loopStop = 1;
	double loopStep = 1;
	bool executeLoopType = 1;

	// check for our custom loop types
	if(manyJpgs)
	{
		loopStart = jpgStart;
		loopStop = jpgStop;
		loopStep = jpgStep;
		executeLoopType = 2;
	}
	else if(revJpgs)
	{
		loopStart = revStart;
		loopStop = revStop;
		loopStep = revStep;
		executeLoopType = 3;
	}

	// check for too many global inserts or revisions
	if((executeLoopType == 2) && (loopStop >= git->globalInserts))
	{
		loopStop = git->globalInserts-1;
	}
	else if((executeLoopType == 3) && (loopStop >= git->globalRevs))
	{
		loopStop = git->globalRevs-1;
	}

	// loop over a bunch of increasingly large trees for debug or revision tree generation
	// use our user-set parameters to define our step
	for(double i = loopStart; i<loopStop;i+= loopStep)
	{

		// reset our insert variables
		if(executeLoopType == 2)
		{
			git->localInserts = 0;
			git->insertTarget = i;
		}
		else if(executeLoopType == 3)
		{
			git->localRevs = 0;
			git->revTarget = i;
		}

		// retrieve our source tree
		git->source = git->retrieve();

		// init libmagick
		//InitializeMagick("/");

		DiscursivePrint("Decorating surrogate trees %lf out of %lf step value %lf\n",i,loopStop,loopStep);
		// Decorate surrogate tree nodes with locations
		int START_WIDTH = 5000;
		int START_HEIGHT = 5000;
		int END_WIDTH = 500;
		int END_HEIGHT = 500;
		double widthRescaling = END_WIDTH/(double)START_WIDTH;
		double heightRescaling = END_HEIGHT/(double)START_HEIGHT;
		SpatialDisplacement disp(START_WIDTH,START_HEIGHT,scaleWidth*widthRescaling,scaleHeight*heightRescaling);
		disp.decorate(git->source);

		DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %lf out of %lf step value %lf\n",i,loopStop,loopStep);
		// Digitize decorated surrogate tree into line segment tree
	    SpaceColonizer digitizer(1);
		DrawableData* lines = digitizer.digitize(git->source);

		// Transform

		// Draw tree
		DiscursivePrint("Drawing Tree %lf out of %lf step value %lf",i,loopStop,loopStep);
		Image canvas(Geometry(500,500),"white");
		ScanlineArtist artist;
		artist.draw(canvas, lines);

		// actually generate a tree
		DiscursivePrint("Writing Tree %lf out of %lf step value %lf\n",i,loopStop,loopStep);
		git->WriteJPGFromCanvas(&canvas);

	}
	return 0;
}
<commit_msg>updatd sscanf to work correctly<commit_after>/*
 * simple_tree.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: programmer
 */

#include "../system/discursive_system.h"
#include "./initial_agents.h"

#include "repository_access.h"
#include <Magick++.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../model/surrogate_tree_node.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"

using namespace Magick;
int debugLevel;

// display our command usage
void display_usage( void )
{
	std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n";
	usage_string += "where option can be any of the following";
	usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n";
	usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n";
	usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n";
	usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
	usage_string += "\n-i option - interactive mode (asks you questions) \n";
	usage_string += "\n-d option - debug level, defaults to 1\n";
	usage_string += "\n-O option - output file name, defaults to tree.jpg\n";
	usage_string += "\n-m option - output the creation of the current tree one step at a time via many .jpgs in sequence\n";
	usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-R and -r option -output the creation of the current tree one revision at a time via many .jpgs in sequence\n";
	usage_string += "\n-------------- -R also expects the following start:stop:step i.e. 1:400:5       \n";
	usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
	usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n";
	usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
	usage_string += "\n-W option - spatial displacement scaling width level, defaults to .9\n";
	usage_string += "\n-H option - spatial displacement scaling height level, defaults to .85\n";

	DiscursivePrint("%s",usage_string.c_str());
    DiscursiveError("Copyright Discursive Labs LLC, 2010");
}

int main(int argc, char **argv)
{
	// set the debug level
	SetDiscursiveDebugLevel(0);

	// agentName equates to the passed command line parameter argument string
	char *agentName = NULL;

	// type of agent to use, ie command line options or interactive
	int agentType = 0;

	// scaling factors to use for spatial displacement
	double scaleHeight = 0.85;
	double scaleWidth = 0.9;

	// our filename for output file
	std::string fileName = "tree.jpg";

	// should we make many jpgs?
	int manyJpgs = 0;

	// options for many jpgs
	int jpgStep = 1;
	int jpgStart = 3;
	int jpgStop = 10000;

	// should we output a jpg per revision?
	int revJpgs = 0;

	// options for jpg per revison
	int revStep = 1;
	int revStart = 2;
	int revStop = 10000;

	// our option string
	static const char *optString = "g:G:S:C:H:W:O:m:R:ridh?";

	// loop over our command options in the normal unix way

	int opt;
	opt = getopt( argc, argv, optString );
	while( opt != -1 ) {
		switch( opt ) {
			case 'g':
				agentName = optarg;
				agentType = 1;
				break;
			case 'G':
				agentName = optarg;
				agentType = 2;
				break;
			case 'S':
				agentName = optarg;
				agentType = 3;
				break;
			case 'C':
				agentName = optarg;
				agentType = 4;
				break;
			case 'W':
				scaleWidth = atof(optarg);
				break;
			case 'm':
				manyJpgs = 1;
				sscanf(optarg,"%d:%d:%d",&jpgStart,&jpgStop,&jpgStep);
				if(jpgStart < 3)
				{
					jpgStart = 3;
				}
				break;
			case 'R':
				revJpgs = 1;
				sscanf(optarg,"%d:%d:%d",&revStart,&revStop,&revStep);
				if(revStart < 3)
				{
					revStart = 3;
				}
				break;
			case 'r':
				revJpgs = 1;
				revStart = 3;
				revStop = 100000;
				revStep = 1;
				break;
			case 'H':
				scaleHeight = atof(optarg);
				break;
			case 'O':
				fileName = optarg;
				break;
			case 'd':
				// set the debug level
				SetDiscursiveDebugLevel(1);
				break;
			case 'i':
				// set the interactivity level
				agentType = 5;
				break;
			case 'h':   /* fall-through is intentional */
			case '?':
				display_usage();
				break;
			default:
				DiscursiveError("bad cli, bad!");
				break;
		}
		// get the next Command Line option
		opt = getopt( argc, argv, optString );
	}

	// Tree Generation pipeline
	// create an abstract method for repository access
	RepositoryAccess* git;

	// let an interactive or command line agent create the repository access type
	switch(agentType)
	{
		case 5:
			git = interactive_agent();
			break;
		case 1:
		case 2:
		case 3:
		case 4:
			printf("%s\n",agentName);
			git = noninteractive_agent(agentType, agentName);
			break;
		case 0:
			display_usage();
			break;
        default:
            /* You won't actually get here. */
        	DiscursiveError("an impossibility occured in error processing");
            break;
	}

    // set our repository single or manyjpg options
	git->snapshotJpgs = manyJpgs;
	git->jpgIndex = 1000;
	git->scaleHeight = scaleHeight;
	git->scaleWidth = scaleWidth;
	git->fileName = (char*)fileName.c_str();
	git->globalInserts = 0;
	git->localInserts = 0;
	git->insertTarget = 0;
	git->revJpgs = revJpgs;
	git->globalRevs = 0;
	git->localRevs = 0;
	git->revTarget = 0;
	git->currentTreeSize = 0;
	git->logGenerated = 0;

	// retrieve our source tree
	git->source = git->retrieve();

	// output tree info
	DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str());
	DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts);

	// create loop step variables generically for any jpg looping type
	int loopStart = 0;
	int loopStop = 1;
	int loopStep = 1;
	bool executeLoopType = 1;

	// check for our custom loop types
	if(manyJpgs)
	{
		loopStart = jpgStart;
		loopStop = jpgStop;
		loopStep = jpgStep;
		executeLoopType = 2;
	}
	else if(revJpgs)
	{
		loopStart = revStart;
		loopStop = revStop;
		loopStep = revStep;
		executeLoopType = 3;
	}

	// check for too many global inserts or revisions
	if((executeLoopType == 2) && (loopStop >= git->globalInserts))
	{
		loopStop = git->globalInserts-1;
	}
	else if((executeLoopType == 3) && (loopStop >= git->globalRevs))
	{
		loopStop = git->globalRevs-1;
	}

	// loop over a bunch of increasingly large trees for debug or revision tree generation
	// use our user-set parameters to define our step
	for(int i = loopStart; i<loopStop;i+= loopStep)
	{

		// reset our insert variables
		if(executeLoopType == 2)
		{
			git->localInserts = 0;
			git->insertTarget = i;
		}
		else if(executeLoopType == 3)
		{
			git->localRevs = 0;
			git->revTarget = i;
		}

		// retrieve our source tree
		git->source = git->retrieve();

		// init libmagick
		//InitializeMagick("/");

		DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,loopStop,loopStep);
		// Decorate surrogate tree nodes with locations
		int START_WIDTH = 5000;
		int START_HEIGHT = 5000;
		int END_WIDTH = 500;
		int END_HEIGHT = 500;
		double widthRescaling = END_WIDTH/(double)START_WIDTH;
		double heightRescaling = END_HEIGHT/(double)START_HEIGHT;
		SpatialDisplacement disp(START_WIDTH,START_HEIGHT,scaleWidth*widthRescaling,scaleHeight*heightRescaling);
		disp.decorate(git->source);

		DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,loopStop,loopStep);
		// Digitize decorated surrogate tree into line segment tree
	    SpaceColonizer digitizer(1);
		DrawableData* lines = digitizer.digitize(git->source);

		// Transform

		// Draw tree
		DiscursivePrint("Drawing Tree %d out of %d step value %d",i,loopStop,loopStep);
		Image canvas(Geometry(500,500),"white");
		ScanlineArtist artist;
		artist.draw(canvas, lines);

		// actually generate a tree
		DiscursivePrint("Writing Tree %d out of %d step value %d\n",i,loopStop,loopStep);
		git->WriteJPGFromCanvas(&canvas);

	}
	return 0;
}
<|endoftext|>