Ejemplo n.º 1
0
static void getWritePaths(Paths& paths)
{
	paths.push_back(PathInfo(SlPaths::GetLobbyWriteDir(), "LobbyWriteDir", true));
	paths.push_back(PathInfo(SlPaths::GetCachePath(), "CachePath", true));
	paths.push_back(PathInfo(SlPaths::GetExecutableFolder(), "ExecutableFolder", false));
	paths.push_back(PathInfo(SlPaths::GetDownloadDir(), "DownloadDir", true));
	paths.push_back(PathInfo(SlPaths::GetDataDir(), "Current SpringData:", true));
}
Ejemplo n.º 2
0
InfoDialog::InfoDialog(wxWindow* parent)
    : wxDialog(parent, wxID_ANY, _("Paths"), wxDefaultPosition, wxSize(620, 400), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX | wxCLOSE_BOX)
{
	m_main_sizer = new wxBoxSizer(wxVERTICAL);

	typedef std::vector<std::pair<std::string, wxString> > Paths;
	Paths paths;
	paths.push_back(std::make_pair(SlPaths::GetLobbyWriteDir(), _T("LobbyWriteDir")));
	paths.push_back(std::make_pair(SlPaths::GetCachePath(), _T("CachePath")));
	paths.push_back(std::make_pair(SlPaths::GetExecutableFolder(), _T("ExecutableFolder")));
	paths.push_back(std::make_pair(SlPaths::GetDownloadDir(), _T("DownloadDir")));
	paths.push_back(std::make_pair(SlPaths::GetDataDir(), _T("Current SpringData:")));

	wxTextCtrl* out = new wxTextCtrl(this, wxNewId(), wxEmptyString, wxDefaultPosition, wxDefaultSize,
					 wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH | wxTE_AUTO_URL);

	*out << TowxString(getSpringlobbyAgent()) + _T("\n");
	*out << wxString::Format(_T("SpringLobby config file: %s (%s writable)\n"),
				 TowxString(SlPaths::GetConfigPath()).c_str(),
				 BtS(wxFileName::IsFileWritable(TowxString(SlPaths::GetConfigPath())), "", "not").c_str());

	for (size_t i = 0; i < paths.size(); ++i) {
		const wxString path = TowxString(paths[i].first);
		*out << wxString::Format(_T("%s (%s)\n"), paths[i].second.c_str(), path.c_str());
		const bool wx = wxFileName::IsDirWritable(path);
		const bool posix = access(STD_STRING(path).c_str(), WRITABLE) == 0;
		bool tried = false;
		try {
			std::ofstream of;
			const wxString dummy_fn = path + wxFileName::GetPathSeparator() + _T("dummy.txt");
			of.open(STD_STRING(dummy_fn).c_str());

			if (of.is_open()) {
				of << "fhreuohgeiuhguie";
				of.flush();
				of.close();
				tried = wxRemoveFile(dummy_fn);
			}
		} catch (...) {
		}
		*out << wxString::Format(_T("\tWX: %s POSIX: %s TRY: %s\n"), BtS(wx).c_str(), BtS(posix).c_str(), BtS(tried).c_str());
	}

	*out << wxString::Format(_T("Current unitsync: %s\n"), TowxString(SlPaths::GetUnitSync()).c_str());
	*out << wxString::Format(_T("Current spring executable: %s\n"), TowxString(SlPaths::GetSpringBinary()).c_str());
	*out << wxString::Format(_T("Current uikeys.txt: %s\n"), TowxString(SlPaths::GetUikeys()).c_str());

	*out << wxString::Format(_T("Portable mode: %s\n"), BtS(SlPaths::IsPortableMode()).c_str());

	*out << wxString::Format(_T("Compiled with wxWidgets %d.%d.%d.%d"), wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, wxSUBRELEASE_NUMBER) + _T("\n");
	*out << _T("Started with: \n");
	for (int i = 0; i < wxTheApp->argc; ++i)
		*out << wxTheApp->argv[i] << _T(" ");
	m_main_sizer->Add(out, 1, wxALL | wxEXPAND | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 0);
	SetSizer(m_main_sizer);
	Layout();
}
Ejemplo n.º 3
0
InfoDialog::InfoDialog(wxWindow* parent )
	:wxDialog(parent,wxID_ANY, _("path shit"), wxDefaultPosition, wxSize(620,400), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxMAXIMIZE_BOX)
{
	wxBoxSizer* main_sizer = new wxBoxSizer( wxVERTICAL );

	typedef  std::vector< std::pair< wxString,wxString > >
		Paths;
	Paths paths;
	paths.push_back( std::make_pair( sett().GetLobbyWriteDir(), _T("LobbyWriteDir") ) );
	paths.push_back( std::make_pair( sett().GetTempStorage(), _T("TempStorage")) );
	paths.push_back( std::make_pair( sett().GetCachePath(), _T("CachePath")) );
	paths.push_back( std::make_pair( sett().GetCurrentUsedDataDir(), _T("CurrentUsedDataDir")) );
	paths.push_back( std::make_pair( GetExecutableFolder() , _T("ExecutableFolder")));
	wxTextCtrl* out = new wxTextCtrl( this, wxNewId(), _T( "" ), wxDefaultPosition, wxDefaultSize,
									 wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH | wxTE_AUTO_URL );
	for ( size_t i =0; i < paths.size(); ++i )
	{
		*out << wxString::Format( _T("%s (%s)\n"), paths[i].second.c_str(), paths[i].first.c_str());
		wxString path = paths[i].first;
		wxString dummy_fn = path + wxFileName::GetPathSeparator() + _T("dummy.txt");
		const bool wx = wxFileName::IsDirWritable( path );
		const bool posix = access(STD_STRING(path).c_str(), WRITABLE) == 0;
		bool tried = false;
		try{
			std::ofstream of;
			of.open( STD_STRING(dummy_fn).c_str() );

			if ( of.is_open() )
			{
				of << "fhreuohgeiuhguie";
				of.flush();
				of.close();
				tried = wxRemoveFile(dummy_fn);
			}
		}
		catch (...){}
		*out << wxString::Format( _T("\tWX: %s POSIX: %s TRY: %s\n"), BtS(wx).c_str(), BtS(posix).c_str(), BtS(tried).c_str() );
	}
	*out << wxString::Format( _T("Global config: %s (%s %s )\n"),
							 sett().GlobalConfigPath().c_str(),
							 BtS(wxFileName::FileExists(sett().GlobalConfigPath()), "exists", "missing").c_str(),
							 BtS(wxFileName::IsFileWritable(sett().GlobalConfigPath()), "writable", "").c_str()  );
	*out << wxString::Format( _T("Local config: %s (%s writable)\n"),
							 sett().FinalConfigPath().c_str(),
							 BtS(wxFileName::IsFileWritable(sett().FinalConfigPath()), "", "not" ).c_str() );
	*out << wxString::Format( _T("Portable mode: %s\n"), BtS(sett().IsPortableMode()).c_str() );


	*out << _T( "Version " ) + GetSpringLobbyVersion()
			<< wxString( wxVERSION_STRING ) + _T(" on ") + wxPlatformInfo::Get().GetOperatingSystemIdName() + _T( "\ncl: " ) ;
	for ( int i = 0; i < wxTheApp->argc; ++i )
		*out << wxTheApp->argv[i] << _T(" ");
	main_sizer->Add( out, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
	SetSizer( main_sizer );
	Layout();
}
Ejemplo n.º 4
0
static bool to_polygons(Paths &polygons, GB_ARRAY array)
{
	int count;
	CPOLYGON *p;
	int i;

	if (GB.CheckObject(array))
		return true;

	count = GB.Array.Count(array);
	if (count == 0)
		return false;

	polygons.clear();

	for(i = 0; i < count; i++)
	{
		p = *(CPOLYGON **)GB.Array.Get(array, i);
		if (!p)
			continue;

		polygons.push_back(*(p->poly));
	}

	return false;
}
Ejemplo n.º 5
0
/** Returns a list of possible paths to the given resource. */
DataManager::Paths DataManager::paths(Path resource) const
{
	Paths p;
	for (Paths::const_iterator d = dirs.begin(); d != dirs.end(); d++)
		p.push_back(*d + resource);
	return p;
}
Ejemplo n.º 6
0
/** Read contig paths from the specified file.
 * @param g the contig adjacency graph
 * @param inPath the file of contig paths
 * @param[out] pathIDs the path IDs
 * @return the paths
 */
static Paths readPaths(Graph& g,
		const string& inPath, vector<string>& pathIDs)
{
	typedef graph_traits<Graph>::vertex_descriptor V;

	assert(pathIDs.empty());
	ifstream fin(inPath.c_str());
	if (opt::verbose > 0)
		cerr << "Reading `" << inPath << "'..." << endl;
	if (inPath != "-")
		assert_good(fin, inPath);
	istream& in = inPath == "-" ? cin : fin;

	assert_good(in, inPath);
	Paths paths;
	string id;
	ContigPath path;
	while (in >> id >> path) {
		if (path.empty()) {
			// Remove this contig from the graph.
			V u = find_vertex(id, false, g);
			clear_vertex(u, g);
			remove_vertex(u, g);
		} else {
			pathIDs.push_back(id);
			paths.push_back(path);
		}
	}
	assert(in.eof());
	return paths;
}
Ejemplo n.º 7
0
static VALUE
rbclipper_offset_polygons(int argc, VALUE* argv, VALUE self)
{
    double multiplier = NUM2DBL(rb_iv_get(self, "@multiplier"));
    double inv_multiplier = 1.0 / multiplier;
    VALUE polygonsValue, deltaValue, joinTypeValue, endTypeValue;

    rb_scan_args(argc, argv, "31", &polygonsValue, &deltaValue, &joinTypeValue, &endTypeValue);

    Paths polygons;
    for(long i = 0; i != RARRAY_LEN(polygonsValue); i++) {
        VALUE sub = rb_ary_entry(polygonsValue, i);
        Check_Type(sub, T_ARRAY);

        ClipperLib::Path tmp;
        ary_to_polygon(sub, &tmp, multiplier);
        polygons.push_back(tmp);
    }

    Paths resultPaths;

    XCLIPPEROFFSET(self)->AddPaths(polygons, sym_to_jointype(joinTypeValue), sym_to_endtype(endTypeValue));
    XCLIPPEROFFSET(self)->Execute(resultPaths, NUM2DBL(deltaValue) * multiplier);

    VALUE r = rb_ary_new();
    for(Paths::iterator i = resultPaths.begin(); i != resultPaths.end(); ++i) {
        VALUE sub = rb_ary_new();
        for(Path::iterator p = i->begin(); p != i->end(); ++p) {
            rb_ary_push(sub, rb_ary_new3(2, DBL2NUM(p->X * inv_multiplier), DBL2NUM(p->Y * inv_multiplier)));
        }
        rb_ary_push(r, sub);
    }
    return r;
}
Ejemplo n.º 8
0
int SHAPE_POLY_SET::NewOutline ()
{
    Path empty_path;
    Paths poly;
    poly.push_back(empty_path);
    m_polys.push_back(poly);
    return m_polys.size() - 1;
}
Ejemplo n.º 9
0
	void getPath(string &a, string &b, Tree &tree, Path &path, Paths &ret)
	{
		if (a == b) { ret.push_back(path); return; }
		for (auto &i : tree[a])
		{
			path.push_back(i);
			getPath(i, b, tree, path, ret);
			path.pop_back();
		}
	}
Ejemplo n.º 10
0
	Paths findLadders(string beginWord, string endWord, Dict &wordList)
	{
		Paths paths;
		Path path(1, beginWord);
		if (beginWord == endWord) { paths.push_back(path); return paths; }
		Dict _front, _back;
		_front.insert(beginWord);
		_back.insert(endWord);
		Tree tree;
		if (build(_front, _back, wordList, tree, false))
			getPath(beginWord, endWord, tree, path, paths);
		return paths;
	}
Ejemplo n.º 11
0
static void find_mp3_files(const Path& dir_path, Paths& paths) {
  if (!exists(dir_path)) {
    return;
  }
  boost::filesystem::directory_iterator it(dir_path);
  const boost::filesystem::directory_iterator end_it;
  for (; it != end_it; ++it) {
    if (is_directory(it->status())) {
      find_mp3_files(it->path(), paths);
    } else if (boost::ends_with(it->path().string(), ".mp3")) {
      paths.push_back(it->path());
    }
  }
}
Ejemplo n.º 12
0
static VALUE
rbclipper_add_polygons_internal(VALUE self, VALUE polygonsValue, PolyType polytype) {
  double multiplier = NUM2DBL(rb_iv_get(self, "@multiplier"));
  Paths polygons;
  for(long i = 0; i != RARRAY_LEN(polygonsValue); i++) {
    VALUE sub = rb_ary_entry(polygonsValue, i);
    Check_Type(sub, T_ARRAY);

    ClipperLib::Path tmp;
    ary_to_polygon(sub, &tmp, multiplier);
    polygons.push_back(tmp);
  }
  XCLIPPER(self)->AddPaths(polygons, polytype, true);
  return Qnil;
}
Ejemplo n.º 13
0
/** Assemble overlapping paths. */
static void assembleOverlappingPaths(Graph& g,
		Paths& paths, vector<string>& pathIDs)
{
	if (paths.empty())
		return;

	// Find overlapping paths.
	Overlaps overlaps = findOverlaps(g, paths);
	addPathOverlapEdges(g, paths, pathIDs, overlaps);

	// Create a property map of path overlaps.
	OverlapMap overlapMap;
	for (Overlaps::const_iterator it = overlaps.begin();
			it != overlaps.end(); ++it)
		overlapMap.insert(OverlapMap::value_type(
				OverlapMap::key_type(
					it->source.descriptor(),
					it->target.descriptor()),
				it->overlap));

	// Assemble unambiguously overlapping paths.
	Paths merges;
	assemble_if(g, back_inserter(merges),
			IsPathOverlap(g, overlapMap, IsPositive<Graph>(g)));

	// Merge overlapping paths.
	g_contigNames.unlock();
	assert(!pathIDs.empty());
	setNextContigName(pathIDs.back());
	for (Paths::const_iterator it = merges.begin();
			it != merges.end(); ++it) {
		string name = createContigName();
		if (opt::verbose > 0)
			cerr << name << '\t' << *it << '\n';
		Vertex u(paths.size(), false);
		put(vertex_name, g, u.descriptor(), name);
		pathIDs.push_back(name);
		paths.push_back(mergePaths(paths, overlapMap, *it));

		// Remove the merged paths.
		for (ContigPath::const_iterator it2 = it->begin();
				it2 != it->end(); ++it2) {
			if (isPath(*it2))
				paths[it2->id() - Vertex::s_offset].clear();
		}
	}
	g_contigNames.lock();
}
Ejemplo n.º 14
0
int SHAPE_POLY_SET::AddOutline( const SHAPE_LINE_CHAIN& aOutline )
{
    assert ( aOutline.IsClosed() );

    Path p = convert ( aOutline );
    Paths poly;

    if( !Orientation( p ) )
        ReversePath(p); // outlines are always CW

    poly.push_back( p );

    m_polys.push_back( poly );

    return m_polys.size() - 1;
}
Ejemplo n.º 15
0
		void Instance::Language::EnumerateResources(Paths& paths) const
		{
			for (uint i=0; i < 2 && paths.empty(); ++i)
			{
				struct FileFinder
				{
					WIN32_FIND_DATA data;
					HANDLE const handle;

					FileFinder(wcstring const path)
					: handle(::FindFirstFile( path, &data )) {}

					~FileFinder()
					{
						if (handle != INVALID_HANDLE_VALUE)
							::FindClose( handle );
					}
				};

				Path path( Instance::GetExePath(i ? L"*.*" : L"language\\*.*") );

				FileFinder findFile( path.Ptr() );

				if (findFile.handle != INVALID_HANDLE_VALUE)
				{
					do
					{
						if (!(findFile.data.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_DIRECTORY)))
						{
							path.File() = findFile.data.cFileName;

							if (path.Extension() == L"nlg")
								paths.push_back( path );
						}
					}
					while (::FindNextFile( findFile.handle, &findFile.data ));
				}
			}
		}
Ejemplo n.º 16
0
void DataManager::init()
{
	LOG(INFO, "initializing data dirs");

	Path path = app->getPath();
	string name = /*path.name()*/"OpenSkyscraper";
#ifdef __APPLE__
# ifdef BUILD_DEBUG
	//TODO: there's an issue with climbing up paths that go like ../../, since path.up() will first erase these ../ segments, instead of directly appending to them.
	//dirs.push_back(path.up(0).down("data"));
	dirs.push_back(Path("data"));
	dirs.push_back(path.up(1).down("Resources"));
# endif
	dirs.push_back(Path("~/Library/Application Support/OpenSkyscraper"));
	dirs.push_back(Path("/Library/Application Support/OpenSkyscraper"));
	dirs.push_back(".");
#else
# ifdef BUILD_DEBUG
	dirs.push_back(path.up(2).down("data"));
# endif
	dirs.push_back(path.down("data"));
	dirs.push_back(path.up().down("data"));
# ifndef _WIN32
	dirs.push_back(Path("~").down(".openskyscraper"));
	dirs.push_back(Path("/usr/local/share/openskyscraper"));
	dirs.push_back(Path("/usr/share/openskyscraper"));
# endif
#endif

	Paths existing;
	for (Paths::const_iterator it = dirs.begin(); it != dirs.end(); ++it) {
		bool exists = DirectoryExists(it->c_str());
		LOG(DEBUG, (exists ? "  %s" : "  %s (not found)"), it->c_str());
		if (exists)
			existing.push_back(*it);
	}
	std::swap(dirs, existing);
}
Ejemplo n.º 17
0
void PathManager::init()
{
	/// Search for the OGRE plugin folder
	ogre_plugin_dir = "";
	
	 // Use environment variable, if present
	char *plugindir = getenv("OGRE_PLUGIN_DIR");
	if (plugindir)
	{
		ogre_plugin_dir = plugindir;
		return;
	}
	
	#ifdef _WIN32
		// Windows: we assume the ogre plugins are in the directory the program is run from (".")
		ogre_plugin_dir = ".";
	#else
		// Linux: Check a list of common path names
		typedef std::vector<boost::filesystem::path> Paths;
		Paths dirs;
		#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(_M_X64)
			dirs.push_back("/usr/local/lib64");
			dirs.push_back("/usr/lib64");
		#else
			dirs.push_back("/usr/local/lib32");
			dirs.push_back("/usr/lib32");
		#endif
		dirs.push_back("/usr/local");
		dirs.push_back("/usr/lib");
		// Loop through the paths and pick the first one that contains a plugin
		for (Paths::const_iterator p = dirs.begin(); p != dirs.end(); ++p) {
			if (boost::filesystem::exists(*p / "OGRE/RenderSystem_GL.so")) {
				ogre_plugin_dir = (*p / "OGRE").string();
				break;
			} else if (boost::filesystem::exists(*p / "ogre/RenderSystem_GL.so")) {
				ogre_plugin_dir = (*p / "ogre").string();
				break;
			}
		}
	#endif
}
Ejemplo n.º 18
0
void PATHMANAGER::Init(std::ostream & info_output, std::ostream & error_output)
{
	typedef std::vector<fs::path> Paths;

	// Set Ogre plugins dir
	{
		ogre_plugin_dir = "";
		char *plugindir = getenv("OGRE_PLUGIN_DIR");
		if (plugindir) {
			ogre_plugin_dir = plugindir;
		#ifndef _WIN32
		} else if (fs::exists(fs::path(OGRE_PLUGIN_DIR) / "RenderSystem_GL.so")) {
			ogre_plugin_dir = OGRE_PLUGIN_DIR;
		#endif
		} else {
			#ifdef _WIN32
			ogre_plugin_dir = ".";
			#else
			Paths dirs;
			#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(_M_X64)
			dirs.push_back("/usr/local/lib64");
			dirs.push_back("/usr/lib64");
			#else
			dirs.push_back("/usr/local/lib32");
			dirs.push_back("/usr/lib32");
			#endif
			dirs.push_back("/usr/local");
			dirs.push_back("/usr/lib");
			// Loop through the paths and pick the first one that contain a plugin
			for (Paths::const_iterator p = dirs.begin(); p != dirs.end(); ++p) {
				if (fs::exists(*p / "OGRE/RenderSystem_GL.so")) {
					ogre_plugin_dir = (*p / "OGRE").string();
					break;
				} else if (fs::exists(*p / "ogre/RenderSystem_GL.so")) {
					ogre_plugin_dir = (*p / "ogre").string();
					break;
				}
			}
			#endif
		}
	}

	fs::path shortDir = "stuntrally";
	// Figure out the user's home directory
	{
		home_dir = "";
		#ifndef _WIN32 // POSIX
			char *homedir = getenv("HOME");
			if (homedir == NULL)
			{
				home_dir = "/home/";
				homedir = getenv("USER");
				if (homedir == NULL) {
					homedir = getenv("USERNAME");
					if (homedir == NULL) {
						error_output << "Could not find user's home directory!" << std::endl;
						home_dir = "/tmp/";
					}
				}
			}
		#else // Windows
			char *homedir = getenv("USERPROFILE");
			if (homedir == NULL) homedir = "data"; // WIN 9x/Me
		#endif
		home_dir += homedir;
	}

	// Find user's config dir
	#ifndef _WIN32 // POSIX
	{
		char const* conf = getenv("XDG_CONFIG_HOME");
		if (conf) user_config_dir = (fs::path(conf) / "stuntrally").string();
		else user_config_dir = (fs::path(home_dir) / ".config" / "stuntrally").string();
	}
	#else // Windows
	{
		// Open AppData directory
		std::string str;
		ITEMIDLIST* pidl;
		char AppDir[MAX_PATH];
		HRESULT hRes = SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE , &pidl);
		if (hRes == NOERROR)
		{
			SHGetPathFromIDList(pidl, AppDir);
			int i;
			for (i = 0; AppDir[i] != '\0'; i++) {
				if (AppDir[i] == '\\') str += '/';
				else str += AppDir[i];
			}
			user_config_dir = (fs::path(str) / "stuntrally").string();
		}
	}
	#endif
	// Create user's config dir
	CreateDir(user_config_dir, error_output);

	// Find user's data dir (for additional data)
	#ifdef _WIN32
	user_data_dir = user_config_dir;  // APPDATA/stuntrally
	#else
	{
		fs::path shareDir = SHARED_DATA_DIR;
		char const* xdg_data_home = getenv("XDG_DATA_HOME");
		user_data_dir = (xdg_data_home ? xdg_data_home / shortDir : fs::path(home_dir) / ".local" / shareDir).string();
	}
	#endif
	// Create user's data dir and its children
	CreateDir(user_data_dir, error_output);
	CreateDir(GetTrackRecordsPath(), error_output);
	CreateDir(GetScreenShotDir(), error_output);
	CreateDir(GetTrackPathUser(), error_output);  // user tracks
	CreateDir(GetTrackPathUser()+"/_previews", error_output);
	CreateDir(GetReplayPath(), error_output);
	CreateDir(GetGhostsPath(), error_output);

	// Find game data dir and defaults config dir
	char *datadir = getenv("STUNTRALLY_DATA_ROOT");
	if (datadir)
		game_data_dir = std::string(datadir);
	else
	{	fs::path shareDir = SHARED_DATA_DIR;
		Paths dirs;

		// Adding users data dir
		// TODO: Disabled for now until this is handled properly
		//dirs.push_back(user_data_dir);

		// Adding relative path from installed executable
		dirs.push_back(execname().parent_path().parent_path() / shareDir);
		// Adding relative path for running from sources
		dirs.push_back(execname().parent_path().parent_path() / "data");
		dirs.push_back(execname().parent_path().parent_path());
		dirs.push_back(execname().parent_path() / "data");
		dirs.push_back(execname().parent_path());
		#ifndef _WIN32
		// Adding XDG_DATA_DIRS
		{
			char const* xdg_data_dirs = getenv("XDG_DATA_DIRS");
			std::istringstream iss(xdg_data_dirs ? xdg_data_dirs : "/usr/local/share/:/usr/share/");
			for (std::string p; std::getline(iss, p, ':'); dirs.push_back(p / shortDir)) {}
		}
		#endif
		// TODO: Adding path from config file

		// Loop through the paths and pick the first one that contain some data
		for (Paths::const_iterator p = dirs.begin(); p != dirs.end(); ++p) {
			// Data dir
			if (fs::exists(*p / "hud")) game_data_dir = p->string();
			// Config dir
			if (fs::exists(*p / "config"))
				game_config_dir = (*p / "config").string();
			// Check if both are found
			if (!game_data_dir.empty() && !game_config_dir.empty()) break;
		}
	}

	// Find cache dir
	#ifdef _WIN32
	cache_dir = user_config_dir + "/cache";  // APPDATA/stuntrally/cache
	#else
	char const* xdg_cache_home = getenv("XDG_CACHE_HOME");
	cache_dir = (xdg_cache_home ? xdg_cache_home / shortDir : fs::path(home_dir) / ".cache" / shortDir).string();
	#endif
	// Create cache dir
	CreateDir(cache_dir, error_output);
	CreateDir(GetShaderCacheDir(), error_output);

	// Print diagnostic info
	std::stringstream out;
	out << "--- Directories: ---" << ogre_plugin_dir << std::endl;
	out << "Ogre plugin:  " << ogre_plugin_dir << std::endl;
	out << "Home:         " << home_dir << std::endl;
	out << "Default cfg:  " << GetGameConfigDir() << std::endl;
	out << "User cfg:     " << GetUserConfigDir() << std::endl;
	out << "Data:         " << GetDataPath() << std::endl;
	out << "User data:    " << GetUserDataDir() << std::endl;
	out << "Cache:        " << GetCacheDir() << std::endl;
	out << "Shader cache: " << GetShaderCacheDir() << std::endl;
	out << "Log:          " << GetLogDir() << std::endl;
	info_output << out.str();
}
Ejemplo n.º 19
0
void Kernel::infer(std::vector<std::string> args)
{
    if (args.empty())
    {
        std::cout << getUsageString() << std::flush;
        return;
    }

    if (args.size() == 1)
    {
        if (args[0] == "help" || args[0] == "-h" || args[0] == "--help")
        {
            std::cout << getUsageString() << std::flush;
            return;
        }
    }

    // TODO Allow multiple.
    Paths paths;

    std::size_t threads(4);
    Json::Value jsonReprojection;
    std::string user;
    std::string tmpPath("tmp");
    bool trustHeaders(true);

    std::string output;

    std::size_t a(0);

    while (a < args.size())
    {
        const std::string arg(args[a]);

        if (arg.front() != '-')
        {
            // If this is not an option argument, use it as the path.
            if (paths.empty())
            {
                paths.push_back(arg);
            }
            else
            {
                throw std::runtime_error(
                        "Only one path allowed - found both '" +
                        paths.front() + "' and '" + arg + "'");
            }
        }
        else if (arg == "-a")
        {
            if (++a < args.size())
            {
                tmpPath = args[a];
            }
            else
            {
                throw std::runtime_error("Invalid tmp specification");
            }
        }
        else if (arg == "-o")
        {
            if (++a < args.size())
            {
                output = args[a] + ".entwine-inference";
            }
            else
            {
                throw std::runtime_error("Invalid output specification");
            }
        }
        else if (arg == "-r")
        {
            if (++a < args.size())
            {
                const bool onlyOutput(
                        a + 1 >= args.size() ||
                        args[a + 1].front() == '-');

                if (onlyOutput)
                {
                    jsonReprojection["out"] = args[a];
                }
                else
                {
                    jsonReprojection["in"] = args[a];
                    jsonReprojection["out"] = args[++a];
                }
            }
            else
            {
                throw std::runtime_error("Invalid reprojection argument");
            }
        }
        else if (arg == "-h")
        {
            jsonReprojection["hammer"] = true;
        }
        else if (arg == "-x")
        {
            trustHeaders = false;
        }
        else if (arg == "-t")
        {
            if (++a < args.size())
            {
                threads = Json::UInt64(std::stoul(args[a]));
            }
            else
            {
                throw std::runtime_error("Invalid thread count specification");
            }
        }
        else if (arg == "-u")
        {
            if (++a < args.size())
            {
                user = args[a];
            }
            else
            {
                throw std::runtime_error("Invalid AWS user argument");
            }
        }

        ++a;
    }

    entwine::arbiter::fs::mkdirp(tmpPath);

    std::unique_ptr<Reprojection> reprojection;

    if (jsonReprojection.isMember("out"))
    {
        reprojection.reset(new Reprojection(jsonReprojection));
    }

    Json::Value arbiterConfig;
    arbiterConfig["s3"]["profile"] = user;

    auto arbiter(std::make_shared<entwine::arbiter::Arbiter>(arbiterConfig));

    const auto reprojString(getReprojString(reprojection.get()));
    const auto trustHeadersString(trustHeaders ? "yes" : "no");

    std::cout << "Inferring from: " << paths.front() << std::endl;
    std::cout << "\tTemp path: " << tmpPath << std::endl;
    std::cout << "\tThreads: " << threads << std::endl;
    std::cout << "\tReprojection: " << reprojString << std::endl;
    std::cout << "\tTrust file headers? " << trustHeadersString << std::endl;

    const bool allowDelta(true);
    const bool verbose(true);
    const bool cesiumify(false);

    Inference inference(
            paths,
            reprojection.get(),
            trustHeaders,
            allowDelta,
            tmpPath,
            threads,
            verbose,
            cesiumify,
            arbiter.get());

    inference.go();

    if (output.size())
    {
        std::cout << "Writing details to " << output << "..." << std::endl;
        Json::Value json(inference.toJson());
        arbiter->put(output, json.toStyledString());
    }

    std::cout << "Schema: " << inference.schema() << std::endl;
    std::cout << "Bounds: " << inference.bounds() << std::endl;
    std::cout << "Points: " << commify(inference.numPoints()) << std::endl;

    if (reprojection)
    {
        std::cout << "Reprojection: " << *reprojection << std::endl;
    }

    if (const auto delta = inference.delta())
    {
        std::cout << "Scale:  " << delta->scale() << std::endl;
        std::cout << "Offset: " << delta->offset() << std::endl;
    }
}
Ejemplo n.º 20
0
void PATHMANAGER::Init(bool log_paths)
{
	typedef vector<fs::path> Paths;

	// Set Ogre plugins dir
	{
		ogre_plugin = "";
		char *plugindir = getenv("OGRE_PLUGIN_DIR");
		if (plugindir) {
			ogre_plugin = plugindir;
		} else {
			#ifdef _WIN32
			ogre_plugin = ".";
			#else
			ogre_plugin = OGRE_PLUGIN_DIR_REL;
			#endif
		}
	}

	fs::path stuntrally = "stuntrally";
	// Figure out the user's home directory
	{
		home_dir = "";
		#ifndef _WIN32 // POSIX
			char *homedir = getenv("HOME");
			if (homedir == NULL)
			{
				home_dir = "/home/";
				homedir = getenv("USER");
				if (homedir == NULL) {
					homedir = getenv("USERNAME");
					if (homedir == NULL) {
						cerr << "Could not find user's home directory!" << endl;
						home_dir = "/tmp/";
					}
				}
			}
		#else // Windows
			char *homedir = getenv("USERPROFILE");
			if (homedir == NULL) homedir = "data"; // WIN 9x/Me
		#endif
		home_dir += homedir;
	}

	// Find user's config dir
	#ifndef _WIN32 // POSIX
	{
		char const* conf = getenv("XDG_CONFIG_HOME");
		if (conf) user_config = (fs::path(conf) / stuntrally).string();
		else user_config = (fs::path(home_dir) / ".config" / stuntrally).string();
	}
	#else // Windows
	{
		// Open AppData directory
		string str;
		ITEMIDLIST* pidl;
		char AppDir[MAX_PATH];
		HRESULT hRes = SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, &pidl);
		if (hRes == NOERROR)
		{
			SHGetPathFromIDList(pidl, AppDir);
			int i;
			for (i = 0; AppDir[i] != '\0'; ++i) {
				if (AppDir[i] == '\\') str += '/';
				else str += AppDir[i];
			}
			user_config = (fs::path(str) / stuntrally).string();
		}
	}
	#endif
	// Create user's config dir
	CreateDir(user_config);

	// Find user's data dir (for additional data)
	#ifdef _WIN32
	user_data = user_config;  // APPDATA/stuntrally
	#else
	{
		char const* xdg_data_home = getenv("XDG_DATA_HOME");
		user_data = (xdg_data_home ? xdg_data_home / stuntrally
					: fs::path(home_dir) / ".local/share" / stuntrally).string();
	}
	#endif

	// Create user's data dir and its children
	///--------------------------------------------------
	CreateDir(user_data);
	CreateDir(Records());
	CreateDir(Ghosts());
	
	CreateDir(Replays());
	CreateDir(Screenshots());
	CreateDir(TracksUser());  // user tracks

	CreateDir(DataUser());  // user data


	// Find game data dir and defaults config dir
	char *datadir = getenv("STUNTRALLY_DATA_ROOT");
	if (datadir)
		game_data = string(datadir);
	else
	{	fs::path shareDir = SHARED_DATA_DIR;
		Paths dirs;

		// Adding users data dir
		// TODO: Disabled for now until this is handled properly
		//dirs.push_back(user_data_dir);

		// Adding relative path for running from sources
		dirs.push_back(execname().parent_path().parent_path() / "data");
		dirs.push_back(execname().parent_path().parent_path());
		dirs.push_back(execname().parent_path() / "data");
		dirs.push_back(execname().parent_path());
		// Adding relative path from installed executable
		dirs.push_back(execname().parent_path().parent_path() / shareDir);
		#ifndef _WIN32
		// Adding XDG_DATA_DIRS
		{
			char const* xdg_data_dirs = getenv("XDG_DATA_DIRS");
			istringstream iss(xdg_data_dirs ? xdg_data_dirs : "/usr/local/share/:/usr/share/");
			for (string p; getline(iss, p, ':'); dirs.push_back(p / stuntrally)) {}
		}
		#endif
		// TODO: Adding path from config file

		//  Loop through the paths and pick the first one that contain some data
		for (Paths::const_iterator p = dirs.begin(); p != dirs.end(); ++p)
		{	//  Data dir
			if (fs::exists(*p / "hud"))
				game_data = p->string();
			//  Config dir
			if (fs::exists(*p / "config"))
				game_config = (*p / "config").string();
			//  Check if both are found
			if (!game_data.empty() && !game_config.empty())  break;
		}
	}


	//  Subdirs for each sim_mode
	///--------------------------------------------------
	list <string> li;
	PATHMANAGER::DirList(PATHMANAGER::CarSim(), li);
	for (list <string>::iterator i = li.begin(); i != li.end(); ++i)
	{
		CreateDir(Records()+"/"+*i);
		CreateDir(Ghosts()+"/"+*i);
	}

	// Find cache dir
	#ifdef _WIN32
	cache_dir = user_config + "/cache";  // APPDATA/stuntrally/cache
	#else
	char const* xdg_cache_home = getenv("XDG_CACHE_HOME");
	cache_dir = (xdg_cache_home ? xdg_cache_home / stuntrally
				: fs::path(home_dir) / ".cache" / stuntrally).string();
	#endif
	// Create cache dir
	CreateDir(CacheDir());
	CreateDir(CacheDir()+"/tracks");
	CreateDir(ShaderDir());

	// Print diagnostic info
	if (log_paths)
	{
		info << "Paths info" << endl;
		info << "-------------------------" << endl;
		info << "Ogre plugin:  " << ogre_plugin << endl;
		info << "Data:         " << Data() << endl;
		//info << "Default cfg:  " << GetGameConfigDir() << endl;
		info << "Home:         " << home_dir << endl;
		info << "User cfg,log: " << UserConfigDir() << endl;
		info << "User data:    " << user_data << endl;
		info << "Cache:        " << CacheDir() << endl;
		info << "-------------------------";
	}
}
Ejemplo n.º 21
0
Paths CorrespondenceGenerator::generate()
{
	Paths result;

	auto boxA = a->bbox(), boxB = b->bbox();

	QStringList nodesA, nodesB;
	for (auto n : a->nodes) nodesA << n->id;
	for (auto n : b->nodes) nodesB << n->id;
	for (auto g : a->groups) for (auto nid : g) nodesA.removeAll(nid);
	for (auto g : b->groups) for (auto nid : g) nodesB.removeAll(nid);
	Structure::NodeGroups tmpA, tmpB;
	for (auto nid : nodesA) tmpA.push_back( QVector<QString>() << nid );
	for (auto nid : nodesB) tmpB.push_back( QVector<QString>() << nid );
	for (auto g : a->groups) tmpA.push_back(g);
	for (auto g : b->groups) tmpB.push_back(g);
	a->groups = tmpA;
	b->groups = tmpB;

	/// Build similarity matrix of groups:
	Eigen::MatrixXd similiarity = Eigen::MatrixXd::Ones(a->groups.size(), b->groups.size() + 1);

	for (size_t i = 0; i < similiarity.rows(); i++){
		double minVal = DBL_MAX;
		for (size_t j = 0; j < similiarity.cols(); j++){
			double val = 0;

			if (j < b->groups.size())
			{
				Eigen::AlignedBox3d groupBoxA, groupBoxB;
				for (auto sid : a->groups[i]) groupBoxA.extend(a->getNode(sid)->bbox(1.01));
				for (auto sid : b->groups[j]) groupBoxB.extend(b->getNode(sid)->bbox(1.01));

				Vector3 relativeCenterA = (groupBoxA.center() - boxA.min()).array() / boxA.sizes().array();
				Vector3 relativeCenterB = (groupBoxB.center() - boxB.min()).array() / boxB.sizes().array();

				val = (relativeCenterA - relativeCenterB).norm();

				minVal = std::min(minVal, val);
			}

			similiarity(i, j) = val;
		}
		double maxVal = similiarity.row(i).maxCoeff();
		if (maxVal == 0) maxVal = 1.0;

		for (size_t j = 0; j < b->groups.size(); j++)
			similiarity(i, j) = (similiarity(i, j) - minVal) / maxVal;
	}

	std::vector< std::vector<float> > data;
	for (int i = 0; i < similiarity.rows(); i++){
		std::vector<float> dataRow;
		for (int j = 0; j < similiarity.cols(); j++)
			dataRow.push_back(similiarity(i, j));
		data.push_back(dataRow);
	}
	//if (false) showTableColorMap(data, true); // DEBUG

	// Parameters:
	double similarity_threshold = 0.4;

	if (similiarity.rows() < 4) similarity_threshold = 1.0;

	// Collect good candidates
	Assignments candidates;
	for (size_t i = 0; i < similiarity.rows(); i++){
		QVector<size_t> candidate;
		for (size_t j = 0; j < similiarity.cols(); j++){
			if (similiarity(i, j) < similarity_threshold)
				candidate << j;
		}
		candidates << candidate;
	}

	int count_threshold = 1;

	Assignments assignments;
	if (candidates.size() > 7)
	{
		debugBox(QString("%1 candidates. Too complex (lower similairty?)").arg(candidates.size()));

		similarity_threshold = 0.1;

		Assignments candidates;
		for (size_t i = 0; i < similiarity.rows(); i++){
			QVector<size_t> candidate;
			for (size_t j = 0; j < similiarity.cols(); j++){
				if (similiarity(i, j) < similarity_threshold)
					candidate << j;
			}
			candidates << candidate;
		}

		cart_product(assignments, candidates, 10000);
		count_threshold = 12;
	}
	else
	{
		cart_product(assignments, candidates);
	}

	// Filter assignments
	Assignments filtered;
	for (auto & a : assignments)
	{
		QMap<size_t, size_t> counts;
		bool accept = true;
		auto NOTHING_SEGMENT = similiarity.cols() - 1;

		for (auto i : a) counts[i]++;
		for (auto k : counts.keys())
		{
			if (k != NOTHING_SEGMENT && counts[k] > count_threshold){
				accept = false;
				break;
			}
		}

		if (accept) filtered << a;
	}

	for (auto & assignment : filtered)
	{
		QVector < QStringList > landmarksA, landmarksB;

		for (size_t i = 0; i < assignment.size(); i++)
		{
			if (assignment[i] == b->groups.size()) continue;

			auto grpA = a->groups[i];
			auto grpB = b->groups[assignment[i]];

			// Resolve many-to-many
			if (grpA.size() > 1 && grpB.size() > 1)
			{
				QVector<QString> tmpA, tmpB;

				Eigen::AlignedBox3d groupBoxA, groupBoxB;
				for (auto sid : grpA) groupBoxA.extend(a->getNode(sid)->bbox(1.01));
				for (auto sid : grpB) groupBoxB.extend(b->getNode(sid)->bbox(1.01));

				for (auto nodeid_i : grpA){
					auto nodeA = a->getNode(nodeid_i);

					QMap < QString, double > dists;
					for (auto nodeid_j : grpB){
						auto nodeB = b->getNode(nodeid_j);

						Vector3 posA = (nodeA->position(Eigen::Vector4d(0.5, 0.5, 0, 0)) - boxA.min()).array() / boxA.sizes().array();
						Vector3 posB = (nodeB->position(Eigen::Vector4d(0.5, 0.5, 0, 0)) - boxB.min()).array() / boxB.sizes().array();

						dists[nodeid_j] = (posA - posB).norm();
					}
					auto nodeid_j = sortQMapByValue(dists).first().second;

					landmarksA << (QStringList() << nodeid_i);
					landmarksB << (QStringList() << nodeid_j);
				}
			}
			else
			{
				landmarksA << QStringList::fromVector(grpA);
				landmarksB << QStringList::fromVector(grpB);
			}
		}

		result.push_back( qMakePair(landmarksA, landmarksB) );
	}

    return result;
}
Ejemplo n.º 22
0
toolpath::toolpath(preprocess &p)
{
    QElapsedTimer timer;
    timer.start();

    int i,j;
    struct net tempPreprocessNetPath;

    //produce toolpath for every element
    //method:offset the shape with the radius of the bit
    //then link the breaking points
    for(j=0;j<p.netList.size();j++)
    {
        struct netPath tempToolPathNetPath;
        tempPreprocessNetPath=p.netList.at(j);
        Paths tempCPaths;
        for(i=0;i<tempPreprocessNetPath.elements.size();i++)
        {
            struct myPath tempPath;
            struct element e=tempPreprocessNetPath.elements.at(i);
            struct segment s;
            tempPath.element=e;
            if(e.elementType=='T')//track
            {
                struct myRect r=trackToMyRect(e.track,toolDiameter);

                s.point=r.p1;
                s.type='L';
                tempPath.segmentList.append(s);
                s.point=r.p2;
                s.type='C';
                tempPath.segmentList.append(s);
                s.point=r.p3;
                s.type='L';
                tempPath.segmentList.append(s);
                s.point=r.p4;
                s.type='C';
                tempPath.segmentList.append(s);

                IntPoint point;
                point.X=r.p1.x();point.Y=r.p1.y();
                tempPath.toolpath<<point;
                arcToSegments(r.p2,r.p3,tempPath.toolpath);
                point.X=r.p4.x();point.Y=r.p4.y();
                tempPath.toolpath<<point;
                arcToSegments(r.p4,r.p1,tempPath.toolpath);
            }
            else//pad
            {
                if(e.pad.shape=='C')
                {
                    QPoint point;
                    QPoint point1,point2;
                    point.setX(e.pad.point.x());
                    point.setY(e.pad.point.y()+e.pad.parameter[0]/2+toolDiameter/2);
                    point1=point;
                    s.point=point;
                    s.type='C';
                    tempPath.segmentList.append(s);

                    point.setY(e.pad.point.y()-e.pad.parameter[0]/2-toolDiameter/2);
                    point2=point;
                    s.point=point;
                    s.type='C';
                    tempPath.segmentList.append(s);

                    arcToSegments(point1,point2,tempPath.toolpath);
                    arcToSegments(point2,point1,tempPath.toolpath);
                }
                else if(e.pad.shape=='R')
                {
                    struct myRect r=rectToMyRect(e.pad,toolDiameter);
                    s.point=r.p1;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p2;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p3;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p4;
                    s.type='L';
                    tempPath.segmentList.append(s);

                    IntPoint point;
                    point.X=r.p1.x();point.Y=r.p1.y();
                    tempPath.toolpath<<point;
                    point.X=r.p2.x();point.Y=r.p2.y();
                    tempPath.toolpath<<point;
                    point.X=r.p3.x();point.Y=r.p3.y();
                    tempPath.toolpath<<point;
                    point.X=r.p4.x();point.Y=r.p4.y();
                    tempPath.toolpath<<point;
                }
                else if(e.pad.shape=='O')
                {
                    struct track t=obroundToTrack(e.pad);
                    struct myRect r=trackToMyRect(t,toolDiameter);
                    s.point=r.p1;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p2;
                    s.type='C';
                    tempPath.segmentList.append(s);
                    s.point=r.p3;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p4;
                    s.type='C';
                    tempPath.segmentList.append(s);

                    IntPoint point;
                    point.X=r.p1.x();point.Y=r.p1.y();
                    tempPath.toolpath<<point;
                    arcToSegments(r.p2,r.p3,tempPath.toolpath);
                    point.X=r.p4.x();point.Y=r.p4.y();
                    tempPath.toolpath<<point;
                    arcToSegments(r.p4,r.p1,tempPath.toolpath);
                }
            }
            tempCPaths.push_back(tempPath.toolpath);
            tempPath.boundingRect=expandBoundingRect(e.boundingRect,toolDiameter);
            tempToolPathNetPath.pathList.append(tempPath);

        }
        SimplifyPolygons(tempCPaths,tempToolPathNetPath.toolpath,pftNonZero);
        netPathList.append(tempToolPathNetPath);
    }
    cToolpathIntersects(netPathList,tpCollisionNum);
    int sum=0;
    for(int i=0;i<tpCollisionNum.size();i++)
    {
        collisionToolpath temp=tpCollisionNum.at(i);
        sum+=temp.pair.size();
        for(int j=0;j<temp.pair.size();j++)
        {
            net n=p.netList.at(temp.pair.at(j).p1);
            n.collisionFlag=true;
            p.netList.replace(temp.pair.at(j).p1,n);

            n=p.netList.at(temp.pair.at(j).p2);
            n.collisionFlag=true;
            p.netList.replace(temp.pair.at(j).p2,n);
        }
    }
    qDebug()<<"toolpath collision num="<<sum;
    collisionSum=sum;

    Paths tempPath;
    for(i=0;i<netPathList.size();i++)
        tempPath.push_back(netPathList.at(i).toolpath.at(0));

    SimplifyPolygons(tempPath,totalToolpath,pftNonZero);

    for(i=0;i<netPathList.size();i++)
        if(netPathList.at(i).toolpath.size()>1)
        {
            for(j=1;j<netPathList.at(i).toolpath.size();j++)
            totalToolpath.push_back(netPathList.at(i).toolpath.at(j));
        }

    time=timer.elapsed();

}