<commit_before>/******************************
** Tsunagari Tile Engine     **
** main.cpp                  **
** Copyright 2011 OmegaSDG   **
******************************/

#include <iostream>
#include <fstream>
#include <stdarg.h>
#include <stdio.h>
#include <string>
#include <string.h>

#include <boost/config.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <libxml/parser.h>
#include <libxml/tree.h>

#include "common.h"
#include "config.h"
#include "cmd.h"
#include "log.h"
#include "window.h"

#ifdef _WINDOWS
	#include <Windows.h>
#endif

#ifndef LIBXML_TREE_ENABLED
	#error Tree must be enabled in libxml2
#endif

/* Output compiled-in engine defaults. */
static void defaultsQuery()
{
	std::cerr << "CLIENT_CONF_FILE:                       "
		<< CLIENT_CONF_FILE << std::endl;
	std::cerr << "MESSAGE_MODE:                           ";
	if (MESSAGE_MODE == MM_DEBUG)
		std::cerr << "MM_DEBUG" << std::endl;
	else if (MESSAGE_MODE == MM_DEVELOPER)
		std::cerr << "MM_DEVELOPER" << std::endl;
	else
		std::cerr << "MM_ERROR" << std::endl;
	std::cerr << "ROGUELIKE_PERSIST_DELAY_INIT:           "
		<< ROGUELIKE_PERSIST_DELAY_INIT << std::endl;
	std::cerr << "ROGUELIKE_PERSIST_DELAY_CONSECUTIVE:    "
		<< ROGUELIKE_PERSIST_DELAY_CONSECUTIVE << std::endl;
	std::cerr << "CACHE_EMPTY_TTL:                        "
		<< CACHE_EMPTY_TTL << std::endl;
	std::cerr << "CACHE_MAX_SIZE:                         "
		<< CACHE_MAX_SIZE << std::endl;
}

/**
 * Load the values we need to start initializing the game from an ini file.
 *
 * We need to know what size window to create and which World to load. This
 * information will be stored in an ini file which we parse here.
 *
 * @param filename Name of the ini file to load from.
 *
 * @return ClientValues object if successful
 */
static ClientValues* parseConfig(const char* filename)
{
	namespace pod = boost::program_options::detail;

	ClientValues* conf = new ClientValues;

	conf->cache_enabled = CACHE_EMPTY_TTL && CACHE_MAX_SIZE;

	std::ifstream config(filename);
	if (!config) {
		Log::err(filename, "could not parse config");
		delete conf;
		return NULL;
	}

	std::set<std::string> options;
	std::map<std::string, std::string> parameters;
	options.insert("*");

	for (pod::config_file_iterator i(config, options), e ; i != e; ++i) {
		parameters[i->string_key] = i->value[0];
	}

	if (parameters["engine.world"].empty()) {
		Log::err(filename, "\"[engine] world\" option expected");
		return NULL;
	}
	else
		conf->world = parameters["engine.world"];

	if (parameters["window.width"].empty()) {
		Log::err(filename, "\"[window] width\" option expected");
		return NULL;
	}
	else
		conf->windowsize.x = atoi(parameters["window.width"].c_str());

	if (parameters["window.height"].empty()) {
		Log::err(filename, "\"[window] height\" option expected");
		return NULL;
	}
	else
		conf->windowsize.y = atoi(parameters["window.height"].c_str());

	if (parameters["window.fullscreen"].empty()) {
		Log::err(filename, "\"[window] fullscreen\" option expected");
		return NULL;
	}
	else
		conf->fullscreen = parseBool(parameters["window.fullscreen"]);

	if (!parameters["cache.enable"].empty()) {
		if (parseBool(parameters["cache.enable"]))
			conf->cache_enabled = true;
		else
			conf->cache_enabled = false;
	}

	if (!parameters["cache.ttl"].empty()) {
		if (atoi(parameters["cache.ttl"].c_str()) == 0)
			conf->cache_enabled = 0;
		conf->cache_ttl = atoi(parameters["cache.ttl"].c_str());
	}

	if (parameters["cache.size"].empty())
		conf->cache_size = CACHE_MAX_SIZE;
	else {
		if (atoi(parameters["cache.size"].c_str()) == 0)
			conf->cache_enabled = 0;
		conf->cache_size = atoi(parameters["cache.size"].c_str());
	}

	if (parameters["engine.loglevel"].empty())
		conf->loglevel = MESSAGE_MODE;
	else if (parameters["engine.loglevel"] == "error" ||
	    parameters["engine.loglevel"] == "Error" ||
	    parameters["engine.loglevel"] == "ERROR")
		conf->loglevel = MM_SILENT;
	else if (parameters["engine.loglevel"] == "devel" ||
	    parameters["engine.loglevel"] == "Devel" ||
	    parameters["engine.loglevel"] == "DEVEL")
	conf->loglevel = MM_DEVELOPER;
	else if (parameters["engine.loglevel"] == "debug" ||
	    parameters["engine.loglevel"] == "Debug" ||
	    parameters["engine.loglevel"] == "DEBUG")
	conf->loglevel = MM_DEBUG;
	else {
		Log::err(filename, "unknown value for \"[engine] loglevel\", using default");
		conf->loglevel = MESSAGE_MODE;
	}

	return conf;
}

/* Parse and process command line options and arguments. */
static bool parseCommandLine(int argc, char* argv[], ClientValues* conf)
{
	CommandLineOptions cmd(argc, argv);

	cmd.insert("-h", "--help", "", "Display this help message");
	cmd.insert("-g", "--gameworld", "<world file>", "Game world to load");
	cmd.insert("-c", "--config", "<config file>", "Client config file to use");
	cmd.insert("-v", "--verbosity", "<error,devel,debug>", "Log message level");
	cmd.insert("-t", "--cache-ttl", "<seconds>", "Cache time-to-live in seconds");
	cmd.insert("-m", "--cache-size", "<megabytes>", "Cache size in megabytes");
	cmd.insert("-s", "--size", "<WxH>", "Window dimensions");
	cmd.insert("-f", "--fullscreen", "", "Run in fullscreen mode");
	cmd.insert("-w", "--window", "", "Run in windowed mode");
	cmd.insert("-q", "--query", "", "Query compiled-in engine defaults");

	if (!cmd.parse()) {
		Log::err(argv[0], "bad command line");
		cmd.usage();
		return false;
	}

	if (cmd.check("--help")) {
		cmd.usage();
		return false;
	}

	if (cmd.check("--config")) {
		delete conf;
		conf = parseConfig(cmd.get("--config").c_str());
		if (!conf) {
			Log::err(cmd.get("--config"), "loading config failed");
			return false;
		}
	}

	if (cmd.check("--gameworld"))
		conf->world = cmd.get("--gameworld");

	if (cmd.check("--verbosity")) {
		if (!cmd.get("--verbosity").compare("error"))
			conf->loglevel = MM_SILENT;
		else if (!cmd.get("--verbosity").compare("devel"))
			conf->loglevel = MM_DEVELOPER;
		else if (!cmd.get("--verbosity").compare("debug"))
			conf->loglevel = MM_DEBUG;
		else {
			Log::err(argv[0], "invalid argument for --verbosity");
			return false;
		}
	}

	if (cmd.check("--cache-ttl")) {
		conf->cache_ttl = atoi(cmd.get("--cache-ttl").c_str());
		if (conf->cache_ttl == 0)
			conf->cache_enabled = false;
	}

	if (cmd.check("--cache-size")) {
		conf->cache_ttl = atoi(cmd.get("--cache-size").c_str());
		if (conf->cache_size == 0)
			conf->cache_enabled = false;
	}

	if (cmd.check("--size")) {
		std::vector<std::string> dim = splitStr(cmd.get("--size"), "x");
		if (dim.size() != 2) {
			Log::err(argv[0], "invalid argument for --size");
			return false;
		}
		conf->windowsize.x = atoi(dim[0].c_str());
		conf->windowsize.y = atoi(dim[1].c_str());
	}

	if (cmd.check("--fullscreen") && cmd.check("--window")) {
		Log::err(argv[0], "--fullscreen and --window mutually exclusive");
		return false;
	}

	if (cmd.check("--fullscreen"))
		conf->fullscreen = true;

	if (cmd.check("--window"))
		conf->fullscreen = false;

	if (cmd.check("--query")) {
		defaultsQuery();
		return false;
	}

	return true;
}

static void initLibraries()
{
	/*
	 * This initializes the library and checks for potential ABI mismatches
	 * between the version it was compiled for and the actual shared
	 * library used.
	 */
	LIBXML_TEST_VERSION
}

static void cleanupLibraries()
{
	// Clean the XML library.
	xmlCleanupParser();
}

/**
 * Load client config and instantiate window.
 *
 * The client config tells us our window parameters along with which World
 * we're going to load. The GameWindow class then loads and plays the game.
 */
int main(int argc, char** argv)
{
	#if _WINDOWS /* Fix console output on Windows */
	if (AttachConsole(ATTACH_PARENT_PROCESS)) {
		freopen("CONOUT$","wb",stdout);
		freopen("CONOUT$","wb",stderr);
	}
	#endif

	initLibraries();

	ClientValues* conf = parseConfig(CLIENT_CONF_FILE);

	if (!parseCommandLine(argc, argv, conf)) {
		delete conf;
		return 1;
	}

	if (conf && conf->loglevel)
		Log::setMode(conf->loglevel);

	if (!conf) {
		Log::err(CLIENT_CONF_FILE, "loading config failed");
		delete conf;
		return 1;
	}

	GameWindow window((unsigned)conf->windowsize.x,
	                  (unsigned)conf->windowsize.y,
	                  conf->fullscreen);

	if (window.init(conf))
		window.show();

	delete conf;

	cleanupLibraries();

	return 0;
}

<commit_msg>Typos in main.cpp<commit_after>/******************************
** Tsunagari Tile Engine     **
** main.cpp                  **
** Copyright 2011 OmegaSDG   **
******************************/

#include <iostream>
#include <fstream>
#include <stdarg.h>
#include <stdio.h>
#include <string>
#include <string.h>

#include <boost/config.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <libxml/parser.h>
#include <libxml/tree.h>

#include "common.h"
#include "config.h"
#include "cmd.h"
#include "log.h"
#include "window.h"

#ifdef _WINDOWS
	#include <Windows.h>
#endif

#ifndef LIBXML_TREE_ENABLED
	#error Tree must be enabled in libxml2
#endif

/* Output compiled-in engine defaults. */
static void defaultsQuery()
{
	std::cerr << "CLIENT_CONF_FILE:                       "
		<< CLIENT_CONF_FILE << std::endl;
	std::cerr << "MESSAGE_MODE:                           ";
	if (MESSAGE_MODE == MM_DEBUG)
		std::cerr << "MM_DEBUG" << std::endl;
	else if (MESSAGE_MODE == MM_DEVELOPER)
		std::cerr << "MM_DEVELOPER" << std::endl;
	else
		std::cerr << "MM_ERROR" << std::endl;
	std::cerr << "ROGUELIKE_PERSIST_DELAY_INIT:           "
		<< ROGUELIKE_PERSIST_DELAY_INIT << std::endl;
	std::cerr << "ROGUELIKE_PERSIST_DELAY_CONSECUTIVE:    "
		<< ROGUELIKE_PERSIST_DELAY_CONSECUTIVE << std::endl;
	std::cerr << "CACHE_EMPTY_TTL:                        "
		<< CACHE_EMPTY_TTL << std::endl;
	std::cerr << "CACHE_MAX_SIZE:                         "
		<< CACHE_MAX_SIZE << std::endl;
}

/**
 * Load the values we need to start initializing the game from an ini file.
 *
 * We need to know what size window to create and which World to load. This
 * information will be stored in an ini file which we parse here.
 *
 * @param filename Name of the ini file to load from.
 *
 * @return ClientValues object if successful
 */
static ClientValues* parseConfig(const char* filename)
{
	namespace pod = boost::program_options::detail;

	ClientValues* conf = new ClientValues;

	conf->cache_enabled = CACHE_EMPTY_TTL && CACHE_MAX_SIZE;

	std::ifstream config(filename);
	if (!config) {
		Log::err(filename, "could not parse config");
		delete conf;
		return NULL;
	}

	std::set<std::string> options;
	std::map<std::string, std::string> parameters;
	options.insert("*");

	for (pod::config_file_iterator i(config, options), e ; i != e; ++i) {
		parameters[i->string_key] = i->value[0];
	}

	if (parameters["engine.world"].empty()) {
		Log::err(filename, "\"[engine] world\" option expected");
		return NULL;
	}
	else
		conf->world = parameters["engine.world"];

	if (parameters["window.width"].empty()) {
		Log::err(filename, "\"[window] width\" option expected");
		return NULL;
	}
	else
		conf->windowsize.x = atoi(parameters["window.width"].c_str());

	if (parameters["window.height"].empty()) {
		Log::err(filename, "\"[window] height\" option expected");
		return NULL;
	}
	else
		conf->windowsize.y = atoi(parameters["window.height"].c_str());

	if (parameters["window.fullscreen"].empty()) {
		Log::err(filename, "\"[window] fullscreen\" option expected");
		return NULL;
	}
	else
		conf->fullscreen = parseBool(parameters["window.fullscreen"]);

	if (!parameters["cache.enable"].empty()) {
		if (parseBool(parameters["cache.enable"]))
			conf->cache_enabled = true;
		else
			conf->cache_enabled = false;
	}

	if (parameters["cache.ttl"].empty())
		conf->cache_ttl = CACHE_EMPTY_TTL;
	else {
		if (atoi(parameters["cache.ttl"].c_str()) == 0)
			conf->cache_enabled = 0;
		conf->cache_ttl = atoi(parameters["cache.ttl"].c_str());
	}

	if (parameters["cache.size"].empty())
		conf->cache_size = CACHE_MAX_SIZE;
	else {
		if (atoi(parameters["cache.size"].c_str()) == 0)
			conf->cache_enabled = 0;
		conf->cache_size = atoi(parameters["cache.size"].c_str());
	}

	if (parameters["engine.loglevel"].empty())
		conf->loglevel = MESSAGE_MODE;
	else if (parameters["engine.loglevel"] == "error" ||
	    parameters["engine.loglevel"] == "Error" ||
	    parameters["engine.loglevel"] == "ERROR")
		conf->loglevel = MM_SILENT;
	else if (parameters["engine.loglevel"] == "devel" ||
	    parameters["engine.loglevel"] == "Devel" ||
	    parameters["engine.loglevel"] == "DEVEL")
	conf->loglevel = MM_DEVELOPER;
	else if (parameters["engine.loglevel"] == "debug" ||
	    parameters["engine.loglevel"] == "Debug" ||
	    parameters["engine.loglevel"] == "DEBUG")
	conf->loglevel = MM_DEBUG;
	else {
		Log::err(filename, "unknown value for \"[engine] loglevel\", using default");
		conf->loglevel = MESSAGE_MODE;
	}

	return conf;
}

/* Parse and process command line options and arguments. */
static bool parseCommandLine(int argc, char* argv[], ClientValues* conf)
{
	CommandLineOptions cmd(argc, argv);

	cmd.insert("-h", "--help", "", "Display this help message");
	cmd.insert("-g", "--gameworld", "<world file>", "Game world to load");
	cmd.insert("-c", "--config", "<config file>", "Client config file to use");
	cmd.insert("-v", "--verbosity", "<error,devel,debug>", "Log message level");
	cmd.insert("-t", "--cache-ttl", "<seconds>", "Cache time-to-live in seconds");
	cmd.insert("-m", "--cache-size", "<megabytes>", "Cache size in megabytes");
	cmd.insert("-s", "--size", "<WxH>", "Window dimensions");
	cmd.insert("-f", "--fullscreen", "", "Run in fullscreen mode");
	cmd.insert("-w", "--window", "", "Run in windowed mode");
	cmd.insert("-q", "--query", "", "Query compiled-in engine defaults");

	if (!cmd.parse()) {
		Log::err(argv[0], "bad command line");
		cmd.usage();
		return false;
	}

	if (cmd.check("--help")) {
		cmd.usage();
		return false;
	}

	if (cmd.check("--config")) {
		delete conf;
		conf = parseConfig(cmd.get("--config").c_str());
		if (!conf) {
			Log::err(cmd.get("--config"), "loading config failed");
			return false;
		}
	}

	if (cmd.check("--gameworld"))
		conf->world = cmd.get("--gameworld");

	if (cmd.check("--verbosity")) {
		if (!cmd.get("--verbosity").compare("error"))
			conf->loglevel = MM_SILENT;
		else if (!cmd.get("--verbosity").compare("devel"))
			conf->loglevel = MM_DEVELOPER;
		else if (!cmd.get("--verbosity").compare("debug"))
			conf->loglevel = MM_DEBUG;
		else {
			Log::err(argv[0], "invalid argument for --verbosity");
			return false;
		}
	}

	if (cmd.check("--cache-ttl")) {
		conf->cache_ttl = atoi(cmd.get("--cache-ttl").c_str());
		if (conf->cache_ttl == 0)
			conf->cache_enabled = false;
	}

	if (cmd.check("--cache-size")) {
		conf->cache_size = atoi(cmd.get("--cache-size").c_str());
		if (conf->cache_size == 0)
			conf->cache_enabled = false;
	}

	if (cmd.check("--size")) {
		std::vector<std::string> dim = splitStr(cmd.get("--size"), "x");
		if (dim.size() != 2) {
			Log::err(argv[0], "invalid argument for --size");
			return false;
		}
		conf->windowsize.x = atoi(dim[0].c_str());
		conf->windowsize.y = atoi(dim[1].c_str());
	}

	if (cmd.check("--fullscreen") && cmd.check("--window")) {
		Log::err(argv[0], "--fullscreen and --window mutually exclusive");
		return false;
	}

	if (cmd.check("--fullscreen"))
		conf->fullscreen = true;

	if (cmd.check("--window"))
		conf->fullscreen = false;

	if (cmd.check("--query")) {
		defaultsQuery();
		return false;
	}

	return true;
}

static void initLibraries()
{
	/*
	 * This initializes the library and checks for potential ABI mismatches
	 * between the version it was compiled for and the actual shared
	 * library used.
	 */
	LIBXML_TEST_VERSION
}

static void cleanupLibraries()
{
	// Clean the XML library.
	xmlCleanupParser();
}

/**
 * Load client config and instantiate window.
 *
 * The client config tells us our window parameters along with which World
 * we're going to load. The GameWindow class then loads and plays the game.
 */
int main(int argc, char** argv)
{
	#if _WINDOWS /* Fix console output on Windows */
	if (AttachConsole(ATTACH_PARENT_PROCESS)) {
		freopen("CONOUT$","wb",stdout);
		freopen("CONOUT$","wb",stderr);
	}
	#endif

	initLibraries();

	ClientValues* conf = parseConfig(CLIENT_CONF_FILE);

	if (!parseCommandLine(argc, argv, conf)) {
		delete conf;
		return 1;
	}

	if (conf && conf->loglevel)
		Log::setMode(conf->loglevel);

	if (!conf) {
		Log::err(CLIENT_CONF_FILE, "loading config failed");
		delete conf;
		return 1;
	}

	GameWindow window((unsigned)conf->windowsize.x,
	                  (unsigned)conf->windowsize.y,
	                  conf->fullscreen);

	if (window.init(conf))
		window.show();

	delete conf;

	cleanupLibraries();

	return 0;
}

<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>

#include "qpp.h"
//#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping
// TODO: write a timer class, tic/toc

using namespace std;

using namespace qpp;
using namespace qpp::types;

//int main(int argc, char **argv)
int main()
{
	_init();

	// Display formatting
	std::cout << std::fixed; // use fixed format for nice formatting
//	std::cout << std::scientific;
	std::cout << std::setprecision(4); // only for fixed or scientific modes

	cout << "Starting qpp..." << endl;

	size_t N = 7000;
	cmat testmat = cmat::Random(N, N);

	// TIMING
	Timer t;  // start the timer
	cout << "The norm of a " << N << " x " << N << " random complex matrix is: "
			<< norm(testmat) << endl;
	t.toc(); // read the time
	cout << "It took me " << t.ticks() << " ticks (" << t.secs()
			<< " seconds) to compute the norm." << endl;
	// END TIMING
	t.reset(); // reset the timer to current time
	for (size_t i = 0; i < 10000; i++)
		; // wait a bit
	t.toc(); // read again
	cout << "New timer reading immediately after reset : " << t.ticks()
			<< " ticks (" << t.secs() << " seconds).";

	cout << endl << "Exiting qpp..." << endl;
}
<commit_msg>commit<commit_after>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>

#include "qpp.h"
//#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping

using namespace std;

using namespace qpp;
using namespace qpp::types;

//int main(int argc, char **argv)
int main()
{
	_init();

	// Display formatting
	std::cout << std::fixed; // use fixed format for nice formatting
//	std::cout << std::scientific;
	std::cout << std::setprecision(4); // only for fixed or scientific modes

	cout << "Starting qpp..." << endl;

	size_t N = 7000;
	cmat testmat = cmat::Random(N, N);

	// TIMING
	Timer t;  // start the timer
	cout << "The norm of a " << N << " x " << N << " random complex matrix is: "
			<< norm(testmat) << endl;
	t.toc(); // read the time
	cout << "It took me " << t.ticks() << " ticks (" << t.secs()
			<< " seconds) to compute the norm." << endl;
	// END TIMING
	t.reset(); // reset the timer to current time
	for (size_t i = 0; i < 10000; i++)
		; // wait a bit
	t.toc(); // read again
	cout << "New timer reading immediately after reset : " << t.ticks()
			<< " ticks (" << t.secs() << " seconds).";

	cout << endl << "Exiting qpp..." << endl;
}
<|endoftext|>


<commit_before>/*! \file main.cpp
 *  \brief Program to run the grid code. */

#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"

#define OUTPUT
//#define CPU_TIME

int main(int argc, char *argv[])
{
  // timing variables
  double start_total, stop_total, start_step, stop_step;
  #ifdef CPU_TIME
  double stop_init, init_min, init_max, init_avg;
  double start_bound, stop_bound, bound_min, bound_max, bound_avg;
  double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
  double init, bound, hydro;
  init = bound = hydro = 0;
  #endif //CPU_TIME

  // start the total time
  start_total = get_time();

  /* Initialize MPI communication */
  #ifdef MPI_CHOLLA
  InitializeChollaMPI(&argc, &argv);
  #endif /*MPI_CHOLLA*/

  Real dti = 0; // inverse time step, 1.0 / dt

  // input parameter variables
  char *param_file;
  struct parameters P;
  int nfile = 0; // number of output files
  Real outtime = 0; // current output time

  // read in command line arguments
  if (argc != 2)
  {
    chprintf("usage: %s <parameter_file>\n", argv[0]);
    chexit(-1);
  } else {
    param_file = argv[1];
  }

  // create the grid
  Grid3D G;

  // read in the parameters
  parse_params (param_file, &P);
  // and output to screen
  chprintf ("Parameter values:  nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
    P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
  chprintf ("Output directory:  %s\n", P.outdir);

  // initialize the grid
  G.Initialize(&P);
  chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);

  // Set initial conditions and calculate first dt
  chprintf("Setting initial conditions...\n");
  G.Set_Initial_Conditions(P);
  chprintf("Initial conditions set.\n");
  // set main variables for Read_Grid inital conditions
  if (strcmp(P.init, "Read_Grid") == 0) {
    dti = C_cfl / G.H.dt;
    outtime += G.H.t;
    nfile = P.nfile*P.nfull;
  }

  #ifdef CPU_TIME
  G.Timer.Initialize();
  #endif

  #ifdef GRAVITY
  G.Initialize_Gravity(&P);
  #endif

  #ifdef PARTICLES
  G.Initialize_Particles(&P);
  #endif

  #ifdef COSMOLOGY
  G.Initialize_Cosmology(&P);
  #endif

  #ifdef COOLING_GRACKLE
  G.Initialize_Grackle(&P);
  #endif

  #ifdef GRAVITY
  G.Compute_Gravitational_Potential( &P);
  #endif

  // set boundary conditions (assign appropriate values to ghost cells)
  chprintf("Setting boundary conditions...\n");
  G.Set_Boundary_Conditions_All(P);
  chprintf("Boundary conditions set.\n");

  #ifdef PARTICLES
  G.Get_Particles_Accelration();
  #endif

  chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
  chprintf("Ratio of specific heats gamma = %f\n",gama);
  chprintf("Nstep = %d  Timestep = %f  Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);

  #ifdef OUTPUT
  if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
  // write the initial conditions to file
  chprintf("Writing initial conditions to file...\n");
  WriteData(G, P, nfile);
  }
  // add one to the output file count
  nfile++;
  #endif //OUTPUT
  // increment the next output time
  outtime += P.outstep;

  #ifdef CPU_TIME
  stop_init = get_time();
  init = stop_init - start_total;
  #ifdef MPI_CHOLLA
  init_min = ReduceRealMin(init);
  init_max = ReduceRealMax(init);
  init_avg = ReduceRealAvg(init);
  chprintf("Init  min: %9.4f  max: %9.4f  avg: %9.4f\n", init_min, init_max, init_avg);
  #else
  printf("Init %9.4f\n", init);
  #endif //MPI_CHOLLA
  #endif //CPU_TIME

  // Evolve the grid, one timestep at a time
  chprintf("Starting calculations.\n");
  while (G.H.t < P.tout)
  // while (G.H.n_step < 20)
  {
    chprintf("n_step: %d \n", G.H.n_step + 1 );
    // get the start time
    start_step = get_time();

    // calculate the timestep
    G.set_dt(dti);

    if (G.H.t + G.H.dt > outtime)
    {
      G.H.dt = outtime - G.H.t;
    }

    // This is not necessary, G.set_dt finds the global max_dti, dt is the same in all processes by now
    // #ifdef MPI_CHOLLA
    // G.H.dt = ReduceRealMin(G.H.dt);
    // #endif

    #ifdef PARTICLES
    //Advance the particles KDK( first step )
    G.Advance_Particles( 1 );
    #endif

    // Advance the grid by one timestep
    dti = G.Update_Hydro_Grid();

    // update the simulation time ( t += dt )
    G.Update_Time();

    #ifdef GRAVITY
    //Compute Gravitational potential for next step
    G.Compute_Gravitational_Potential( &P);
    #endif

    // add one to the timestep count
    G.H.n_step++;

    // set boundary conditions for next time step
    G.Set_Boundary_Conditions_All(P);

    #ifdef PARTICLES
    //Advance the particles KDK( second step )
    G.Advance_Particles( 2 );
    #endif

    #ifdef CPU_TIME
    G.Timer.Print_Times();
    #endif

    // get the time to compute the total timestep
    stop_step = get_time();
    stop_total = get_time();
    G.H.t_wall = stop_total-start_total;
    #ifdef MPI_CHOLLA
    G.H.t_wall = ReduceRealMax(G.H.t_wall);
    #endif
    chprintf("n_step: %d   sim time: %10.7f   sim timestep: %7.4e  timestep time = %9.3f ms   total time = %9.4f s\n\n",
      G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);

    if (G.H.t == outtime || G.H.Output_Now )
    {
      #ifdef OUTPUT
      /*output the grid data*/
      WriteData(G, P, nfile);
      // add one to the output file count
      nfile++;
      #endif //OUTPUT
      // update to the next output time
      outtime += P.outstep;
    }

    #ifdef CPU_TIME
    G.Timer.n_steps += 1;
    #endif

    #ifdef COSMOLOGY
    if ( G.Cosmo.current_a >= G.Cosmo.scale_outputs[G.Cosmo.n_outputs-1] ) {
      chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
      break;
    }
    #endif
/*
    // check for failures
    for (int i=G.H.n_ghost; i<G.H.nx-G.H.n_ghost; i++) {
      for (int j=G.H.n_ghost; j<G.H.ny-G.H.n_ghost; j++) {
        for (int k=G.H.n_ghost; k<G.H.nz-G.H.n_ghost; k++) {
          int id = i + j*G.H.nx + k*G.H.nx*G.H.ny;
          if (G.C.density[id] < 0.0 || G.C.density[id] != G.C.density[id]) {
            printf("Failure in cell %d %d %d. Density %e\n", i, j, k, G.C.density[id]);
            #ifdef MPI_CHOLLA
            MPI_Finalize();
            chexit(-1);
            #endif
            exit(0);
          }
        }
      }
    }
*/

  } /*end loop over timesteps*/

  #ifdef CPU_TIME
  G.Timer.Get_Average_Times();
  G.Timer.Print_Average_Times( P );
  #endif

  // free the grid
  G.Reset();

  #ifdef MPI_CHOLLA
  MPI_Finalize();
  #endif /*MPI_CHOLLA*/

  return 0;

}
<commit_msg>limit 11 steps<commit_after>/*! \file main.cpp
 *  \brief Program to run the grid code. */

#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"

#define OUTPUT
//#define CPU_TIME

int main(int argc, char *argv[])
{
  // timing variables
  double start_total, stop_total, start_step, stop_step;
  #ifdef CPU_TIME
  double stop_init, init_min, init_max, init_avg;
  double start_bound, stop_bound, bound_min, bound_max, bound_avg;
  double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
  double init, bound, hydro;
  init = bound = hydro = 0;
  #endif //CPU_TIME

  // start the total time
  start_total = get_time();

  /* Initialize MPI communication */
  #ifdef MPI_CHOLLA
  InitializeChollaMPI(&argc, &argv);
  #endif /*MPI_CHOLLA*/

  Real dti = 0; // inverse time step, 1.0 / dt

  // input parameter variables
  char *param_file;
  struct parameters P;
  int nfile = 0; // number of output files
  Real outtime = 0; // current output time

  // read in command line arguments
  if (argc != 2)
  {
    chprintf("usage: %s <parameter_file>\n", argv[0]);
    chexit(-1);
  } else {
    param_file = argv[1];
  }

  // create the grid
  Grid3D G;

  // read in the parameters
  parse_params (param_file, &P);
  // and output to screen
  chprintf ("Parameter values:  nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
    P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
  chprintf ("Output directory:  %s\n", P.outdir);

  // initialize the grid
  G.Initialize(&P);
  chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);

  // Set initial conditions and calculate first dt
  chprintf("Setting initial conditions...\n");
  G.Set_Initial_Conditions(P);
  chprintf("Initial conditions set.\n");
  // set main variables for Read_Grid inital conditions
  if (strcmp(P.init, "Read_Grid") == 0) {
    dti = C_cfl / G.H.dt;
    outtime += G.H.t;
    nfile = P.nfile*P.nfull;
  }

  #ifdef CPU_TIME
  G.Timer.Initialize();
  #endif

  #ifdef GRAVITY
  G.Initialize_Gravity(&P);
  #endif

  #ifdef PARTICLES
  G.Initialize_Particles(&P);
  #endif

  #ifdef COSMOLOGY
  G.Initialize_Cosmology(&P);
  #endif

  #ifdef COOLING_GRACKLE
  G.Initialize_Grackle(&P);
  #endif

  #ifdef GRAVITY
  G.Compute_Gravitational_Potential( &P);
  #endif

  // set boundary conditions (assign appropriate values to ghost cells)
  chprintf("Setting boundary conditions...\n");
  G.Set_Boundary_Conditions_All(P);
  chprintf("Boundary conditions set.\n");

  #ifdef PARTICLES
  G.Get_Particles_Accelration();
  #endif

  chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
  chprintf("Ratio of specific heats gamma = %f\n",gama);
  chprintf("Nstep = %d  Timestep = %f  Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);

  #ifdef OUTPUT
  if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
  // write the initial conditions to file
  chprintf("Writing initial conditions to file...\n");
  WriteData(G, P, nfile);
  }
  // add one to the output file count
  nfile++;
  #endif //OUTPUT
  // increment the next output time
  outtime += P.outstep;

  #ifdef CPU_TIME
  stop_init = get_time();
  init = stop_init - start_total;
  #ifdef MPI_CHOLLA
  init_min = ReduceRealMin(init);
  init_max = ReduceRealMax(init);
  init_avg = ReduceRealAvg(init);
  chprintf("Init  min: %9.4f  max: %9.4f  avg: %9.4f\n", init_min, init_max, init_avg);
  #else
  printf("Init %9.4f\n", init);
  #endif //MPI_CHOLLA
  #endif //CPU_TIME

  // Evolve the grid, one timestep at a time
  chprintf("Starting calculations.\n");
  while (G.H.t < P.tout)
  // while (G.H.n_step < 20)
  {
    chprintf("n_step: %d \n", G.H.n_step + 1 );
    // get the start time
    start_step = get_time();

    // calculate the timestep
    G.set_dt(dti);

    if (G.H.t + G.H.dt > outtime)
    {
      G.H.dt = outtime - G.H.t;
    }

    // This is not necessary, G.set_dt finds the global max_dti, dt is the same in all processes by now
    // #ifdef MPI_CHOLLA
    // G.H.dt = ReduceRealMin(G.H.dt);
    // #endif

    #ifdef PARTICLES
    //Advance the particles KDK( first step )
    G.Advance_Particles( 1 );
    #endif

    // Advance the grid by one timestep
    dti = G.Update_Hydro_Grid();

    // update the simulation time ( t += dt )
    G.Update_Time();

    #ifdef GRAVITY
    //Compute Gravitational potential for next step
    G.Compute_Gravitational_Potential( &P);
    #endif

    // add one to the timestep count
    G.H.n_step++;

    // set boundary conditions for next time step
    G.Set_Boundary_Conditions_All(P);

    #ifdef PARTICLES
    //Advance the particles KDK( second step )
    G.Advance_Particles( 2 );
    #endif

    #ifdef CPU_TIME
    G.Timer.Print_Times();
    #endif

    // get the time to compute the total timestep
    stop_step = get_time();
    stop_total = get_time();
    G.H.t_wall = stop_total-start_total;
    #ifdef MPI_CHOLLA
    G.H.t_wall = ReduceRealMax(G.H.t_wall);
    #endif
    chprintf("n_step: %d   sim time: %10.7f   sim timestep: %7.4e  timestep time = %9.3f ms   total time = %9.4f s\n\n",
      G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);

    if (G.H.t == outtime || G.H.Output_Now )
    {
      #ifdef OUTPUT
      /*output the grid data*/
      WriteData(G, P, nfile);
      // add one to the output file count
      nfile++;
      #endif //OUTPUT
      // update to the next output time
      outtime += P.outstep;
    }

    #ifdef CPU_TIME
    G.Timer.n_steps += 1;
    #endif

    if ( G.H.n_step == 11) break;

    #ifdef COSMOLOGY
    if ( G.Cosmo.current_a >= G.Cosmo.scale_outputs[G.Cosmo.n_outputs-1] ) {
      chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
      break;
    }
    #endif
/*
    // check for failures
    for (int i=G.H.n_ghost; i<G.H.nx-G.H.n_ghost; i++) {
      for (int j=G.H.n_ghost; j<G.H.ny-G.H.n_ghost; j++) {
        for (int k=G.H.n_ghost; k<G.H.nz-G.H.n_ghost; k++) {
          int id = i + j*G.H.nx + k*G.H.nx*G.H.ny;
          if (G.C.density[id] < 0.0 || G.C.density[id] != G.C.density[id]) {
            printf("Failure in cell %d %d %d. Density %e\n", i, j, k, G.C.density[id]);
            #ifdef MPI_CHOLLA
            MPI_Finalize();
            chexit(-1);
            #endif
            exit(0);
          }
        }
      }
    }
*/

  } /*end loop over timesteps*/

  #ifdef CPU_TIME
  G.Timer.Get_Average_Times();
  G.Timer.Print_Average_Times( P );
  #endif

  // free the grid
  G.Reset();

  #ifdef MPI_CHOLLA
  MPI_Finalize();
  #endif /*MPI_CHOLLA*/

  return 0;

}
<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>

#include "qpp.h"
#include "internal.h"

using namespace std;
using namespace qpp;
using namespace qpp::types;

// TODO: add functions.h, or similar, for matrix functional calculus function pointers;
// TODO: add sqrtm, absm

//int main(int argc, char **argv)
int main()
{
	_init(); // this will be done automatically in the framework

	Eigen::MatrixXd _a = Eigen::MatrixXd::Random(4, 4);
	save(_a, "/Users/vlad/tmp/_a");

	Eigen::MatrixXd a = load<Eigen::MatrixXd>("/Users/vlad/tmp/_a");

	std::vector<size_t> subsys =
	{ 2, 2 };
	std::vector<size_t> perm =
	{ 1, 0 };

	cout << "Error in norm difference load/save: " << norm(_a - a) << endl;

	disp(ptrace2(a,
	{ 2, 2 }));
	cout << endl << endl;
	disp(ptrace(a,
	{ 0 },
	{ 2, 2 }));
	cout << endl << endl;

	imat kt(3, 1);
	kt << 0, 0, 1;

	imat bt(1, 3);
	bt << 0, 1, 0;

	disp(kron(kt, bt).template cast<double>());
	cout << endl << endl;

	disp(kron(bt, kt));
	cout << endl << endl;

	disp(bt * kt);
	cout << endl << endl;

	size_t dim = 10;
	cout << "generating random unitary..." << endl;
	cmat u = rand_unitary(dim);
	cout << "done generating random unitary";
	disp(u);
	cout << endl;
	double normdiff = norm((cmat) (u * adjoint(u) - cmat::Identity(dim, dim)));
	cout << "Norm difference: " << normdiff << endl;
	disp(normdiff, std::cout, 18);
	if (normdiff > std::numeric_limits<double>::epsilon())
		cout << "YES";
	else
		cout << "NO";
	cout << endl << endl;
	cout << "The eigenvalues of u are: " << endl;
	disp(transpose(evals(u)));
	cout << endl << endl;

	cout << "The absolute values of the eigenvalues of u are: " << endl;
	disp(abs(transpose(evals(u))));
	cout << endl << endl;

	// matrix functional calculus
	cmat mat(2, 2);
	mat << 1. + ct::ii, 2, 3, 4;
	disp(logm(expm(mat)), std::cout, 16);
	cout << endl << endl;
}
<commit_msg>commit<commit_after>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>

#include "qpp.h"
#include "internal.h"

using namespace std;
using namespace qpp;
using namespace qpp::types;

// TODO: add functions.h, or similar, for matrix functional calculus function pointers;
// TODO: add sqrtm, absm

//int main(int argc, char **argv)
int main()
{
	_init(); // this will be done automatically in the framework

	Eigen::MatrixXd _a = Eigen::MatrixXd::Random(4, 4);
	save(_a, "/Users/vlad/tmp/_a");

	Eigen::MatrixXd a = load<Eigen::MatrixXd>("/Users/vlad/tmp/_a");

	std::vector<size_t> subsys =
	{ 2, 2 };
	std::vector<size_t> perm =
	{ 1, 0 };

	cout << "Error in norm difference load/save: " << norm(_a - a) << endl;

	disp(ptrace2(a,
	{ 2, 2 }));
	cout << endl << endl;
	disp(ptrace(a,
	{ 0 },
	{ 2, 2 }));
	cout << endl << endl;

	imat kt(3, 1);
	kt << 0, 0, 1;

	imat bt(1, 3);
	bt << 0, 1, 0;

	disp(kron(kt, bt).template cast<double>());
	cout << endl << endl;

	disp(kron(bt, kt));
	cout << endl << endl;

	disp(bt * kt);
	cout << endl << endl;

	size_t dim = 10;
	cout << "generating random unitary..." << endl;
	cmat u = rand_unitary(dim);
	cout << "done generating random unitary";
	disp(u);
	cout << endl;
	double normdiff = norm((cmat) (u * adjoint(u) - cmat::Identity(dim, dim)));
	cout << "Norm difference: " << normdiff << endl;
	disp(normdiff, std::cout, 18);
	if (normdiff > std::numeric_limits<double>::epsilon())
		cout << "YES";
	else
		cout << "NO";
	cout << endl << endl;
	cout << "The eigenvalues of u are: " << endl;
	disp(transpose(evals(u)));
	cout << endl << endl;

	cout << "The absolute values of the eigenvalues of u are: " << endl;
	disp(abs(transpose(evals(u))));
	cout << endl << endl;

	// matrix functional calculus
	cmat mat(2, 2);
	mat << 1. + ct::ii, 2, 3, 4;
	disp(mat);
	cout<<endl<<endl;
	disp(expm(logm(mat)), std::cout, 16);
	cout << endl << endl;
}
<|endoftext|>


<commit_before>#include "StdAfx.h"

/*
    ultracomm -- main
*/

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

    int exit_status;
    const bool blocking = true;  // block until ulterius commands have succeeded
    const bool lazy_param_set = true;  // Do not set ultrasound params if they already have the correct value.
    ofstream logfile;    // Log file.
    SYSTEMTIME lt;

    try {
        // Get command line and config file options.
        UltracommOptions uopt = UltracommOptions::UltracommOptions(argc, argv);
        int verbose = uopt.opt["verbose"].as<int>();

        std::string outname = uopt.opt["output"].as<string>();
        std::string logname = outname + ".log.txt";
        logfile.open(logname, ios::out | ios::binary);
        if (logfile.fail())
        {
            throw std::runtime_error("Could not open logfile.");
        }
        GetSystemTime(&lt);
        logfile << "main: Connecting to ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();

        // Connect to Ultrasonix and set parameters.
        Ultracomm uc = Ultracomm::Ultracomm(uopt, logfile);
        GetSystemTime(&lt);
        logfile << "main: Setting parameters. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        uc.set_int_imaging_params(lazy_param_set);
        uc.check_int_imaging_params();
        uc.freeze(blocking);

        if (uopt.opt.count("dump-params")) {
            uc.dump_params();
        }
        else if (! uopt.opt.count("freeze-only")) {
            // Start acquisition, wait for user interaction, then stop.
//            uc.unset_data_to_acquire(blocking);
            uc.set_data_to_acquire(blocking);
            //uc.freeze(blocking);
            uc.unfreeze(blocking);
            if (! uopt.opt.count("named-pipe")) {
                cout << "*** Acquiring images. Press any key to stop. ***\n";
                _getch();  // Wait for user input.
            }
            else {
                if (verbose) {
                    cout << "*** Acquiring images. Waiting on named pipe. ***\n";
                }
                block_on_named_pipe();
                if (verbose) {
                    cout << "*** Read data from named pipe. ***\n";
                }
            }
            uc.freeze(blocking);
            // When unset_data_to_acquire() is not used, we often get several frames
            // of repeat data in our ulterius callback.
            uc.unset_data_to_acquire(blocking);
            if (uopt.opt["acqmode"].as<string>() == "buffered") {
                // Get data from Ultrasonix and save to file.
                uc.save_data();
            }
        }
        Sleep(200);  // allow time for callbacks to finish

        // We're done.
        if (uopt.opt.count("delay-exit")) {
            cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
            _getch();  // Wait for user input.
        }
        uc.disconnect();
        GetSystemTime(&lt);
        logfile << "main: disconnected from ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        exit_status = EXIT_SUCCESS;
    }
    catch(const UltracommOptions::WantsToStop& e) {   // --help or --version
        e.what();   // Doesn't do much besides avoid unused variable warning.
        exit_status = EXIT_SUCCESS;
    }
    catch(const UltracommOptions::WantsToStopWithDelay& e) {
        e.what();   // Doesn't do much besides avoid unused variable warning.
        cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
        _getch();  // Wait for user input.
        exit_status = EXIT_SUCCESS;
    }
    catch(const po::required_option& e) {
        cerr << "Missing required option: " << e.what() << "\n";
        exit_status = MISSING_REQUIRED_OPTION_ERROR;
    }
    catch(const UltracommOptions::MissingOptionsFileError& e) {
        cerr << e.what() << "\n";
        exit_status = MISSING_OPTIONS_FILE_ERROR;
    }
    catch(const UltracommOptions::UnimplementedFeatureError& e) {
        cerr << e.what() << "\n";
        exit_status = UNIMPLEMENTED_FEATURE_ERROR;
    }
    catch(const Ultracomm::ConnectionError& e) {
        cerr << e.what() << "\n";
        exit_status = CONNECTION_ERROR;
    }
    catch(const exception& e) {
        logfile << "main: Caught generic exception. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        cerr << "Exception: " << e.what() << "\n";
        exit_status = UNKNOWN_ERROR;
    }
    catch(...) {
        logfile << "main: Caught unhandled exception. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        cerr << "Unhandled exception of unknown type!\n";
        exit_status = UNKNOWN_ERROR;
    }

    GetSystemTime(&lt);
    logfile << "main: Exiting. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
    logfile.flush();
    return exit_status;
}

<commit_msg>Set ErrorMode to swallow errors at program end.<commit_after>#include "StdAfx.h"

/*
    ultracomm -- main
*/

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

    int exit_status;

    /* Temporary hack to swallow access violation errors at program end. */
    SetErrorMode(SetErrorMode(0) | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);

    const bool blocking = true;  // block until ulterius commands have succeeded
    const bool lazy_param_set = true;  // Do not set ultrasound params if they already have the correct value.
    ofstream logfile;    // Log file.
    SYSTEMTIME lt;

    try {
        // Get command line and config file options.
        UltracommOptions uopt = UltracommOptions::UltracommOptions(argc, argv);
        int verbose = uopt.opt["verbose"].as<int>();

        std::string outname = uopt.opt["output"].as<string>();
        std::string logname = outname + ".log.txt";
        logfile.open(logname, ios::out | ios::binary);
        if (logfile.fail())
        {
            throw std::runtime_error("Could not open logfile.");
        }
        GetSystemTime(&lt);
        logfile << "main: Connecting to ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();

        // Connect to Ultrasonix and set parameters.
        Ultracomm uc = Ultracomm::Ultracomm(uopt, logfile);
        GetSystemTime(&lt);
        logfile << "main: Setting parameters. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        uc.set_int_imaging_params(lazy_param_set);
        uc.check_int_imaging_params();
        uc.freeze(blocking);

        if (uopt.opt.count("dump-params")) {
            uc.dump_params();
        }
        else if (! uopt.opt.count("freeze-only")) {
            // Start acquisition, wait for user interaction, then stop.
//            uc.unset_data_to_acquire(blocking);
            uc.set_data_to_acquire(blocking);
            //uc.freeze(blocking);
            uc.unfreeze(blocking);
            if (! uopt.opt.count("named-pipe")) {
                cout << "*** Acquiring images. Press any key to stop. ***\n";
                _getch();  // Wait for user input.
            }
            else {
                if (verbose) {
                    cout << "*** Acquiring images. Waiting on named pipe. ***\n";
                }
                block_on_named_pipe();
                if (verbose) {
                    cout << "*** Read data from named pipe. ***\n";
                }
            }
            uc.freeze(blocking);
            // When unset_data_to_acquire() is not used, we often get several frames
            // of repeat data in our ulterius callback.
            uc.unset_data_to_acquire(blocking);
            if (uopt.opt["acqmode"].as<string>() == "buffered") {
                // Get data from Ultrasonix and save to file.
                uc.save_data();
            }
        }
        Sleep(200);  // allow time for callbacks to finish

        // We're done.
        if (uopt.opt.count("delay-exit")) {
            cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
            _getch();  // Wait for user input.
        }
        uc.disconnect();
        GetSystemTime(&lt);
        logfile << "main: disconnected from ultracomm. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        exit_status = EXIT_SUCCESS;
    }
    catch(const UltracommOptions::WantsToStop& e) {   // --help or --version
        e.what();   // Doesn't do much besides avoid unused variable warning.
        exit_status = EXIT_SUCCESS;
    }
    catch(const UltracommOptions::WantsToStopWithDelay& e) {
        e.what();   // Doesn't do much besides avoid unused variable warning.
        cout << "*** ultracomm finished. Press any key to exit the program. ***\n";
        _getch();  // Wait for user input.
        exit_status = EXIT_SUCCESS;
    }
    catch(const po::required_option& e) {
        cerr << "Missing required option: " << e.what() << "\n";
        exit_status = MISSING_REQUIRED_OPTION_ERROR;
    }
    catch(const UltracommOptions::MissingOptionsFileError& e) {
        cerr << e.what() << "\n";
        exit_status = MISSING_OPTIONS_FILE_ERROR;
    }
    catch(const UltracommOptions::UnimplementedFeatureError& e) {
        cerr << e.what() << "\n";
        exit_status = UNIMPLEMENTED_FEATURE_ERROR;
    }
    catch(const Ultracomm::ConnectionError& e) {
        cerr << e.what() << "\n";
        exit_status = CONNECTION_ERROR;
    }
    catch(const exception& e) {
        logfile << "main: Caught generic exception. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        cerr << "Exception: " << e.what() << "\n";
        exit_status = UNKNOWN_ERROR;
    }
    catch(...) {
        logfile << "main: Caught unhandled exception. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
        logfile.flush();
        cerr << "Unhandled exception of unknown type!\n";
        exit_status = UNKNOWN_ERROR;
    }

    GetSystemTime(&lt);
    logfile << "main: Exiting. Localtime: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << "." << lt.wMilliseconds << "\n";
    logfile.flush();
    return exit_status;
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2015, Mike Tzou
All rights reserved.

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

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

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

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "stdafx.h"
#include "main.h"

#define PLUGIN_NAME "XSPF Playlist"
#define PLUGIN_VERSION "2.1"
DECLARE_COMPONENT_VERSION
(
	PLUGIN_NAME , PLUGIN_VERSION ,

	PLUGIN_NAME"\n"
	"Compiled on: "__DATE__"\n"
	"https://github.com/Chocobo1/foo_xspf_1\n"
	"This plugin is released under BSD 3-Clause license\n"
	"\n"
	"Mike Tzou (Chocobo1)\n"
	"\n"
	"This plugin links statically with the following open source library:\n"
	"TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n"
);

const char *xspf::get_extension()
{
	return "xspf";
}

bool xspf::is_our_content_type( const char *p_content_type )
{
	const char mime[] = "application/xspf+xml";
	if( strcmp( p_content_type , mime ) != 0 )
		return false;
	return true;
}

bool xspf::is_associatable()
{
	return true;
}

bool xspf::can_write()
{
	return true;
}

void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort )
{
	// avoid file open loop
	if( file_list.find( p_path ) != file_list.cend() )
		return;
	file_list.emplace( p_path );

	pfc::hires_timer t;
	t.start();
	try
	{
		p_callback->on_progress( p_path );
		open_helper( p_path , p_file , p_callback , p_abort );
	}
	catch( ... )
	{
		file_list.erase( p_path );
		throw;
	}
	console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path );

	file_list.erase( p_path );
	return;
}

void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort )
{
	pfc::hires_timer t;
	t.start();
	write_helper( p_path , p_file , p_data , p_abort );
	console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path );

	return;
}
<commit_msg>version bump<commit_after>/*
Copyright (c) 2015, Mike Tzou
All rights reserved.

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

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

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

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "stdafx.h"
#include "main.h"

#define PLUGIN_NAME "XSPF Playlist"
#define PLUGIN_VERSION "2.2"
DECLARE_COMPONENT_VERSION
(
	PLUGIN_NAME , PLUGIN_VERSION ,

	PLUGIN_NAME"\n"
	"Compiled on: "__DATE__"\n"
	"https://github.com/Chocobo1/foo_xspf_1\n"
	"This plugin is released under BSD 3-Clause license\n"
	"\n"
	"Mike Tzou (Chocobo1)\n"
	"\n"
	"This plugin links statically with the following open source library:\n"
	"TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n"
);

const char *xspf::get_extension()
{
	return "xspf";
}

bool xspf::is_our_content_type( const char *p_content_type )
{
	const char mime[] = "application/xspf+xml";
	if( strcmp( p_content_type , mime ) != 0 )
		return false;
	return true;
}

bool xspf::is_associatable()
{
	return true;
}

bool xspf::can_write()
{
	return true;
}

void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort )
{
	// avoid file open loop
	if( file_list.find( p_path ) != file_list.cend() )
		return;
	file_list.emplace( p_path );

	pfc::hires_timer t;
	t.start();
	try
	{
		p_callback->on_progress( p_path );
		open_helper( p_path , p_file , p_callback , p_abort );
	}
	catch( ... )
	{
		file_list.erase( p_path );
		throw;
	}
	console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path );

	file_list.erase( p_path );
	return;
}

void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort )
{
	pfc::hires_timer t;
	t.start();
	write_helper( p_path , p_file , p_data , p_abort );
	console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path );

	return;
}
<|endoftext|>


<commit_before>#include <time.h>

#include "../include/PSATsolver.hpp"
#include "../include/TestGenerator.hpp"

using namespace std;
using namespace arma;

void test(int N, int k, int n, double step, int begin, int end, string prefix);

int main(int argc, char** argv)
{
    bool v;
    if(argc < 20)
        v = true;
    else
        v = false;

    if (argc < 2)
    {
        std::cout << "I need a input file " << "\n";
        return -1;
    }

    if((string) argv[1] == "--maketest")
    {
        TestGenerator t(atoi(argv[2]));
        t.createAll(atoi(argv[3]),
                    atoi(argv[4]),
                    atoi(argv[5]),
                    atof(argv[6]),
                    atoi(argv[7]),
                    atoi(argv[8]),
                    argv[9]);
        return 1;
    }

    if((string) argv[1] == "--test")
    {
        test(atoi(argv[1]),
             atoi(argv[2]),
             atoi(argv[3]),
             atof(argv[4]),
             atoi(argv[5]),
             atoi(argv[6]),
             argv[7]);
    }

    int** matrix;
    int**& M = matrix;
    vector<double> pi;
    double time;

    PSATsolver::solve(M, pi, &time, argv[1], true);

    return 1;
}

void test(int N,     int k,   int n,         double step,
          int begin, int end, string prefix)
{
    int** matrix;
    int**& M = matrix;
    vector<double> pi;
    ofstream output;
    output.open("./data/time.txt");
    output.open("./data/sat.txt");
    for(double i = begin; i <= end; i+=step)
    {
        double y = 0;
        double sat = 0;
        for(int j = 0; j < N; j++)
        {
            double time = 0;
            int m = round(n*i);
            string file = prefix;
            file += "_K" + to_string(k)
                 +  "_N" + to_string(n)
                 +  "_M" + to_string(m)
                 +  "_"  + to_string(j)
                 +  ".pcnf";
            cout << file << ": ";

            PSATsolver::solve(M, pi, &time,
                             (char*) file.c_str(), false);

            if (pi[0] == 1)
            {
                sat += 1/n;
                cout << "sat, time: ";
            }
            else cout << "unsat, time: ";

            cout << time << "\n";
            y += time/N;
        }
        output << i << " " << y << "\n";
        cout <<"media: "<< y << "\n";
    }
    output.close();
}
<commit_msg>improved testing<commit_after>#include <time.h>

#include "../include/PSATsolver.hpp"
#include "../include/TestGenerator.hpp"

using namespace std;
using namespace arma;

void test(int N, int k, int n, double step, int begin, int end, string prefix);

int main(int argc, char** argv)
{
    bool v;
    if(argc < 20)
        v = true;
    else
        v = false;

    if (argc < 2)
    {
        std::cout << "I need a input file " << "\n";
        return -1;
    }

    if((string) argv[1] == "--maketest")
    {
        TestGenerator t(atoi(argv[2]));
        t.createAll(atoi(argv[3]),
                    atoi(argv[4]),
                    atoi(argv[5]),
                    atof(argv[6]),
                    atoi(argv[7]),
                    atoi(argv[8]),
                    argv[9]);
        return 1;
    }

    if((string) argv[1] == "--test")
    {
        test(atoi(argv[2]),
             atoi(argv[3]),
             atoi(argv[4]),
             atof(argv[5]),
             atoi(argv[6]),
             atoi(argv[7]),
             argv[8]);
    }

    int** matrix;
    int**& M = matrix;
    vector<double> pi;
    double time;

    PSATsolver::solve(M, pi, &time, argv[1], true);

    return 1;
}

void test(int N,     int k,   int n,         double step,
          int begin, int end, string prefix)
{
    int** matrix;
    int**& M = matrix;
    vector<double> pi;
    ofstream outtime;
    ofstream outsat;
    outtime.open("./data/time.txt");
    outsat.open("./data/sat.txt");
    for(double i = begin; i <= end; i+=step)
    {
        double y = 0;
        double sat = 0;
        for(int j = 0; j < N; j++)
        {
            double time = 0;
            int m = round(n*i);
            string file = prefix;
            file += "_K" + to_string(k)
                 +  "_N" + to_string(n)
                 +  "_M" + to_string(m)
                 +  "_"  + to_string(j)
                 +  ".pcnf";
            cout << file << ": ";

            PSATsolver::solve(M, pi, &time,
                             (char*) file.c_str(), false);

            if (pi[0] == 1)
            {
                sat += 1.0/N;
                cout << "sat, time: ";
            }
            else cout << "unsat, time: ";

            cout << time << "\n";
            y += time/N;
        }
        outtime << i << " " << y << "\n";
        outsat << i << " " << sat << "\n";
        cout <<"media tempo: "<< y << "\n";
        cout <<"media sat: " << sat << "\n";
    }
    outtime.close();
    outsat.close();
}
<|endoftext|>


<commit_before>#include "gl.hpp"
#include "program.hpp"
#include "scene.hpp"
#include "camera.hpp"

#include <cstdlib>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include <emscripten/emscripten.h>
#include <emscripten/html5.h>

static void iterate();

static GLFWCALL void on_key(int key, int action);
static EM_BOOL on_em_mousemove(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data);

GLuint mvp_uniform;
GLuint local_modelview_uniform;

static GLuint texture_uniform;

static bool keys[GLFW_KEY_LAST];

static Scene scene;

static Camera camera(scene);
static float camera_angles_x = 0;

static Camera camera1(scene);
static Camera camera2(scene);
static Camera camera3(scene);

static Model *protagonist;
static Model *suzanne;
static Model *teapot;
static Model *bunny;

static Object *protagonist1;
static Object *suzanne1;
static Object *teapot1;
static Object *bunny1;

int main()
{
  if (!glfwInit())
    exit(EXIT_FAILURE);

  if (!glfwOpenWindow(640, 480, 8, 8, 8, 8, 16, 0, GLFW_WINDOW))
  {
    glfwTerminate();
    exit(EXIT_FAILURE);
  }

  if (glewInit() != GLEW_OK)
  {
    glfwCloseWindow();
    glfwTerminate();
    exit(EXIT_FAILURE);
  }

  glfwSetKeyCallback(on_key);
  emscripten_set_mousemove_callback(nullptr, nullptr, false, on_em_mousemove);

  Program program("textured");
  program.use();

  mvp_uniform = program.get_uniform_location("mvp");
  local_modelview_uniform = program.get_uniform_location("local_modelview");

  texture_uniform = program.get_uniform_location("texture");
  glUniform1i(texture_uniform, 0);

  camera.projection = glm::perspective(45.0f, (float)640 / (float)480, 0.1f, 10.0f);
  camera.position.z = 2;

  camera1.projection = camera.projection;
  camera1.position.y = 1.5;
  camera1.position.x = -5;
  camera1.angles.y = -90;

  camera2.projection = camera.projection;
  camera2.position.y = 1.5;
  camera2.position.z = -5;
  camera2.angles.y = -180;

  camera3.projection = camera.projection;
  camera3.position.y = -5;
  camera3.angles.x = 90;

  protagonist = new Model("protagonist.obj");
  suzanne = new Model("suzanne.obj");
  teapot = new Model("teapot.obj");
  bunny = new Model("bunny.obj");

  protagonist1 = new Object(*protagonist);
  protagonist1->position.z = 4;

  suzanne1 = new Object(*suzanne);
  suzanne1->position.z = -2;
  suzanne1->position.y = 2;

  teapot1 = new Object(*teapot);
  teapot1->position.x = -2.0;
  teapot1->position.y = 1.0;
  teapot1->angles.y = 45;

  bunny1 = new Object(*bunny);
  bunny1->position.x = 2.0;

  scene << protagonist1
        << suzanne1
        << teapot1
        << bunny1;

  glEnable(GL_DEPTH_TEST);

  glClearColor(1, 1, 1, 0);

  emscripten_set_main_loop(iterate, 0, 1);
}

void iterate()
{
  if (keys[(unsigned char)'W'])
  {
    protagonist1->position.x -= 0.1 * sin(glm::radians(protagonist1->angles.y));
    protagonist1->position.z -= 0.1 * cos(glm::radians(protagonist1->angles.y));
  }

  if (keys[(unsigned char)'S'])
  {
    protagonist1->position.x += 0.1 * sin(glm::radians(protagonist1->angles.y));
    protagonist1->position.z += 0.1 * cos(glm::radians(protagonist1->angles.y));
  }

  if (keys[(unsigned char)'D'])
  {
    protagonist1->position.x += 0.1 * cos(glm::radians(protagonist1->angles.y));
    protagonist1->position.z -= 0.1 * sin(glm::radians(protagonist1->angles.y));
  }

  if (keys[(unsigned char)'A'])
  {
    protagonist1->position.x -= 0.1 * cos(glm::radians(protagonist1->angles.y));
    protagonist1->position.z += 0.1 * sin(glm::radians(protagonist1->angles.y));
  }

  camera.base = protagonist1->transformation()
    * glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 2.0f, 0.0f))
    * glm::rotate(glm::mat4(1.0f), glm::radians(camera_angles_x), glm::vec3(1.0f, 0.0f, 0.0f));

  suzanne1->angles.z = glfwGetTime() * 360 / 4;
  teapot1->angles.x = glfwGetTime() * 360 / 6;
  bunny1->angles.y = glfwGetTime() * 360 / 2;

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glViewport(0, 0, 640 / 2, 480 / 2);
  camera.draw();

  glViewport(640 / 2, 0, 640 / 2, 480 / 2);
  camera1.draw();

  glViewport(640 / 2, 480 / 2, 640 / 2, 480 / 2);
  camera2.draw();

  glViewport(0, 480 / 2, 640 / 2, 480 / 2);
  camera3.draw();
}

GLFWCALL void on_key(int key, int action)
{
  keys[key] = action != GLFW_RELEASE;
}

EM_BOOL on_em_mousemove(__attribute__((unused)) int event_type,
                        const EmscriptenMouseEvent *mouse_event,
                        __attribute__((unused)) void *user_data)
{
  protagonist1->angles.y -= mouse_event->movementX;
  camera_angles_x -= mouse_event->movementY;

  if (protagonist1->angles.y < 0)
    protagonist1->angles.y = 359;
  else
  if (protagonist1->angles.y >= 360)
    protagonist1->angles.y = 0;

  if (camera_angles_x < -90)
    camera_angles_x = -90;
  else
  if (camera_angles_x > 90)
    camera_angles_x = 90;

  return true;
}
<commit_msg>One viewport again<commit_after>#include "gl.hpp"
#include "program.hpp"
#include "scene.hpp"
#include "camera.hpp"

#include <cstdlib>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include <emscripten/emscripten.h>
#include <emscripten/html5.h>

static void iterate();

static GLFWCALL void on_key(int key, int action);
static EM_BOOL on_em_mousemove(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data);

GLuint mvp_uniform;
GLuint local_modelview_uniform;

static GLuint texture_uniform;

static bool keys[GLFW_KEY_LAST];

static Scene scene;

static Camera camera(scene);
static float camera_angles_x = 0;

static Model *protagonist;
static Model *suzanne;
static Model *teapot;
static Model *bunny;

static Object *protagonist1;
static Object *suzanne1;
static Object *teapot1;
static Object *bunny1;

int main()
{
  if (!glfwInit())
    exit(EXIT_FAILURE);

  if (!glfwOpenWindow(640, 480, 8, 8, 8, 8, 16, 0, GLFW_WINDOW))
  {
    glfwTerminate();
    exit(EXIT_FAILURE);
  }

  if (glewInit() != GLEW_OK)
  {
    glfwCloseWindow();
    glfwTerminate();
    exit(EXIT_FAILURE);
  }

  glfwSetKeyCallback(on_key);
  emscripten_set_mousemove_callback(nullptr, nullptr, false, on_em_mousemove);

  Program program("textured");
  program.use();

  mvp_uniform = program.get_uniform_location("mvp");
  local_modelview_uniform = program.get_uniform_location("local_modelview");

  texture_uniform = program.get_uniform_location("texture");
  glUniform1i(texture_uniform, 0);

  camera.projection = glm::perspective(45.0f, (float)640 / (float)480, 0.1f, 10.0f);
  camera.position.z = 2;

  protagonist = new Model("protagonist.obj");
  suzanne = new Model("suzanne.obj");
  teapot = new Model("teapot.obj");
  bunny = new Model("bunny.obj");

  protagonist1 = new Object(*protagonist);
  protagonist1->position.z = 4;

  suzanne1 = new Object(*suzanne);
  suzanne1->position.z = -2;
  suzanne1->position.y = 2;

  teapot1 = new Object(*teapot);
  teapot1->position.x = -2.0;
  teapot1->position.y = 1.0;
  teapot1->angles.y = 45;

  bunny1 = new Object(*bunny);
  bunny1->position.x = 2.0;

  scene << protagonist1
        << suzanne1
        << teapot1
        << bunny1;

  glViewport(0, 0, 640, 480);

  glEnable(GL_DEPTH_TEST);

  glClearColor(1, 1, 1, 0);

  emscripten_set_main_loop(iterate, 0, 1);
}

void iterate()
{
  if (keys[(unsigned char)'W'])
  {
    protagonist1->position.x -= 0.1 * sin(glm::radians(protagonist1->angles.y));
    protagonist1->position.z -= 0.1 * cos(glm::radians(protagonist1->angles.y));
  }

  if (keys[(unsigned char)'S'])
  {
    protagonist1->position.x += 0.1 * sin(glm::radians(protagonist1->angles.y));
    protagonist1->position.z += 0.1 * cos(glm::radians(protagonist1->angles.y));
  }

  if (keys[(unsigned char)'D'])
  {
    protagonist1->position.x += 0.1 * cos(glm::radians(protagonist1->angles.y));
    protagonist1->position.z -= 0.1 * sin(glm::radians(protagonist1->angles.y));
  }

  if (keys[(unsigned char)'A'])
  {
    protagonist1->position.x -= 0.1 * cos(glm::radians(protagonist1->angles.y));
    protagonist1->position.z += 0.1 * sin(glm::radians(protagonist1->angles.y));
  }

  camera.base = protagonist1->transformation()
    * glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 2.0f, 0.0f))
    * glm::rotate(glm::mat4(1.0f), glm::radians(camera_angles_x), glm::vec3(1.0f, 0.0f, 0.0f));

  suzanne1->angles.z = glfwGetTime() * 360 / 4;
  teapot1->angles.x = glfwGetTime() * 360 / 6;
  bunny1->angles.y = glfwGetTime() * 360 / 2;

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  camera.draw();
}

GLFWCALL void on_key(int key, int action)
{
  keys[key] = action != GLFW_RELEASE;
}

EM_BOOL on_em_mousemove(__attribute__((unused)) int event_type,
                        const EmscriptenMouseEvent *mouse_event,
                        __attribute__((unused)) void *user_data)
{
  protagonist1->angles.y -= mouse_event->movementX;
  camera_angles_x -= mouse_event->movementY;

  if (protagonist1->angles.y < 0)
    protagonist1->angles.y = 359;
  else
  if (protagonist1->angles.y >= 360)
    protagonist1->angles.y = 0;

  if (camera_angles_x < -90)
    camera_angles_x = -90;
  else
  if (camera_angles_x > 90)
    camera_angles_x = 90;

  return true;
}
<|endoftext|>


<commit_before>#include <windows.h>
#include <stdio.h>
#include <stdexcept>
#include <vector>
#include "macros.h"
#include "snippets.h"
#include "lib_window.h"
#include "lib_font.h"

using namespace lib;

#define DEBUG_FR_DELAY 1000

#define WM_FR_MESSAGE_UPDATE	(WM_USER + 1)

bool const draw_while_thumb_tracking = false;

struct FontRenderWorker
		: snippets::Worker
{
	struct Job
	{
		size_t index;
		size_t & count_rendered;

		Job(size_t, size_t &);
	};

	FontRenderWorker();

	void setup(HWND, window::BackgroundDC &,
		std::vector<font::EnumFontInfo> &);
	void queue(size_t, size_t &);
	char const * get_msg() const;

private:
	CRITICAL_SECTION mutex;
	HWND hwnd = nullptr;
	window::BackgroundDC * offscreen = nullptr;
	std::vector<font::EnumFontInfo> * fonts;
	std::vector<Job> jobs;
	char const * msg = nullptr;

	void task();
};

LRESULT CALLBACK MainFrameProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE i, HINSTANCE, LPSTR, int iCmdShow)
{
	char const * const class_name = "MAINFRAME";

	window::create_class(class_name, MainFrameProc, i);

	HWND frame = window::create_frame(class_name, i);
	SetWindowText(frame, "monotide-redux");
	window::set_size(frame, 600, 800);
	window::center_to_parent(frame);

	ShowWindow(frame, iCmdShow);
	UpdateWindow(frame);

	MSG msg;
	window::run_main_loop(msg);
	return msg.wParam;
}

void draw_fonts(HWND, HDC, std::vector<font::EnumFontInfo> &,
	size_t, size_t &);
void draw_info(HDC, char const * const info_text=
	"( use mouse-wheel to scroll )");

LRESULT CALLBACK MainFrameProc(HWND h, UINT m, WPARAM w, LPARAM l)
{
	static std::vector<font::EnumFontInfo> ff;
	static UINT rows_per_scroll = 1;
	static window::BackgroundDC offscreen;
	static snippets::ScrollBar vbar(h, SB_VERT);
	static size_t count_rendered = 0;
	static FontRenderWorker font_renderer;

	switch(m)
	{
		default: break;

		case WM_FR_MESSAGE_UPDATE:
		{
			RECT client_rect;
			GetClientRect(h, &client_rect);
			HDC dc = GetDC(h);
			FillRect(dc, &client_rect, (HBRUSH)COLOR_WINDOW);
			draw_info(dc, font_renderer.get_msg());
			ReleaseDC(h, dc);
			return 0;
		}

		case WM_PAINT:
		{
			PAINTSTRUCT ps;
			BeginPaint(h, &ps);

			RECT client_rect;
			GetClientRect(h, &client_rect);
			FillRect(ps.hdc, &client_rect, (HBRUSH)COLOR_WINDOW);
			PostMessage(h, WM_FR_MESSAGE_UPDATE, 0, 0);

			EndPaint(h, &ps);

			// draw_fonts(h, offscreen.handle, ff, vbar.index, count_rendered);
			// offscreen.flip();
			font_renderer.queue(vbar.index, count_rendered);

			return 0;
		}

		case WM_ERASEBKGND:
		{
			InvalidateRect(h, NULL, FALSE);

			// RECT client_rect;
			// GetClientRect(h, &client_rect);
			// HDC dc = GetDC(h);
			// FillRect(dc, &client_rect, (HBRUSH)COLOR_WINDOW);
			// draw_info(dc, "hi");
			// ReleaseDC(h, dc);
			return 0;
		}

		case WM_NCLBUTTONDOWN:
		{
			INT const nHittest = (INT) w;
			// POINTS pts = MAKEPOINTS(l);

			if (!draw_while_thumb_tracking && HTVSCROLL == nHittest)
			{
				// offscreen.clear(0);
				// draw_info(offscreen.handle);
				// offscreen.flip();
			}
			break;
		}

		case WM_VSCROLL:
		{
			int const nScrollCode = (int) LOWORD(w);
			short int const nPos = (short int) HIWORD(w);
			// HWND const hwndScrollBar = (HWND) l;

			switch(nScrollCode)
			{
				case SB_LINEUP:
					if (vbar.scroll(-1))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_LINEDOWN:
					if (vbar.scroll(+1))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_PAGEUP:
					if (vbar.scroll(-rows_per_scroll))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_PAGEDOWN:
					if (vbar.scroll(+count_rendered-1))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_THUMBTRACK:
					vbar.index = nPos;
					if (draw_while_thumb_tracking)
					{
						vbar.update();
						InvalidateRect(h, NULL, TRUE);
					}
					break;

				case SB_THUMBPOSITION:
					vbar.update();
					InvalidateRect(h, NULL, TRUE);
					break;

			}

			return 0;
		}

		case WM_MOUSEWHEEL:
		{
			short const zDelta = (short) HIWORD(w);

			// printf("WM_MOUSEWHEEL %d\n", zDelta);

			if (zDelta > 0 && vbar.scroll(-rows_per_scroll))
				InvalidateRect(h, NULL, TRUE);

			else if (zDelta < 0 && vbar.scroll(+rows_per_scroll))
				InvalidateRect(h, NULL, TRUE);

			return 0;
		}

		case WM_SIZE:
		{
			HDC dc = GetDC(h);
			offscreen = window::BackgroundDC(dc);
			ReleaseDC(h, dc);
			InvalidateRect(h, NULL, TRUE);
			return 0;
		}

		case WM_CREATE:
		{
			SystemParametersInfo(SPI_GETWHEELSCROLLLINES,
				0, &rows_per_scroll, 0);

			HDC dc = GetDC(h);
			font::list_fonts(ff, ANSI_CHARSET, true, dc);
			ReleaseDC(h, dc);

			// printf(" %d fonts found\n", ff.size());

			vbar.set_count(ff.size());

			font_renderer.setup(h, offscreen, ff);
			font_renderer.start();

			return 0;
		}

		case WM_KEYDOWN:
		{
			switch(w)
			{
				case VK_PRIOR:
				{
					int const steps = count_rendered >= rows_per_scroll ?
						rows_per_scroll : count_rendered;
					if (vbar.scroll(-steps))
						InvalidateRect(h, NULL, TRUE);
					break;
				}

				case VK_NEXT:
				{
					int const steps = count_rendered > 1 ?
						count_rendered-1 : count_rendered;
					if (vbar.scroll(steps))
						InvalidateRect(h, NULL, TRUE);
					break;
				}

				case VK_ESCAPE:
					SendMessage(h, WM_CLOSE, 0, 0);
					break;

				case VK_F5:
					InvalidateRect(h, NULL, TRUE);
					UpdateWindow(h);
					break;
			}
			return 0;
		}

		case WM_CLOSE:
			DestroyWindow(h);
			return 0;

		case WM_DESTROY:
			font_renderer.stop();
			font_renderer.wait(1500);
			PostQuitMessage(0);
			return 0;
	}
	return DefWindowProc(h, m, w, l);
}

void draw_fonts(HWND h, HDC dc, std::vector<font::EnumFontInfo> & ff,
		size_t skip, size_t & count_rendered)
{
	HBRUSH const frame_brush = (HBRUSH) GetStockObject(DC_BRUSH);
	SIZE const frame_extra = {3, 2};
	SIZE const padding = {8, 64};
	SIZE client_size;
	lib::window::get_inner_size(h, client_size);
	SIZE const cutoff = {
		client_size.cx - padding.cx,
		client_size.cy - padding.cy};

	count_rendered = 0;
	int y = 0;

	for (size_t i=skip; i<ff.size(); ++i, ++count_rendered)
	{
		char const * text = (char const *) ff[i].elfe.elfFullName;
		size_t const text_len = strlen(text);

		lib::font::EnumFontInfoLoader efil(dc, ff[i]);

		RECT tr = {padding.cx, padding.cy + y, 0, 0};
		snippets::calc_text_rect_2(tr, dc, text, text_len);

		int const next_y = tr.bottom - padding.cy + frame_extra.cy + 1;

		if (next_y > cutoff.cy) break;

		InflateRect(&tr, frame_extra.cx, frame_extra.cy);
		// SetDCBrushColor(dc, RGB(200,80,80));
		SetDCBrushColor(dc, RGB(100,100,100));
		FrameRect(dc, &tr, frame_brush);

		RECT rc = {padding.cx, padding.cy + y, 0, 0};
		// lib::font::draw_font_label(dc, rc, ff[i]);
		// SetBkColor(dc, RGB(10,10,10));
		// SetTextColor(dc, RGB(200,200,200));
		ExtTextOut(dc, rc.left, rc.top,
			0, nullptr, text, text_len, nullptr);

		y = next_y;
	}
}

void quick_draw(HDC dc, int x, int y, char const * text, size_t text_len, int text_height, COLORREF text_color)
{
	HFONT hf = CreateFont(text_height, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_SWISS, nullptr);

	SaveDC(dc);
	SetBkMode(dc, TRANSPARENT);
	SetTextColor(dc, text_color);
	SelectObject(dc, hf);
	TextOut(dc, x, y, text, text_len);
	RestoreDC(dc, -1);

	DeleteObject(hf);
}

void draw_info(HDC dc, char const * const info_text)
{
	size_t const info_text_len = strlen(info_text);
	// COLORREF const text_color = RGB(200,100,100);
	COLORREF const text_color = RGB(100,100,100);

	SIZE client_size;
	lib::window::get_inner_size(WindowFromDC(dc), client_size);

	quick_draw(dc, 8, 8, info_text, info_text_len, 42, text_color);
}

FontRenderWorker::Job::Job(size_t index, size_t & count_rendered)
		: index(index), count_rendered(count_rendered)
{
}

FontRenderWorker::FontRenderWorker()
{
	InitializeCriticalSection(&mutex);
	// mutex = CreateMutex(nullptr, FALSE, nullptr);
	// if (!mutex) throw std::runtime_error("FontRenderWorker : unable to create mutex");
}

void FontRenderWorker::task()
{
	bool skip = true;

	size_t jobs_dropped = 0;

	size_t index = 0;
	size_t * count_rendered = nullptr;

	printf(" [ font renderer %08x ] tick\n", (size_t) this);

	EnterCriticalSection(&mutex);
	if (!jobs.empty())
	{
		if (!msg || !*msg) msg = "rendering...";
		else msg = "still rendering... ( stop scrolling! :)";
		PostMessage(hwnd, WM_FR_MESSAGE_UPDATE, 0, 0);

		skip = false;
		jobs_dropped = jobs.size() - 1;
		index = jobs.back().index;
		count_rendered = &jobs.back().count_rendered;
		jobs.clear();
	}
	LeaveCriticalSection(&mutex);

	if (skip)
	{
		msg = "";

		offscreen->flip();

		Sleep(100);

		return;
	}

	printf(" [ jobs dropped ] %d\n", jobs_dropped);

#ifdef DEBUG_FR_DELAY
	Sleep(DEBUG_FR_DELAY);
#endif

	offscreen->clear(0);
	draw_fonts(hwnd, offscreen->handle, *fonts, index, *count_rendered);
	// offscreen->flip();
}

void FontRenderWorker::setup(HWND hwnd, window::BackgroundDC & offscreen,
		std::vector<font::EnumFontInfo> & fonts)
{
	EnterCriticalSection(&mutex);
	this->hwnd = hwnd;
	this->offscreen = &offscreen;
	this->fonts = &fonts;
	LeaveCriticalSection(&mutex);
}

void FontRenderWorker::queue(size_t index, size_t & count_rendered)
{
	EnterCriticalSection(&mutex);
	jobs.push_back(Job(index, count_rendered));
	LeaveCriticalSection(&mutex);
}

char const * FontRenderWorker::get_msg() const
{
	return msg ? msg : "";
}

<commit_msg>just fiddling around; it's getting messy<commit_after>#include <windows.h>
#include <stdio.h>
#include <stdexcept>
#include <vector>
#include "macros.h"
#include "snippets.h"
#include "lib_window.h"
#include "lib_font.h"

#define WM_FR_MESSAGE_UPDATE	(WM_USER + 1)

using namespace lib;

// #define DEBUG_FR_DELAY 1000

bool const draw_while_thumb_tracking = true;

struct FontRenderWorker
		: snippets::Worker
{
	struct Job
	{
		size_t index;
		size_t & count_rendered;

		Job(size_t, size_t &);
	};

	FontRenderWorker();

	void setup(HWND, window::BackgroundDC &,
		std::vector<font::EnumFontInfo> &);
	void queue(size_t, size_t &);
	char const * get_msg() const;

private:
	CRITICAL_SECTION mutex;
	HWND hwnd = nullptr;
	window::BackgroundDC * offscreen = nullptr;
	std::vector<font::EnumFontInfo> * fonts;
	std::vector<Job> jobs;
	char const * msg = nullptr;

	void task();
};

LRESULT CALLBACK MainFrameProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE i, HINSTANCE, LPSTR, int iCmdShow)
{
	char const * const class_name = "MAINFRAME";

	window::create_class(class_name, MainFrameProc, i);

	HWND frame = window::create_frame(class_name, i);
	SetWindowText(frame, "monotide-redux");
	window::set_size(frame, 600, 800);
	window::center_to_parent(frame);

	ShowWindow(frame, iCmdShow);
	UpdateWindow(frame);

	MSG msg;
	window::run_main_loop(msg);
	return msg.wParam;
}

void draw_fonts(HWND, HDC, std::vector<font::EnumFontInfo> &,
	size_t, size_t &);
void draw_info(HDC, char const * const info_text=
	"( use mouse-wheel to scroll )");

LRESULT CALLBACK MainFrameProc(HWND h, UINT m, WPARAM w, LPARAM l)
{
	static std::vector<font::EnumFontInfo> ff;
	static UINT rows_per_scroll = 1;
	static window::BackgroundDC offscreen;
	static snippets::ScrollBar vbar(h, SB_VERT);
	static size_t count_rendered = 0;
	static FontRenderWorker font_renderer;

	switch(m)
	{
		default: break;

		case WM_FR_MESSAGE_UPDATE:
		{
			RECT client_rect;
			GetClientRect(h, &client_rect);
			HDC dc = GetDC(h);
			FillRect(dc, &client_rect, (HBRUSH)(COLOR_MENU+1));
#ifdef DEBUG_FR_DELAY
			draw_info(dc, font_renderer.get_msg());
#endif
			ReleaseDC(h, dc);
			return 0;
		}

		case WM_PAINT:
		{
			PAINTSTRUCT ps;
			BeginPaint(h, &ps);

			RECT client_rect;
			GetClientRect(h, &client_rect);
			FillRect(ps.hdc, &client_rect, (HBRUSH)(COLOR_MENU+1));
			PostMessage(h, WM_FR_MESSAGE_UPDATE, 0, 0);

			EndPaint(h, &ps);

			// draw_fonts(h, offscreen.handle, ff, vbar.index, count_rendered);
			// offscreen.flip();
			font_renderer.queue(vbar.index, count_rendered);

			return 0;
		}

		case WM_ERASEBKGND:
		{
			InvalidateRect(h, NULL, FALSE);

			// RECT client_rect;
			// GetClientRect(h, &client_rect);
			// HDC dc = GetDC(h);
			// FillRect(dc, &client_rect, (HBRUSH)(COLOR_MENU+1));
			// draw_info(dc, "hi");
			// ReleaseDC(h, dc);
			return 0;
		}

		case WM_NCLBUTTONDOWN:
		{
			INT const nHittest = (INT) w;
			// POINTS pts = MAKEPOINTS(l);

			if (!draw_while_thumb_tracking && HTVSCROLL == nHittest)
			{
				// offscreen.clear(COLOR_MENU);
				// draw_info(offscreen.handle);
				// offscreen.flip();
			}
			break;
		}

		case WM_VSCROLL:
		{
			int const nScrollCode = (int) LOWORD(w);
			short int const nPos = (short int) HIWORD(w);
			// HWND const hwndScrollBar = (HWND) l;

			switch(nScrollCode)
			{
				case SB_LINEUP:
					if (vbar.scroll(-1))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_LINEDOWN:
					if (vbar.scroll(+1))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_PAGEUP:
					if (vbar.scroll(-rows_per_scroll))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_PAGEDOWN:
					if (vbar.scroll(+count_rendered-1))
						InvalidateRect(h, NULL, TRUE);
					break;

				case SB_THUMBTRACK:
					vbar.index = nPos;
					if (draw_while_thumb_tracking)
					{
						vbar.update();
						InvalidateRect(h, NULL, TRUE);
					}
					break;

				case SB_THUMBPOSITION:
					vbar.update();
					InvalidateRect(h, NULL, TRUE);
					break;

			}

			return 0;
		}

		case WM_MOUSEWHEEL:
		{
			short const zDelta = (short) HIWORD(w);

			// printf("WM_MOUSEWHEEL %d\n", zDelta);

			if (zDelta > 0 && vbar.scroll(-rows_per_scroll))
				InvalidateRect(h, NULL, TRUE);

			else if (zDelta < 0 && vbar.scroll(+rows_per_scroll))
				InvalidateRect(h, NULL, TRUE);

			return 0;
		}

		case WM_SIZE:
		{
			HDC dc = GetDC(h);
			offscreen = window::BackgroundDC(dc);
			ReleaseDC(h, dc);
			InvalidateRect(h, NULL, TRUE);
			return 0;
		}

		case WM_CREATE:
		{
			SystemParametersInfo(SPI_GETWHEELSCROLLLINES,
				0, &rows_per_scroll, 0);

			HDC dc = GetDC(h);
			font::list_fonts(ff, ANSI_CHARSET, true, dc);
			ReleaseDC(h, dc);

			// printf(" %d fonts found\n", ff.size());

			vbar.set_count(ff.size());

			font_renderer.setup(h, offscreen, ff);
			font_renderer.start();

			return 0;
		}

		case WM_KEYDOWN:
		{
			switch(w)
			{
				case VK_PRIOR:
				{
					int const steps = count_rendered >= rows_per_scroll ?
						rows_per_scroll : count_rendered;
					if (vbar.scroll(-steps))
						InvalidateRect(h, NULL, TRUE);
					break;
				}

				case VK_NEXT:
				{
					int const steps = count_rendered > 1 ?
						count_rendered-1 : count_rendered;
					if (vbar.scroll(steps))
						InvalidateRect(h, NULL, TRUE);
					break;
				}

				case VK_ESCAPE:
					SendMessage(h, WM_CLOSE, 0, 0);
					break;

				case VK_F5:
					InvalidateRect(h, NULL, TRUE);
					UpdateWindow(h);
					break;
			}
			return 0;
		}

		case WM_CLOSE:
			DestroyWindow(h);
			return 0;

		case WM_DESTROY:
			font_renderer.stop();
			font_renderer.wait(1500);
			PostQuitMessage(0);
			return 0;
	}
	return DefWindowProc(h, m, w, l);
}

void draw_fonts(HWND h, HDC dc, std::vector<font::EnumFontInfo> & ff,
		size_t skip, size_t & count_rendered)
{
	HBRUSH const frame_brush = (HBRUSH) GetStockObject(DC_BRUSH);
	SIZE const frame_extra = {3, 2};
	SIZE const padding = {8, 8};
	SIZE client_size;
	lib::window::get_inner_size(h, client_size);
	SIZE const cutoff = {
		client_size.cx - padding.cx,
		client_size.cy - padding.cy};

	count_rendered = 0;
	int y = 0;

	for (size_t i=skip; i<ff.size(); ++i, ++count_rendered)
	{
		char const * text = (char const *) ff[i].elfe.elfFullName;
		size_t const text_len = strlen(text);

		lib::font::EnumFontInfoLoader efil(dc, ff[i]);

		RECT tr = {padding.cx, padding.cy + y, 0, 0};
		snippets::calc_text_rect_2(tr, dc, text, text_len);

		int const next_y = tr.bottom - padding.cy + frame_extra.cy + 1;

		if (next_y > cutoff.cy) break;

		InflateRect(&tr, frame_extra.cx, frame_extra.cy);
		// SetDCBrushColor(dc, RGB(200,80,80));
		SetDCBrushColor(dc, RGB(100,100,100));
		FrameRect(dc, &tr, frame_brush);

		RECT rc = {padding.cx, padding.cy + y, 0, 0};
		// lib::font::draw_font_label(dc, rc, ff[i]);
		// SetBkColor(dc, RGB(10,10,10));
		// SetTextColor(dc, RGB(200,200,200));
		ExtTextOut(dc, rc.left, rc.top,
			0, nullptr, text, text_len, nullptr);

		y = next_y;
	}
}

void quick_draw(HDC dc, int x, int y, char const * text, size_t text_len, int text_height, COLORREF text_color)
{
	HFONT hf = CreateFont(text_height, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_SWISS, nullptr);

	SaveDC(dc);
	SetBkMode(dc, TRANSPARENT);
	SetTextColor(dc, text_color);
	SelectObject(dc, hf);
	TextOut(dc, x, y, text, text_len);
	RestoreDC(dc, -1);

	DeleteObject(hf);
}

void draw_info(HDC dc, char const * const info_text)
{
	size_t const info_text_len = strlen(info_text);
	// COLORREF const text_color = RGB(200,100,100);
	COLORREF const text_color = RGB(100,100,100);

	SIZE client_size;
	lib::window::get_inner_size(WindowFromDC(dc), client_size);

	quick_draw(dc, 8, 8, info_text, info_text_len, 42, text_color);
}

FontRenderWorker::Job::Job(size_t index, size_t & count_rendered)
		: index(index), count_rendered(count_rendered)
{
}

FontRenderWorker::FontRenderWorker()
{
	InitializeCriticalSection(&mutex);
	// mutex = CreateMutex(nullptr, FALSE, nullptr);
	// if (!mutex) throw std::runtime_error("FontRenderWorker : unable to create mutex");
}

void FontRenderWorker::task()
{
	bool skip = true;

	size_t jobs_dropped = 0;

	size_t index = 0;
	size_t * count_rendered = nullptr;

	printf(" [ font renderer %08x ] tick\n", (size_t) this);

	EnterCriticalSection(&mutex);
	if (!jobs.empty())
	{
		if (!msg || !*msg) msg = "rendering...";
		else msg = "still rendering... ( stop scrolling! :)";

#ifdef DEBUG_FR_DELAY
		PostMessage(hwnd, WM_FR_MESSAGE_UPDATE, 0, 0);
#endif

		skip = false;
		jobs_dropped = jobs.size() - 1;
		index = jobs.back().index;
		count_rendered = &jobs.back().count_rendered;
		jobs.clear();
	}
	LeaveCriticalSection(&mutex);

	if (skip)
	{
		msg = "";
		offscreen->flip();
		// FIXME: Wait for event instead of busy looping.
		Sleep(100);
		return;
	}

	printf(" [ jobs dropped ] %d\n", jobs_dropped);

#ifdef DEBUG_FR_DELAY
	Sleep(DEBUG_FR_DELAY);
#endif

	offscreen->clear(COLOR_MENU);
	draw_fonts(hwnd, offscreen->handle, *fonts, index, *count_rendered);
	// offscreen->flip();
}

void FontRenderWorker::setup(HWND hwnd, window::BackgroundDC & offscreen,
		std::vector<font::EnumFontInfo> & fonts)
{
	EnterCriticalSection(&mutex);
	this->hwnd = hwnd;
	this->offscreen = &offscreen;
	this->fonts = &fonts;
	LeaveCriticalSection(&mutex);
}

void FontRenderWorker::queue(size_t index, size_t & count_rendered)
{
	EnterCriticalSection(&mutex);
	jobs.push_back(Job(index, count_rendered));
	LeaveCriticalSection(&mutex);
}

char const * FontRenderWorker::get_msg() const
{
	return msg ? msg : "";
}

<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include "ResourcePath.h"

int main()
{
	sf::RenderWindow window(sf::VideoMode(200, 200), "SFML Works!");
	sf::CircleShape shape(100.f);
	shape.setFillColor(sf::Color::Green);

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.clear();
		window.draw(shape);
		window.display();
	}

	return 0;
}
<commit_msg>Map and Walls<commit_after>#include <SFML/Graphics.hpp>
#include "ResourcePath.h"
#include "Overlap.h"
#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;
const int ROW = 9;
const int COL = 11;
/*
void reset(sf::Sprite& cookieSprite)
{
cookieSprite.setPosition(rand() % 750, rand() % 550);
}

void handleCollision(sf::Sprite& charizardSprite, sf::Sprite& cookieSprite, int& eaten)
{
if (overlap(charizardSprite, cookieSprite))
{
eaten++;
reset(cookieSprite);
charizardSprite.scale(1.1, 1.1);
}
}
*/
void handleEvent(sf::RenderWindow& window)
{
	sf::Event event;
	while (window.pollEvent(event))
	{
		if (event.type == sf::Event::Closed)
			window.close();
	}
}
/* //Pacman
void update(sf::Sprite& charizardSprite, sf::Sprite& cookieSprite, int& eaten)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
charizardSprite.move(0, -5);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
charizardSprite.move(0, 5);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
charizardSprite.move(-5, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
charizardSprite.move(5, 0);

}
*/
void draw(sf::RenderWindow& window)
{
	window.clear();

	window.display();
}

void drawWall(sf::RenderWindow& window, bool arr[][COL], sf::Sprite *tileArr, sf::Texture wallTexture)
{
	int i = 0;
	//insert wall sprite
	for (int r = 0; r < ROW; r++)
	{
		for (int c = 0; c < COL; c++)
		{
			if (arr[r][c] == true)
			{
				tileArr[i] = sf::Sprite(wallTexture);
				tileArr[i].setPosition(r * 64, c * 64);
				window.draw(tileArr[i]);
				// place the sprite
				// this need to be the new sprite every time.
				// use vector
				i++;
			}
		}
	}
	window.display();

}

int main()
{
	srand(time(NULL));
	sf::RenderWindow window(sf::VideoMode(800, 800), "SFML Works!");
	window.setVerticalSyncEnabled(true);

	sf::Texture wallTexture;
	wallTexture.loadFromFile(resourcePath() + "assets/wall.png");

	sf::Sprite *tileArray = NULL;

	//this would be better if we can call the inputfile.
	// map array beta
	// please finish design the map so I can finish this!
	int map[9][11] =
	{
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1 },
		{ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1 },
		{ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 },
		{ 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1 },
		{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
	};
	//bool array
	int counter = 0;
	bool wall[9][11];
	for (int r = 0; r < ROW; r++)
	{
		for (int c = 0; c < COL; c++)
		{
			if (map[r][c] == 1)
			{
				wall[r][c] = true; // there is a wall
				counter++;
			}
			if (map[r][c] == 0)
				wall[r][c] = false; // blank
		}
	}

	tileArray = new sf::Sprite[counter];

	drawWall(window, wall, tileArray, wallTexture);

	while (window.isOpen())
	{
		handleEvent(window);

		window.clear();

	}

	//delete tileArray;
	return 0;
}<|endoftext|>


<commit_before>/*
  The MIT License (MIT)

  Copyright (c) 2016 Andrea Scarpino <me@andreascarpino.it>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <QtQuick>

#include <sailfishapp.h>

#include "mpwmanager.h"

int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    QCoreApplication::setApplicationName(QStringLiteral("MPW"));

    qmlRegisterType<MPWManager>("harbour.mpw", 1, 0, "MPWManager");

    MPWManager manager;
    view->rootContext()->setContextProperty("manager", &manager);

    view->setSource(SailfishApp::pathTo("qml/MPW.qml"));
    view->show();

    return app->exec();
}
<commit_msg>Set Organization Domain<commit_after>/*
  The MIT License (MIT)

  Copyright (c) 2016 Andrea Scarpino <me@andreascarpino.it>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <QtQuick>

#include <sailfishapp.h>

#include "mpwmanager.h"

int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    QCoreApplication::setApplicationName(QStringLiteral("MPW"));
    QCoreApplication::setOrganizationDomain(QStringLiteral("it.andreascarpino"));

    qmlRegisterType<MPWManager>("harbour.mpw", 1, 0, "MPWManager");

    MPWManager manager;
    view->rootContext()->setContextProperty("manager", &manager);

    view->setSource(SailfishApp::pathTo("qml/MPW.qml"));
    view->show();

    return app->exec();
}
<|endoftext|>