Esempio n. 1
0
// This function creates the parsed file
void Parser::parse() {
    std::cout << "running parser:\n";
    this->next();

    // parse number of inputs
    std::string inputs_str = "";
    if (this->_current == '#')
        this->next();
    if (this->_current == 'i')
        this->next();
    if (this->_current == ':')
        this->next();

    while (isdigit(this->_current)) {
        inputs_str = inputs_str + this->_current;
        this->next();
    }
    this->_inputCount = stoi(inputs_str);
    this->_possibleIO = (int)pow(2,this->_inputCount);

    // allocate input array
    this->_vhdlInputs = new IO[this->_inputCount];

    // loop through all inputs
    int i = 0;
    while (this->_current != '#'){

        // parse variable name
        std::string name = "";
        while (this->_current != ':') {
            name = name + this->_current;
            this->next();
        }
        this->next();

        // set input name
        this->_vhdlInputs[i].name = name;
        this->_vhdlInputs[i].values = new bool[this->_possibleIO];

        // parse variable values
        int j = 0;
        while (this->_current == '0' || this->_current == '1') {
            if (this->_current == '0'){
                this->_vhdlInputs[i].values[j] = false;
            }else{
                this->_vhdlInputs[i].values[j] = true;
            }
            this->next();
            j++;
        }

        std::cout << "successfully parsed input " << name << "\n";
        i++;
    }
    this->next();

    // parse number of outputs
    std::string outputs_str = "";
    if (this->_current == 'o')
        this->next();
    if (this->_current == ':')
        this->next();

    while (isdigit(this->_current)) {
        outputs_str = outputs_str + this->_current;
        this->next();
    }
    this->_outputCount = stoi(outputs_str);

    // allocate input array
    this->_vhdlOutputs = new IO[this->_outputCount];

    // loop through all outputs
    int k = 0;
    while(!this->_inputFile.eof()){

        // parse variable name
        std::string name = "";
        while (this->_current != ':') {
            name = name + this->_current;
            this->next();
        }
        this->next();

        // set input name
        this->_vhdlOutputs[k].name = name;
        this->_vhdlOutputs[k].values = new bool[this->_possibleIO];

        // parse variable values
        int l = 0;
        while (this->_current == '0' || this->_current == '1') {
            if (this->_current == '0'){
                this->_vhdlOutputs[k].values[l] = false;
            }else{
                this->_vhdlOutputs[k].values[l] = true;
            }
            this->next();
            l++;
        }

        std::cout << "successfully parsed output " << name << "\n";
        k++;
    }

    this->_inputFile.close();
    std::cout << "parsing complete\n";
}
Esempio n. 2
0
//the same for attributed graphs
//read all cluster tree information
//make changes to this as well as the recursive function
bool GmlParser::attributedClusterRead(
	GmlObject* rootCluster,
	ClusterGraph& CG,
	ClusterGraphAttributes& ACG)
{

	//the root cluster is only allowed to hold child clusters and
	//nodes in a list

	if (rootCluster->m_valueType != gmlListBegin) return false;

	// read all clusters and nodes
	GmlObject *rootClusterSon = rootCluster->m_pFirstSon;

	for(; rootClusterSon; rootClusterSon = rootClusterSon->m_pBrother)
	{
		switch(id(rootClusterSon))
		{
		case clusterPredefKey:
			{
				//we could delete this, but we avoid the call
				if (rootClusterSon->m_valueType != gmlListBegin) return false;
				// set attributes to default values
				//we currently do not set any values
				cluster c = CG.newCluster(CG.rootCluster());

				//recursively read cluster
				recursiveAttributedClusterRead(rootClusterSon, CG, ACG, c);

			} //case cluster
			break;

		case vertexPredefKey: //direct root vertices
			{
				if (rootClusterSon->m_valueType != gmlStringValue) return false;
				string vIDString = rootClusterSon->m_stringValue;

				//we only allow a vertex id as string identification
				if ((vIDString[0] != 'v') &&
					(!isdigit((int)vIDString[0])))return false; //do not allow labels
				//if old style entry "v"i
				if (!isdigit((int)vIDString[0])) //should check prefix?
					vIDString[0] = '0'; //leading zero to allow conversion
				int vID = stoi(vIDString);

				OGDF_ASSERT(m_mapToNode[vID] != 0)

					//we assume that no node is already assigned
					//CG.reassignNode(mapToNode[vID], CG.rootCluster());
					//changed: all nodes are already assigned to root
					//this code seems to be obsolete, todo: check
					CG.reassignNode(m_mapToNode[vID], CG.rootCluster());
				//char* vIDChar = new char[vIDString.length()+1];
				//for (int ind = 1; ind < vIDString.length(); ind++)
				//	vIDChar

			}//case vertex
		}//switch
	}//for all rootcluster sons

	return true;

}//attributedclusterread
Esempio n. 3
0
int main(int argc, char *argv[])
{
	int retval = 0;

	/*
		Initialization
	*/

	log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
	log_add_output_all_levs(&main_dstream_no_stderr_log_out);

	log_register_thread("main");

	// This enables internatonal characters input
	if( setlocale(LC_ALL, "") == NULL )
	{
		fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] );
	}

	// Set locale. This is for forcing '.' as the decimal point.
	try {
		std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
		setlocale(LC_NUMERIC, "C");
	} catch (const std::exception& ex) {
		errorstream<<"Could not set numeric locale to C"<<std::endl;
	}
	/*
		Parse command line
	*/
	
	// List all allowed options
	core::map<std::string, ValueSpec> allowed_options;
	allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
			_("Show allowed options")));
	allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
			_("Load configuration from specified file")));
	allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
			_("Set network port (UDP)")));
	allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
			_("Disable unit tests")));
	allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
			_("Enable unit tests")));
	allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
			_("Same as --world (deprecated)")));
	allowed_options.insert("world", ValueSpec(VALUETYPE_STRING,
			_("Set world path (implies local game) ('list' lists all)")));
	allowed_options.insert("worldname", ValueSpec(VALUETYPE_STRING,
			_("Set world by name (implies local game)")));
	allowed_options.insert("info", ValueSpec(VALUETYPE_FLAG,
			_("Print more information to console")));
	allowed_options.insert("verbose", ValueSpec(VALUETYPE_FLAG,
			_("Print even more information to console")));
	allowed_options.insert("trace", ValueSpec(VALUETYPE_FLAG,
			_("Print enormous amounts of information to log and console")));
	allowed_options.insert("logfile", ValueSpec(VALUETYPE_STRING,
			_("Set logfile path ('' = no logging)")));
	allowed_options.insert("gameid", ValueSpec(VALUETYPE_STRING,
			_("Set gameid (\"--gameid list\" prints available ones)")));
#ifndef SERVER
	allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
			_("Run speed tests")));
	allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
			_("Address to connect to. ('' = local game)")));
	allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
			_("Enable random user input, for testing")));
	allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
			_("Run dedicated server")));
	allowed_options.insert("name", ValueSpec(VALUETYPE_STRING,
			_("Set player name")));
	allowed_options.insert("password", ValueSpec(VALUETYPE_STRING,
			_("Set password")));
	allowed_options.insert("go", ValueSpec(VALUETYPE_FLAG,
			_("Disable main menu")));
#endif

	Settings cmd_args;
	
	bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);

	if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
	{
		dstream<<_("Allowed options:")<<std::endl;
		for(core::map<std::string, ValueSpec>::Iterator
				i = allowed_options.getIterator();
				i.atEnd() == false; i++)
		{
			std::ostringstream os1(std::ios::binary);
			os1<<"  --"<<i.getNode()->getKey();
			if(i.getNode()->getValue().type == VALUETYPE_FLAG)
				{}
			else
				os1<<_(" <value>");
			dstream<<padStringRight(os1.str(), 24);

			if(i.getNode()->getValue().help != NULL)
				dstream<<i.getNode()->getValue().help;
			dstream<<std::endl;
		}

		return cmd_args.getFlag("help") ? 0 : 1;
	}
	
	/*
		Low-level initialization
	*/
	
	// If trace is enabled, enable logging of certain things
	if(cmd_args.getFlag("trace")){
		dstream<<_("Enabling trace level debug output")<<std::endl;
		log_trace_level_enabled = true;
		dout_con_ptr = &verbosestream; // this is somewhat old crap
		socket_enable_debug_output = true; // socket doesn't use log.h
	}
	// In certain cases, output info level on stderr
	if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
			cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
		log_add_output(&main_stderr_log_out, LMT_INFO);
	// In certain cases, output verbose level on stderr
	if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
		log_add_output(&main_stderr_log_out, LMT_VERBOSE);

	porting::signal_handler_init();
	bool &kill = *porting::signal_handler_killstatus();
	
	porting::initializePaths();

	// Create user data directory
	fs::CreateDir(porting::path_user);

	init_gettext((porting::path_share + DIR_DELIM + "locale").c_str());

	infostream<<"path_share = "<<porting::path_share<<std::endl;
	infostream<<"path_user  = "******"gameid") && cmd_args.get("gameid") == "list")
	{
		std::set<std::string> gameids = getAvailableGameIds();
		for(std::set<std::string>::const_iterator i = gameids.begin();
				i != gameids.end(); i++)
			dstream<<(*i)<<std::endl;
		return 0;
	}
	
	// List worlds if requested
	if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
		dstream<<_("Available worlds:")<<std::endl;
		std::vector<WorldSpec> worldspecs = getAvailableWorlds();
		print_worldspecs(worldspecs, dstream);
		return 0;
	}
	
	// Print startup message
	infostream<<PROJECT_NAME<<
			" "<<_("with")<<" SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
			<<", "<<BUILD_INFO
			<<std::endl;
	
	/*
		Basic initialization
	*/

	// Initialize default settings
	set_default_settings(g_settings);
	
	// Initialize sockets
	sockets_init();
	atexit(sockets_cleanup);
	
	/*
		Read config file
	*/
	
	// Path of configuration file in use
	std::string configpath = "";
	
	if(cmd_args.exists("config"))
	{
		bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
		if(r == false)
		{
			errorstream<<"Could not read configuration from \""
					<<cmd_args.get("config")<<"\""<<std::endl;
			return 1;
		}
		configpath = cmd_args.get("config");
	}
	else
	{
		core::array<std::string> filenames;
		filenames.push_back(porting::path_user +
				DIR_DELIM + "minetest.conf");
		// Legacy configuration file location
		filenames.push_back(porting::path_user +
				DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
#if RUN_IN_PLACE
		// Try also from a lower level (to aid having the same configuration
		// for many RUN_IN_PLACE installs)
		filenames.push_back(porting::path_user +
				DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
#endif

		for(u32 i=0; i<filenames.size(); i++)
		{
			bool r = g_settings->readConfigFile(filenames[i].c_str());
			if(r)
			{
				configpath = filenames[i];
				break;
			}
		}
		
		// If no path found, use the first one (menu creates the file)
		if(configpath == "")
			configpath = filenames[0];
	}
	
	// Initialize debug streams
#define DEBUGFILE "debug.txt"
#if RUN_IN_PLACE
	std::string logfile = DEBUGFILE;
#else
	std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
#endif
	if(cmd_args.exists("logfile"))
		logfile = cmd_args.get("logfile");
	
	log_remove_output(&main_dstream_no_stderr_log_out);
	int loglevel = g_settings->getS32("debug_log_level");

	if (loglevel == 0) //no logging
		logfile = "";
	else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
		log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));

	if(logfile != "")
		debugstreams_init(false, logfile.c_str());
	else
		debugstreams_init(false, NULL);
		
	infostream<<"logfile    = "<<logfile<<std::endl;

	// Initialize random seed
	srand(time(0));
	mysrand(time(0));

	/*
		Run unit tests
	*/

	if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
			|| cmd_args.getFlag("enable-unittests") == true)
	{
		run_tests();
	}
	
	/*
		Game parameters
	*/

	// Port
	u16 port = 30000;
	if(cmd_args.exists("port"))
		port = cmd_args.getU16("port");
	else if(g_settings->exists("port"))
		port = g_settings->getU16("port");
	if(port == 0)
		port = 30000;
	
	// World directory
	std::string commanded_world = "";
	if(cmd_args.exists("world"))
		commanded_world = cmd_args.get("world");
	else if(cmd_args.exists("map-dir"))
		commanded_world = cmd_args.get("map-dir");
	else if(cmd_args.exists("nonopt0")) // First nameless argument
		commanded_world = cmd_args.get("nonopt0");
	else if(g_settings->exists("map-dir"))
		commanded_world = g_settings->get("map-dir");
	
	// World name
	std::string commanded_worldname = "";
	if(cmd_args.exists("worldname"))
		commanded_worldname = cmd_args.get("worldname");
	
	// Strip world.mt from commanded_world
	{
		std::string worldmt = "world.mt";
		if(commanded_world.size() > worldmt.size() &&
				commanded_world.substr(commanded_world.size()-worldmt.size())
				== worldmt){
			dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
			commanded_world = commanded_world.substr(
					0, commanded_world.size()-worldmt.size());
		}
	}
	
	// If a world name was specified, convert it to a path
	if(commanded_worldname != ""){
		// Get information about available worlds
		std::vector<WorldSpec> worldspecs = getAvailableWorlds();
		bool found = false;
		for(u32 i=0; i<worldspecs.size(); i++){
			std::string name = worldspecs[i].name;
			if(name == commanded_worldname){
				if(commanded_world != ""){
					dstream<<_("--worldname takes precedence over previously "
							"selected world.")<<std::endl;
				}
				commanded_world = worldspecs[i].path;
				found = true;
				break;
			}
		}
		if(!found){
			dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
					"available. Available worlds:")<<std::endl;
			print_worldspecs(worldspecs, dstream);
			return 1;
		}
	}

	// Gamespec
	SubgameSpec commanded_gamespec;
	if(cmd_args.exists("gameid")){
		std::string gameid = cmd_args.get("gameid");
		commanded_gamespec = findSubgame(gameid);
		if(!commanded_gamespec.isValid()){
			errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
			return 1;
		}
	}

	/*
		Run dedicated server if asked to or no other option
	*/
#ifdef SERVER
	bool run_dedicated_server = true;
#else
	bool run_dedicated_server = cmd_args.getFlag("server");
#endif
	g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
	if(run_dedicated_server)
	{
		DSTACK("Dedicated server branch");
		// Create time getter if built with Irrlicht
#ifndef SERVER
		g_timegetter = new SimpleTimeGetter();
#endif

		// World directory
		std::string world_path;
		verbosestream<<_("Determining world path")<<std::endl;
		bool is_legacy_world = false;
		// If a world was commanded, use it
		if(commanded_world != ""){
			world_path = commanded_world;
			infostream<<"Using commanded world path ["<<world_path<<"]"
					<<std::endl;
		}
		// No world was specified; try to select it automatically
		else
		{
			// Get information about available worlds
			std::vector<WorldSpec> worldspecs = getAvailableWorlds();
			// If a world name was specified, select it
			if(commanded_worldname != ""){
				world_path = "";
				for(u32 i=0; i<worldspecs.size(); i++){
					std::string name = worldspecs[i].name;
					if(name == commanded_worldname){
						world_path = worldspecs[i].path;
						break;
					}
				}
				if(world_path == ""){
					dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
							"available. Available worlds:")<<std::endl;
					print_worldspecs(worldspecs, dstream);
					return 1;
				}
			}
			// If there is only a single world, use it
			if(worldspecs.size() == 1){
				world_path = worldspecs[0].path;
				dstream<<_("Automatically selecting world at")<<" ["
						<<world_path<<"]"<<std::endl;
			// If there are multiple worlds, list them
			} else if(worldspecs.size() > 1){
				dstream<<_("Multiple worlds are available.")<<std::endl;
				dstream<<_("Please select one using --worldname <name>"
						" or --world <path>")<<std::endl;
				print_worldspecs(worldspecs, dstream);
				return 1;
			// If there are no worlds, automatically create a new one
			} else {
				// This is the ultimate default world path
				world_path = porting::path_user + DIR_DELIM + "worlds" +
						DIR_DELIM + "world";
				infostream<<"Creating default world at ["
						<<world_path<<"]"<<std::endl;
			}
		}

		if(world_path == ""){
			errorstream<<"No world path specified or found."<<std::endl;
			return 1;
		}
		verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;

		// We need a gamespec.
		SubgameSpec gamespec;
		verbosestream<<_("Determining gameid/gamespec")<<std::endl;
		// If world doesn't exist
		if(!getWorldExists(world_path))
		{
			// Try to take gamespec from command line
			if(commanded_gamespec.isValid()){
				gamespec = commanded_gamespec;
				infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
			}
			// Otherwise we will be using "minetest"
			else{
				gamespec = findSubgame(g_settings->get("default_game"));
				infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
			}
		}
		// World exists
		else
		{
			std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
			// If commanded to use a gameid, do so
			if(commanded_gamespec.isValid()){
				gamespec = commanded_gamespec;
				if(commanded_gamespec.id != world_gameid){
					errorstream<<"WARNING: Using commanded gameid ["
							<<gamespec.id<<"]"<<" instead of world gameid ["
							<<world_gameid<<"]"<<std::endl;
				}
			} else{
				// If world contains an embedded game, use it;
				// Otherwise find world from local system.
				gamespec = findWorldSubgame(world_path);
				infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
			}
		}
		if(!gamespec.isValid()){
			errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
					<<std::endl;
			return 1;
		}
		verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;

		// Create server
		Server server(world_path, configpath, gamespec, false);
		server.start(port);
		
		// Run server
		dedicated_server_loop(server, kill);

		return 0;
	}

#ifndef SERVER // Exclude from dedicated server build

	/*
		More parameters
	*/
	
	std::string address = g_settings->get("address");
	if(commanded_world != "")
		address = "";
	else if(cmd_args.exists("address"))
		address = cmd_args.get("address");
	
	std::string playername = g_settings->get("name");
	if(cmd_args.exists("name"))
		playername = cmd_args.get("name");
	
	bool skip_main_menu = cmd_args.getFlag("go");

	/*
		Device initialization
	*/

	// Resolution selection
	
	bool fullscreen = g_settings->getBool("fullscreen");
	u16 screenW = g_settings->getU16("screenW");
	u16 screenH = g_settings->getU16("screenH");

	// bpp, fsaa, vsync

	bool vsync = g_settings->getBool("vsync");
	u16 bits = g_settings->getU16("fullscreen_bpp");
	u16 fsaa = g_settings->getU16("fsaa");

	// Determine driver

	video::E_DRIVER_TYPE driverType;
	
	std::string driverstring = g_settings->get("video_driver");

	if(driverstring == "null")
		driverType = video::EDT_NULL;
	else if(driverstring == "software")
		driverType = video::EDT_SOFTWARE;
	else if(driverstring == "burningsvideo")
		driverType = video::EDT_BURNINGSVIDEO;
	else if(driverstring == "direct3d8")
		driverType = video::EDT_DIRECT3D8;
	else if(driverstring == "direct3d9")
		driverType = video::EDT_DIRECT3D9;
	else if(driverstring == "opengl")
		driverType = video::EDT_OPENGL;
	else
	{
		errorstream<<"WARNING: Invalid video_driver specified; defaulting "
				"to opengl"<<std::endl;
		driverType = video::EDT_OPENGL;
	}

	/*
		Create device and exit if creation failed
	*/

	MyEventReceiver receiver;

	IrrlichtDevice *device;

	SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
	params.DriverType    = driverType;
	params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
	params.Bits          = bits;
	params.AntiAlias     = fsaa;
	params.Fullscreen    = fullscreen;
	params.Stencilbuffer = false;
	params.Vsync         = vsync;
	params.EventReceiver = &receiver;

	device = createDeviceEx(params);

	if (device == 0)
		return 1; // could not create selected driver.
	
	/*
		Continue initialization
	*/

	video::IVideoDriver* driver = device->getVideoDriver();

	/*
		This changes the minimum allowed number of vertices in a VBO.
		Default is 500.
	*/
	//driver->setMinHardwareBufferVertexCount(50);

	// Create time getter
	g_timegetter = new IrrlichtTimeGetter(device);
	
	// Create game callback for menus
	g_gamecallback = new MainGameCallback(device);
	
	/*
		Speed tests (done after irrlicht is loaded to get timer)
	*/
	if(cmd_args.getFlag("speedtests"))
	{
		dstream<<"Running speed tests"<<std::endl;
		SpeedTests();
		return 0;
	}
	
	device->setResizable(true);

	bool random_input = g_settings->getBool("random_input")
			|| cmd_args.getFlag("random-input");
	InputHandler *input = NULL;
	if(random_input)
		input = new RandomInputHandler();
	else
		input = new RealInputHandler(device, &receiver);
	
	scene::ISceneManager* smgr = device->getSceneManager();

	guienv = device->getGUIEnvironment();
	gui::IGUISkin* skin = guienv->getSkin();
	#if USE_FREETYPE
	std::string font_path = g_settings->get("font_path");
	u16 font_size = g_settings->getU16("font_size");
	gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
	#else
	gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
	#endif
	if(font)
		skin->setFont(font);
	else
		errorstream<<"WARNING: Font file was not found."
				" Using default font."<<std::endl;
	// If font was not found, this will get us one
	font = skin->getFont();
	assert(font);
	
	u32 text_height = font->getDimension(L"Hello, world!").Height;
	infostream<<"text_height="<<text_height<<std::endl;

	//skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
	skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
	//skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
	//skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
	skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
	skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
	skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
	skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));

#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
	// Irrlicht 1.8 input colours
	skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
	skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
#endif

	/*
		GUI stuff
	*/

	ChatBackend chat_backend;

	/*
		If an error occurs, this is set to something and the
		menu-game loop is restarted. It is then displayed before
		the menu.
	*/
	std::wstring error_message = L"";

	// The password entered during the menu screen,
	std::string password;

	bool first_loop = true;

	/*
		Menu-game loop
	*/
	while(device->run() && kill == false)
	{
		// Set the window caption
		device->setWindowCaption((std::wstring(L"Minetest [")+wgettext("Main Menu")+L"]").c_str());

		// This is used for catching disconnects
		try
		{

			/*
				Clear everything from the GUIEnvironment
			*/
			guienv->clear();
			
			/*
				We need some kind of a root node to be able to add
				custom gui elements directly on the screen.
				Otherwise they won't be automatically drawn.
			*/
			guiroot = guienv->addStaticText(L"",
					core::rect<s32>(0, 0, 10000, 10000));
			
			SubgameSpec gamespec;
			WorldSpec worldspec;
			bool simple_singleplayer_mode = false;

			// These are set up based on the menu and other things
			std::string current_playername = "inv£lid";
			std::string current_password = "";
			std::string current_address = "does-not-exist";
			int current_port = 0;

			/*
				Out-of-game menu loop.

				Loop quits when menu returns proper parameters.
			*/
			while(kill == false)
			{
				// If skip_main_menu, only go through here once
				if(skip_main_menu && !first_loop){
					kill = true;
					break;
				}
				first_loop = false;
				
				// Cursor can be non-visible when coming from the game
				device->getCursorControl()->setVisible(true);
				// Some stuff are left to scene manager when coming from the game
				// (map at least?)
				smgr->clear();
				
				// Initialize menu data
				MainMenuData menudata;
				if(g_settings->exists("selected_mainmenu_tab"))
					menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab");
				menudata.address = narrow_to_wide(address);
				menudata.name = narrow_to_wide(playername);
				menudata.port = narrow_to_wide(itos(port));
				if(cmd_args.exists("password"))
					menudata.password = narrow_to_wide(cmd_args.get("password"));
				menudata.fancy_trees = g_settings->getBool("new_style_leaves");
				menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
				menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
				menudata.opaque_water = g_settings->getBool("opaque_water");
				menudata.mip_map = g_settings->getBool("mip_map");
				menudata.anisotropic_filter = g_settings->getBool("anisotropic_filter");
				menudata.bilinear_filter = g_settings->getBool("bilinear_filter");
				menudata.trilinear_filter = g_settings->getBool("trilinear_filter");
				menudata.enable_shaders = g_settings->getS32("enable_shaders");
				menudata.preload_item_visuals = g_settings->getBool("preload_item_visuals");
				menudata.enable_particles = g_settings->getBool("enable_particles");
				driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, menudata.mip_map);
				menudata.creative_mode = g_settings->getBool("creative_mode");
				menudata.enable_damage = g_settings->getBool("enable_damage");
				menudata.enable_public = g_settings->getBool("server_announce");
				// Default to selecting nothing
				menudata.selected_world = -1;
				// Get world listing for the menu
				std::vector<WorldSpec> worldspecs = getAvailableWorlds();
				// If there is only one world, select it
				if(worldspecs.size() == 1){
					menudata.selected_world = 0;
				}
				// Otherwise try to select according to selected_world_path
				else if(g_settings->exists("selected_world_path")){
					std::string trypath = g_settings->get("selected_world_path");
					for(u32 i=0; i<worldspecs.size(); i++){
						if(worldspecs[i].path == trypath){
							menudata.selected_world = i;
							break;
						}
					}
				}
				// If a world was commanded, append and select it
				if(commanded_world != ""){
					std::string gameid = getWorldGameId(commanded_world, true);
					std::string name = _("[--world parameter]");
					if(gameid == ""){
						gameid = g_settings->get("default_game");
						name += " [new]";
					}
					WorldSpec spec(commanded_world, name, gameid);
					worldspecs.push_back(spec);
					menudata.selected_world = worldspecs.size()-1;
				}
				// Copy worldspecs to menu
				menudata.worlds = worldspecs;

				if(skip_main_menu == false)
				{
					video::IVideoDriver* driver = device->getVideoDriver();
					
					infostream<<"Waiting for other menus"<<std::endl;
					while(device->run() && kill == false)
					{
						if(noMenuActive())
							break;
						driver->beginScene(true, true,
								video::SColor(255,128,128,128));
						drawMenuBackground(driver);
						guienv->drawAll();
						driver->endScene();
						// On some computers framerate doesn't seem to be
						// automatically limited
						sleep_ms(25);
					}
					infostream<<"Waited for other menus"<<std::endl;

					GUIMainMenu *menu =
							new GUIMainMenu(guienv, guiroot, -1, 
								&g_menumgr, &menudata, g_gamecallback);
					menu->allowFocusRemoval(true);

					if(error_message != L"")
					{
						verbosestream<<"error_message = "
								<<wide_to_narrow(error_message)<<std::endl;

						GUIMessageMenu *menu2 =
								new GUIMessageMenu(guienv, guiroot, -1, 
									&g_menumgr, error_message.c_str());
						menu2->drop();
						error_message = L"";
					}

					infostream<<"Created main menu"<<std::endl;

					while(device->run() && kill == false)
					{
						if(menu->getStatus() == true)
							break;

						//driver->beginScene(true, true, video::SColor(255,0,0,0));
						driver->beginScene(true, true, video::SColor(255,128,128,128));

						drawMenuBackground(driver);

						guienv->drawAll();
						
						driver->endScene();
						
						// On some computers framerate doesn't seem to be
						// automatically limited
						sleep_ms(25);
					}
					
					infostream<<"Dropping main menu"<<std::endl;

					menu->drop();
				}

				playername = wide_to_narrow(menudata.name);
				password = translatePassword(playername, menudata.password);
				//infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;

				address = wide_to_narrow(menudata.address);
				int newport = stoi(wide_to_narrow(menudata.port));
				if(newport != 0)
					port = newport;
				simple_singleplayer_mode = menudata.simple_singleplayer_mode;
				// Save settings
				g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab);
				g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
				g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
				g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
				g_settings->set("opaque_water", itos(menudata.opaque_water));

				g_settings->set("mip_map", itos(menudata.mip_map));
				g_settings->set("anisotropic_filter", itos(menudata.anisotropic_filter));
				g_settings->set("bilinear_filter", itos(menudata.bilinear_filter));
				g_settings->set("trilinear_filter", itos(menudata.trilinear_filter));

				g_settings->setS32("enable_shaders", menudata.enable_shaders);
				g_settings->set("preload_item_visuals", itos(menudata.preload_item_visuals));
				g_settings->set("enable_particles", itos(menudata.enable_particles));

				g_settings->set("creative_mode", itos(menudata.creative_mode));
				g_settings->set("enable_damage", itos(menudata.enable_damage));
				g_settings->set("server_announce", itos(menudata.enable_public));
				g_settings->set("name", playername);
				g_settings->set("address", address);
				g_settings->set("port", itos(port));
				if(menudata.selected_world != -1)
					g_settings->set("selected_world_path",
							worldspecs[menudata.selected_world].path);

				// Break out of menu-game loop to shut down cleanly
				if(device->run() == false || kill == true)
					break;
				
				current_playername = playername;
				current_password = password;
				current_address = address;
				current_port = port;

				// If using simple singleplayer mode, override
				if(simple_singleplayer_mode){
					current_playername = "singleplayer";
					current_password = "";
					current_address = "";
					current_port = 30011;
				}
				else if (address != "")
				{
					ServerListSpec server;
					server["name"] = menudata.servername;
					server["address"] = wide_to_narrow(menudata.address);
					server["port"] = wide_to_narrow(menudata.port);
					server["description"] = menudata.serverdescription;
					ServerList::insert(server);
				}
				
				// Set world path to selected one
				if(menudata.selected_world != -1){
					worldspec = worldspecs[menudata.selected_world];
					infostream<<"Selected world: "<<worldspec.name
							<<" ["<<worldspec.path<<"]"<<std::endl;
				}

				// Only refresh if so requested
				if(menudata.only_refresh){
					infostream<<"Refreshing menu"<<std::endl;
					continue;
				}
				
				// Create new world if requested
				if(menudata.create_world_name != L"")
				{
					std::string path = porting::path_user + DIR_DELIM
							"worlds" + DIR_DELIM
							+ wide_to_narrow(menudata.create_world_name);
					// Create world if it doesn't exist
					if(!initializeWorld(path, menudata.create_world_gameid)){
						error_message = wgettext("Failed to initialize world");
						errorstream<<wide_to_narrow(error_message)<<std::endl;
						continue;
					}
					g_settings->set("selected_world_path", path);
					continue;
				}

				// If local game
				if(current_address == "")
				{
					if(menudata.selected_world == -1){
						error_message = wgettext("No world selected and no address "
								"provided. Nothing to do.");
						errorstream<<wide_to_narrow(error_message)<<std::endl;
						continue;
					}
					// Load gamespec for required game
					gamespec = findWorldSubgame(worldspec.path);
					if(!gamespec.isValid() && !commanded_gamespec.isValid()){
						error_message = wgettext("Could not find or load game \"")
								+ narrow_to_wide(worldspec.gameid) + L"\"";
						errorstream<<wide_to_narrow(error_message)<<std::endl;
						continue;
					}
					if(commanded_gamespec.isValid() &&
							commanded_gamespec.id != worldspec.gameid){
						errorstream<<"WARNING: Overriding gamespec from \""
								<<worldspec.gameid<<"\" to \""
								<<commanded_gamespec.id<<"\""<<std::endl;
						gamespec = commanded_gamespec;
					}

					if(!gamespec.isValid()){
						error_message = wgettext("Invalid gamespec.");
						error_message += L" (world_gameid="
								+narrow_to_wide(worldspec.gameid)+L")";
						errorstream<<wide_to_narrow(error_message)<<std::endl;
						continue;
					}
				}

				// Continue to game
				break;
			}
			
			// Break out of menu-game loop to shut down cleanly
			if(device->run() == false || kill == true)
				break;

			/*
				Run game
			*/
			the_game(
				kill,
				random_input,
				input,
				device,
				font,
				worldspec.path,
				current_playername,
				current_password,
				current_address,
				current_port,
				error_message,
				configpath,
				chat_backend,
				gamespec,
				simple_singleplayer_mode
			);

		} //try
		catch(con::PeerNotFoundException &e)
		{
			error_message = wgettext("Connection error (timed out?)");
			errorstream<<wide_to_narrow(error_message)<<std::endl;
		}
		catch(ServerError &e)
		{
			error_message = narrow_to_wide(e.what());
			errorstream<<wide_to_narrow(error_message)<<std::endl;
		}
		catch(ModError &e)
		{
			errorstream<<e.what()<<std::endl;
			error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
		}
#ifdef NDEBUG
		catch(std::exception &e)
		{
			std::string narrow_message = "Some exception: \"";
			narrow_message += e.what();
			narrow_message += "\"";
			errorstream<<narrow_message<<std::endl;
			error_message = narrow_to_wide(narrow_message);
		}
#endif

		// If no main menu, show error and exit
		if(skip_main_menu)
		{
			if(error_message != L""){
				verbosestream<<"error_message = "
						<<wide_to_narrow(error_message)<<std::endl;
				retval = 1;
			}
			break;
		}
	} // Menu-game loop
	
	delete input;

	/*
		In the end, delete the Irrlicht device.
	*/
	device->drop();

#endif // !SERVER
	
	// Update configuration file
	if(configpath != "")
		g_settings->updateConfigFile(configpath.c_str());
	
	// Print modified quicktune values
	{
		bool header_printed = false;
		std::vector<std::string> names = getQuicktuneNames();
		for(u32 i=0; i<names.size(); i++){
			QuicktuneValue val = getQuicktuneValue(names[i]);
			if(!val.modified)
				continue;
			if(!header_printed){
				dstream<<"Modified quicktune values:"<<std::endl;
				header_printed = true;
			}
			dstream<<names[i]<<" = "<<val.getString()<<std::endl;
		}
	}

	END_DEBUG_EXCEPTION_HANDLER(errorstream)
	
	debugstreams_deinit();
	
	return retval;
}
void Inventory::fromFile(std::string filename){
    std::ifstream infile(filename);
    if (infile){
        if(filename == "game.txt"){
            while (infile){
                if(infile){
                    std::string strInput;
                    std::getline(infile, strInput);
                    if(strInput.length()>0){
                        std::stringstream splitter(strInput);
                        //std::string title,price,copies,condition,genre,rating,maker;
                        std::string title,price,copies,condition,genre,rating,maker,preorder;
                        getline(splitter,title,',');
                        getline(splitter,price,',');
                        getline(splitter,copies,',');
                        getline(splitter,condition,',');
                        getline(splitter,preorder,',');
                        getline(splitter,genre,',');
                        getline(splitter,rating,',');
                        getline(splitter,maker,',');
                        Game* g = new Game(stoi(copies), stof(price), title, genre,rating, to_bool(condition),maker, to_bool(preorder));
                        gameStock.add(g);
//                        std::cout << "\nRead:\t" << g->toString() << "\n";
                    }
                }
            }
        }
        if(filename == "console.txt"){
            while (infile){
                if(infile){
                    std::string strInput;
                    std::getline(infile, strInput);
                    if(strInput.length()>0){
                        std::stringstream splitter(strInput);
                        std::string title,price,copies,condition,edition,maker,warranty;
                        getline(splitter,title,',');
                        getline(splitter,price,',');
                        getline(splitter,copies,',');
                        getline(splitter,condition,',');
                        getline(splitter,edition,',');
                        getline(splitter,maker,',');
                        getline(splitter,warranty,',');
                        Console* c = new Console(stoi(copies), stof(price), title, edition,maker, stoi(warranty), to_bool(condition));
                        consoleStock.add(c);
//                        std::cout << "\nRead:\t" << c->toString() << "\n";
                    }
                }
            }
        }
        if(filename == "accessory.txt"){
            while (infile){
                if(infile){
                    std::string strInput;
                    std::getline(infile, strInput);
                    if(strInput.length()>0){
                        std::stringstream splitter(strInput);
                        std::string title,price,copies,condition,consoleTo,warranty;
                        getline(splitter,title,',');
                        getline(splitter,price,',');
                        getline(splitter,copies,',');
                        getline(splitter,condition,',');
                        getline(splitter,consoleTo,',');
                        getline(splitter,warranty,',');
                        Accessory* a = new Accessory(stoi(copies), stof(price), title, consoleTo, to_bool(condition), stoi(warranty));
                        acessStock.add(a);
//                        std::cout << "\nRead:\t" << a->toString() << "\n";
                        
                    }
                }
            }
        }
        infile.close();
    }
    else {
        std::cout << "Can't read from file. Inventory not loaded.\n";
    }
}
void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
{
	// Remove children
	removeChildren();
	
	v2s32 size(100,100);
	s32 helptext_h = 15;
	core::rect<s32> rect;

	// Base position of contents of form
	v2s32 basepos = getBasePos();
	// State of basepos, 0 = not set, 1= set by formspec, 2 = set by size[] element
	// Used to adjust form size automatically if needed
	// A proceed button is added if there is no size[] element
	int bp_set = 0;
	
	/* Convert m_init_draw_spec to m_inventorylists */
	
	m_inventorylists.clear();
	m_images.clear();
	m_fields.clear();

	Strfnd f(m_formspec_string);
	while(f.atend() == false)
	{
		std::string type = trim(f.next("["));
		if(type == "invsize" || type == "size")
		{
			v2f invsize;
			invsize.X = stof(f.next(","));
			if(type == "size")
			{
				invsize.Y = stof(f.next("]"));
			}
			else{
				invsize.Y = stof(f.next(";"));
				f.next("]");
			}
			infostream<<"Form size ("<<invsize.X<<","<<invsize.Y<<")"<<std::endl;

			padding = v2s32(screensize.Y/40, screensize.Y/40);
			spacing = v2s32(screensize.Y/12, screensize.Y/13);
			imgsize = v2s32(screensize.Y/15, screensize.Y/15);
			size = v2s32(
				padding.X*2+spacing.X*(invsize.X-1.0)+imgsize.X,
				padding.Y*2+spacing.Y*(invsize.Y-1.0)+imgsize.Y + (helptext_h-5)
			);
			rect = core::rect<s32>(
					screensize.X/2 - size.X/2,
					screensize.Y/2 - size.Y/2,
					screensize.X/2 + size.X/2,
					screensize.Y/2 + size.Y/2
			);
			DesiredRect = rect;
			recalculateAbsolutePosition(false);
			basepos = getBasePos();
			bp_set = 2;
		}
		else if(type == "list")
		{
			std::string name = f.next(";");
			InventoryLocation loc;
			if(name == "context" || name == "current_name")
				loc = m_current_inventory_location;
			else
				loc.deSerialize(name);
			std::string listname = f.next(";");
			v2s32 pos = basepos;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = stoi(f.next(","));
			geom.Y = stoi(f.next(";"));
			infostream<<"list inv="<<name<<", listname="<<listname
					<<", pos=("<<pos.X<<","<<pos.Y<<")"
					<<", geom=("<<geom.X<<","<<geom.Y<<")"
					<<std::endl;
			std::string start_i_s = f.next("]");
			s32 start_i = 0;
			if(start_i_s != "")
				start_i = stoi(start_i_s);
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of list without a size[] element"<<std::endl;
			m_inventorylists.push_back(ListDrawSpec(loc, listname, pos, geom, start_i));
		}
		else if(type == "image")
		{
			v2s32 pos = basepos;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = stof(f.next(",")) * (float)imgsize.X;
			geom.Y = stof(f.next(";")) * (float)imgsize.Y;
			std::string name = f.next("]");
			infostream<<"image name="<<name
					<<", pos=("<<pos.X<<","<<pos.Y<<")"
					<<", geom=("<<geom.X<<","<<geom.Y<<")"
					<<std::endl;
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;
			m_images.push_back(ImageDrawSpec(name, pos, geom));
		}
		else if(type == "field")
		{
			std::string fname = f.next(";");
			std::string flabel = f.next(";");
			
			if(fname.find(",") == std::string::npos && flabel.find(",") == std::string::npos)
			{
				if(!bp_set)
				{
					rect = core::rect<s32>(
						screensize.X/2 - 580/2,
						screensize.Y/2 - 300/2,
						screensize.X/2 + 580/2,
						screensize.Y/2 + 300/2
					);
					DesiredRect = rect;
					recalculateAbsolutePosition(false);
					basepos = getBasePos();
					bp_set = 1;
				}
				else if(bp_set == 2)
					errorstream<<"WARNING: invalid use of unpositioned field in inventory"<<std::endl;

				v2s32 pos = basepos;
				pos.Y = ((m_fields.size()+2)*60);
				v2s32 size = DesiredRect.getSize();
				rect = core::rect<s32>(size.X/2-150, pos.Y, (size.X/2-150)+300, pos.Y+30);
			}
			else
			{
				v2s32 pos;
				pos.X = stof(fname.substr(0,fname.find(","))) * (float)spacing.X;
				pos.Y = stof(fname.substr(fname.find(",")+1)) * (float)spacing.Y;
				v2s32 geom;
				geom.X = (stof(flabel.substr(0,flabel.find(","))) * (float)spacing.X)-(spacing.X-imgsize.X);
				pos.Y += (stof(flabel.substr(flabel.find(",")+1)) * (float)imgsize.Y)/2;

				rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
				
				fname = f.next(";");
				flabel = f.next(";");
				if(bp_set != 2)
					errorstream<<"WARNING: invalid use of positioned field without a size[] element"<<std::endl;
				
			}

			std::string odefault = f.next("]");
			std::string fdefault;
			
			// fdefault may contain a variable reference, which
			// needs to be resolved from the node metadata
			if(m_form_src)
				fdefault = m_form_src->resolveText(odefault);
			else
				fdefault = odefault;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(fname.c_str()),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(fdefault.c_str()),
				258+m_fields.size()
			);
			
			// three cases: field and no label, label and no field, label and field
			if (flabel == "") 
			{
				spec.send = true;
				gui::IGUIElement *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
				Environment->setFocus(e);

				irr::SEvent evt;
				evt.EventType = EET_KEY_INPUT_EVENT;
				evt.KeyInput.Key = KEY_END;
				evt.KeyInput.PressedDown = true;
				e->OnEvent(evt);
			}
			else if (fname == "")
			{
				// set spec field id to 0, this stops submit searching for a value that isn't there
				Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
			}
			else
			{
				spec.send = true;
				gui::IGUIElement *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
				Environment->setFocus(e);
				rect.UpperLeftCorner.Y -= 15;
				rect.LowerRightCorner.Y -= 15;
				Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);

				irr::SEvent evt;
				evt.EventType = EET_KEY_INPUT_EVENT;
				evt.KeyInput.Key = KEY_END;
				evt.KeyInput.PressedDown = true;
				e->OnEvent(evt);
			}
			
			m_fields.push_back(spec);
		}
		else if(type == "label")
		{
			v2s32 pos = padding;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;

			rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
			
			std::string flabel = f.next("]");
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(""),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(""),
				258+m_fields.size()
			);
			Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
			m_fields.push_back(spec);
		}
		else if(type == "button" || type == "button_exit")
		{
			v2s32 pos = padding;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = (stof(f.next(",")) * (float)spacing.X)-(spacing.X-imgsize.X);
			pos.Y += (stof(f.next(";")) * (float)imgsize.Y)/2;

			rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
			
			std::string fname = f.next(";");
			std::string flabel = f.next("]");
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(fname.c_str()),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(""),
				258+m_fields.size()
			);
			spec.is_button = true;
			if(type == "button_exit")
				spec.is_exit = true;
			Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
			m_fields.push_back(spec);
		}
		else if(type == "image_button" || type == "image_button_exit")
		{
			v2s32 pos = padding;
			pos.X += stof(f.next(",")) * (float)spacing.X;
			pos.Y += stof(f.next(";")) * (float)spacing.Y;
			v2s32 geom;
			geom.X = (stof(f.next(",")) * (float)spacing.X)-(spacing.X-imgsize.X);
			geom.Y = (stof(f.next(";")) * (float)spacing.Y)-(spacing.Y-imgsize.Y);

			rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
			
			std::string fimage = f.next(";");
			std::string fname = f.next(";");
			std::string flabel = f.next("]");
			if(bp_set != 2)
				errorstream<<"WARNING: invalid use of image_button without a size[] element"<<std::endl;

			FieldSpec spec = FieldSpec(
				narrow_to_wide(fname.c_str()),
				narrow_to_wide(flabel.c_str()),
				narrow_to_wide(fimage.c_str()),
				258+m_fields.size()
			);
			spec.is_button = true;
			if(type == "image_button_exit")
				spec.is_exit = true;
			
			video::ITexture *texture = m_gamedef->tsrc()->getTextureRaw(fimage);
			gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
			e->setImage(texture);
			e->setPressedImage(texture);
			e->setScaleImage(true);
			
			m_fields.push_back(spec);
		}
		else
		{
			// Ignore others
			std::string ts = f.next("]");
			infostream<<"Unknown DrawSpec: type="<<type<<", data=\""<<ts<<"\""
					<<std::endl;
		}
	}

	// If there's inventory, put the usage string at the bottom
	if (m_inventorylists.size())
	{
		changeCtype("");
		core::rect<s32> rect(0, 0, size.X-padding.X*2, helptext_h);
		rect = rect + v2s32(size.X/2 - rect.getWidth()/2,
				size.Y-rect.getHeight()-5);
		const wchar_t *text = wgettext("Left click: Move all items, Right click: Move single item");
		Environment->addStaticText(text, rect, false, true, this, 256);
		changeCtype("C");
	}
	// If there's fields, add a Proceed button
	if (m_fields.size() && bp_set != 2) 
	{
		// if the size wasn't set by an invsize[] or size[] adjust it now to fit all the fields
		rect = core::rect<s32>(
			screensize.X/2 - 580/2,
			screensize.Y/2 - 300/2,
			screensize.X/2 + 580/2,
			screensize.Y/2 + 240/2+(m_fields.size()*60)
		);
		DesiredRect = rect;
		recalculateAbsolutePosition(false);
		basepos = getBasePos();

		changeCtype("");
		{
			v2s32 pos = basepos;
			pos.Y = ((m_fields.size()+2)*60);

			v2s32 size = DesiredRect.getSize();
			rect = core::rect<s32>(size.X/2-70, pos.Y, (size.X/2-70)+140, pos.Y+30);
			Environment->addButton(rect, this, 257, wgettext("Proceed"));
		}
		changeCtype("C");
	}
	// Add tooltip
	{
		// Note: parent != this so that the tooltip isn't clipped by the menu rectangle
		m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
		m_tooltip_element->enableOverrideColor(true);
		m_tooltip_element->setBackgroundColor(video::SColor(255,110,130,60));
		m_tooltip_element->setDrawBackground(true);
		m_tooltip_element->setDrawBorder(true);
		m_tooltip_element->setOverrideColor(video::SColor(255,255,255,255));
		m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
		m_tooltip_element->setWordWrap(false);
	}
}
Esempio n. 6
0
void Arg_Interpreter::fill_arglist_from_argfile(string argfile_name) {
  

        string argfile_path = this->PATH + argfile_name;

        this->UI->cout_str("AI-> creating arglist from argfile " + argfile_path + " :" );
        
        ifstream file(argfile_path,ios::in);

        string equal, arg_name, arg_val;

        // caractérisation du patern
        READ 
        try {this->arglist.x_size = stoi(arg_val);}
        catch (...) {throw "AI: Invalid x size";}
    
        READ
        try {this->arglist.y_size = stoi(arg_val);}
        catch (...) {throw "AI: Invalid y size";}

        READ
        try {this->arglist.init_time_step = stod(arg_val);}
        catch (...) {throw "AI: Invalid initial time step";}

        READ
        try {this->arglist.space_step = stod(arg_val);}
        catch (...) {throw "AI: Invalid space space";}

        READ
        try {this->arglist.CFL_cond = stod(arg_val);}
        catch (...) {throw "AI: Invalid CFL condition";}

        READ
        try {this->arglist.iter_number_solver = stoi(arg_val);}
        catch (...) {throw "AI: Invalid number of iteration on differential equation solver";}

        READ
        try {this->arglist.iter_number_profiler = stoi(arg_val);}
        catch (...) {throw "AI: Invalid number of iteration on nozzle profiler";}

        READ
        try {this->arglist.nb_of_threads = stoi(arg_val);}
        catch (...) {throw "AI: Invalid number of threads";}

        // Paramètre de fitting, choix algo et arguments pour les conditions initiales

        
        READ
        try {this->arglist.nozzle_fitting_init_arg.nb_pts = stoi(arg_val);}
        catch (...) {throw "AI: Invalid number of points for the initial profile";}
        
        for (int i=0; i<this->arglist.nozzle_fitting_init_arg.nb_pts; i++){
                READ
                try {this->arglist.nozzle_fitting_init_arg.abscisses.push_back( stoi(arg_val) );}
                catch (...) {throw "AI: Bad abcisse value";}
        }

        for (int i=0; i<this->arglist.nozzle_fitting_init_arg.nb_pts; i++){
                READ
                try {this->arglist.nozzle_fitting_init_arg.ordinates.push_back( stoi(arg_val) );}
                catch (...) {throw "AI: Bad ordinate value";}
        }

        READ
        if (arg_val == "0") {this->arglist.init_cond_type = INIT_GRAD;}
        else {
            if (arg_val == "1") {this->arglist.init_cond_type = EVOL_CHAMBER;}
            else {throw "AI: Invalid choice of initial condition type";}
        }
    
        READ
        try {this->arglist.iter_number_evol_chamber = stoi(arg_val);}
        catch (...) {throw "AI: Invalid a number of iteration to reach the final chamber conditions";}
        if (this->arglist.iter_number_evol_chamber + 2 >= this->arglist.iter_number_solver) {
            throw "AI: Number of iteration to reach the final chamber conditions must be strictly inferior to the number of iteration of the solver minus o,e";
        }


        READ 
        if (arg_val == "0") {this->arglist.diff_eq_solver_algo = PG_cart;}
        else {
                if (arg_val == "1") {this->arglist.diff_eq_solver_algo = VDW_cart;}
                else {
                        if (arg_val == "2") {this->arglist.diff_eq_solver_algo = PG_cyl;}
                        else {
                                if (arg_val == "3") {this->arglist.diff_eq_solver_algo = VDW_cyl;}
                                        if (arg_val == "4") {this->arglist.diff_eq_solver_algo = PG_cart_turb;}
                                        else {throw "AI: Invalid choice of differential solver algorithm";}
                        }
                }
        }

        // Constantes numériques pour l'eq diff

        READ
        try {this->arglist.VDW_a_coef = stof(arg_val);}
        catch (...) {throw "AI: Invalid a coefficient of Van Der Waals";}

        READ
        try {this->arglist.VDW_b_coef = stof(arg_val);}
        catch (...) {throw "AI: Invalid b coefficient of Van Der Waals";}
    
        READ
        if (arg_val == "false")  {this->arglist.thermal_conduction = false;}
        else {
                if (arg_val == "true")  {this->arglist.thermal_conduction = true;}
                else {throw "AI: Invalid choice of thermal conduction";}
        }

        READ
        try {this->arglist.lambda = stof(arg_val);}
        catch (...) {throw "AI: Invalid lambda";}

        //caractéristiques numériques initiales

        READ
        try {this->arglist.mol_mass = stof(arg_val);}
        catch (...) {throw "AI: Invalid molar mass";}

        READ
        try {this->arglist.dyn_visc = stof(arg_val);}
        catch (...) {throw "AI: Invalid dynamic viscosity";}

        READ
        try {this->arglist.init_cond.chamber_pressure = stof(arg_val);}
        catch (...) {throw "AI: Invalid initial chamber pressure";}

        READ
        try {this->arglist.init_cond.chamber_temp = stof(arg_val);}
        catch (...) {throw "AI: Invalid initial chamber temperature";}

        READ
        try {this->arglist.init_cond.chamber_speed = stof(arg_val);}
        catch (...) {throw "AI: Invalid initial chamber gaz speed";}

        READ
        try {this->arglist.init_cond.chamber_turb_en = stof(arg_val);}
        catch (...) {throw "AI: Invalid value of initial chamber turbulence energy";}
        
        READ
        try {this->arglist.init_cond.chamber_turb_dis = stof(arg_val);}
        catch (...) {throw "AI: Invalid value of initial chamber turbulence dissipation";}
        
        READ
        try {this->arglist.init_cond.atmosphere_pressure = stof(arg_val);}
        catch (...) {throw "AI: Invalid initial atmosphere pressure";}

        READ
        try {this->arglist.init_cond.atmosphere_temp = stof(arg_val);}
        catch (...) {throw "AI: Invalid initial atmosphere temperature";}

        READ
        try {this->arglist.init_cond.atmosphere_speed = stof(arg_val);}
        catch (...) {throw "AI: Invalid initial atmosphere gaz speed";}

        READ
        try {this->arglist.init_cond.atmosphere_turb_en = stof(arg_val);}
        catch (...) {throw "AI: Invalid value of initial atmosphere turbulence energy";}
        
        READ
        try {this->arglist.init_cond.atmosphere_turb_dis = stof(arg_val);}
        catch (...) {throw "AI: Invalid value of initial atmosphere turbulence dissipation";}

        this->UI->new_line();

        file.close();
}
Esempio n. 7
0
int main(int argc, char* argv[])
{
  TString inputFileName_;
  std::vector<std::string> inputVarNames_;
  std::vector<std::string> inputTrackParameterNames_;
  double eventsFractionStartBuild_;
  double eventsFractionEndBuild_;
  double eventsFractionStartTest_;
  double eventsFractionEndTest_;
  bool singleModules_;
  bool mapSectors_;
  bool computeDistances_;
  bool computeCorrelations_;
  bool usePcs_;
  // Geometric cuts
  double oneOverPtMin_;
  double oneOverPtMax_;
  int oneOverPtRegions_;
  double phiMin_;
  double phiMax_;
  int phiRegions_;
  double etaMin_;
  double etaMax_;
  int etaRegions_;
  double z0Min_;
  double z0Max_;
  int z0Regions_;
  int chargeRegions_;
  int endcapRegions_;
  bool buildMatrix_;
  bool testMatrix_;

  // Specify to select a single sector (made of single modules)
  singleModules_ = false;

  // Optional for the buildMatrix step
  mapSectors_ = false;
  computeDistances_ = true;
  computeCorrelations_ = true;

  // Use the principal components to estimate track parameters
  usePcs_ = true;

  // Pre-estimate coefficient files
  std::string firstOrderChargeOverPtCoefficientsFileName_;
  std::string firstOrderCotThetaCoefficientsFileName_;

  // To remove outlier stubs. Each number is, for each layer, the maximum allowed distance in cm in
  // the transverse plane between the stub and the extrapolated generator-level track associated to it.
//  std::vector<double> distanceCutsTransverse_{1., 2., 4., 5., 8., 10.};
//  std::vector<double> distanceCutsLongitudinal_{0.3, 0.5, 0.8, 3., 3.5, 4.};

  std::unordered_map<int, double> distanceCutsTransverse_;
  distanceCutsTransverse_.insert(std::make_pair(5, 0.007));
  distanceCutsTransverse_.insert(std::make_pair(6, 0.009));
  distanceCutsTransverse_.insert(std::make_pair(7, 0.01));
  distanceCutsTransverse_.insert(std::make_pair(8, 0.012));
  distanceCutsTransverse_.insert(std::make_pair(9, 0.013));
  distanceCutsTransverse_.insert(std::make_pair(10, 0.015));
  distanceCutsTransverse_.insert(std::make_pair(11, 0.02));
  distanceCutsTransverse_.insert(std::make_pair(12, 0.02));
  distanceCutsTransverse_.insert(std::make_pair(13, 0.023));
  distanceCutsTransverse_.insert(std::make_pair(14, 0.027));
  distanceCutsTransverse_.insert(std::make_pair(15, 0.032));
  std::unordered_map<int, double> distanceCutsLongitudinal_;
  distanceCutsLongitudinal_.insert(std::make_pair(5, 0.43));
  distanceCutsLongitudinal_.insert(std::make_pair(6, 0.52));
  distanceCutsLongitudinal_.insert(std::make_pair(7, 0.7));
  distanceCutsLongitudinal_.insert(std::make_pair(8, 15.));
  distanceCutsLongitudinal_.insert(std::make_pair(9, 15.));
  distanceCutsLongitudinal_.insert(std::make_pair(10, 15.));
  distanceCutsLongitudinal_.insert(std::make_pair(11, 10.));
  distanceCutsLongitudinal_.insert(std::make_pair(12, 10.));
  distanceCutsLongitudinal_.insert(std::make_pair(13, 10.));
  distanceCutsLongitudinal_.insert(std::make_pair(14, 10.));
  distanceCutsLongitudinal_.insert(std::make_pair(15, 10.));
  // We use this for the high resolution part of the disks
  distanceCutsLongitudinal_.insert(std::make_pair(110, 2.));
  distanceCutsLongitudinal_.insert(std::make_pair(120, 2.5));
  distanceCutsLongitudinal_.insert(std::make_pair(130, 3.5));
  distanceCutsLongitudinal_.insert(std::make_pair(140, 4.5));
  distanceCutsLongitudinal_.insert(std::make_pair(150, 6.5));
//  std::vector<double> distanceCutsTransverse_{100000., 100000., 100000., 100000., 100000., 100000.};
//  std::vector<double> distanceCutsLongitudinal_{100000., 100000., 100000., 100000., 100000., 100000.};

//  std::vector<double> distanceCutsTransverse_{0.1, 0.2, 0.4, 0.5, 0.8, 1.0};
//  std::vector<double> distanceCutsLongitudinal_{0.3, 0.5, 0.8, 3., 3.5, 4.};


  std::unordered_map<int, std::pair<double, double> > radiusCuts_;

  // Hard-coded parameter for fast turn-around testing
  if (argc < 2) {

//  radiusCuts_.insert({5, {0., 21.95}});
//  radiusCuts_.insert({6, {0., 34.6}});
//  radiusCuts_.insert({7, {0., 49.7}});
//  radiusCuts_.insert({8, {0., 67.4}});
//  radiusCuts_.insert({9, {0., 87.55}});
//  radiusCuts_.insert({10, {0., 106.75}});
//  radiusCuts_.insert({5, {21.95, 22.6}});
//  radiusCuts_.insert({5, {22.6, 23.72}});
//  radiusCuts_.insert({5, {23.72, 1000.}});
    radiusCuts_.insert({5, {0., 1000.}});
    radiusCuts_.insert({6, {0., 1000.}});
    radiusCuts_.insert({7, {0., 1000.}});
    radiusCuts_.insert({8, {0., 1000.}});
    radiusCuts_.insert({9, {0., 1000.}});
    radiusCuts_.insert({10, {0., 1000.}});

    // Endcaps high R resolution
//    radiusCuts_.insert({11, {0., 61.}});
//    radiusCuts_.insert({12, {0., 61.}});
//    radiusCuts_.insert({13, {0., 61.}});
//    radiusCuts_.insert({14, {0., 61.}});
//    radiusCuts_.insert({15, {0., 61.}});

//    // Endcaps low R resolution
//    radiusCuts_.insert({11, {61., 1000.}});
//    radiusCuts_.insert({12, {61., 1000.}});
//    radiusCuts_.insert({13, {61., 1000.}});
//    radiusCuts_.insert({14, {61., 1000.}});
//    radiusCuts_.insert({15, {61., 1000.}});

//    // Endcaps
    radiusCuts_.insert({11, {0., 1000.}});
    radiusCuts_.insert({12, {0., 1000.}});
    radiusCuts_.insert({13, {0., 1000.}});
    radiusCuts_.insert({14, {0., 1000.}});
    radiusCuts_.insert({15, {0., 1000.}});

    // Flat in all variables
//  inputFileName_ = "/Users/demattia/RemoteProjects/extracted_d0_FLAT_new_1cm_larger.root";

    // The prompt sample
  inputFileName_ = "/Users/demattia/RemoteProjects/extracted_prompt_extrapolated.root";

    // Hybrid
//  inputFileName_ = "/Users/demattia/RemoteProjects/extracted_hybrid.root";

    // Endcaps
//    inputFileName_ = "/Users/demattia/RemoteProjects/extracted_endcaps.root";

    // Full Tracker (slice in 0 < phi < 0.8 and eta > 0)
//    inputFileName_ = "/Users/demattia/RemoteProjects/extracted_fullTracker.root";


//    bool train = true;
    bool train = false;


    if (train) {
      buildMatrix_ = true;
      testMatrix_ = false;
    }
    else {
      buildMatrix_ = false;
      testMatrix_ = true;
    }


    bool testFitter_ = false;
//  buildMatrix_ = false;
//  testMatrix_ = false;
//  bool testFitter_ = true;


    // Select layers to use for each stub coordinate
  std::vector<int> layersAll_{5, 6, 7, 8, 9, 10};
//   std::vector<int> layersAll_{6, 7, 8, 9, 10};

    // Hybrid
//  std::vector<int> layersAll_{5, 6, 7, 8, 9, 11}; // region 7
//  std::vector<int> layersAll_{5, 6, 7, 8, 11, 12}; // region 6
//  std::vector<int> layersAll_{5, 6, 7, 11, 12, 13}; // region 5

    // Endcaps
//    std::vector<int> layersAll_{5, 11, 12, 13, 14, 15};
//  std::vector<int> layersAll_{5, 6, 11, 13, 14, 15};
//  std::vector<int> layersAll_{5, 6, 11, 12, 13, 15};
//  std::vector<int> layersAll_{11, 12, 13, 14, 15};

    // Endcaps regions 3 and 4. Remove the next to last disk to make room for the second barrel layer.
//  if (region == 3 || region == 4) {
//    layersAll_ = std::vector<int>{5, 6, 11, 12, 13, 15};
//    //  layersAll_ = std::vector<int>{11, 12, 13, 15};
//  }
    //   std::vector<int> layersAll_{5, 6, 11, 12, 13, 15};
//    std::vector<int> layersAll_{11, 12, 13, 15};

    std::unordered_map<std::string, std::set<int> > requiredLayers_;
    requiredLayers_.insert(std::make_pair("phi", std::set<int>(layersAll_.begin(), layersAll_.end())));
    requiredLayers_.insert(std::make_pair("R", std::set<int>(layersAll_.begin(), layersAll_.end())));
    requiredLayers_.insert(std::make_pair("z", std::set<int>(layersAll_.begin(), layersAll_.end())));
    requiredLayers_.insert(std::make_pair("DeltaS", std::set<int>(layersAll_.begin(), layersAll_.end())));


    // Fraction of the events in the input file to use. Use only 1/2 of them so that the testing phase can use the rest as a statistically independent sample.
    eventsFractionStartBuild_ = 0.;
    eventsFractionEndBuild_ = 0.2;

    eventsFractionStartTest_ = 0.8;
    eventsFractionEndTest_ = 1.;


    // Barrel pre-estimate
    firstOrderChargeOverPtCoefficientsFileName_ = "matrixVD_pre_chargeOverPt.txt";
    firstOrderCotThetaCoefficientsFileName_ = "matrixVD_0_pre_cotTheta_region7.txt";

    // Input coordinates
    // -----------------
  std::vector<std::string> inputVarNames_{"phi"};
//    inputVarNames_ = {"CorrectedPhi"};
//  std::vector<std::string> inputVarNames_{"CorrectedPhiSecondOrder"};
//  std::vector<std::string> inputVarNames_{"CorrectedPhiExactWithD0Gen"};
//  std::vector<std::string> inputVarNames_{"CorrectedPhiSecondOrderWithD0Gen"};
//  std::vector<std::string> inputVarNames_{"CorrectedPhiEndcaps"};
//  std::vector<std::string> inputVarNames_{"CorrectedPhiSecondOrderEndcaps"};
//  std::vector<std::string> inputVarNames_{"CorrectedPhiEndcapsPz"};

//  std::vector<std::string> inputVarNames_{"z"};
//  std::vector<std::string> inputVarNames_{"CorrectedZ"};
//  std::vector<std::string> inputVarNames_{"CorrectedZSecondOrder"};
//  std::vector<std::string> inputVarNames_{"CorrectedZExactWithD0Gen"};
//  std::vector<std::string> inputVarNames_{"CorrectedZEndcaps"};

//  std::vector<std::string> inputVarNames_{"R"};
//  std::vector<std::string> inputVarNames_{"CorrectedR"};

//  std::vector<std::string> inputVarNames_{"R", "z"};

//  std::vector<std::string> inputVarNames_{"DeltaZOverDeltaR"};

    // Track parameters
    // ----------------
//    inputTrackParameterNames_ = {"charge/pt", "phi"};
  std::vector<std::string> inputTrackParameterNames_{"charge/pt"};
//  std::vector<std::string> inputTrackParameterNames_{"charge/pt", "phi", "d0"};
//  std::vector<std::string> inputTrackParameterNames_{"phi", "d0"};
//  std::vector<std::string> inputTrackParameterNames_{"d0"};
//  std::vector<std::string> inputTrackParameterNames_{"charge/ptELC", "phi"};
//  std::vector<std::string> inputTrackParameterNames_{"charge/ptELC", "phi", "d0"};
//  std::vector<std::string> inputTrackParameterNames_{"1/pt", "phi"};
//  std::vector<std::string> inputTrackParameterNames_{"charge/pt", "phi", "cotTheta", "z0"};
//  std::vector<std::string> inputTrackParameterNames_{"cotTheta", "z0"};

//  std::vector<std::string> inputTrackParameterNames_{"z0TgTheta", "tgTheta"};
//  std::vector<std::string> inputTrackParameterNames_{"chargeOverPz"};
//  std::vector<std::string> inputTrackParameterNames_{"chargeOverPz", "phi0PlusChargeZ0Over2RhoZ"};



//  // Use this to test the linearized track fitter
//  std::vector<std::string> inputVarNames_{"phi", "R", "z"};
//  std::vector<std::string> inputTrackParameterNames_{"charge/pt", "phi", "cotTheta", "z0"};
//  std::vector<std::string> inputTrackParameterNames_{"charge/pt", "phi", "d0", "cotTheta", "z0"};


//  // Use this to test the linearized track fitter in the endcaps
//  std::vector<std::string> inputVarNames_{"phi", "R", "z"};
//  std::vector<std::string> inputTrackParameterNames_{"z0TgTheta", "tgTheta"};


    // Geometric cuts
    oneOverPtMax_ = 1 / 2.;
    oneOverPtMin_ = 0.;
//    oneOverPtMax_ = 1. / 2.;
//    oneOverPtMin_ = 1. / 10.;
    oneOverPtRegions_ = 1;
    phiMin_ = 0.;
    phiMax_ = 0.8;
    phiRegions_ = 1;
    etaMin_ = -3.;
    etaMax_ = 3.;
    etaRegions_ = 1;
    z0Min_ = -15.;
    z0Max_ = 15.;
    z0Regions_ = 1;
    // Specify 1 for no charge splitting and 2 for separating positive and negative charge in difference regions
    chargeRegions_ = 1;
    // Either 0 for no endcap region splitting or != 0 for endcap region splitting
    endcapRegions_ = 0;


    if (buildMatrix_) {
      GeometricIndex::GeometricIndexConfiguration gic;
      gic.oneOverPtMin = oneOverPtMin_;
      gic.oneOverPtMax = oneOverPtMax_;
      gic.oneOverPtRegions = oneOverPtRegions_;
      gic.phiMin = phiMin_;
      gic.phiMax = phiMax_;
      gic.phiRegions = phiRegions_;
      gic.etaMin = etaMin_;
      gic.etaMax = etaMax_;
      gic.etaRegions = etaRegions_;
      gic.z0Min = z0Min_;
      gic.z0Max = z0Max_;
      gic.z0Regions = z0Regions_;
      gic.chargeRegions = chargeRegions_;
      gic.endcapRegions = endcapRegions_;

      LinearFit::buildMatrix(inputFileName_, eventsFractionStartBuild_, eventsFractionEndBuild_,
                             requiredLayers_, radiusCuts_, distanceCutsTransverse_, distanceCutsLongitudinal_,
                             inputVarNames_,
                             inputTrackParameterNames_, singleModules_, mapSectors_, computeDistances_,
                             computeCorrelations_, gic, usePcs_, firstOrderChargeOverPtCoefficientsFileName_,
                             firstOrderCotThetaCoefficientsFileName_);

    }

    if (testMatrix_) {
      LinearFit::testMatrix(inputFileName_, eventsFractionStartTest_, eventsFractionEndTest_,
                            inputVarNames_, inputTrackParameterNames_, distanceCutsTransverse_,
                            distanceCutsLongitudinal_,
                            radiusCuts_, singleModules_, firstOrderChargeOverPtCoefficientsFileName_,
                            firstOrderCotThetaCoefficientsFileName_);
    }


    if (testFitter_) {

      const std::string baseDir("/Users/demattia/RemoteProjects/LinearizedTrackFit/LinearizedTrackFit/python/ConstantsProduction/");

      bool fiveOutOfSix_ = true;

      LinearFit::testFitter(inputFileName_, eventsFractionStartTest_, eventsFractionEndTest_,
                            inputVarNames_, inputTrackParameterNames_, distanceCutsTransverse_,
                            distanceCutsLongitudinal_,
                            radiusCuts_, singleModules_,
                            firstOrderChargeOverPtCoefficientsFileName_, firstOrderCotThetaCoefficientsFileName_,
                            oneOverPtMin_, oneOverPtMax_, phiMin_, phiMax_, etaMin_, etaMax_, z0Min_, z0Max_, fiveOutOfSix_,
                            baseDir);
//      LinearFit::testFitterEndcaps(inputFileName_, eventsFractionStartTest_, eventsFractionEndTest_,
//                                   inputVarNames_, inputTrackParameterNames_, distanceCutsTransverse_,
//                                   distanceCutsLongitudinal_,
//                                   radiusCuts_, singleModules_,
//                                   firstOrderChargeOverPtCoefficientsFileName_, firstOrderCotThetaCoefficientsFileName_,
//                                   oneOverPtMin_, oneOverPtMax_, phiMin_, phiMax_, etaMin_, etaMax_, z0Min_, z0Max_);
    }
  }
  else {
    // Read the parameters from a configuration file

    std::ifstream inputFile;
    inputFile.open(argv[1]);
    if (!inputFile) {
      std::cout << "Error opening " << argv[1] << std::endl;
      throw;
    }
    std::string line;
    std::getline(inputFile, line);
    int test = stoi(line);

    std::getline(inputFile, line);
    inputFileName_ = line;

    std::vector<int> layersAll_;
    std::getline(inputFile, line);
    int layer = 0;
    std::stringstream sl(line);
    while (sl >> layer) {
      layersAll_.push_back(layer);
    }
    for (auto l : layersAll_) std::cout << l << " " << std::endl;

    std::getline(inputFile, line);
    eventsFractionStartBuild_ = std::stod(line);
    std::getline(inputFile, line);
    eventsFractionEndBuild_ = std::stod(line);
    std::getline(inputFile, line);
    eventsFractionStartTest_ = std::stod(line);
    std::getline(inputFile, line);
    eventsFractionEndTest_ = std::stod(line);

    std::cout << "inputFileName = " << inputFileName_ << std::endl;
    std::cout << "eventsFractionStartBuild = " << eventsFractionStartBuild_ << std::endl;
    std::cout << "eventsFractionEndBuild = " << eventsFractionEndBuild_ << std::endl;
    std::cout << "eventsFractionStartTest = " << eventsFractionStartTest_ << std::endl;
    std::cout << "eventsFractionEndTest = " << eventsFractionEndTest_ << std::endl;

    // std::string line;
    std::getline(inputFile, line);
    // std::cout << "line = " << line << std::endl;
    std::stringstream vline(line);
    std::string name;
    while (vline >> name) {
      std::cout << "var name = " << name << std::endl;
      inputVarNames_.push_back(name);
    }
    std::getline(inputFile, line);
    std::stringstream pline(line);
    while (pline >> name) {
      std::cout << "par name = " << name << std::endl;
      inputTrackParameterNames_.push_back(name);
    }

    std::getline(inputFile, line);
    std::stringstream rMinLine(line);
    std::vector<double> rMinVec;
    double rMin;
    while (rMinLine >> rMin) {
      rMinVec.push_back(rMin);
    }
    std::getline(inputFile, line);
    std::stringstream rMaxLine(line);
    std::vector<double> rMaxVec;
    double rMax = 0.;
    while (rMaxLine >> rMax) {
      rMaxVec.push_back(rMax);
    }
    if (rMinVec.size() != rMaxVec.size()) {
      std::cout << "Error: inconsistent number of rMin and rMax" << std::endl;
      throw;
    }
    for (int i = 0; i < rMinVec.size(); ++i) {
      radiusCuts_.insert({i + 5, {rMinVec.at(i), rMaxVec.at(i)}});
    }
    std::getline(inputFile, line);
    firstOrderChargeOverPtCoefficientsFileName_ = line;
    std::getline(inputFile, line);
    firstOrderCotThetaCoefficientsFileName_ = line;

    std::cout << "firstOrderChargeOverPtCoefficientsFileName = " << firstOrderChargeOverPtCoefficientsFileName_ << std::endl;
    std::cout << "firstOrderCotThetaCoefficientsFileName = " << firstOrderCotThetaCoefficientsFileName_ << std::endl;


    // Geometric cuts
    inputFile >> oneOverPtMin_;
    inputFile >> oneOverPtMax_;
    inputFile >> oneOverPtRegions_;
    inputFile >> phiMin_;
    inputFile >> phiMax_;
    inputFile >> phiRegions_;
    inputFile >> etaMin_;
    inputFile >> etaMax_;
    inputFile >> etaRegions_;
    inputFile >> z0Min_;
    inputFile >> z0Max_;
    inputFile >> z0Regions_;
    // Specify 1 for no charge splitting and 2 for separating positive and negative charge in difference regions
    inputFile >> chargeRegions_;
    // Either 0 for no endcap region splitting or != 0 for endcap region splitting
    inputFile >> endcapRegions_;

    if (oneOverPtMin_ == 0.) std::cout << "pT > " << 1 / oneOverPtMax_;
    else std::cout << 1 / oneOverPtMax_ << " < pT < " << 1 / oneOverPtMin_;
    std::cout << ", pT regions = " << oneOverPtRegions_ << std::endl;
    std::cout << phiMin_ << " < phi < " << phiMax_ << ", phi regions = " << phiRegions_ << std::endl;
    std::cout << etaMin_ << " < eta < " << etaMax_ << ", eta regions = " << etaRegions_ << std::endl;
    std::cout << z0Min_ << " < z0 < " << z0Max_ << ", eta regions = " << z0Regions_ << std::endl;
    std::cout << "charge regions = " << chargeRegions_ << std::endl;
    std::cout << "endcap regions = " << endcapRegions_ << std::endl;

    GeometricIndex::GeometricIndexConfiguration gic;
    gic.oneOverPtMin = oneOverPtMin_;
    gic.oneOverPtMax = oneOverPtMax_;
    gic.oneOverPtRegions = oneOverPtRegions_;
    gic.phiMin = phiMin_;
    gic.phiMax = phiMax_;
    gic.phiRegions = phiRegions_;
    gic.etaMin = etaMin_;
    gic.etaMax = etaMax_;
    gic.etaRegions = etaRegions_;
    gic.z0Min = z0Min_;
    gic.z0Max = z0Max_;
    gic.z0Regions = z0Regions_;
    gic.chargeRegions = chargeRegions_;
    gic.endcapRegions = endcapRegions_;


    std::unordered_map<std::string, std::set<int> > requiredLayers_;
    requiredLayers_.insert(std::make_pair("phi", std::set<int>(layersAll_.begin(), layersAll_.end())));
    requiredLayers_.insert(std::make_pair("R", std::set<int>(layersAll_.begin(), layersAll_.end())));
    requiredLayers_.insert(std::make_pair("z", std::set<int>(layersAll_.begin(), layersAll_.end())));
    requiredLayers_.insert(std::make_pair("DeltaS", std::set<int>(layersAll_.begin(), layersAll_.end())));

    // Train
    if (test == 0) {
      std::cout << "Training" << std::endl;
      LinearFit::buildMatrix(inputFileName_, eventsFractionStartBuild_, eventsFractionEndBuild_,
                             requiredLayers_, radiusCuts_, distanceCutsTransverse_, distanceCutsLongitudinal_,
                             inputVarNames_,
                             inputTrackParameterNames_, singleModules_, mapSectors_, computeDistances_,
                             computeCorrelations_, gic,
                             usePcs_, firstOrderChargeOverPtCoefficientsFileName_,
                             firstOrderCotThetaCoefficientsFileName_);
    }
    else {
      // Test
      std::cout << "Testing" << std::endl;
      LinearFit::testMatrix(inputFileName_, eventsFractionStartTest_, eventsFractionEndTest_,
                            inputVarNames_, inputTrackParameterNames_, distanceCutsTransverse_,
                            distanceCutsLongitudinal_,
                            radiusCuts_, singleModules_, firstOrderChargeOverPtCoefficientsFileName_,
                            firstOrderCotThetaCoefficientsFileName_);
    }
  }
};
Esempio n. 8
0
void IPXMenic::changeIPXPacket(vector<unsigned char> *actualPacket)
{
	int tmp;

	if (!changeSrcMAC.empty())
	{
		for (int i = 0; i < 6; i++)
		{
			tmp = (unsigned char)stoi(changeSrcMAC.substr(i * 3, 2).c_str(), 0, 16);
			actualPacket->at(i) = tmp;
		}
	}
	if (!changeDstMAC.empty())
	{
		for (int i = 0; i < 6; i++)
		{
			tmp = (unsigned char)stoi(changeDstMAC.substr(i * 3, 2).c_str(), 0, 16);
			actualPacket->at(i + 6) = tmp;
		}
	}
	if (!changetransControl.empty())
	{
		actualPacket->at(18) = (unsigned char)stoi(type, 0, 16);
	}
	if (!changeType.empty())
	{
		tmp = getNumOfProtocol(changeType);
		actualPacket->at(19) = tmp;
	}
	if (!changeDstNetwork.empty())
	{
		for (int i = 0; i < 4; i++)
		{
			tmp = (unsigned char)stoi(changeDstNetwork.substr(i * 3, 2).c_str(), 0, 16);
			actualPacket->at(20 + i) = tmp;
		}
	}
	if (!changeDstNode.empty())
	{
		for (int i = 0; i < 4; i++)
		{
			tmp = (unsigned char)stoi(changeDstNode.substr(i * 3, 2).c_str(), 0, 16);
			actualPacket->at(24 + i) = tmp;
		}
	}
	if (!changeDstSocket.empty())
	{
		actualPacket->at(30) = stoi(changeDstSocket.substr(0, 2).c_str(), 0, 16);
		actualPacket->at(31) = stoi(changeDstSocket.substr(3, 2).c_str(), 0, 16);
	}
	if (!changeSrcNetwork.empty())
	{
		for (int i = 0; i < 4; i++)
		{
			tmp = (unsigned char)stoi(changeSrcNetwork.substr(i * 3, 2).c_str(), 0, 16);
			actualPacket->at(32 + i) = tmp;
		}
	}
	if (!changeSrcNode.empty())
	{
		for (int i = 0; i < 6; i++)
		{
			tmp = (unsigned char)stoi(changeSrcNode.substr(i * 3, 2).c_str(), 0, 16);
			actualPacket->at(36 + i) = tmp;
		}
	}
	if (!changeSrcSocket.empty())
	{
		actualPacket->at(42) = stoi(changeSrcSocket.substr(0, 2).c_str(), 0, 16);
		actualPacket->at(43) = stoi(changeSrcSocket.substr(3, 2).c_str(), 0, 16);
	}
}
void Reprojector::load(IPC& ipc, bool flipped)
{
	bool serial_first_non_zero = false;
	string serial = "";

	for (int i = 4; i < 10; ++i)
	{
		string str_temp = "";
		str_temp += serial_number[i];

		if (!serial_first_non_zero && str_temp != "0")
			serial_first_non_zero = true;

		if (serial_first_non_zero)
			serial += serial_number[i];
	}

	bool has_complete_calib_data = false;

	if (directory_exists(data_path_current_module))
		if (file_exists(data_path_current_module + "\\0.jpg"))
			if (file_exists(data_path_current_module + "\\1.jpg"))
				if (file_exists(data_path_current_module + "\\stereoCalibData.txt"))
					if (file_exists(data_path_current_module + "\\rect0.txt"))
						if (file_exists(data_path_current_module + "\\rect1.txt"))
							has_complete_calib_data = true;

	if (!has_complete_calib_data)
	{
		static bool block_thread = true;
		ipc.send_message("menu_plus", "show window", "");
		ipc.get_response("menu_plus", "show download", "", [](const string message_body)
		{
			COUT << "unblock" << endl;
			block_thread = false;
		});
		
		while (block_thread)
		{
			ipc.update();
			Sleep(100);
		}

        create_directory(data_path);
        create_directory(data_path_current_module);

		copy_file(executable_path + "\\rectifier.exe", data_path_current_module + "\\rectifier.exe");
		copy_file(executable_path + "\\opencv_core249.dll", data_path_current_module + "\\opencv_core249.dll");
		copy_file(executable_path + "\\opencv_highgui249.dll", data_path_current_module + "\\opencv_highgui249.dll");
		copy_file(executable_path + "\\opencv_imgproc249.dll", data_path_current_module + "\\opencv_imgproc249.dll");
		copy_file(executable_path + "\\opencv_calib3d249.dll", data_path_current_module + "\\opencv_calib3d249.dll");
		copy_file(executable_path + "\\opencv_flann249.dll", data_path_current_module + "\\opencv_flann249.dll");
		copy_file(executable_path + "\\opencv_features2d249.dll", data_path_current_module + "\\opencv_features2d249.dll");

		//http://s3-us-west-2.amazonaws.com/ractiv.com/data/
		//http://d2i9bzz66ghms6.cloudfront.net/data/

		string param0 = "http://s3-us-west-2.amazonaws.com/ractiv.com/data/" + serial + "/0.jpg";
		string param1 = data_path_current_module + "\\0.jpg";

		string* serial_ptr = &serial;
		IPC* ipc_ptr = &ipc;
		ipc.get_response("menu_plus", "download", param0 + "`" + param1, [serial_ptr, ipc_ptr](const string message_body)
		{
			if (message_body == "false")
				ipc_ptr->send_message("daemon_plus", "exit", "");
			else
			{
				string param0 = "http://s3-us-west-2.amazonaws.com/ractiv.com/data/" + *serial_ptr + "/1.jpg";
				string param1 = data_path_current_module + "\\1.jpg";

				ipc_ptr->get_response("menu_plus", "download", param0 + "`" + param1, [serial_ptr, ipc_ptr](const string message_body)
				{
					if (message_body == "false")
						ipc_ptr->send_message("daemon_plus", "exit", "");
					else
					{
						string param0 = "http://s3-us-west-2.amazonaws.com/ractiv.com/data/" + *serial_ptr + "/stereoCalibData.txt";
						string param1 = data_path_current_module + "\\stereoCalibData.txt";

						ipc_ptr->get_response("menu_plus", "download", param0 + "`" + param1, [serial_ptr, ipc_ptr](const string message_body)
						{
							if (message_body == "false")
								ipc_ptr->send_message("daemon_plus", "exit", "");
							else
							{
								bool has_complete_calib_data = false;
								while (!has_complete_calib_data)
								{
									system(("cd " + cmd_quote + data_path_current_module + cmd_quote + " && rectifier.exe").c_str());

									if (directory_exists(data_path_current_module))
										if (file_exists(data_path_current_module + "\\0.jpg"))
											if (file_exists(data_path_current_module + "\\1.jpg"))
												if (file_exists(data_path_current_module + "\\stereoCalibData.txt"))
													if (file_exists(data_path_current_module + "\\rect0.txt"))
														if (file_exists(data_path_current_module + "\\rect1.txt"))
															has_complete_calib_data = true;
								}

								block_thread = false;
							}
						});
					}
				});
			}
		});

		block_thread = true;

		while (block_thread)
		{
			ipc.update();
			Sleep(100);
		}
	}

	ifstream file_stereo_calib_data(data_path_current_module + "\\stereoCalibData.txt");

	bool is_number_new = false;
	bool is_number_old = false;

	int block_count = 0;
	int block[4];

	vector<Point> disparity_data;

	string str_num_temp = "";
	string disparities_string = "";
	
	while (getline(file_stereo_calib_data, disparities_string))
	{
		const int i_max = disparities_string.length();
		for (int i = 0; i < i_max; ++i)
		{
			string str_temp = "";
			str_temp += disparities_string[i];

			if (str_temp != "," && str_temp != ";")
				is_number_new = true;
			else
				is_number_new = false;

			if (is_number_new)
			{
				if (!is_number_old)
					str_num_temp = str_temp;
				else
					str_num_temp += str_temp;
			}
			else if (is_number_old)
			{
				block[block_count] = stoi(str_num_temp);
				++block_count;
			}

			if (block_count == 3)
			{
				bool found = false;

				for (int a = 0; a < disparity_data.size(); ++a)
				{
					if (disparity_data[a].x == block[0])
					{
						found = true;
						disparity_data[a].y = (disparity_data[a].y + abs(block[1] - block[2])) / 2;
					}
					else if (disparity_data[a].y == abs(block[1] - block[2]))
					{
						found = true;
						disparity_data[a].x = min(disparity_data[a].x, block[0]);
					}
				}
				if (!found)
					disparity_data.push_back(Point(block[0], abs(block[1] - block[2])));

				block_count = 0;
			}

			is_number_old = is_number_new;
		}
	}
	sort(disparity_data.begin(), disparity_data.end(), compare_point_x());

	double *t, *y;

	t = new double[disparity_data.size()];
	y = new double[disparity_data.size()];

	for (unsigned int a = 0; a < disparity_data.size(); a++)
	{
		t[a] = (double)(disparity_data[a].y);
		y[a] = (double)(disparity_data[a].x);
	}
	CCurveFitting cf;
	cf.curve_fitting4(t, disparity_data.size(), y, &a_out, &b_out, &c_out, &d_out);

	delete []t;
	delete []y;

	ifstream file0(data_path_current_module + "\\rect0.txt");
	is_number_new = false;
	is_number_old = false;
	block_count = 0;

	rect_mat0 = new Point*[WIDTH_LARGE];
	for (int i = 0; i < WIDTH_LARGE; ++i)
		rect_mat0[i] = new Point[HEIGHT_LARGE];

	string rect0_string = "";
	while (getline(file0, rect0_string))
	{
		const int i_max = rect0_string.length();
		for (int i = 0; i < i_max; ++i)
		{
			string str_temp = "";
			str_temp += rect0_string[i];

			if (str_temp != " " && str_temp != "," && str_temp != ";")
				is_number_new = true;
			else
				is_number_new = false;

			if (is_number_new)
			{
				if (!is_number_old)
					str_num_temp = str_temp;
				else
					str_num_temp += str_temp;
			}
			else if (is_number_old)
			{
				block[block_count] = stoi(str_num_temp);
				++block_count;
			}
			if (block_count == 4)
			{
				if (!flipped)
					rect_mat0[block[0]][block[1]] = Point(block[2], block[3]);
				else
					rect_mat0[block[0]][HEIGHT_LARGE_MINUS - block[1]] = Point(block[2], block[3]);

				block_count = 0;
			}
			is_number_old = is_number_new;
		}
	}
	ifstream file1(data_path_current_module + "\\rect1.txt");
	is_number_new = false;
	is_number_old = false;
	block_count = 0;

	rect_mat1 = new Point*[WIDTH_LARGE];
	for (int i = 0; i < WIDTH_LARGE; ++i)
		rect_mat1[i] = new Point[HEIGHT_LARGE];

	string rect1_string = "";
	while (getline(file1, rect1_string))
	{
		const int i_max = rect1_string.length();
		for (int i = 0; i < i_max; ++i)
		{
			string str_temp = "";
			str_temp += rect1_string[i];

			if (str_temp != " " && str_temp != "," && str_temp != ";")
				is_number_new = true;
			else
				is_number_new = false;

			if (is_number_new)
			{
				if (!is_number_old)
					str_num_temp = str_temp;
				else
					str_num_temp += str_temp;
			}
			else if (is_number_old)
			{
				block[block_count] = stoi(str_num_temp);
				++block_count;
			}
			if (block_count == 4)
			{
				if (!flipped)
					rect_mat1[block[0]][block[1]] = Point(block[2], block[3]);
				else
					rect_mat1[block[0]][HEIGHT_LARGE_MINUS - block[1]] = Point(block[2], block[3]);

				block_count = 0;
			}
			is_number_old = is_number_new;
		}
	}
}
Esempio n. 10
0
void Command::edi(std::string cmd, GameEngine *game)
{
  std::string		str(cmd.begin() + 5, cmd.end());
  int val = stoi(str);
  game->deleteEgg(val, 0);
}
Esempio n. 11
0
void f_firmAddr(char* value, int* dummy) {
  if(strlen(value)>0) {
    firmAddress=stoi(value);
    writeFirm++;
  }
}
Esempio n. 12
0
Day15::Day15() {

	auto input = split(openFile("day15/d15.txt", true), "\n");

	std::vector<Spoonful> ingredients;

	Spoonful sp;
	for (std::string s : input)
	{
		auto parts = split(s, " ");

		switch (parts[0][1])
		{
		case 'p':
			sp.type = SPRINKLES;
			break;

		case 'e':
			sp.type = PEANUTBUTTER;
			break;

		case 'r':
			sp.type = FROSTING;
			break;

		case 'u':
			sp.type = SUGAR;
			break;
		}
		
		sp.capacity = stoi(parts[2]);
		sp.durability = stoi(parts[4]);
		sp.flavor = stoi(parts[6]);
		sp.texture = stoi(parts[8]);
		sp.calories = stoi(parts[10]);

		ingredients.push_back(sp);
	}

	Spoonful sprinkles = ingredients.at(0);
	Spoonful peanutButter = ingredients.at(1);
	Spoonful frosting = ingredients.at(2);
	Spoonful sugar = ingredients.at(3);

	// Make mix
	int highscore = 0;
	std::vector<Spoonful> mix;
	for (int i = 1; i <= 100; ++i)
	{
		for (int j = 1; i + j <= 100; ++j)
		{
			for (int k = 1; i + j + k <= 100; ++k)
			{
				for (int l = 1; i + j + k + l <= 100; ++l)
				{	
					// lol brute force!

					mix.clear();

					for (int a = 0; a < i; a++)
					{
						mix.push_back(sprinkles);
					}

					for (int b = 0; b < j; b++)
					{
						mix.push_back(peanutButter);
					}

					for (int c = 0; c < k; c++)
					{
						mix.push_back(frosting);
					}

					for (int d = 0; d < l; d++)
					{
						mix.push_back(sugar);
					}

					if (mix.size() == 100 && GetScore(mix) > highscore)
					{
						highscore = GetScore(mix);
						printf("High Score: %d, SP: %d, PB: %d, FR: %d, SU: %d, Spoons: %d\n", GetScore(mix), i, j, k, l, mix.size());
					}
				}
			}
		}
	}
}
Esempio n. 13
0
	void merge(const vector<string> & in_vcf_filenames, const string & outfile_prefix) {

		assert(in_vcf_filenames.size() > 1);
		GenotypedVcfFileReader tmpl_vcf(in_vcf_filenames.front(), true);

		// Prepare output metadata
		VcfMetaData output_meta_data = tmpl_vcf.metaData();
		uint num_samples = tmpl_vcf.metaData().numSamples();

		vector<unique_ptr<GenotypedVcfFileReader> > in_vcfs;
		
		for (uint in_vcf_idx = 1; in_vcf_idx < in_vcf_filenames.size(); in_vcf_idx++) {

			in_vcfs.push_back(unique_ptr<GenotypedVcfFileReader> (new GenotypedVcfFileReader(in_vcf_filenames.at(in_vcf_idx), true)));
			num_samples += in_vcfs.back()->metaData().numSamples();

			for (auto & smpl_id : in_vcfs.back()->metaData().sampleIds()) {

				output_meta_data.addSample(smpl_id);
			}

			assert(tmpl_vcf.metaData().contigs() == in_vcfs.back()->metaData().contigs());
			assert(tmpl_vcf.metaData().infoDescriptors() == in_vcfs.back()->metaData().infoDescriptors());
			assert(tmpl_vcf.metaData().filterDescriptors() == in_vcfs.back()->metaData().filterDescriptors());
			assert(tmpl_vcf.metaData().formatDescriptors() == in_vcfs.back()->metaData().formatDescriptors());
		}

		cout << "[" << Utils::getLocalTime() << "] Running BayesTyperUtils (" << BTU_VERSION << ") merge on " << in_vcf_filenames.size() << " files with containing " << num_samples << " samples in total ...\n" << endl;

		assert(output_meta_data.infoDescriptors().erase("HC"));

		VcfFileWriter output_vcf(outfile_prefix + ".vcf", output_meta_data, true);

		vector<string> var_value_assert_keys = {"VT", "VCS", "VCI", "VCGS", "VCGI", "HCR", "AE", "ACO", "AsmVar_ASQR"};

        auto sample_ids = output_meta_data.sampleIds();

		uint num_variants = 0;

		uint cache_size = 10000;
		vector<Variant*> tmpl_var_cache(cache_size, nullptr);
		vector<vector<Variant*> > in_var_caches(in_vcfs.size(), vector<Variant*>(cache_size, nullptr));

		bool reached_last_var = false;

		while (!reached_last_var) {

			/*
				Fill cache
			*/
			for (uint cache_idx = 0; cache_idx < cache_size; cache_idx++) {

				reached_last_var = !tmpl_vcf.getNextVariant(&tmpl_var_cache.at(cache_idx));

				if (reached_last_var) {

					cache_size = cache_idx;
					tmpl_var_cache.resize(cache_size);
				}
			}

			for (uint in_vcf_idx = 0; in_vcf_idx < in_vcfs.size(); in_vcf_idx++) {

				for (uint cache_idx = 0; cache_idx < cache_size; cache_idx++) {

					assert(in_vcfs.at(in_vcf_idx)->getNextVariant(&in_var_caches.at(in_vcf_idx).at(cache_idx)));
				}
			}

			/*
				Merge vars in cache
			*/

			for (uint cache_idx = 0; cache_idx < cache_size; cache_idx++) {

				num_variants++;

				Variant * cur_tmpl_var = tmpl_var_cache.at(cache_idx);
				
				assert(cur_tmpl_var);
				assert(cur_tmpl_var->filters().size() == 1);
				assert((cur_tmpl_var->filters().front() == "PASS") or (cur_tmpl_var->filters().front() == "UV"));

				set<ushort> alleles_not_covered;

				auto cur_tmpl_var_anc_values = cur_tmpl_var->info().getValue<string>("ANC");

				if (cur_tmpl_var_anc_values.second) {

					auto cur_tmpl_var_anc_values_split = Utils::splitString(cur_tmpl_var_anc_values.first, ',');

					for (auto &anc_value: cur_tmpl_var_anc_values_split) {

						alleles_not_covered.insert(stoi(anc_value));
					}
				}

				for (uint in_vcf_idx = 0; in_vcf_idx < in_vcfs.size(); in_vcf_idx++) {

					Variant * cur_in_var = in_var_caches.at(in_vcf_idx).at(cache_idx);
					assert(cur_in_var);

					assert(cur_tmpl_var->chrom() == cur_in_var->chrom());
					assert(cur_tmpl_var->pos() == cur_in_var->pos());

					assert(cur_tmpl_var->ids() == cur_in_var->ids());
					assert(cur_tmpl_var->numAlts() == cur_in_var->numAlts());

					for (auto & var_value_assert_key : var_value_assert_keys) {

						assert(cur_tmpl_var->info().getValue(var_value_assert_key) == cur_in_var->info().getValue(var_value_assert_key));
					}

					assert(cur_in_var->filters().size() == 1);
					assert((cur_tmpl_var->filters().front() == "UV") == (cur_in_var->filters().front() == "UV"));

					if (cur_in_var->filters().front() == "UV") {

						assert(Utils::splitString(fetchValue<string>(cur_in_var->info(), "AE"), ',').size() == cur_in_var->numAlls());

						assert(cur_tmpl_var->info().getValue("AC") == cur_in_var->info().getValue("AC"));
						assert(cur_tmpl_var->info().getValue("AF") == cur_in_var->info().getValue("AF"));
						assert(cur_tmpl_var->info().getValue("AN") == cur_in_var->info().getValue("AN"));
						assert(cur_tmpl_var->info().getValue("ACP") == cur_in_var->info().getValue("ACP"));
						assert(cur_tmpl_var->info().getValue("ANC") == cur_in_var->info().getValue("ANC"));

					} else {

						assert(cur_in_var->filters().front() == "PASS");
					}

					if (cur_in_var->info().getValue("HRS").second) {

						cur_tmpl_var->info().addFlag("HRS");
					}

					auto cur_in_var_anc_values = cur_in_var->info().getValue<string>("ANC");

					if (cur_in_var_anc_values.second) {

						auto cur_in_var_anc_values_split = Utils::splitString(cur_in_var_anc_values.first, ',');

						for (auto &anc_value: cur_in_var_anc_values_split) {

							alleles_not_covered.insert(stoi(anc_value));
						}
					}

					for (uint all_idx = 0; all_idx < cur_tmpl_var->numAlls(); all_idx++) {

						assert(cur_tmpl_var->allele(all_idx) == cur_in_var->allele(all_idx));
					}

					for (auto & smpl_id : in_vcfs.at(in_vcf_idx)->metaData().sampleIds()) {

						cur_tmpl_var->addSample(smpl_id, cur_in_var->getSample(smpl_id));
					}

					delete cur_in_var;
				}

				if (!(alleles_not_covered.empty())) {

					JoiningString anc_elements(',');

					for (auto &allele: alleles_not_covered) {

						anc_elements.join(to_string(allele));
					}

					cur_tmpl_var->info().setValue<string>("ANC", anc_elements.str());
				}

        		auto allele_stats = Stats::calcAlleleStats(cur_tmpl_var);
            	assert(!cur_tmpl_var->info().setValue<int>("AN", allele_stats.first.allele_count_sum));

				auto map_call_prob_and_var_qual = Stats::calcAlleleCallProbAndQualFromAllelePosteriors(cur_tmpl_var);
				assert(map_call_prob_and_var_qual.first.size() == cur_tmpl_var->numAlls());

				for (uint all_idx = 0; all_idx < cur_tmpl_var->numAlls(); all_idx++) {

					assert(!(cur_tmpl_var->allele(all_idx).info().setValue<float>("ACP", map_call_prob_and_var_qual.first.at(all_idx))));
   		
                    if (all_idx > 0) {

                        assert(!cur_tmpl_var->allele(all_idx).info().setValue<int>("AC", allele_stats.first.allele_counts.at(all_idx)));
                        assert(!cur_tmpl_var->allele(all_idx).info().setValue<float>("AF", allele_stats.first.allele_freqs.at(all_idx)));
                    }
                }

			    cur_tmpl_var->setQual(make_pair(map_call_prob_and_var_qual.second, true));
			    
				output_vcf.write(cur_tmpl_var);
				delete cur_tmpl_var;

				if (num_variants % 100000 == 0) {

					cout << "[" << Utils::getLocalTime() << "] Merged " << num_variants << " variant(s)" << endl;
				}
			}

			tmpl_var_cache = vector<Variant*>(cache_size, nullptr);
			in_var_caches = vector<vector<Variant*> >(in_vcfs.size(), vector<Variant*>(cache_size, nullptr));
		}

		Variant * dummy_var;

		for (auto & in_vcf : in_vcfs) {

			assert(!in_vcf->getNextVariant(&dummy_var));
		}

		cout << "\n[" << Utils::getLocalTime() << "] Completed merge of " << num_variants << " variant(s)" << endl;
		cout << endl;
	}
Esempio n. 14
0
		int extractInt(const DataKey& dataKey, TileKey::Dimension dimEnum) const {
			DataKeyDimension dim(TileKey::dimToString(dimEnum));
			DataKeyElement ele = dataKey.getElement(dim);
			std::string strVal = ele.getIdentifier();
			return stoi(strVal);
		}
 int helper(string& data) {
     int pos = data.find(',');
     int val = stoi(data.substr(0,pos));
     data = data.substr(pos+1);
     return val;
 }
Esempio n. 16
0
int main(int argc, char *argv[]) {
	clock_t start = clock();
	/*
		Parsing the arguments
	*/
	string TASK, filename, SFILE, TFILE;
	uint64_t len_samp, len_test;

	int num_iter = 51, probes, num_simuls = 1, ind; 
	double epsilon = 0.1, theta = 0.75;

	for (int i=0; i<argc; ++i) {			
		if (! strcmp(argv[i],"-TASK")) {			
			TASK = argv[i+1];
		} else if (! strcmp(argv[i],"-SAMPLE")) {
			len_samp = stoi(argv[i+1]);
		} else if (! strcmp(argv[i],"-TEST")) {
			len_test = stoi(argv[i+1]);
		} else if (! strcmp(argv[i],"-DIR")) {
			filename = argv[i+1];
			filename +=  "graph";			
		} else if (! strcmp(argv[i],"-EPSILON")) {
			epsilon = stod(argv[i+1]);
		} else if (! strcmp(argv[i],"-THETA")) {
			theta = stod(argv[i+1]);
		} else if (! strcmp(argv[i],"-NUM_ITER")) {
			num_iter = stod(argv[i+1]);
		} else if (! strcmp(argv[i],"-PROBES")) {
			probes = stod(argv[i+1]);
		} else if (! strcmp(argv[i],"-NUM_SIMULS")) {
			num_simuls = stod(argv[i+1]);
		} else if (! strcmp(argv[i],"-IND")) {
			ind = stod(argv[i+1]);
		} else if (! strcmp(argv[i],"-SAMPLE_FILE")) {
			SFILE = argv[i+1];
		} else if (! strcmp(argv[i],"-TEST_FILE")) {
			TFILE = argv[i+1];
		}

	}

	/*
		Running the tasks
	*/



	if (TASK == "sampler") {
		Graph g(filename, theta);
		sampler(g, my_get_dir_name(filename), len_samp);
	} else if (TASK == "auto_sampler") {
		Graph g(filename, theta);
		len_samp = getAutoLenSamp(g.number_of_nodes, epsilon, theta); // computing the sample size
		sampler(g, my_get_dir_name(filename), len_samp);

	} else if (TASK == "indexed_sampler") {
		Graph g(filename, theta);
		indexed_sampler(g, my_get_dir_name(filename), len_samp, ind);

	} else if (TASK == "auto_indexed_sampler") {
		Graph g(filename, theta);
		len_samp = getAutoLenSamp(g.number_of_nodes, epsilon, theta); // computing the sample size
		indexed_sampler(g, my_get_dir_name(filename), len_samp, ind);		

	} else if (TASK == "solver") {
		string samp_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_samp);
		solver(samp_file, theta, num_iter, probes);	

	} else if (TASK == "auto_solver") {
		Graph g(filename, theta);
		len_samp = getAutoLenSamp(g.number_of_nodes, epsilon, theta); // computing the sample size
		string samp_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_samp);
		solver(samp_file, theta, num_iter, probes);	

	} else if (TASK == "solver-with-file") {
		string samp_file = SFILE;
		solver(samp_file, theta, num_iter, probes);	

	} else if (TASK == "indexed_solver") {
		string samp_file = my_get_dir_name(filename)  +"indexed/S-"+to_string(len_samp)+"-"+to_string(ind);
		solver(samp_file, theta, num_iter, probes);	

	} else if (TASK == "tester") {
		string samp_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_samp);
		string test_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_test);
		tester(samp_file, test_file, num_iter, probes, theta);

	} else if (TASK == "indexed_tester") {
		string samp_file = my_get_dir_name(filename)  +"indexed/S-"+to_string(len_samp)+"-"+to_string(ind);
		string test_file = my_get_dir_name(filename)  +"indexed/S-"+to_string(len_test)+"-"+to_string(ind);
		tester(samp_file, test_file, num_iter, probes, theta);
		
	} else if (TASK == "simulator") {
		epsilon = 0.1;
		simulator(filename, num_simuls, num_iter, theta, epsilon);
	
	} else if (TASK == "compare") {
		string samp_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_samp);
		string test_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_test);
		compare(filename, samp_file, test_file, num_iter, probes, theta);	
	} else if (TASK == "compare-with-file") {
		string samp_file = SFILE;
		string test_file = TFILE;
		compare_with_file(samp_file, test_file, num_iter, probes, theta);	
	
	//  -------------------------------
	} else if (TASK == "auto_compare") {
		Graph g(filename, theta);
		len_samp = getAutoLenSamp(g.number_of_nodes, epsilon, theta);
		probes = 1;

		string samp_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_samp);
		string test_file = my_get_dir_name(filename)  +"samples/S-"+to_string(len_samp)+"-"+to_string(ind);
		compare(filename, samp_file, test_file, num_iter, probes, theta);
	
//  ---------------------------------------
	} else if (TASK == "solver_uniform") {
		vector<int> lens = {5,10,20,50,100,200,500,1000,2000,5000,10000,20000};
		// vector<int> lens = {10};
		probes = 1;
		// num_iter = 101;
		theta = 0.99;
		
		string samp_file;
		for (auto l : lens) {
			cout << "working on lenght " << l << ": ";
			for (int idx=0; idx<10; ++idx) {
				samp_file = my_get_dir_name(filename) + "S-" + to_string(l) + "-" + to_string(idx);
				cout << idx << ", ";
				randsolver(samp_file, theta, num_iter, probes);
				// cout << samp_file << endl;
				
			}
			cout << endl;
		}
	} else if (TASK == "cost_uniform") {
		vector<int> lens = {5,10,20,50,100,200,500,1000,2000,5000,10000,20000};
		
		probes = 1;
		// num_iter = 101;
		theta = 0.99;
		
		string samp_file, test_file;
		double c;
		ofstream fout("D100-costs");

		for (auto l : lens) {
			cout << "working on lenght " << l << ": ";
			fout << l << "\t";
			for (int idx=0; idx<10; ++idx) {
				samp_file = my_get_dir_name(filename) + "S-" + to_string(l) + "-" + to_string(idx);
				test_file = my_get_dir_name(filename) + "T";
				// cout << idx << ", ";
				
				c = unif_compare_with_file(samp_file, test_file, num_iter,probes, theta);
				cout << " " << c;
				fout << c << "\t";
				
			}
			cout << endl;
			fout << endl;
		}
		fout.close();

		cout << endl << endl;
		fout.open("D100-vardist");
		for (auto l : lens) {
			cout << "working on lenght " << l << ": ";
			fout << l << "\t";
			for (int idx=0; idx<10; ++idx) {
				samp_file = my_get_dir_name(filename) + "S-" + to_string(l) + "-" + to_string(idx);
				test_file = my_get_dir_name(filename) + "T";
				// cout << idx << ", ";
				
				c = vardist_f(samp_file, test_file, num_iter,probes, theta);
				cout << " " << c;
				fout << c << "\t";
				
			}
			cout << endl;
			fout << endl;
		}
		fout.close();

	}

	clock_t stop = clock();
	cout << "total_time: " << double(stop-start) / CLOCKS_PER_SEC << endl;
	
	return 0;
}
Esempio n. 17
0
 int parse(string &str) {
     int pos = str.find('.');
     int val = stoi(str.substr(0, pos));
     str = pos==string::npos?"":str.substr(pos+1);
     return val;
 }
Esempio n. 18
0
bool generate_image(std::string part_of_name, video::IImage *& baseimg,
		IrrlichtDevice *device)
{
	video::IVideoDriver* driver = device->getVideoDriver();
	assert(driver);

	// Stuff starting with [ are special commands
	if(part_of_name[0] != '[')
	{
		// A normal texture; load it from a file
		std::string path = getTexturePath(part_of_name.c_str());
		/*infostream<<"generate_image(): Loading path \""<<path
				<<"\""<<std::endl;*/
		
		video::IImage *image = driver->createImageFromFile(path.c_str());

		if(image == NULL)
		{
			infostream<<"generate_image(): Could not load image \""
                    <<part_of_name<<"\" from path \""<<path<<"\""
					<<" while building texture"<<std::endl;

			//return false;

			infostream<<"generate_image(): Creating a dummy"
                    <<" image for \""<<part_of_name<<"\""<<std::endl;

			// Just create a dummy image
			//core::dimension2d<u32> dim(2,2);
			core::dimension2d<u32> dim(1,1);
			image = driver->createImage(video::ECF_A8R8G8B8, dim);
			assert(image);
			/*image->setPixel(0,0, video::SColor(255,255,0,0));
			image->setPixel(1,0, video::SColor(255,0,255,0));
			image->setPixel(0,1, video::SColor(255,0,0,255));
			image->setPixel(1,1, video::SColor(255,255,0,255));*/
			image->setPixel(0,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			/*image->setPixel(1,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(0,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(1,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));*/
		}

		// If base image is NULL, load as base.
		if(baseimg == NULL)
		{
			//infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
			/*
				Copy it this way to get an alpha channel.
				Otherwise images with alpha cannot be blitted on 
				images that don't have alpha in the original file.
			*/
			core::dimension2d<u32> dim = image->getDimension();
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			image->copyTo(baseimg);
			image->drop();
		}
		// Else blit on base.
		else
		{
			//infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
			// Size of the copied area
			core::dimension2d<u32> dim = image->getDimension();
			//core::dimension2d<u32> dim(16,16);
			// Position to copy the blitted to in the base image
			core::position2d<s32> pos_to(0,0);
			// Position to copy the blitted from in the blitted image
			core::position2d<s32> pos_from(0,0);
			// Blit
			image->copyToWithAlpha(baseimg, pos_to,
					core::rect<s32>(pos_from, dim),
					video::SColor(255,255,255,255),
					NULL);
			// Drop image
			image->drop();
		}
	}
	else
	{
		// A special texture modification

		infostream<<"generate_image(): generating special "
				<<"modification \""<<part_of_name<<"\""
				<<std::endl;
		
		/*
			This is the simplest of all; it just adds stuff to the
			name so that a separate texture is created.

			It is used to make textures for stuff that doesn't want
			to implement getting the texture from a bigger texture
			atlas.
		*/
		if(part_of_name == "[forcesingle")
		{
		}
		/*
			[crackN
			Adds a cracking texture
		*/
		else if(part_of_name.substr(0,6) == "[crack")
		{
			if(baseimg == NULL)
			{
				infostream<<"generate_image(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}
			
			// Crack image number
			u16 progression = stoi(part_of_name.substr(6));

			// Size of the base image
			core::dimension2d<u32> dim_base = baseimg->getDimension();
			
			/*
				Load crack image.

				It is an image with a number of cracking stages
				horizontally tiled.
			*/
			video::IImage *img_crack = driver->createImageFromFile(
					getTexturePath("crack.png").c_str());
		
			if(img_crack)
			{
				// Dimension of original image
				core::dimension2d<u32> dim_crack
						= img_crack->getDimension();
				// Count of crack stages
				u32 crack_count = dim_crack.Height / dim_crack.Width;
				// Limit progression
				if(progression > crack_count-1)
					progression = crack_count-1;
				// Dimension of a single scaled crack stage
				core::dimension2d<u32> dim_crack_scaled_single(
					dim_base.Width,
					dim_base.Height
				);
				// Dimension of scaled size
				core::dimension2d<u32> dim_crack_scaled(
					dim_crack_scaled_single.Width,
					dim_crack_scaled_single.Height * crack_count
				);
				// Create scaled crack image
				video::IImage *img_crack_scaled = driver->createImage(
						video::ECF_A8R8G8B8, dim_crack_scaled);
				if(img_crack_scaled)
				{
					// Scale crack image by copying
					img_crack->copyToScaling(img_crack_scaled);
					
					// Position to copy the crack from
					core::position2d<s32> pos_crack_scaled(
						0,
						dim_crack_scaled_single.Height * progression
					);
					
					// This tiling does nothing currently but is useful
					for(u32 y0=0; y0<dim_base.Height
							/ dim_crack_scaled_single.Height; y0++)
					for(u32 x0=0; x0<dim_base.Width
							/ dim_crack_scaled_single.Width; x0++)
					{
						// Position to copy the crack to in the base image
						core::position2d<s32> pos_base(
							x0*dim_crack_scaled_single.Width,
							y0*dim_crack_scaled_single.Height
						);
						// Rectangle to copy the crack from on the scaled image
						core::rect<s32> rect_crack_scaled(
							pos_crack_scaled,
							dim_crack_scaled_single
						);
						// Copy it
						img_crack_scaled->copyToWithAlpha(baseimg, pos_base,
								rect_crack_scaled,
								video::SColor(255,255,255,255),
								NULL);
					}

					img_crack_scaled->drop();
				}
				
				img_crack->drop();
			}
		}
		/*
			[combine:WxH:X,Y=filename:X,Y=filename2
			Creates a bigger texture from an amount of smaller ones
		*/
		else if(part_of_name.substr(0,8) == "[combine")
		{
			Strfnd sf(part_of_name);
			sf.next(":");
			u32 w0 = stoi(sf.next("x"));
			u32 h0 = stoi(sf.next(":"));
			infostream<<"combined w="<<w0<<" h="<<h0<<std::endl;
			core::dimension2d<u32> dim(w0,h0);
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			while(sf.atend() == false)
			{
				u32 x = stoi(sf.next(","));
				u32 y = stoi(sf.next("="));
				std::string filename = sf.next(":");
				infostream<<"Adding \""<<filename
						<<"\" to combined ("<<x<<","<<y<<")"
						<<std::endl;
				video::IImage *img = driver->createImageFromFile(
						getTexturePath(filename.c_str()).c_str());
				if(img)
				{
					core::dimension2d<u32> dim = img->getDimension();
					infostream<<"Size "<<dim.Width
							<<"x"<<dim.Height<<std::endl;
					core::position2d<s32> pos_base(x, y);
					video::IImage *img2 =
							driver->createImage(video::ECF_A8R8G8B8, dim);
					img->copyTo(img2);
					img->drop();
					img2->copyToWithAlpha(baseimg, pos_base,
							core::rect<s32>(v2s32(0,0), dim),
							video::SColor(255,255,255,255),
							NULL);
					img2->drop();
				}
				else
				{
					infostream<<"img==NULL"<<std::endl;
				}
			}
		}
		/*
			[progressbarN
			Adds a progress bar, 0.0 <= N <= 1.0
		*/
		else if(part_of_name.substr(0,12) == "[progressbar")
		{
			if(baseimg == NULL)
			{
				infostream<<"generate_image(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			float value = stof(part_of_name.substr(12));
			make_progressbar(value, baseimg);
		}
		/*
			"[noalpha:filename.png"
			Use an image without it's alpha channel.
			Used for the leaves texture when in old leaves mode, so
			that the transparent parts don't look completely black 
			when simple alpha channel is used for rendering.
		*/
		else if(part_of_name.substr(0,8) == "[noalpha")
		{
			if(baseimg != NULL)
			{
				infostream<<"generate_image(): baseimg!=NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			std::string filename = part_of_name.substr(9);

			std::string path = getTexturePath(filename.c_str());

			infostream<<"generate_image(): Loading path \""<<path
					<<"\""<<std::endl;
			
			video::IImage *image = driver->createImageFromFile(path.c_str());
			
			if(image == NULL)
			{
				infostream<<"generate_image(): Loading path \""
						<<path<<"\" failed"<<std::endl;
			}
			else
			{
				core::dimension2d<u32> dim = image->getDimension();
				baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
				
				// Set alpha to full
				for(u32 y=0; y<dim.Height; y++)
				for(u32 x=0; x<dim.Width; x++)
				{
					video::SColor c = image->getPixel(x,y);
					c.setAlpha(255);
					image->setPixel(x,y,c);
				}
				// Blit
				image->copyTo(baseimg);

				image->drop();
			}
		}
		/*
			"[makealpha:R,G,B:filename.png"
			Use an image with converting one color to transparent.
		*/
		else if(part_of_name.substr(0,11) == "[makealpha:")
		{
			if(baseimg != NULL)
			{
				infostream<<"generate_image(): baseimg!=NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			Strfnd sf(part_of_name.substr(11));
			u32 r1 = stoi(sf.next(","));
			u32 g1 = stoi(sf.next(","));
			u32 b1 = stoi(sf.next(":"));
			std::string filename = sf.next("");

			std::string path = getTexturePath(filename.c_str());

			infostream<<"generate_image(): Loading path \""<<path
					<<"\""<<std::endl;
			
			video::IImage *image = driver->createImageFromFile(path.c_str());
			
			if(image == NULL)
			{
				infostream<<"generate_image(): Loading path \""
						<<path<<"\" failed"<<std::endl;
			}
			else
			{
				core::dimension2d<u32> dim = image->getDimension();
				baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
				
				// Blit
				image->copyTo(baseimg);

				image->drop();

				for(u32 y=0; y<dim.Height; y++)
				for(u32 x=0; x<dim.Width; x++)
				{
					video::SColor c = baseimg->getPixel(x,y);
					u32 r = c.getRed();
					u32 g = c.getGreen();
					u32 b = c.getBlue();
					if(!(r == r1 && g == g1 && b == b1))
						continue;
					c.setAlpha(0);
					baseimg->setPixel(x,y,c);
				}
			}
		}
		/*
			"[makealpha2:R,G,B;R2,G2,B2:filename.png"
			Use an image with converting two colors to transparent.
		*/
		else if(part_of_name.substr(0,12) == "[makealpha2:")
		{
			if(baseimg != NULL)
			{
				infostream<<"generate_image(): baseimg!=NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			Strfnd sf(part_of_name.substr(12));
			u32 r1 = stoi(sf.next(","));
			u32 g1 = stoi(sf.next(","));
			u32 b1 = stoi(sf.next(";"));
			u32 r2 = stoi(sf.next(","));
			u32 g2 = stoi(sf.next(","));
			u32 b2 = stoi(sf.next(":"));
			std::string filename = sf.next("");

			std::string path = getTexturePath(filename.c_str());

			infostream<<"generate_image(): Loading path \""<<path
					<<"\""<<std::endl;
			
			video::IImage *image = driver->createImageFromFile(path.c_str());
			
			if(image == NULL)
			{
				infostream<<"generate_image(): Loading path \""
						<<path<<"\" failed"<<std::endl;
			}
			else
			{
				core::dimension2d<u32> dim = image->getDimension();
				baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);

				// Blit
				image->copyTo(baseimg);

				image->drop();
				
				for(u32 y=0; y<dim.Height; y++)
				for(u32 x=0; x<dim.Width; x++)
				{
					video::SColor c = baseimg->getPixel(x,y);
					u32 r = c.getRed();
					u32 g = c.getGreen();
					u32 b = c.getBlue();
					if(!(r == r1 && g == g1 && b == b1) &&
					   !(r == r2 && g == g2 && b == b2))
						continue;
					c.setAlpha(0);
					baseimg->setPixel(x,y,c);
				}
			}
		}
		/*
			[inventorycube{topimage{leftimage{rightimage
			In every subimage, replace ^ with &.
			Create an "inventory cube".
			NOTE: This should be used only on its own.
			Example (a grass block (not actually used in game):
			"[inventorycube{grass.png{mud.png&grass_side.png{mud.png&grass_side.png"
		*/
		else if(part_of_name.substr(0,14) == "[inventorycube")
		{
			if(baseimg != NULL)
			{
				infostream<<"generate_image(): baseimg!=NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			str_replace_char(part_of_name, '&', '^');
			Strfnd sf(part_of_name);
			sf.next("{");
			std::string imagename_top = sf.next("{");
			std::string imagename_left = sf.next("{");
			std::string imagename_right = sf.next("{");

#if 1
			//TODO

			if(driver->queryFeature(video::EVDF_RENDER_TO_TARGET) == false)
			{
				infostream<<"generate_image(): EVDF_RENDER_TO_TARGET"
						" not supported. Creating fallback image"<<std::endl;
				baseimg = generate_image_from_scratch(
						imagename_top, device);
				return true;
			}
			
			u32 w0 = 64;
			u32 h0 = 64;
			//infostream<<"inventorycube w="<<w0<<" h="<<h0<<std::endl;
			core::dimension2d<u32> dim(w0,h0);
			
			// Generate images for the faces of the cube
			video::IImage *img_top = generate_image_from_scratch(
					imagename_top, device);
			video::IImage *img_left = generate_image_from_scratch(
					imagename_left, device);
			video::IImage *img_right = generate_image_from_scratch(
					imagename_right, device);
			assert(img_top && img_left && img_right);

			// TODO: Create textures from images
			video::ITexture *texture_top = driver->addTexture(
					(imagename_top + "__temp__").c_str(), img_top);
			assert(texture_top);
			
			// Drop images
			img_top->drop();
			img_left->drop();
			img_right->drop();
			
			// Create render target texture
			video::ITexture *rtt = NULL;
			std::string rtt_name = part_of_name + "_RTT";
			rtt = driver->addRenderTargetTexture(dim, rtt_name.c_str(),
					video::ECF_A8R8G8B8);
			assert(rtt);
			
			// Set render target
			driver->setRenderTarget(rtt, true, true,
					video::SColor(0,0,0,0));
			
			// Get a scene manager
			scene::ISceneManager *smgr_main = device->getSceneManager();
			assert(smgr_main);
			scene::ISceneManager *smgr = smgr_main->createNewSceneManager();
			assert(smgr);
			
			/*
				Create scene:
				- An unit cube is centered at 0,0,0
				- Camera looks at cube from Y+, Z- towards Y-, Z+
				NOTE: Cube has to be changed to something else because
				the textures cannot be set individually (or can they?)
			*/

			scene::ISceneNode* cube = smgr->addCubeSceneNode(1.0, NULL, -1,
					v3f(0,0,0), v3f(0, 45, 0));
			// Set texture of cube
			cube->setMaterialTexture(0, texture_top);
			//cube->setMaterialFlag(video::EMF_LIGHTING, false);
			cube->setMaterialFlag(video::EMF_ANTI_ALIASING, false);
			cube->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);

			scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(0,
					v3f(0, 1.0, -1.5), v3f(0, 0, 0));
			// Set orthogonal projection
			core::CMatrix4<f32> pm;
			pm.buildProjectionMatrixOrthoLH(1.65, 1.65, 0, 100);
			camera->setProjectionMatrix(pm, true);

			/*scene::ILightSceneNode *light =*/ smgr->addLightSceneNode(0,
					v3f(-50, 100, 0), video::SColorf(0.5,0.5,0.5), 1000);

			smgr->setAmbientLight(video::SColorf(0.2,0.2,0.2));

			// Render scene
			driver->beginScene(true, true, video::SColor(0,0,0,0));
			smgr->drawAll();
			driver->endScene();
			
			// NOTE: The scene nodes should not be dropped, otherwise
			//       smgr->drop() segfaults
			/*cube->drop();
			camera->drop();
			light->drop();*/
			// Drop scene manager
			smgr->drop();
			
			// Unset render target
			driver->setRenderTarget(0, true, true, 0);

			//TODO: Free textures of images
			driver->removeTexture(texture_top);
			
			// Create image of render target
			video::IImage *image = driver->createImage(rtt, v2s32(0,0), dim);

			assert(image);
			
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);

			if(image)
			{
				image->copyTo(baseimg);
				image->drop();
			}
#endif
		}
		else
		{
			infostream<<"generate_image(): Invalid "
					" modification: \""<<part_of_name<<"\""<<std::endl;
		}
	}

	return true;
}
Esempio n. 19
0
void Arg_Interpreter::create_argfile_from_cons(string argfile_name) {

        string argfile_path = this->PATH + argfile_name;
        this->UI->cout_str("AI-> creating argfile " + argfile_path);

        ofstream file;
        file.open(argfile_path,ios::out); //création du fichier txt arg_file

        //caractéristiques du pattern
        (this->UI)->cout_str("Enter the height of the pattern (int)");
        file << "x_size = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the width of the pattern (int)");
        file << "y_size = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the initial time step (float)");
        file << "time_step = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the space step (float)");
        file << "space_step = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the CFL condition (float)");
        file << "CFL_cond = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the number of iterations for the eq_diff solver (int)");
        file << "iter_number_solver = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the number of iterations for the profiler (int)");
        file << "iter_number_profiler = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the number of threads allocated to the program (int)");
        file << "nb_of_threads = " << (this->UI)->cin_str() << endl;

        //Paramètres de fitting, et conditions initiales


        this->UI->cout_str("Choose how many points you want to usei for the initial nozzle profile (int)");
        string answer = this->UI->cin_str();
        file << "->nb_pts = " << answer << endl;
                
        this->UI->cout_str("Give the abscisses of your points (int)");
        for (int i=0; i < stoi(answer); i++) {
                file << "->abs = " << this->UI->cin_str() << endl;
        }

        this->UI->cout_str("Give the ordinates of your points (int)");
        for (int i=0; i < stoi(answer); i++) {
                file << "->ord = " << this->UI->cin_str() << endl;
        }

        (this->UI)->cout_str("Choose the type of initial condition (initial_gradient=0, evoluting_chamber_conditions=1");
        answer = (this->UI)->cin_str();
        file << "init_cond_type = " << answer << endl;

        if (answer == "1"){
            (this->UI)->cout_str("Enter the number of iterations to reach the final chamber conditions (int)");
            file << "iter_number_evol_chamber = " << (this->UI)->cin_str() << endl;

        }
        else {file << "iter_number_evol_chamber = " << 0 << endl;}
        
        (this->UI)->cout_str("Choose the differential equation solver algorithm (PG_cart=0,VDW_cart=1,PG_cyl=2,VDW_cyl=3,PG_cart_turb=4)");
        answer = (this->UI)->cin_str();
        file << "differential_equation_solver_algo = " << answer << endl;
        
        // Constantes numériques pour l'eq diff

        string diff_eq_solver_algo = answer; //degueu mais nécéssaire pour plus tard --> constante pour les gaz et turbulences

        if ( answer == "1" or answer == "3" ) {
                (this->UI)->cout_str("Enter the Van der Waals coefficient 'a' (float)");
                file << "VDW_a_coeff = " << (this->UI)->cin_str() << endl;

                (this->UI)->cout_str("Enter the Van der Waals coefficient 'b' (float)");
                file << "VDW_b_coeff = " << (this->UI)->cin_str() << endl;
        }
        else {
                file << "VDW_a_coeff = 0" << endl;
                file << "VDW_b_coeff = 0" << endl;
        }

        (this->UI)->cout_str("Activate thermal conduction ? (bool: true/false)");
        answer = (this->UI)->cin_str();
        file << "thermal_conduction = " << answer << endl;

        if (answer == "true") {
        (this->UI)->cout_str("Enter the thermal conduction value (float)");
        file << "lambda = " << (this->UI)->cin_str() << endl;
        }
        else file << "lambda = 0" << endl;

        (this->UI)->cout_str("Enter the mole mass of the gaz (float)");
        file << "mol_mass = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the coefficient of dynamic viscosity (float)");
        file << "dyn_visc = " << (this->UI)->cin_str() << endl;

        //caractéristiques numériques initiales
        
        (this->UI)->cout_str("Enter the initial pressure of the chamber (float)");
        file << "init_chamber_pressure = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the initial temperature of the chamber (float)");
        file << "init_chamber_temperature = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the initial speed of the chamber (float)");
        file << "init_chamber_speed = " << (this->UI)->cin_str() << endl;

        if ( diff_eq_solver_algo == "4") {
                (this->UI)->cout_str("Enter the value of k (turbulence energy) in the chamber (float)");
                file << "init_chamber_turb_en = " << (this->UI)->cin_str() << endl;
                
                (this->UI)->cout_str("Enter the value of epsilon (turbulence dissipation) in the chamber (float)");
                file << "init_chamber_turb_dis = " << (this->UI)->cin_str() << endl;
        }
        else {
                file << "init_chamber_turb_en = 0" << endl;
                file << "init_chamber_turb_dis = 0" << endl;
        }

        (this->UI)->cout_str("Enter the initial pressure of the atmostphere (float)");
        file << "init_atmosphere_pressure = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the initial temperature of the atmostphere (float)");
        file << "init_atmosphere_temperature = " << (this->UI)->cin_str() << endl;

        (this->UI)->cout_str("Enter the initial speed of the atmosphere (float)");
        file << "init_atmosphere_speed = " << (this->UI)->cin_str() << endl;

        if ( diff_eq_solver_algo == "4") {
                (this->UI)->cout_str("Enter the value of k (turbulence energy) in the atmosphere (float)");
                file << "init_atmosphere_turb_en = " << (this->UI)->cin_str() << endl;
                
                (this->UI)->cout_str("Enter the value of epsilon (turbulence dissipation) in the atmosphere (float)");
                file << "init_atmosphere_turb_dis = " << (this->UI)->cin_str() << endl;
        }
        else {
                file << "init_atmosphere_turb_en = 0" << endl;
                file << "init_atmosphere_turb_dis = 0" << endl;
        }

        file.close();
}
Esempio n. 20
0
void BattleMap::f_generateEnemy( int i )
{
	CC_SAFE_RELEASE_NULL(m_itemlist);
	m_itemlist = new CCDictionary();
	vector<map<string,string>> vdata;
	DBUtil::initDB("save.db");
	string m_sSql = CCString::createWithFormat("select * from enemy_group where id = %d",i)->getCString();
	vdata = DBUtil::getDataInfo(m_sSql,NULL);

	map<string,string> t_ssm = (map<string,string>) vdata.at(0);
	string t_mask	= t_ssm.at("mask");
	string t_is		= t_ssm.at("member");
	vdata.clear();
	m_sSql = CCString::createWithFormat("select * from enemy_list where id IN (%s)", t_mask.c_str())->getCString();
	vdata = DBUtil::getDataInfo(m_sSql,NULL);
	DBUtil::closeDB();

	//Prepare to analysis enemy group data get from db.
	m_miEnemis.clear();
	stringstream teststream;
	teststream<<t_is;
	int t_id,t_num;
	do{
		t_id = 0;
		teststream>>t_id;
		if(t_id < 1) break;
		teststream>>t_num;
		m_miEnemis[t_id] = t_num;
		CCLOG("Read out :%d.%d.:",t_id,t_num);
	} while(1);
	CCLOG(">Enemy Generationg Over.");

	//Where to place the EChesses should be decided here, f_load_entile() only init the map.
	for(int i = 0; i<vdata.size(); ++i){
		map<string,string> t_ssm = (map<string,string>) vdata.at(i);
		int t_fi_id	=	stoi(t_ssm.at("id"));
		int t_fi_sum	=	m_miEnemis[t_fi_id];

		//if(t_fi_sum == 0) exit(0x5008);	//If here ends a zero sum. There might be some problem with db_sp.

		Scriptor* t_scp = new Scriptor();
		t_scp->parse_string(t_ssm.at("attr"));					//Sp stored in attr. This is to make the enemy always the same to Chara.

		//EChesses* t_fij_ec = new EChesses();




		//t_fij_ec->m_pChara->retain();

		for(int j = 0; j<t_fi_sum; ++j){			//Generate the number that is needed.			

			EChesses* t_fij_ecd = new EChesses();

			t_fij_ecd->load_chara_dbsp((Script*) t_scp->m_caScript->objectAtIndex(0));


			t_fij_ecd->psz	=	"grossinis_sister2.png";			//Test Only.
			t_fij_ecd->pos	=	ccp(10,10);
			t_fij_ecd->group_id = 0x02;
			t_fij_ecd->group_mask = 0x01;

			t_fij_ecd->name	=	CCString::createWithFormat("enemy_%d",j)->getCString();
			m_itemlist->setObject(t_fij_ecd,t_fij_ecd->name);
			//t_fij_ecd->autorelease();

			t_fij_ecd->m_pChara->m_sName		 =	 t_ssm.at("name");			//TODO:IN:PB: all the generated enemy may use the same chara(), if so put down this to next stage.
			t_fij_ecd->m_pChara->m_sPsz		 =	 t_ssm.at("psz");
			t_fij_ecd->m_pChara->m_iElement	 =	 stoi(t_ssm.at("element"));
		}

		CC_SAFE_DELETE(t_scp);
		CCLOG("Lock out.");
	}	

}
Esempio n. 21
0
std::unique_ptr<sf::RectangleShape> CreateRectangleShape (std::map<std::string, std::string> rectShape)
{
    
    std::unique_ptr<sf::RectangleShape> rectangleShape(new sf::RectangleShape());
    
    try
    {
        sf::Vector2f vectorSize;
        sf::Vector2f vectorPosition;
        std::string outlineColor, fillColor;
        int outlineRed = 0, outlineBlue = 0, outlineGreen = 0, outlineAlpha = 255;
        int fillRed = 0, fillBlue = 0, fillGreen = 0, fillAlpha = 255;
        float outlineThickness = 0;
        bool fillColorSet = false, outlineColorSet = false;

        for (auto attribute : rectShape)
        {
            if (attribute.first == SIZE_X)
            {
                vectorSize.x = stof (attribute.second);
            }
            else if (attribute.first == SIZE_Y)
            {
                vectorSize.y = stof (attribute.second);
            }
            else if (attribute.first == POS_X)
            {
                vectorPosition.x = stof (attribute.second);
            }
            else if (attribute.first == POS_Y)
            {
                vectorPosition.y = stof (attribute.second);
            }
            else if (attribute.first == OUTLINE_COLOR)
            {
                outlineColor = (attribute.second);
                outlineColorSet = true;
            }
            else if (attribute.first == OUTLINE_R)
            {
                outlineRed = stoi (attribute.second);
            }
            else if (attribute.first == OUTLINE_G)
            {
                outlineGreen = stoi (attribute.second);
            }
            else if (attribute.first == OUTLINE_B)
            {
                outlineBlue = stoi (attribute.second);
            }
            else if (attribute.first == OUTLINE_A)
            {
                outlineAlpha = stoi (attribute.second);
            }
            else if (attribute.first == OUTLINE_THICK)
            {
                outlineThickness = stof (attribute.second);
            }
            else if (attribute.first == FILL_COLOR)
            {
                fillColor = (attribute.second);
                fillColorSet = true;
            }
            else if (attribute.first == FILL_R)
            {
                fillRed = stoi (attribute.second);
            }
            else if (attribute.first == FILL_G)
            {
                fillGreen = stoi (attribute.second);
            }
            else if (attribute.first == FILL_B)
            {
                fillBlue = stoi (attribute.second);
            }
            else if (attribute.first == FILL_A)
            {
                fillAlpha = stoi (attribute.second);
            }
            else if (attribute.first == NAME || attribute.first == TYPE)
            {
                // Not used to create shape
                // Used to stop else printing errors for these two attributes
            }
            else
            {
                std::cout << "Error creating RectangleShape: " << attribute.first
                          << " is either misspelled or not implemented." << std::endl;
            }
        }
        rectangleShape->setSize (vectorSize);
        rectangleShape->setPosition (vectorPosition);

        // FillColor takes precedence over RBGA
        if (fillColorSet == true)
        {
            rectangleShape->setFillColor (ColorWrapper::matchColor (fillColor));
        }
        else
        {
            rectangleShape->setFillColor (ColorWrapper::rbgaColor (fillRed, fillBlue, fillGreen, fillAlpha));
        }

        // OutlineColor takes precedence over RBGA
        if (outlineColorSet == true)
        {
            rectangleShape->setOutlineColor (ColorWrapper::matchColor (outlineColor));
        }
        else
        {
            rectangleShape->setOutlineColor (ColorWrapper::rbgaColor (outlineRed, outlineBlue, outlineGreen, outlineAlpha));
        }

        rectangleShape->setOutlineThickness (outlineThickness);

    }
    catch (std::runtime_error &e)
    {
        std::cout << "Exception in createRectangleShape: " << rectShape[NAME] << " : " << e.what() << std::endl;
    }
    catch (std::invalid_argument &a) // invalid from stof or stoi
    {
        std::cout << "Invalid Argument in createRectangleShape: " << rectShape[NAME] << " : " << a.what() << std::endl;
    }
    catch (std::out_of_range &o) // out of range from stof or stoi
    {
        std::cout << "Out of range in createRectangleShape: " << rectShape[NAME] << " : " << o.what() << std::endl;
    }
    
    if (rectangleShape != nullptr)
    {
        assert (rectangleShape);
        return rectangleShape;
    }
    else
    {
        rectangleShape = nullptr;
        return rectangleShape;
    }

} // RectangleWrapper::CreateRectangleShape
Esempio n. 22
0
bool ClientLauncher::launch_game(std::string &error_message,
                                 bool reconnect_requested, GameParams &game_params,
                                 const Settings &cmd_args)
{
    // Initialize menu data
    MainMenuData menudata;
    menudata.address                         = address;
    menudata.name                            = playername;
    menudata.password                        = password;
    menudata.port                            = itos(game_params.socket_port);
    menudata.script_data.errormessage        = error_message;
    menudata.script_data.reconnect_requested = reconnect_requested;

    error_message.clear();

    if (cmd_args.exists("password"))
        menudata.password = cmd_args.get("password");

    menudata.enable_public = g_settings->getBool("server_announce");

    // If a world was commanded, append and select it
    if (game_params.world_path != "") {
        worldspec.gameid = getWorldGameId(game_params.world_path, true);
        worldspec.name = _("[--world parameter]");

        if (worldspec.gameid == "") {	// Create new
            worldspec.gameid = g_settings->get("default_game");
            worldspec.name += " [new]";
        }
        worldspec.path = game_params.world_path;
    }

    /* Show the GUI menu
     */
    if (!skip_main_menu) {
        main_menu(&menudata);

        // Skip further loading if there was an exit signal.
        if (*porting::signal_handler_killstatus())
            return false;

        address = menudata.address;
        int newport = stoi(menudata.port);
        if (newport != 0)
            game_params.socket_port = newport;

        simple_singleplayer_mode = menudata.simple_singleplayer_mode;

        std::vector<WorldSpec> worldspecs = getAvailableWorlds();

        if (menudata.selected_world >= 0
                && menudata.selected_world < (int)worldspecs.size()) {
            g_settings->set("selected_world_path",
                            worldspecs[menudata.selected_world].path);
            worldspec = worldspecs[menudata.selected_world];
        }
    }

    if (!menudata.script_data.errormessage.empty()) {
        /* The calling function will pass this back into this function upon the
         * next iteration (if any) causing it to be displayed by the GUI
         */
        error_message = menudata.script_data.errormessage;
        return false;
    }

    if (menudata.name == "")
        menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
    else
        playername = menudata.name;

    password = menudata.password;

    g_settings->set("name", playername);

    current_playername = playername;
    current_password   = password;
    current_address    = address;
    current_port       = game_params.socket_port;

    // If using simple singleplayer mode, override
    if (simple_singleplayer_mode) {
        assert(skip_main_menu == false);
        current_playername = "singleplayer";
        current_password = "";
        current_address = "";
        current_port = myrand_range(49152, 65535);
    } else if (address != "") {
        ServerListSpec server;
        server["name"] = menudata.servername;
        server["address"] = menudata.address;
        server["port"] = menudata.port;
        server["description"] = menudata.serverdescription;
        ServerList::insert(server);
    }

    infostream << "Selected world: " << worldspec.name
               << " [" << worldspec.path << "]" << std::endl;

    if (current_address == "") { // If local game
        if (worldspec.path == "") {
            error_message = gettext("No world selected and no address "
                                    "provided. Nothing to do.");
            errorstream << error_message << std::endl;
            return false;
        }

        if (!fs::PathExists(worldspec.path)) {
            error_message = gettext("Provided world path doesn't exist: ")
                            + worldspec.path;
            errorstream << error_message << std::endl;
            return false;
        }

        // Load gamespec for required game
        gamespec = findWorldSubgame(worldspec.path);
        if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
            error_message = gettext("Could not find or load game \"")
                            + worldspec.gameid + "\"";
            errorstream << error_message << std::endl;
            return false;
        }

        if (porting::signal_handler_killstatus())
            return true;

        if (game_params.game_spec.isValid() &&
                game_params.game_spec.id != worldspec.gameid) {
            warningstream << "Overriding gamespec from \""
                          << worldspec.gameid << "\" to \""
                          << game_params.game_spec.id << "\"" << std::endl;
            gamespec = game_params.game_spec;
        }

        if (!gamespec.isValid()) {
            error_message = gettext("Invalid gamespec.");
            error_message += " (world.gameid=" + worldspec.gameid + ")";
            errorstream << error_message << std::endl;
            return false;
        }
    }

    return true;
}
Esempio n. 23
0
void Controller::addFilter(std::string fltName, std::vector<std::string> args) {
    Filter *flt;
    std::string name;
    bool resume = false;

    if((flt = pipeline->addFilter2(fltName.c_str()))) {
        if((resume = player.isRunning())) {
            pause();
        }

        try {
        if (fltName == "grayscale")
        {
          name = "Grayscale";
        }
        else if (fltName ==  "sepia")
        {
          name = "Sepia";
        }
        else if (fltName == "colorinvert")
        {
          name = "Color inversion";
        }
        else if (fltName == "transform")
        {
          name = "Transformation";
          //set arguments
          std::string::size_type sz;
          TransformFilter *filter = dynamic_cast<TransformFilter*>(flt);
          float m[args.size()];
          for(int i = 0; i < args.size(); i++) {
              if(!args[i].empty())
                m[i] = stof(args[i], &sz);
              else m[i] = 0;
          }
          filter->setMatrix(m);
#ifdef DEBUG
          for(int i = 0; i < args.size(); i++) {
              std::cout << m[i] << std::endl;
          }
#endif
        }
        else if (fltName == "conv2d")
        {
            name = "Convolution 2D";
            //set arguments
            //stored row by row
            std::string::size_type sz;
            Conv2DFilter *filter = dynamic_cast<Conv2DFilter*>(flt);
            float kernel[args.size()];
            //try {
            for(int i = 0; i < args.size(); i++) {
                if(!args[i].empty())
                  kernel[i] = stof(args[i], &sz);
                else kernel[i] = 0;
            }
//            } catch (const std::invalid_argument& ia) {
//                Controller::ctrlInst()->writeMsg(ia.w);
//            }

            for(int i = 0; i < args.size(); i++) {
                std::cout << kernel[i] << std::endl;
            }

            filter->setFilterKernel(kernel, sqrt(args.size()));
        }
        else if (fltName == "separableconv2d")
        {
            name = "Separable Convolution 2D";
            //set arguments
            std::string::size_type sz;
            SeparableConv2DFilter *filter = dynamic_cast<SeparableConv2DFilter*>(flt);
            int size = args.size() / 2;
            float horizKernel[size];
            float verticKernel[size];

            for(int i = 0; i < size; i++) {
                if(!args[i].empty()) {
                  horizKernel[i] = stof(args[i], &sz);
                  verticKernel[i] = stof(args[i + size], &sz);
                } else {
                    horizKernel[i] = 0;
                    verticKernel[i] = 0;
                }
            }
#ifdef DEBUG
            for(int i = 0; i < size; i++) {
                std::cout << horizKernel[i] << ":vert=" << verticKernel[i] << std::endl;
            }
#endif
            filter->setHorizontalFilterKernel(horizKernel, size);
            filter->setVerticalFilterKernel(verticKernel, size);
        }
        else if (fltName == "sobel")
        {
            name = "Sobel Operator";


        }
        else if (fltName == "emboss")
        {
            name = "Embossing";

            //set arguments
            std::string::size_type sz;
            EmbossFilter *filter = dynamic_cast<EmbossFilter*>(flt);

#ifdef DEBUG
            for(int i = 0; i < args.size(); i++) {
                std::cout << args[i] << std::endl;
            }
#endif

            //first gray level
            float grayLevel = stof(args[0], &sz);
            filter->setGrayLevel(grayLevel);

            //second size
            //0 = EmbossFilter::NORMAL
            //1 = EmbossFilter::LARGE
            switch(stoi(args[1], &sz)) {
            case 0: {
                filter->setSize(EmbossFilter::NORMAL);
            }break;
            case 1: {
                filter->setSize(EmbossFilter::LARGE);
            }break;
            }
        }
        else if (fltName == "dog")
        {
            name = "Difference of Gaussians";
            //set arguments
            std::string::size_type sz;
            DoGFilter *filter = dynamic_cast<DoGFilter*>(flt);
            //first factor
            float factor = stof(args[0], &sz);
            filter->setFactor(factor);

            //second bias
            float bias = stof(args[1], &sz);
            filter->setBias(bias);

            if (args[2] == "true")
              filter->setInverted(true);

#ifdef DEBUG
           // for(int i = 0; i < args.size(); i++) {
                std::cout << factor << std::endl;
                std::cout << bias << std::endl;
            //}
#endif
        }
        else if (fltName == "gaussianblur")
        {
            name = "Gaussian Blur";
            //set arguments
            std::string::size_type sz;
            GaussianBlurFilter *filter = dynamic_cast<GaussianBlurFilter*>(flt);
            //first sigma
            double sigma = stod(args[0], &sz);
            filter->setSigma(sigma);

            //second variance
            double variance = stod(args[1], &sz);
            filter->setVariance(variance);

            //third size
            int size = stoi(args[2], &sz);
            filter->setSize(size);

#ifdef DEBUG
            for(int i = 0; i < args.size(); i++) {
                std::cout << sigma << std::endl;
                std::cout << variance << std::endl;
                std::cout << size << std::endl;
            }
#endif
        }
        else if (fltName == "oilify")
        {
          name = "Oilify";
          //set arguments
          OilifyFilter *filter = dynamic_cast<OilifyFilter*>(flt);
          filter->setRadius(atoi(args[0].c_str()));
          filter->setLevels(atoi(args[1].c_str()));
        }
        else if (fltName == "shake")
        {
          name = "Shake";
          //set arguments
          ShakeFilter *filter = dynamic_cast<ShakeFilter*>(flt);
          filter->setIntensity(double(atoi(args[0].c_str()) / 100.0f));
        }
        else {
            std::cerr << "Controller: Invalid filter name!" << std::endl;
        }


        filterVec.push_back(std::pair<std::string, Filter*>(name, flt));

        if(resume)
            play();

        Controller::ctrlInst()->writeMsg("Filter successfully added.");
        } catch (const std::invalid_argument) {
            Controller::ctrlInst()->writeMsg("Invalid filter argument (i.e. not a number)");
        }
    }else {
        std::cerr << "Controller: Error adding filter" << std::endl;
    }
}
Esempio n. 24
0
void entercb(Fl_Widget*, void*) {
	int numbero = stoi(number);
	displayStack.push(numbero);
	number = "";
}
Esempio n. 25
0
//recursively read cluster subtree information
bool GmlParser::recursiveAttributedClusterRead(GmlObject* clusterObject,
								ClusterGraph& CG,
								ClusterGraphAttributes& ACG,
								cluster c)
{

	//for direct root cluster sons, this is checked twice...
	if (clusterObject->m_valueType != gmlListBegin) return false;

	GmlObject *clusterSon = clusterObject->m_pFirstSon;

	for(; clusterSon; clusterSon = clusterSon->m_pBrother)
	{
		//we dont read the attributes, therefore look only for
		//id and sons
		switch(id(clusterSon))
		{
			case clusterPredefKey:
				{
					if (clusterSon->m_valueType != gmlListBegin) return false;

					cluster cson = CG.newCluster(c);
					//recursively read child cluster
					recursiveAttributedClusterRead(clusterSon, CG, ACG, cson);
				}
				break;
			case labelPredefKey:
				{
					if (clusterSon->m_valueType != gmlStringValue) return false;
					ACG.label(c) = clusterSon->m_stringValue;
				}
				break;
			case templatePredefKey:
				{
					if (clusterSon->m_valueType != gmlStringValue) return false;
					ACG.templateCluster(c) = clusterSon->m_stringValue;
					break;
				}
			case graphicsPredefKey: //read the info for cluster c
				{
					if (clusterSon->m_valueType != gmlListBegin) return false;

					readClusterAttributes(clusterSon, c , ACG);
				}//graphics
				break;
			case vertexPredefKey: //direct cluster vertex entries
				{
					if (clusterSon->m_valueType != gmlStringValue) return false;
					string vIDString = clusterSon->m_stringValue;

					if ((vIDString[0] != 'v') &&
						(!isdigit((int)vIDString[0])))return false; //do not allow labels
					//if old style entry "v"i
					if (!isdigit((int)vIDString[0])) //should check prefix?
						vIDString[0] = '0'; //leading zero to allow conversion
					int vID = stoi(vIDString);

					OGDF_ASSERT(m_mapToNode[vID] != 0)

					//we assume that no node is already assigned
					//changed: all nodes are already assigned to root
					CG.reassignNode(m_mapToNode[vID], c);

				}//case vertex
		}//switch
	}//for clustersons

	return true;
}//recursiveAttributedClusterRead
Esempio n. 26
0
//PRIVATE FUNCTIONS
void Record::convertStringtoInts(std::string t) 
{
	bool valid = true; //flag to avoid trying to parse invalid input
	int i;
	std::string temp;
	for(i = 0; i < t.length() && valid; i++)
	{
		switch(t[i])
		{
			case ':': //found the separator between mins and secs
				mins = stoi(temp);
				break;
			case '.': //found the separator between secs and milis
				secs = stoi(temp);
				break;
			//Define all valid cases
			case '0':
				temp += t[i];
				break;
			case '1':
				temp += t[i];
				break;
			case '2':
				temp += t[i];
				break;
			case '3':
				temp += t[i];
				break;
			case '4':
				temp += t[i];
				break;
			case '5':
				temp += t[i];
				break;
			case '6':
				temp += t[i];
				break;
			case '7':
				temp += t[i];
				break;
			case '8':
				temp += t[i];
				break;
			case '9':
				temp += t[i];
				break;
			default:
				valid = false;
				std::cout << "\nError with time input!";
				std::cout << "\nExpected a number . or :  instead found " << t[i] << ".";
				std::cout << "\nSetting time to default value";
				break;
		}
		
		//reset temp at the end of the string if valid and not a seperator character
		if(i == t.length() - 1 && (t[i] != '.' && t[i] != ':') && valid)
		{
			milis = stoi(temp);
		}
	}
	
	if(!valid) //reset values for invalid data entry
	{
		mins = 0;
		secs = 0;
		milis = 0;
	}
	
	//remind users to double check entry for suspect values
	if(secs > 59)
	{
		std::cout << "\nReceived a value for seconds of 60 or more.";
		std::cout << "\nPlease check to make sure you have entered data correctly";
	}
	
	if(milis > 99)
	{
		std::cout << "\nRecieved a miliseconds time of 100 or more.";
		std::cout << "\nPlease check to make sure you have entered data correctly";
	}
	
}
void draw_tof_singleparticle(const string ConfigDir="../..", const string InFileBase = "../../output/SingleParticle_rv02-00-01_sv02-00-01_mILD_l5_o1_v02/", const string OutFileBase = "../../output/SP") {
  string plot_config_path  = ConfigDir + "/PlottingSettings.cnf";
  string ptype_config_path = ConfigDir + "/ParticleTypes.cnf";
  string res_config_path   = ConfigDir + "/TimeResolutions.cnf";

  float min_p    = 0,   max_p    = 100;
  float min_beta = 0.5, max_beta = 1.05;
  ConfigReader plot_settings_reader(plot_config_path);
  auto beta_p_settings = plot_settings_reader["BetaPPlots"];
  int bins_p        = stoi(beta_p_settings["NbinsBeta"]);
  int bins_beta     = stoi(beta_p_settings["NbinsP"]);
  int every_nth_bin = stoi(beta_p_settings["BinJumpsPerSlice"]); // Consider only every n-th bin (=slice) in the momentum distribution
  
  ConfigReader ptype_reader(ptype_config_path);
  ParticleVec particle_types {};
  auto ptype_names = ptype_reader.get_keys();
  for (auto & ptype_name: ptype_names) { 
    auto ptype_sec = ptype_reader[ptype_name]; // Section 
    particle_types.push_back( ParticleType(stoi(ptype_sec["pdgID"]), ptype_sec["name_s"],  ptype_name, stod(ptype_sec["mass"]), stoi(ptype_sec["colour"])) );
  }
  int N_ptypes = particle_types.size();
  
  ConfigReader res_reader(res_config_path);
  ResVec resolutions {};
  auto res_values = res_reader.get_keys();
  for (auto & res_value: res_values) {
    auto res_sec = res_reader[res_value]; 
    resolutions.push_back( Resolution(stof(res_value), stoi(res_sec["colour"])) );
  }
  int N_ress = resolutions.size();
  
  HistoMap beta_histos {};
  
  for ( auto &ptype : particle_types ) {
    for ( auto &res : resolutions) {
      beta_histos.addHisto( ptype, res );
    }
  }
  // TODO Also loop over different time estimators?? (Here: CH -> Closest Hit)

  unique_ptr<TCanvas> c_dummy {new TCanvas("dummy","",1000,800)}; // To write histos to that don't need to be written to current canvas

  unique_ptr<TCanvas> c_beta_p {new TCanvas("c_beta_p","#beta_{CH} vs momentum",400*N_ress,400*N_ptypes)}; 
  unique_ptr<TCanvas> c_beta_p_average {new TCanvas("c_beta_p_average","#beta_{CH}^{average} vs momentum",400*N_ress,400*N_ptypes)}; 
  c_beta_p->Clear();
  c_beta_p_average->Clear();
  c_beta_p->Divide(resolutions.size(), particle_types.size());
  c_beta_p_average->Divide(resolutions.size(), particle_types.size());
  int i_pad=0;
  
  vector<TFile*> closables {}; // Because ROOT... To collect files that I need to close later
  
  unique_ptr<TFile> file_beta_p {new TFile ( ( OutFileBase + "_beta_p.root" ).c_str() ,"recreate")};
  
  // Get the beta vs p histograms and save for each particle type
  for ( auto & ptype : particle_types ) {
    TFile* file = new TFile ( ( InFileBase + to_string(ptype.pdg_id) + "_lctuple.root" ).c_str() ,"r");
    TTree* tree = (TTree*) file->Get("MyLCTuple");
    
    TF1* beta_func = new TF1( ("beta_func_" + ptype.name_s).c_str(), "x / sqrt(x^2 + [0]^2)", min_p, max_p);
    beta_func->SetParameter(0, ptype.mass);
    beta_func->SetLineWidth(1);
    beta_func->SetLineColorAlpha(6, 0.5);
    file_beta_p->WriteTObject(beta_func);
    
    for (auto &res : resolutions) {
      i_pad++;
      c_beta_p->cd(i_pad);

      string h_beta_name = "h_beta_" + ptype.name_s + "_" + res.str();

      TH2F *h_beta = new TH2F( h_beta_name.c_str(),
                              ("#beta_{CH} vs momentum, " + ptype.name_l + ", " + res.w_unit() + "; p [GeV/c] ; #beta ").c_str(),
                              bins_p, min_p, max_p, bins_beta, min_beta, max_beta
                             );
      
      string tof_res = "tof" + res.str();
      string draw_string = tof_res + "len/" + tof_res + "ch/299.8:sqrt(rcmox*rcmox+rcmoy*rcmoy+rcmoz*rcmoz)>>" + h_beta_name;
      string cut_string  = tof_res + "len>1.&&" + tof_res + "ch>0.1&&(" + tof_res + "len/" + tof_res + "ch/299.8)<1.1 && sqrt(rcmox*rcmox+rcmoy*rcmoy+rcmoz*rcmoz)<100.&&abs(rccha)>0.005 && abs(rcmoz)/sqrt(rcmox*rcmox+rcmoy*rcmoy+rcmoz*rcmoz) < 0.792573 && sqrt(rcmox*rcmox+rcmoy*rcmoy) > 0.948543 && nrec==1";
        
      tree->Draw( draw_string.c_str(), cut_string.c_str(), "colz" );
      file_beta_p->WriteTObject(h_beta);
      beta_func->Draw("same");
      
      c_dummy->cd();
      beta_histos.getHisto(res, ptype)->histo = h_beta;
      beta_histos.getHisto(res, ptype)->slice_histo(every_nth_bin);
      
      c_beta_p_average->cd(i_pad);
      string h_beta_average_name = "h_beta_average_" + ptype.name_s + "_" + res.str();
      TH1F* h_beta_average = new TH1F( h_beta_average_name.c_str(),
                                       ("#beta_{CH}^{average} vs momentum, " + ptype.name_l + ", " + res.w_unit() + ", error = #sigma_{gaus}; p [GeV/c] ; #beta ").c_str(),
                                       bins_p, min_p, max_p
                                     );
      for ( auto & slice: beta_histos.getHisto(res, ptype)->slices ) {
        int bin = h_beta_average->FindBin(slice.p);
        if (slice.fit_successful) {
          h_beta_average->SetBinContent(bin, slice.mean);
          h_beta_average->SetBinError(  bin, slice.sigma);
        }
      }
      h_beta_average->SetMarkerSize(0);
      h_beta_average->SetFillColor(2);
      h_beta_average->Draw("E5");
      beta_func->Draw("same");
      
      file_beta_p->WriteTObject(h_beta_average);
      file->cd();
    }
    closables.push_back(file);
  }
  c_beta_p->Print( (OutFileBase + "_beta_p.pdf").c_str() );
  c_beta_p_average->Print( (OutFileBase + "_beta_p_average.pdf").c_str() );
  
  file_beta_p->Close();
  
  // Save the sliced histograms
  for ( auto & res: resolutions ) {
    unique_ptr<TFile> file_slices { new TFile( (OutFileBase + "_slices_" + res.w_unit() + ".root").c_str(), "RECREATE" ) };

    for ( auto & histo: beta_histos.getHistosToRes(res) ) {
      for ( auto & slice: histo->slices ) {
        slice.histo->Write();
      }
    }
    file_slices->Close();
  }
  
  unique_ptr<TFile> file_sep_pwr { new TFile( (OutFileBase + "_separation_powers.root").c_str(), "RECREATE" ) };
  // Find separation power for all combinations 
  for (int i=0; i<N_ptypes-1; i++) {
    if ( 1 == N_ptypes ) {
      cout << "Only one particle type given, not creating separation power plots." << endl;
      break;
    }
    for (int j=i+1; j<N_ptypes; j++) { // Loop avoids dublicats
      ParticleType ptype1 = particle_types[i];
      ParticleType ptype2 = particle_types[j];
      
      unique_ptr<TCanvas> c_sep_pwr {new TCanvas( ("c_sep_pwr_" + ptype1.name_s + "_" + ptype2.name_s).c_str() ,
                                                  "Separation power vs momentum",
                                                  800*resolutions.size(),800)}; 
      c_sep_pwr->Divide(resolutions.size(), 1);
      int i_seppwr_pad = 1;
      
      vector<pair<Resolution,TH1D*>> sep_pwr_hists {};
      
      for ( auto & res: resolutions ) {
        auto slices_p1 = beta_histos.getHisto(res, ptype1)->slices;
        auto slices_p2 = beta_histos.getHisto(res, ptype2)->slices;
      
        int N_slices = slices_p1.size();
        
        TH1D* h_seppwr = new TH1D(("h_seppwr_" + ptype1.name_s + ptype2.name_s + res.str()).c_str(), 
                                  (ptype1.name_l + " - " + ptype2.name_l + " TOF-separation, " + res.w_unit() + "; p [GeV/c] ; Separation Power [#sigma]").c_str(),
                                  N_slices, min_p, max_p);
                                  
        for (int i_slice=0; i_slice<N_slices; i_slice++) {
          auto slice_p1 = slices_p1[i_slice];
          auto slice_p2 = slices_p2[i_slice];
          
          double p = slice_p1.p;
          
          if ( ! (slice_p1.fit_successful && slice_p2.fit_successful) ) {
            cout << ptype1.name_l << " - " << ptype2.name_l << ", " << res.w_unit() << 
                    " : Fit in slice p=" << p << " not successful, point won't be drawn." << endl;
            continue;
          }
          
          double diff_mean     = abs(slice_p1.mean - slice_p2.mean);
          double sigma_sqr_sum = pow(slice_p1.sigma, 2) + pow(slice_p2.sigma, 2); 
          double ms_sigma      = sigma_sqr_sum / 2.0; // ms = mean squared 
          double rms_sigma     = sqrt( ms_sigma );    // rms = root mean squared
          
          double sep_pwr     = diff_mean / rms_sigma;
          double sep_pwr_err = sqrt( (pow(slice_p1.mean_err,2) + pow(slice_p2.mean_err,2))/ms_sigma + pow(diff_mean,2) * (pow(slice_p1.sigma,2)*pow(slice_p1.sigma_err,2) + pow(slice_p2.sigma,2)*pow(slice_p2.sigma_err,2)) / (4*pow(ms_sigma,3)) );
          // Check that sep pwr is not NaN
          if ( sep_pwr != sep_pwr) { sep_pwr = sep_pwr_err = 0; }
          
          h_seppwr->SetBinContent(h_seppwr->FindBin(p), sep_pwr);
          h_seppwr->SetBinError(  h_seppwr->FindBin(p), sep_pwr_err);
        }          
        
        h_seppwr->Write();
        
        c_sep_pwr->cd(i_seppwr_pad++);
        h_seppwr->Draw("pe"); // TODO Better drawing style: Set some better markers, REMOVE X ERROR
        h_seppwr->SetMinimum(0);
        h_seppwr->SetMaximum(40);
        
        sep_pwr_hists.push_back(make_pair(res,h_seppwr));
      }
      c_sep_pwr->Write();
      
      unique_ptr<TCanvas> c_sep_pwr_comb {  new TCanvas( ("c_sep_pwr_comb_" + ptype1.name_s + "_" + ptype2.name_s).c_str() ,
                                                          "Separation power vs momentum",
                                                          800,800)
                                          };
      unique_ptr<THStack> h_sep_pwr_comb { new THStack(
                                                ("h_seppwr_comb_" + ptype1.name_s + ptype2.name_s).c_str(), 
                                                (ptype1.name_l + " - " + ptype2.name_l + " TOF-separation; p [GeV/c] ; Separation Power [#sigma]").c_str())
                                          };
      unique_ptr<TLegend> leg_sep_pwr_comb { new TLegend(0.48,0.7,0.8,0.9) };
      for (auto &res_hist: sep_pwr_hists) {
        Resolution res  = res_hist.first;
        TH1D* h_seppwr  = res_hist.second;
        leg_sep_pwr_comb->AddEntry(h_seppwr, res.w_unit().c_str(), "lep");
        h_sep_pwr_comb->Add(h_seppwr);
        h_seppwr->SetLineColor(res.colour_index);
      }
      h_sep_pwr_comb->Draw("nostack");
      h_sep_pwr_comb->SetMinimum(0);
      if( h_sep_pwr_comb->GetMaximum() > 120 ) { h_sep_pwr_comb->SetMaximum(100); }
      gPad->Modified();
      gPad->Update();
      leg_sep_pwr_comb->Draw();
      c_sep_pwr_comb->Write(); 
    }
  }
  file_sep_pwr->Close();

  for ( auto & closable : closables ) { 
    closable->Close();
    delete closable;
  } 
}
Esempio n. 28
0
void CLobbyPanel::Layout()
{
#if 0
	if (!IsVisible())
		return;

	if (!m_bLayout)
		return;

	if (!CGameLobbyClient::L_GetNumPlayers())
		return;

	if (CGameLobbyClient::L_GetPlayerIndexByClient(LobbyNetwork()->GetClientID()) == ~0)
		return;

	m_bLayout = false;

	size_t iWidth = RootPanel()->GetWidth();
	size_t iHeight = RootPanel()->GetHeight();

	SetSize(924, 668);
	SetPos(iWidth/2-GetWidth()/2, iHeight/2-GetHeight()/2);

	bool bAllButMe = true;

	// Find the lobby leader's name
	for (size_t i = 0; i < CGameLobbyClient::L_GetNumPlayers(); i++)
	{
		CLobbyPlayer* pPlayer = CGameLobbyClient::L_GetPlayer(i);
		if (pPlayer->GetInfoValue(_T("host")) == _T("1"))
		{
			m_pLobbyName->SetText(pPlayer->GetInfoValue(_T("name")) + _T("'s Lobby"));

			if (pPlayer->GetInfoValue(_T("ready")) == _T("1"))
				bAllButMe = false;

			continue;
		}

		if (pPlayer->GetInfoValue(_T("ready")) != _T("1"))
			bAllButMe = false;
	}

	if (!LobbyNetwork()->IsHost())
		bAllButMe = false;

	m_pLobbyName->SetSize(GetWidth(), 30);
	m_pLobbyName->SetPos(0, 0);
	m_pLobbyName->SetAlign(glgui::CLabel::TA_MIDDLECENTER);

	m_pPlayerList->SetSize(260, 20);
	m_pPlayerList->SetPos(925 - 280, 30);
	m_pPlayerList->SetAlign(glgui::CLabel::TA_MIDDLECENTER);

	m_pAddPlayer->SetSize(70, 15);
	m_pAddPlayer->SetPos(925 - 90, 20);

	m_pAddBot->SetSize(70, 15);
	m_pAddBot->SetPos(925 - 90, 40);

	if (CGameLobbyClient::L_IsHost())
	{
		m_pAddPlayer->SetVisible(!m_bOnline);
		m_pAddBot->SetVisible(true);
	}
	else
	{
		m_pAddPlayer->SetVisible(false);
		m_pAddBot->SetVisible(false);
	}

	m_pDockPanel->SetSize(375, 480);
	m_pDockPanel->SetPos(20, 50);

	m_pChatBox->SetSize(565, 120); 
	m_pChatBox->SetPos(20, 520);

	m_pLeave->SetSize(100, 35);
	m_pLeave->SetPos(925 - 320, 668 - 55);

	m_pReady->SetSize(180, 35);
	m_pReady->SetPos(925 - 200, 668 - 55);

	if (bAllButMe)
		m_pReady->SetText(_T("Start Game"));
	else if (CGameLobbyClient::L_GetPlayerByClient(LobbyNetwork()->GetClientID()))
	{
		bool bReady = !!stoi(CGameLobbyClient::L_GetPlayerByClient(LobbyNetwork()->GetClientID())->GetInfoValue(_T("ready")).c_str());
		if (bReady)
			m_pReady->SetText(_T("Not Ready"));
		else
			m_pReady->SetText(_T("Ready"));
	}
	else
		m_pReady->SetText(_T("Ready"));

	m_pReady->SetEnabled(CGameLobbyClient::L_GetNumPlayers() >= 2);

	if (LobbyNetwork()->IsHost() && CGameLobbyClient::L_GetInfoValue(_T("level")).length() == 0)
		m_pReady->SetEnabled(false);

	gametype_t eGameType = (gametype_t)stoi(CGameLobbyClient::L_GetInfoValue(_T("gametype")).c_str());
	if (CGameLobbyClient::L_GetNumPlayers() > 8 && eGameType == GAMETYPE_ARTILLERY)
		m_pReady->SetEnabled(false);
	else if (CGameLobbyClient::L_GetNumPlayers() > 4 && eGameType == GAMETYPE_STANDARD)
		m_pReady->SetEnabled(false);

	if (CGameLobbyClient::L_GetNumPlayers() >= 8 && eGameType == GAMETYPE_ARTILLERY)
		m_pAddPlayer->SetEnabled(false);
	else if (CGameLobbyClient::L_GetNumPlayers() >= 4 && eGameType == GAMETYPE_STANDARD)
		m_pAddPlayer->SetEnabled(false);
	else
		m_pAddPlayer->SetEnabled(true);

	if (CGameLobbyClient::L_GetNumPlayers() >= 8 && eGameType == GAMETYPE_ARTILLERY)
		m_pAddBot->SetEnabled(false);
	else if (CGameLobbyClient::L_GetNumPlayers() >= 4 && eGameType == GAMETYPE_STANDARD)
		m_pAddBot->SetEnabled(false);
	else
		m_pAddBot->SetEnabled(true);

	for (size_t i = 0; i < m_apPlayerPanels.size(); i++)
	{
		m_apPlayerPanels[i]->Destructor();
		m_apPlayerPanels[i]->Delete();
	}

	m_apPlayerPanels.clear();

	for (size_t i = 0; i < CGameLobbyClient::L_GetNumPlayers(); i++)
	{
		m_apPlayerPanels.push_back(new CPlayerPanel());
		CPlayerPanel* pPanel = m_apPlayerPanels[m_apPlayerPanels.size()-1];
		AddControl(pPanel);
		pPanel->SetPlayer(CGameLobbyClient::L_GetPlayer(i)->iID);
	}

	BaseClass::Layout();
#endif
}
Esempio n. 29
0
TH1* draw_single_rcp(string energy, string plc, string charge, string iCen = "0", string iPer = "6",
							double cen_nColl = 800.0, double per_nColl = 20.0, 
							int color = kRed, string draw_opt = "", int marker = 8){

	RooPlotLib rpl;

	gStyle->SetOptStat( 0 );

	string cen_fn = file_name( energy, plc, charge, iCen );
	string per_fn = file_name( energy, plc, charge, iPer );

	SpectraLoader cen_sl( cen_fn );
	SpectraLoader per_sl( per_fn );

	TH1* cen_sys = normalize_binning( cen_sl.sysHisto( cen_fn + "_cen_sys" ) );
	TH1* per_sys = normalize_binning( per_sl.sysHisto( per_fn + "_per_sys" ) );
	
	TH1* cen_stat = normalize_binning( cen_sl.statHisto( cen_fn + "_cen_stat" ) );
	TH1* per_stat = normalize_binning( per_sl.statHisto( per_fn + "_per_stat" ) );

	TH1* cen_stat_rcp = (TH1*)cen_stat->Clone( (cen_fn + "_cen_stat_rcp").c_str() );
	TH1* cen_sys_rcp = (TH1*)cen_sys->Clone( (cen_fn + "_cen_sys_rcp").c_str() );

	// do the division
	cen_stat_rcp->Divide( per_stat );
	cen_stat_rcp->Scale( per_nColl / cen_nColl );

	cen_sys_rcp->Divide( per_sys );
	cen_sys_rcp->Scale( per_nColl / cen_nColl );



	rpl.style( cen_sys_rcp )
		.set( "title", " ;p_{T} [GeV/c]; R_{CP} ( " + centrality_labels[ stoi( iCen ) ] + " ) / ( " + centrality_labels[ stoi( iPer ) ] + " )    " )
		.set( "yts", 0.05 )
		.set( "yls", 0.06 )
		.set( "xts", 0.05 )
		.set( "xls", 0.05 )
		.set( "mst", marker )
		.set( "color", color, 0.13 );

	if ( "14.5" == energy )
		rpl.set( "ms", 2 );

	rpl.style( cen_stat_rcp )
		.set( "yts", 0.05 )
		.set( "yls", 0.06 )
		.set( "mst", marker )
		.set( "color", color );

	cen_sys_rcp->Draw( ( draw_opt + " e2").c_str() );
	cen_stat_rcp->Draw( "same e1x0" );

	cen_sys_rcp->GetYaxis()->SetRangeUser( 0.15, 6 );
	gPad->SetLogy(1);
	gPad->SetGrid( 1, 1 );


	return cen_stat_rcp;

}
Esempio n. 30
0
/**
* @brief Read configuration file
* @param fileName configuration filename
*/
void MPS::SNESIM::_readConfigurations(const std::string& fileName) {

	// Check that parameter file exist
	if  (!(MPS::io::file_exist(fileName))) {
		std::cout << "Paremeter file '" << fileName << "' does not exist -> quitting" << std::endl;
		exit(0);
		return;
	}

	std::ifstream file(fileName);
	std::string str;
	std::stringstream ss;
	std::string s;
	std::vector<std::string> data;
	// Process each line
	// Number of realizations
	_readLineConfiguration(file, ss, data, s, str);
	_realizationNumbers = stoi(data[1]);
	// Initial value
	_readLineConfiguration(file, ss, data, s, str);
	_seed = stof(data[1]);
	// Multiple grid level
	_readLineConfiguration(file, ss, data, s, str);
	_totalGridsLevel = stoi(data[1]);
	//Min node count
	_readLineConfiguration(file, ss, data, s, str);
	_minNodeCount = stoi(data[1]);
	//Max conditional count
	_readLineConfiguration(file, ss, data, s, str);
	_maxCondData = stoi(data[1]);
	
	// Template size x
	_readLineConfiguration_mul(file, ss, data, s, str);
	_templateSizeX = stoi(data[1]);
	// optional. Template size x - base when n_mulgrid=0
	if (data.size()>2) {
		_templateSizeX_base = stoi(data[2]);
	} else {
		_templateSizeX_base = _templateSizeX;
	}
  // Template size y
	_readLineConfiguration_mul(file, ss, data, s, str);
	_templateSizeY = stoi(data[1]);
	// optional. Template size y - base when n_mulgrid=0
	if (data.size()>2) {
		_templateSizeY_base = stoi(data[2]);
	} else {
		_templateSizeY_base = _templateSizeY;
	}
  // Template size z
	_readLineConfiguration_mul(file, ss, data, s, str);
	_templateSizeZ = stoi(data[1]);
	// optional. Template size z - base when n_mulgrid=0
	if (data.size()>2) {
		_templateSizeZ_base = stoi(data[2]);
	} else {
		_templateSizeZ_base = _templateSizeZ;
	}
	
	// Simulation Grid size X
	_readLineConfiguration(file, ss, data, s, str);
	_sgDimX = stoi(data[1]);
	// Simulation Grid size Y
	_readLineConfiguration(file, ss, data, s, str);
	_sgDimY = stoi(data[1]);
	// Simulation Grid size Z
	_readLineConfiguration(file, ss, data, s, str);
	_sgDimZ = stoi(data[1]);
	// Simulation Grid World min X
	_readLineConfiguration(file, ss, data, s, str);
	_sgWorldMinX = stof(data[1]);
	// Simulation Grid World min Y
	_readLineConfiguration(file, ss, data, s, str);
	_sgWorldMinY = stof(data[1]);
	// Simulation Grid World min Z
	_readLineConfiguration(file, ss, data, s, str);
	_sgWorldMinZ = stof(data[1]);
	// Simulation Grid Cell Size X
	_readLineConfiguration(file, ss, data, s, str);
	_sgCellSizeX = stof(data[1]);
	// Simulation Grid Cell Size Y
	_readLineConfiguration(file, ss, data, s, str);
	_sgCellSizeY = stof(data[1]);
	// Simulation Grid Cell Size Z
	_readLineConfiguration(file, ss, data, s, str);
	_sgCellSizeZ = stof(data[1]);
	// TI filename
	_readLineConfiguration(file, ss, data, s, str);
	data[1].erase(std::remove_if(data[1].begin(), data[1].end(), [](char x){return std::isspace(x);}), data[1].end()); //Removing spaces
	_tiFilename = data[1];
	// Output directory
	_readLineConfiguration(file, ss, data, s, str);
	data[1].erase(std::remove_if(data[1].begin(), data[1].end(), [](char x){return std::isspace(x);}), data[1].end()); //Removing spaces
	_outputDirectory = data[1];
	// Shuffle SGPATH
	_readLineConfiguration_mul(file, ss, data, s, str);
	_shuffleSgPath = (stoi(data[1]));
	if (data.size()>2) {
		// EntropyFactor is the second value, if it exists
		_shuffleEntropyFactor = stof(data[2]);
	} else {
		_shuffleEntropyFactor = 4;
	}
	// Shuffle TI Path
	_readLineConfiguration(file, ss, data, s, str);
	_shuffleTiPath = (stoi(data[1]) != 0);
	// Hard data
	_readLineConfiguration(file, ss, data, s, str);
	data[1].erase(std::remove_if(data[1].begin(), data[1].end(), [](char x){return std::isspace(x);}), data[1].end()); //Removing spaces
	_hardDataFileNames = data[1];
	// Hard data search radius
	_readLineConfiguration(file, ss, data, s, str);
	_hdSearchRadius = stof(data[1]);
	//Get the maximum value of template size into the search radius
	_hdSearchRadius = std::max(std::max(_templateSizeX, _templateSizeY), _templateSizeZ);
	// Softdata categories
	//std::cout << s << std::endl;
	if(_readLineConfiguration(file, ss, data, s, str)) {
		ss.clear();
		ss << data[1];
		while (getline(ss, s, ';')) {
			//Parsing categories
			if(!s.empty()) {
				_softDataCategories.push_back(stof(s));
			}
		}
	}
	// Softdata filenames
	if(_readLineConfiguration(file, ss, data, s, str)) {
		ss.clear();
		ss << data[1];
		while (getline(ss, s, ';')) {
			//Parsing categories
			if(!s.empty()) {
				s.erase(std::remove_if(s.begin(), s.end(), [](char x){return std::isspace(x);}), s.end()); //Removing spaces
				_softDataFileNames.push_back(s);
			}
		}
		// Resize softdata grids
		_softDataGrids.resize(_softDataFileNames.size());
	}
	// Number of threads
	_readLineConfiguration(file, ss, data, s, str);
	_numberOfThreads = stoi(data[1]);
	// DEBUG MODE
	_readLineConfiguration(file, ss, data, s, str);
	_debugMode = stoi(data[1]);
	// Mask data grid
	if (_readLineConfiguration(file, ss, data, s, str)) {
		data[1].erase(std::remove_if(data[1].begin(), data[1].end(), [](char x) {return std::isspace(x); }), data[1].end()); //Removing spaces
		_maskDataFileName = data[1];
	}
}