Ejemplo n.º 1
0
static const char* Getcwd(char* buf, unsigned int len)
{
  const char* ret = _getcwd(buf, len);
  char* p = NULL;
  if(!ret)
    {
    fprintf(stderr, "No current working directory.\n");
    abort();
    }
  // make sure the drive letter is capital
  if(strlen(buf) > 1 && buf[1] == ':')
    {
    buf[0] = toupper(buf[0]);
    }
  for(p = buf; *p; ++p)
    {
    if(*p == '\\')
      {
      *p = '/';
      }
    }
  return ret;
}
Ejemplo n.º 2
0
std::string UDir::currentDir(bool trailingSeparator)
{
	std::string dir;
	char * buffer;

#ifdef WIN32
	buffer = _getcwd(NULL, 0);
#else
	buffer = getcwd(NULL, MAXPATHLEN);
#endif

	if( buffer != NULL )
	{
		dir = buffer;
		free(buffer);
		if(trailingSeparator)
		{
			dir += separator();
		}
	}

	return dir;
}
Ejemplo n.º 3
0
Globals::Globals() {
    mathLib = Globals::Math_ISPC;

    includeStdlib = true;
    runCPP = true;
    debugPrint = false;
    disableWarnings = false;
    warningsAsErrors = false;
    disableLineWrap = false;
    emitPerfWarnings = true;
    emitInstrumentation = false;
    generateDebuggingSymbols = false;
    mangleFunctionsWithTarget = false;

    ctx = new llvm::LLVMContext;

#ifdef ISPC_IS_WINDOWS
    _getcwd(currentDirectory, sizeof(currentDirectory));
#else
    if (getcwd(currentDirectory, sizeof(currentDirectory)) == NULL)
        FATAL("Current directory path too long!");
#endif
}
Ejemplo n.º 4
0
void CSiteGroupsTree::OnSiteGroupImportChildGroup()
{
    ASSERT(m_actionGroup);

    CWnd *parent = GetParent();
    ASSERT(parent);

    CFileDialog dlg(TRUE, DefaultExtension, 0, OFN_NOCHANGEDIR | OFN_FILEMUSTEXIST, DefaultFilter, parent);
    char currentDir[_MAX_PATH];
    dlg.m_ofn.lpstrInitialDir = _getcwd(currentDir, _MAX_PATH);
    if (dlg.DoModal() != IDOK)
        return;

    CString filename = dlg.GetPathName();

    try {
        WebWatch::SiteItemGroup & importedGroup = WebWatch::Store::Instance().ImportGroup(*m_actionGroup, filename);
        GroupAppender appender(*this, GetItemFromGroup(*m_actionGroup));
        appender(&importedGroup);
    }
    catch(const WebWatch::StoreError & ex) {
        parent->MessageBox(ex.what(), "Failure", MB_OK | MB_ICONERROR);
        return;
    }

    UpdateTree();
    
    WebWatch::SiteItemGroup & selectedGroup = GetGroupFromItem(GetSelectedItem());
    RefreshSiteList(selectedGroup);

    std::string message("Group(s) in file '");
    message += dlg.GetFileName();
    message += "' imported successfully under group '";
    message += m_actionGroup->GetName();
    message += '\'';
    parent->MessageBox(message.c_str(), "Success", MB_OK | MB_ICONINFORMATION);
}
Ejemplo n.º 5
0
void CPath::LoadFromINIfile(void)
{
	Initialize();
	prm = AfxGetApp()->GetProfileString(m_INIheading, m_INIprm);
	mat = AfxGetApp()->GetProfileString(m_INIheading, m_INImat);
	dev = AfxGetApp()->GetProfileString(m_INIheading, m_INIdev);
	exc = AfxGetApp()->GetProfileString(m_INIheading, m_INIexc);
	abs = AfxGetApp()->GetProfileString(m_INIheading, m_INIabs);
	dop = AfxGetApp()->GetProfileString(m_INIheading, m_INIdop);
	inr = AfxGetApp()->GetProfileString(m_INIheading, m_INIinr);
	ref = AfxGetApp()->GetProfileString(m_INIheading, m_INIref);
	gen = AfxGetApp()->GetProfileString(m_INIheading, m_INIgen);
	lgt = AfxGetApp()->GetProfileString(m_INIheading, m_INIlgt);
	spc = AfxGetApp()->GetProfileString(m_INIheading, m_INIspc);
	vlt = AfxGetApp()->GetProfileString(m_INIheading, m_INIvlt);
	bat = AfxGetApp()->GetProfileString(m_INIheading, m_INIbat);
	// if there's no entry in INI file, or if there is but it's NULL, we set the directory
	// to the current working directory, as specified in file manager properties.
	CString cwdbuff;
	char *s =cwdbuff.GetBuffer(_MAX_PATH+1);
	_getcwd(s, _MAX_PATH);
	cwdbuff.ReleaseBuffer();
	cwdbuff.MakeLower();
	if (prm.IsEmpty()) prm=cwdbuff;
	if (mat.IsEmpty()) mat=cwdbuff;
	if (dev.IsEmpty()) dev=cwdbuff;
	if (exc.IsEmpty()) exc=cwdbuff;
	if (abs.IsEmpty()) abs=cwdbuff;
	if (dop.IsEmpty()) dop=cwdbuff;
	if (inr.IsEmpty()) inr=cwdbuff;
	if (ref.IsEmpty()) ref=cwdbuff;
	if (gen.IsEmpty()) gen=cwdbuff;
	if (lgt.IsEmpty()) lgt=cwdbuff;
	if (spc.IsEmpty()) spc=cwdbuff;
	if (vlt.IsEmpty()) vlt=cwdbuff;
	if (bat.IsEmpty()) bat=cwdbuff;
}
Ejemplo n.º 6
0
//! Returns the string of the current working directory
const core::string<c16>& CFileSystem::getWorkingDirectory()
{
	EFileSystemType type = FileSystemType;

	if (type != FILESYSTEM_NATIVE)
	{
		type = FILESYSTEM_VIRTUAL;
	}
	else
	{
		const s32 FILE_SYSTEM_MAX_PATH = 1024;
		WorkingDirectory[type].reserve(FILE_SYSTEM_MAX_PATH);
		c16* r = (c16*) WorkingDirectory[type].c_str();

		#if defined(_IRR_USE_WINDOWS_CE_DEVICE_)
		#elif defined(_IRR_WINDOWS_API_)
			#if defined(_IRR_WCHAR_FILESYSTEM )
				_wgetcwd(r, FILE_SYSTEM_MAX_PATH);
			#else
				_getcwd(r, FILE_SYSTEM_MAX_PATH);
			#endif
		#endif

		#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))

			#if defined(_IRR_WCHAR_FILESYSTEM )
				wgetcwd(r, FILE_SYSTEM_MAX_PATH);
			#else
				getcwd(r, (size_t)FILE_SYSTEM_MAX_PATH);
			#endif
		#endif

		WorkingDirectory[type].validate();
	}

	return WorkingDirectory[type];
}
Ejemplo n.º 7
0
	//--------------------------------
	bool Utils::createDirectoryIfNeeded( const String &pathString )
	{
		bool pathExists = false;

#ifdef COLLADABU_OS_WIN
		SystemType type = getSystemType();
		if( type != WINDOWS )
			return false;

		const char* currentPath = _getcwd( 0, 0);
		const char* testPath = pathString.c_str();

		pathExists = _chdir( testPath ) == 0;
		if( !pathExists )
		{
			_mkdir( testPath );
			pathExists = _chdir( testPath ) == 0;
		}

		_chdir( currentPath );

#else
		SystemType type = getSystemType();
		if( type != POSIX )
			return false;

		const char* currentPath = getcwd( 0, 0);
		const char* testPath = pathString.c_str();
        pathExists = chdir( testPath ) == 0;
		if( !pathExists )
		{
            pathExists = mkdir(testPath, 0755) == false;
        }
        chdir( currentPath );
#endif
		return pathExists;
	}
Ejemplo n.º 8
0
void V_MakeAbsolutePath( char *pOut, int outLen, const char *pPath, const char *pStartingDir )
{
	if ( V_IsAbsolutePath( pPath ) )
	{
		// pPath is not relative.. just copy it.
		V_strncpy( pOut, pPath, outLen );
	}
	else
	{
		// Make sure the starting directory is absolute..
		if ( pStartingDir && V_IsAbsolutePath( pStartingDir ) )
		{
			V_strncpy( pOut, pStartingDir, outLen );
		}
		else
		{
			if ( !_getcwd( pOut, outLen ) )
				Error( "V_MakeAbsolutePath: _getcwd failed." );

			if ( pStartingDir )
			{
				V_AppendSlash( pOut, outLen );
				V_strncat( pOut, pStartingDir, outLen, COPY_ALL_CHARACTERS );
			}
		}

		// Concatenate the paths.
		V_AppendSlash( pOut, outLen );
		V_strncat( pOut, pPath, outLen, COPY_ALL_CHARACTERS );
	}

	if ( !V_RemoveDotSlashes( pOut ) )
		Error( "V_MakeAbsolutePath: tried to \"..\" past the root." );

	V_FixSlashes( pOut );
}
Ejemplo n.º 9
0
extern "C" CDECL rust_str *
rust_getcwd() {
    rust_task *task = rust_scheduler::get_task();
    LOG(task, task, "rust_getcwd()");

    char cbuf[BUF_BYTES];

#if defined(__WIN32__)
    if (!_getcwd(cbuf, sizeof(cbuf))) {
#else
    if (!getcwd(cbuf, sizeof(cbuf))) {
#endif
        task->fail();
        return NULL;
    }

    return make_str(task->kernel, cbuf, strlen(cbuf), "rust_str(getcwd");
}

// TODO: Allow calling native functions that return double results.
extern "C" CDECL
void squareroot(double *input, double *output) {
    *output = sqrt(*input);
}
Ejemplo n.º 10
0
/*********************************************************************
 *		_getdcwd (MSVCRT.@)
 *
 * Get the current working directory on a given disk.
 * 
 * PARAMS
 *  drive [I] Drive letter to get the current working directory from.
 *  buf   [O] Destination for the current working directory.
 *  size  [I] Length of drive in characters.
 *
 * RETURNS
 *  Success: If drive is NULL, returns an allocated string containing the path.
 *           Otherwise populates drive with the path and returns it.
 *  Failure: NULL. errno indicates the error.
 */
char* CDECL _getdcwd(int drive, char * buf, int size)
{
  static char* dummy;

  TRACE(":drive %d(%c), size %d\n",drive, drive + 'A' - 1, size);

  if (!drive || drive == _getdrive())
    return _getcwd(buf,size); /* current */
  else
  {
    char dir[MAX_PATH];
    char drivespec[4] = {'A', ':', 0};
    int dir_len;

    drivespec[0] += drive - 1;
    if (GetDriveTypeA(drivespec) < DRIVE_REMOVABLE)
    {
      *MSVCRT__errno() = MSVCRT_EACCES;
      return NULL;
    }

    dir_len = GetFullPathNameA(drivespec,MAX_PATH,dir,&dummy);
    if (dir_len >= size || dir_len < 1)
    {
      *MSVCRT__errno() = MSVCRT_ERANGE;
      return NULL; /* buf too small */
    }

    TRACE(":returning '%s'\n", dir);
    if (!buf)
      return _strdup(dir); /* allocate */

    strcpy(buf,dir);
  }
  return buf;
}
Ejemplo n.º 11
0
void get_filepath()
{
#ifdef WIN32
    char* buffer;
    if( (buffer = _getcwd( NULL, 0 )) != NULL ) {
        FILEPATH = std::string(buffer);
        FILEPATH += "/";
    }
    delete[] buffer;
#else
    char *buffer = new char[MAXPATHLEN];
    char* res = getcwd(buffer, MAXPATHLEN);
    UNUSED(res);
    if(buffer != NULL){
        FILEPATH = std::string(buffer);
    }
    FILEPATH += "/";
    delete[] buffer;
#endif

    std::cout << "get_filepath - FILEPATH:" << FILEPATH << std::endl;
    GAMEPATH = FILEPATH;
    FILEPATH += "/data/";
}
Ejemplo n.º 12
0
long DirectoryExist(char * name)
{
	long idx;
	struct _finddata_t fd;

	if ((idx = _findfirst(name, &fd)) == -1)
	{
		_findclose(idx);
		char initial[256];
		_getcwd(initial, 255);

		if (_chdir(name) == 0) // success
		{
			_chdir(initial);
			return 1;
		}

		_chdir(initial);
		return 0;
	}

	_findclose(idx);
	return 1;
}
Ejemplo n.º 13
0
    std::string getCurrentDirectory()
    {
        #if defined(_WIN32) || defined (__MINGW32__)
            char* buffer;
            buffer = _getcwd(NULL, 0);
            /*Check for null buffer, indicating a failure*/
            if (!buffer) {
                throw std::runtime_error(_CWD_MALLOC_EXCEPTION_STRING);
            } else {
                return std::string(buffer);
            }
        #else
            char *currentWorkingDirectory;
            char filePathBuffer[PATH_MAX + 1];

            currentWorkingDirectory = getcwd(filePathBuffer, PATH_MAX + 1 );
            //Check if cwd is null
            if (currentWorkingDirectory) {
                return std::string(currentWorkingDirectory);
            } else {
                throw std::runtime_error(_CWD_MALLOC_EXCEPTION_STRING);
            }
        #endif
    }
Ejemplo n.º 14
0
/*
=================
Sys_GetGameAPI

Loads the game dll
=================
*/
void *Sys_GetGameAPI (void *parms)
{
	void	*(*GetGameAPI) (void *);
	char	name[MAX_OSPATH];
	char	cwd[MAX_OSPATH];
#if defined _M_IX86
	const char *gamename = "jk2gamex86.dll";

#ifdef NDEBUG
	const char *debugdir = "release";
#elif MEM_DEBUG
	const char *debugdir = "shdebug";
#else
	const char *debugdir = "debug";
#endif	//NDEBUG

#elif defined _M_ALPHA
	const char *gamename = "jk2gameaxp.dll";

#ifdef NDEBUG
	const char *debugdir = "releaseaxp";
#else
	const char *debugdir = "debugaxp";
#endif //NDEBUG

#endif //_M__IX86

	if (game_library)
		Com_Error (ERR_FATAL, "Sys_GetGameAPI without Sys_UnloadingGame");

	// check the current debug directory first for development purposes
	_getcwd (cwd, sizeof(cwd));
	Com_sprintf (name, sizeof(name), "%s/%s/%s", cwd, debugdir, gamename);
	game_library = LoadLibrary ( name );
	if (game_library)
	{
		Com_DPrintf ("LoadLibrary (%s)\n", name);
	}
	else
	{
		// check the current directory for other development purposes
		Com_sprintf (name, sizeof(name), "%s/%s", cwd, gamename);
		game_library = LoadLibrary ( name );
		if (game_library)
		{
			Com_DPrintf ("LoadLibrary (%s)\n", name);
		} else {
			char *buf;

			FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &buf, 0, NULL );

			Com_Printf( "LoadLibrary(\"%s\") failed\n", name);
			Com_Printf( "...reason: '%s'\n", buf );
			Com_Error( ERR_FATAL, "Couldn't load game" );
		}
	}

	GetGameAPI = (void *(*)(void *))GetProcAddress (game_library, "GetGameAPI");
	if (!GetGameAPI)
	{
		Sys_UnloadGame ();		
		return NULL;
	}
	return GetGameAPI (parms);
}
Ejemplo n.º 15
0
int
main (int ac, char **av)
{
  char rbuff[TBUF];
  char buff[TBUF];
  char savebuff[TBUF];
  char cmd[TBUF];
  char mffile[TBUF];
  char *arg[4];
  static char execfile[TBUF];

  char kpsedot[TBUF];
  char currdir[TBUF];
  char *tmp;
  int cdrive, tdrive;

  FILE *fr, *fw, *fnul;

  int i, savo, savi;
  char *p, *fp, *fpp;
  int issetdest;
  char fontname[TBUF];

  char texbindir[TBUF];
  char fullbin[TBUF];

  kpse_set_program_name (av[0], NULL);
  progname = kpse_program_name;

/*
 * get tex binary dir
 *
 */
  p = kpse_var_value("SELFAUTOLOC");
  if(p == 0) {
     fprintf(stderr, "I cannot get SELFAUTOLOC\n");
     exit(100);
  }
  strcpy(texbindir, p);
  free(p);
  for(p=texbindir; *p; p++) {
     if(*p == '/') *p = '\\';
  }
  *p = '\\';
  *(p+1) = '\0';

  tmp = getenv ("TEMP");
  if (!tmp)
    tmp = getenv ("TMP");
  if (!tmp)
    tmp = getenv ("TMPDIR");
  if (!tmp) {
    fprintf (stderr, "Please define TEMP | TMP | TMPDIR.\n");
    return (100);
  }

  tmp = xstrdup(tmp);

  for (fpp = tmp; *fpp; fpp++) {
    if (IS_KANJI(fpp))
      fpp++;
    else if (*fpp == '\\')
      *fpp = '/';
  }
/*
issetdest = 0 : TDS
issetdest = 1 : user setting
issetdest = 2 : current directory
*/

  issetdest = 0;

  if (ac < 2) {
    usage ();
    free(tmp);
    return (100);
  }

  if ((!strcmp (av[1], "--version")) || (!strcmp (av[1], "-version"))) {
    version ();
    free(tmp);
    return (100);
  }

  if ((!strcmp (av[1], "--help")) || (!strcmp (av[1], "-help"))) {
    help ();
    free(tmp);
    return (100);
  }

  for (i = 0; i < 4; i++)
    arg[i] = (char *) malloc (TBUF);

  if ((!strcmp (av[1], "--destdir")) || (!strcmp (av[1], "-destdir"))) {
    if (ac != 4) {
      usage ();
      relmem (arg);
      free(tmp);
      return (100);
    }
    issetdest = 1;
    if (strlen(av[2]) > TBUF - 1 || strlen(av[3]) > TBUF - 1) {
      fprintf (stderr, "Too long a string.\n");
      return (100);
    }
    strcpy (buff, av[2]);
    strcpy (fontname, av[3]);
    for (p = buff; *p; p++) {
      if (IS_KANJI(p))
        p++;
      else if (*p == '\\')
        *p = '/';
    }
  } else {
    if (strlen(av[1]) > TBUF - 1) {
      fprintf (stderr, "Too long a string.\n");
      return (100);
    }
    strcpy (fontname, av[1]);
  }


  /* fontname = font name
   */
  if ((p = strrchr (fontname, '.')))
    *p = '\0';

  /* mffile is METAFONT file name
   */
  strcpy (mffile, fontname);
  strcat (mffile, ".mf");

  if (!(fp = kpse_var_value ("MFINPUTS"))) {
    fprintf (stderr, "Cannot get value of MFINPUTS\n");
    relmem (arg);
    free(tmp);
    return (100);
  }

  free (fp);

  xputenv("MKTEXMF", "1");
  if (!(p = kpse_find_file (mffile, kpse_mf_format, 1))) {
    fprintf (stderr, "Cannot find %s.\n", mffile);
    relmem (arg);
    free(tmp);
    return (100);
  }

  fpp = _getcwd (currdir, TBUF);
  if (!fpp) {
    fprintf (stderr, "Failed to get current working directory.\n");
    relmem (arg);
    free(tmp);
    return (100);
  }
  for (fpp = currdir; *fpp; fpp++) {
    if (IS_KANJI(fpp))
      fpp++;
    else if (*fpp == '\\')
      *fpp = '/';
  }

  i = (int)strlen (currdir);
  if (currdir[i - 1] == '/')
    currdir[i - 1] = '\0';
  strcpy (kpsedot, "KPSE_DOT=.;");
  strcat (kpsedot, currdir);
  _putenv (kpsedot);

  if ((p[0] == '.') && (p[1] == '/') && (issetdest != 1)) {
    issetdest = 2;
    strcpy (buff, currdir);
  }

  if (issetdest == 0) {
    /* now path of ${name}.mf is in p */
    strcpy (arg[0], "Dummy");
    strcpy (arg[1], "tfm");
    strcpy (arg[2], p);

    if (!(p = getdestdir (3, arg))) {
      fprintf (stderr, "Cannot get destination directory name.\n");
      relmem (arg);
      free(tmp);
      return (100);
    }
    strcpy (buff, p);
  }

/* Now buff is the destdir */
  p = buff;

  i = (int)strlen (p);

  if (p[i - 1] != '/')
    strcat (p, "/");
  strcat (p, fontname);
  strcat (p, ".tfm");

/* now p (or buff) is the full path name of the tfm font */
/* check if it exists */
  if (_access (p, 0) == 0) {
    fprintf (stderr, "%s exists\n", p);
    printf ("%s\n", p);
    relmem (arg);
    free(tmp);
    return (0);
  }

  cdrive = _getdrive ();
  if (tmp[1] == ':') {
    tdrive = tolower (*tmp) - 'a' + 1;
    _chdrive (tdrive);
  }
  _chdir (tmp);

/* save stdout and stdin */
  savo = _dup (fileno (stdout));
  savi = _dup (fileno (stdin));

/* connect stdout to stderr */
  _dup2 (fileno (stderr), fileno (stdout));

/* connect stdin to nul device */
  if (!(fnul = fopen ("nul", "r"))) {
    fprintf (stderr, "Cannot open nul device to read\n");
    relmem (arg);
    _chdrive (cdrive);
    _chdir (currdir);
    free(tmp);
    return (100);
  }
  _dup2 (fileno (fnul), fileno (stdin));

/* METAFONT command line */
  strcpy (cmd, "--progname=mf --base=mf ");
  strcat (cmd, "\\mode:=ljfour; \\mag:=1; nonstopmode; input ");
  strcat (cmd, fontname);
  strcat (cmd, ";");

  strcpy (execfile, "mf-nowin.exe");
  fprintf (stderr, "%s %s\n", execfile, cmd);
  strcpy(fullbin, texbindir);
  strcat(fullbin, execfile);
  (void) _spawnlp (_P_WAIT, fullbin, execfile, cmd, NULL);

/* return to original stdout and stdin */
  _dup2 (savo, fileno (stdout));
  close (savo);
  _dup2 (savi, fileno (stdin));
  close (savi);

/* close nul device */
  fclose (fnul);

/* check consistency */
  strcpy (cmd, fontname);
  strcat (cmd, ".600gf");

  if (_access (cmd, 0) == -1) {
    fprintf (stderr, "METAFONT failed to make gf font.\n");
    relmem (arg);
    _chdrive (cdrive);
    _chdir (currdir);
    free(tmp);
    return (100);
  }

  remove (cmd);

  strcpy (cmd, fontname);
  strcat (cmd, ".tfm");

/* copy the tfm file */
  if (!(fr = fopen (cmd, "rb"))) {
    fprintf (stderr, "Cannot open %s to read\n", cmd);
    _chdrive (cdrive);
    _chdir (currdir);
    relmem (arg);
    free(tmp);
    return (100);
  }
  if (!(fw = fopen (buff, "wb"))) {
    fprintf (stderr, "Cannot open %s to write\n", buff);
    _chdrive (cdrive);
    _chdir (currdir);
    relmem (arg);
    free(tmp);
    return (100);
  }

  while ((i = (int)fread (rbuff, 1, TBUF, fr)))
    fwrite (rbuff, 1, i, fw);
  fclose (fr);
  fclose (fw);

  strcpy(savebuff, buff);

/* 
  copy log file into the current directory
  in the case that issetdest == 2,
  because feynmf package requires the
  log file.
*/

  if(issetdest == 2) {
    i = (int)strlen(buff);
    if(i > 3) {
      i -= 4;
      buff[i] = '\0';
      strcat(buff, ".log");
      strcpy(cmd, fontname);
      strcat(cmd, ".log");
      if (!(fr = fopen (cmd, "rb"))) {
        fprintf (stderr, "Cannot open %s to read\n", cmd);
        _chdrive (cdrive);
        _chdir (currdir);
        relmem (arg);
        free(tmp);
        return (100);
      }
      if (!(fw = fopen (buff, "wb"))) {
        fprintf (stderr, "Cannot open %s to write\n", buff);
        _chdrive (cdrive);
        _chdir (currdir);
        relmem (arg);
        free(tmp);
        return (100);
      }
      while ((i = (int)fread (rbuff, 1, TBUF, fr)))
        fwrite (rbuff, 1, i, fw);
      fclose (fr);
      fclose (fw);
    }
  }

  relmem (arg);
  if(issetdest != 2)
    mktexupd (savebuff);

/* erase files */
  strcpy (cmd, fontname);
  strcat (cmd, ".log");
  remove (cmd);

  strcpy (cmd, fontname);
  strcat (cmd, ".tfm");
  remove (cmd);

  _chdrive (cdrive);
  _chdir (currdir);

/* send message to Kpathsea */
  printf ("%s\n", savebuff);
  free(tmp);

  return (0);
}
Ejemplo n.º 16
0
/*
==================
WinMain

==================
*/
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	char		cwd[MAX_OSPATH];
//	int			startTime, endTime;

    // should never get a previous instance in Win32
    if ( hPrevInstance ) {
        return 0;
	}

	g_wv.hInstance = hInstance;
	Q_strncpyz( sys_cmdline, lpCmdLine, sizeof( sys_cmdline ) );

	// done before Com/Sys_Init since we need this for error output
	Sys_CreateConsole();

	// no abort/retry/fail errors
	SetErrorMode( SEM_FAILCRITICALERRORS );

	// get the initial time base
	Sys_Milliseconds();

	Sys_InitStreamThread();

	Com_Init( sys_cmdline );

	QuickMemTest();

	_getcwd (cwd, sizeof(cwd));
	Com_Printf("Working directory: %s\n", cwd);

	// hide the early console since we've reached the point where we
	// have a working graphics subsystems
	if ( !com_viewlog->integer ) {
		Sys_ShowConsole( 0, qfalse );
	}

    // main game loop
	while( 1 ) {
		// if not running as a game client, sleep a bit
		if ( g_wv.isMinimized ) {
			Sleep( 5 );
		}

		// set low precision every frame, because some system calls
		// reset it arbitrarily
//		_controlfp( _PC_24, _MCW_PC );

//		startTime = Sys_Milliseconds();

		// make sure mouse and joystick are only called once a frame
		IN_Frame();

		// run the game
		Com_Frame();

//		endTime = Sys_Milliseconds();
//		totalMsec += endTime - startTime;
//		countMsec++;
	}

	// never gets here
}
Ejemplo n.º 17
0
int wizardmain(int argc, char **argv)
{
    const char *outfile = NULL, *relpath = NULL;
    for(int i = 1; i < argc; i++)
    {
        if(argv[i][0] == '-') continue;
        if(!outfile) outfile = argv[i];
        else if(!relpath) relpath = argv[i];
    }
    if(!outfile || !relpath)
    {
        printf("invalid arguments specified!\n");
        printf("usage: ac_server <outfile> <relbinarypath>\n");
        return EXIT_FAILURE;
    }

    printf("The AssaultCube Server Wizard\n\n");
    printf("Before setting up a new server, please ensure you've read the rules at:\n"
           "\thttp://masterserver.cubers.net/rules.html\n\n");
    printf("You will also need to ensure that the UDP port you choose is open.\n"
           "Whatever port you choose, you will need to forward that port, plus one port after that.\n"
           "If you're having issues, use and forward the default ports 28763 and 28764\n"
           "Use http://www.portforward.com for guidance.\n\n");
    printf("Now to specify some optional settings for your server.\n"
           "The default settings will be used if you leave the fields blank.\n"
           "If you're unsure about what to specify for the settings, leave the field blank.\n\n"
           "Read http://assault.cubers.net/docs/commandline.html for a description of these settings.\n\n");

    vector<char> argstr;
    readarg(argstr, "Server description", "-n");
    readarg(argstr, "Message of the day", "-o");
    readarg(argstr, "Maximum clients (No more than 20 allowed!)", "-c");
    readarg(argstr, "Administrator password", "-x");
    readarg(argstr, "Server port", "-f");

    printf("\nPrivate server settings:\n"
           "------------------------\n");
    string ispub = "";
    readarg("Public server (Yes/No)?", ispub, sizeof(ispub));
    if(toupper(ispub[0]) == 'N') addarg(argstr, "-mlocalhost");
    string cmds = "";
    readarg(argstr, "Player password", "-p");

    readarg("\nAdditional server switches", cmds, sizeof(cmds));
    if(cmds[0]) addarg(argstr, cmds);

#ifdef WIN32

    string wsname = "", wsdisplayname = "";
    readarg("win service name", wsname, sizeof(wsname));
    if(wsname[0])
        readarg("win service display", wsdisplayname, sizeof(wsdisplayname));

#endif

    printf("\nWriting your configuration to %s ... ", outfile); fflush(stdout);

    argstr.add('\0');

    FILE *script = fopen(outfile, "w");
    if(!script)
    {
        printf("Failed!\n");
        return EXIT_FAILURE;
    }

#ifdef WIN32
        fprintf(script, "%s%s\npause\n", relpath, argstr.getbuf());
#elif __GNUC__
        fprintf(script, "#!/bin/sh\n%s%s\n", relpath, argstr.getbuf());
#endif
    fclose(script);

    printf("Done\n\n");
    printf("Note: You can start %s directly the next time you want to use the same configuration to start the server.\n\n", outfile);

#ifdef WIN32

    if(wsname[0])
    {
        if(!wsdisplayname[0]) copystring(wsdisplayname, wsname);

        printf("Installing the AC Server as windows service ... "); fflush(stdout);

        vector<char> path;
        databuf<char> cwd = path.reserve(MAX_PATH);
        if(!_getcwd(cwd.buf, MAX_PATH))
        {
            printf("Failed!\n");
            printf("Could not get current working directory: %u\n", (uint)GetLastError());
            return EXIT_FAILURE;
        }
        path.advance(strlen(cwd.buf));
        path.add('\\');
        path.put(relpath, strlen(relpath));
        path.put(" -S", 3);
        path.put(wsname, strlen(wsname));
        path.add(' ');
        path.put(argstr.getbuf(), argstr.length());

        winserviceinstaller installer(wsname, wsdisplayname, path.getbuf());

        int r;
        if(!installer.OpenManger())
        {
            printf("Failed!\n");
            printf("Could not open the Service Control Manager: %u\n", (uint)GetLastError());
            installer.CloseManager();
            return EXIT_FAILURE;
        }

        if((r = installer.IsInstalled()) != 0)
        {
            printf("Failed!\n");
            if(r == -1) printf("Error accessing the Service Control Manager\n");
            else if(r == 1) printf("A windows service with this name (%s) is already installed: %u\n", wsname, (uint)GetLastError());
            return EXIT_FAILURE;
        }

        if((r = installer.Install()) != 1)
        {
            printf("Failed!\n");
            if(r == -1) printf("Error accessing the Service Control Manager\n");
            else if(r == 0) printf("Could not create the new windows service: %u\n", (uint)GetLastError());
            return EXIT_FAILURE;
        }

        printf("Done\n\n");
        printf("Note: You can now manage your AC server using services.msc and sc.exe\n\n");
    }

#endif

    printf("Please press ENTER now to start your server...\n");
    fgetc(stdin);
    printf("Starting the AC server ...\n");
    argstr.insert(0, relpath, strlen(relpath));
    system(argstr.getbuf());

    return EXIT_SUCCESS;
}
Ejemplo n.º 18
0
// Program entry point function.
int APIENTRY wWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow) {
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpCmdLine);

  g_appStartupTime = timeGetTime();

  CefMainArgs main_args(hInstance);
  CefRefPtr<ClientApp> app(new ClientApp);

  // Execute the secondary process, if any.
  int exit_code = CefExecuteProcess(main_args, app.get(), NULL);
  if (exit_code >= 0)
    return exit_code;

  // Retrieve the current working directory.
  if (_getcwd(szWorkingDir, MAX_UNC_PATH) == NULL)
    szWorkingDir[0] = 0;

  // Parse command line arguments. The passed in values are ignored on Windows.
  AppInitCommandLine(0, NULL);

  // Determine if we should use an already running instance of Brackets.
  HANDLE hMutex = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, FIRST_INSTANCE_MUTEX_NAME);
  if ((hMutex != NULL) && AppGetCommandLine()->HasArguments() && (lpCmdLine != NULL)) {
	  // for subsequent instances, re-use an already running instance if we're being called to
	  //   open an existing file on the command-line (eg. Open With.. from Windows Explorer)
	  HWND hFirstInstanceWnd = cef_main_window::FindFirstTopLevelInstance();
	  if (hFirstInstanceWnd != NULL) {
		  ::SetForegroundWindow(hFirstInstanceWnd);
		  if (::IsIconic(hFirstInstanceWnd))
			  ::ShowWindow(hFirstInstanceWnd, SW_RESTORE);
		  
		  // message the other Brackets instance to actually open the given filename
		  std::wstring wstrFilename = lpCmdLine;
		  ConvertToUnixPath(wstrFilename);
		  // note: WM_COPYDATA will manage passing the string across process space
		  COPYDATASTRUCT data;
		  data.dwData = ID_WM_COPYDATA_SENDOPENFILECOMMAND;
		  data.cbData = (wstrFilename.length() + 1) * sizeof(WCHAR);
		  data.lpData = (LPVOID)wstrFilename.c_str();
		  ::SendMessage(hFirstInstanceWnd, WM_COPYDATA, (WPARAM)(HWND)hFirstInstanceWnd, (LPARAM)(LPVOID)&data);

		  // exit this instance
		  return 0;
	  }
	  // otherwise, fall thru and launch a new instance
  }

  if (hMutex == NULL) {
	  // first instance of this app, so create the mutex and continue execution of this instance.
	  hMutex = ::CreateMutex(NULL, FALSE, FIRST_INSTANCE_MUTEX_NAME);
  }

  CefSettings settings;

  // Populate the settings based on command line arguments.
  AppGetSettings(settings, app);

  // Check command
  if (CefString(&settings.cache_path).length() == 0) {
	  CefString(&settings.cache_path) = AppGetCachePath();
  }

  // Initialize CEF.
  CefInitialize(main_args, settings, app.get(), NULL);

  CefRefPtr<CefCommandLine> cmdLine = AppGetCommandLine();
  if (cmdLine->HasSwitch(cefclient::kStartupPath)) {
	  wcscpy(szInitialUrl, cmdLine->GetSwitchValue(cefclient::kStartupPath).c_str());
  }
  else {
	// If the shift key is not pressed, look for the index.html file 
	if (GetAsyncKeyState(VK_SHIFT) == 0) {
	// Get the full pathname for the app. We look for the index.html
	// file relative to this location.
	wchar_t appPath[MAX_UNC_PATH];
	wchar_t *pathRoot;
	GetModuleFileName(NULL, appPath, MAX_UNC_PATH);

	// Strip the .exe filename (and preceding "\") from the appPath
	// and store in pathRoot
	pathRoot = wcsrchr(appPath, '\\');

	// Look for .\dev\src\index.html first
	wcscpy(pathRoot, L"\\dev\\src\\index.html");

	// If the file exists, use it
	if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) {
		wcscpy(szInitialUrl, appPath);
	}

	if (!wcslen(szInitialUrl)) {
		// Look for .\www\index.html next
		wcscpy(pathRoot, L"\\www\\index.html");
		if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) {
		wcscpy(szInitialUrl, appPath);
		}
	}
	}
  }

  if (!wcslen(szInitialUrl)) {
      // If we got here, either the startup file couldn't be found, or the user pressed the
      // shift key while launching. Prompt to select the index.html file.
      OPENFILENAME ofn = {0};
      ofn.lStructSize = sizeof(ofn);
      ofn.lpstrFile = szInitialUrl;
      ofn.nMaxFile = MAX_UNC_PATH;
      ofn.lpstrFilter = L"Web Files\0*.htm;*.html\0\0";
      ofn.lpstrTitle = L"Please select the " APP_NAME L" index.html file.";
      ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER;

      if (!GetOpenFileName(&ofn)) {
        // User cancelled, exit the app
        CefShutdown();
        return 0;
      }
  }

  // Perform application initialization
  if (!InitInstance (hInstance, nCmdShow))
    return FALSE;

  // Start the node server process
  startNodeProcess();

  gFilesToOpen = GetFilenamesFromCommandLine();

  int result = 0;

  if (!settings.multi_threaded_message_loop) {
    // Run the CEF message loop. This function will block until the application
    // recieves a WM_QUIT message.
    CefRunMessageLoop();
  } else {
    MSG msg;

    // Run the application message loop.
    while (GetMessage(&msg, NULL, 0, 0)) {
      if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
    }

    result = static_cast<int>(msg.wParam);
  }

  OnBeforeShutdown();

  // Shut down CEF.
  CefShutdown();

  // release the first instance mutex
  if (hMutex != NULL)
	  ReleaseMutex(hMutex);

  return result;
}
Ejemplo n.º 19
0
gmx_bool get_libdir(char *libdir)
{
#define GMX_BINNAME_MAX 512
    char bin_name[GMX_BINNAME_MAX];
    char buf[GMX_BINNAME_MAX];
    char full_path[GMX_PATH_MAX+GMX_BINNAME_MAX];
    char system_path[GMX_PATH_MAX];
    char *dir,*ptr,*s,*pdum;
    gmx_bool found=FALSE;
    int i;

    if (Program() != NULL)
    {

    /* First - detect binary name */
    if (strlen(Program()) >= GMX_BINNAME_MAX)
    {
        gmx_fatal(FARGS,"The name of the binary is longer than the allowed buffer size (%d):\n'%s'",GMX_BINNAME_MAX,Program());
    }
    strncpy(bin_name,Program(),GMX_BINNAME_MAX-1);

    /* On windows & cygwin we need to add the .exe extension
     * too, or we wont be able to detect that the file exists
     */
#if (defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 || defined __CYGWIN__ || defined __CYGWIN32__)
    if(strlen(bin_name)<3 || gmx_strncasecmp(bin_name+strlen(bin_name)-4,".exe",4))
        strcat(bin_name,".exe");
#endif

    /* Only do the smart search part if we got a real name */
    if (NULL!=bin_name && strncmp(bin_name,"GROMACS",GMX_BINNAME_MAX)) {

        if (!strchr(bin_name,DIR_SEPARATOR)) {
            /* No slash or backslash in name means it must be in the path - search it! */
            /* Add the local dir since it is not in the path on windows */
#if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
            pdum=_getcwd(system_path,sizeof(system_path)-1);
#else
            pdum=getcwd(system_path,sizeof(system_path)-1);
#endif
            sprintf(full_path,"%s%c%s",system_path,DIR_SEPARATOR,bin_name);
            found = gmx_fexist(full_path);
            if (!found && (s=getenv("PATH")) != NULL)
            {
                char *dupped;
                
                dupped=gmx_strdup(s);
                s=dupped;
                while(!found && (dir=gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
                {
                    sprintf(full_path,"%s%c%s",dir,DIR_SEPARATOR,bin_name);
                    found = gmx_fexist(full_path);
                }
                sfree(dupped);
            }
            if (!found)
            {
                return FALSE;
            }
        } else if (!filename_is_absolute(bin_name)) {
            /* name contains directory separators, but 
             * it does not start at the root, i.e.
             * name is relative to the current dir 
             */
#if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
            pdum=_getcwd(buf,sizeof(buf)-1);
#else
            pdum=getcwd(buf,sizeof(buf)-1);
#endif
            sprintf(full_path,"%s%c%s",buf,DIR_SEPARATOR,bin_name);
        } else {
            strncpy(full_path,bin_name,GMX_PATH_MAX);
        }

        /* Now we should have a full path and name in full_path,
         * but on unix it might be a link, or a link to a link to a link..
         */
#if (!defined WIN32 && !defined _WIN32 && !defined WIN64 && !defined _WIN64)
        while( (i=readlink(full_path,buf,sizeof(buf)-1)) > 0 ) {
            buf[i]='\0';
            /* If it doesn't start with "/" it is relative */
            if (buf[0]!=DIR_SEPARATOR) {
                strncpy(strrchr(full_path,DIR_SEPARATOR)+1,buf,GMX_PATH_MAX);
            } else
                strncpy(full_path,buf,GMX_PATH_MAX);
        }
#endif

        /* Remove the executable name - it always contains at least one slash */
        *(strrchr(full_path,DIR_SEPARATOR)+1)='\0';
        /* Now we have the full path to the gromacs executable.
         * Use it to find the library dir. 
         */
        found=FALSE;
        while(!found && ( (ptr=strrchr(full_path,DIR_SEPARATOR)) != NULL ) ) {
            *ptr='\0';
            found=search_subdirs(full_path,libdir);
        }
    }
    }
    /* End of smart searching. If we didn't find it in our parent tree,
     * or if the program name wasn't set, at least try some standard 
     * locations before giving up, in case we are running from e.g. 
     * a users home directory. This only works on unix or cygwin...
     */
#if ((!defined WIN32 && !defined _WIN32 && !defined WIN64 && !defined _WIN64) || defined __CYGWIN__ || defined __CYGWIN32__)
    if(!found) 
        found=search_subdirs("/usr/local",libdir);
    if(!found) 
        found=search_subdirs("/usr",libdir);
    if(!found) 
        found=search_subdirs("/opt",libdir);
#endif
    return found;
}
Ejemplo n.º 20
0
char* getcwd(char* buf, int sz) { return _getcwd(buf, sz); }
Ejemplo n.º 21
0
Archivo: Init.c Proyecto: stransky/tage
//------------------------------------------------------------------------------------------------
// Load items into memory
//------------------------------------------------------------------------------------------------
int lsi_Load_Items(LEVELINFO *p_Level)
{
	char	text[256], dir[256], odir[256];
	int		Count,m;
	struct	_finddata_t Data;
	long	Done,error;
	FILE	*file;
	SECONDDATADESC sec;
	APAK_HANDLE	*aHandle;

	GetPrivateProfileString("game","prvky_dir","c:\\",dir,256,ini_file);

	_getcwd(odir, 255);

	chdir(dir);

	strcpy(text,"*.itm");
	Count = 0;
	
	aHandle = apakopen("items.pak", dir, &error);

	if(!aHandle)
	{
		kprintf(1, "nepodarilo se otevrit archiv items.pak!!!");
		exit(0);
	}
	aHandle->pActualNode = aHandle->pRootNode->pNextNode;


	Done = afindfirst(aHandle, text,&Data);
	error = Done;

	while(error != -1)
	{
		Count++;
		error = afindnext(Done,&Data);
	}

	afindclose(Done);

	p_Level->Count_Of_Objects = Count;

	p_Level->Object = (OBJECTDESC *) malloc(Count * sizeof(OBJECTDESC));
		if (!p_Level->Object)
		{
			//MessageBox(p_Level->hWnd,"Unable to allocate memory for objects","Error",MB_OK);
			kprintf(1,"Unable to allocate memory for objects");
			chdir(odir);
			return 0;
		}


	Done = afindfirst(aHandle, text,&Data);
	error = Done;

	for (m=0;m<Count;m++)
		{
		if (error == -1)
		{
			//MessageBox(p_Level->hWnd,"Count Of Models is not matching","Warning",MB_OK);
			kprintf(1,"Count Of Models is not matching");
		}
		else
			{
				file = 0;
				achdir(aHandle, dir);
				file = aopen(aHandle, Data.name,"rb");
				if (file)
				{
					aread(p_Level->Object+m,sizeof(OBJECTDESC),1,file);
					aseek(file,1000,SEEK_SET);
					aread(&sec,sizeof(SECONDDATADESC),1,file);
					p_Level->Object[m].Out_File = sec;
					aclose(file);
				}
				else
				{
					sprintf(text,"Unable to find file %s",Data.name);
					//MessageBox(p_Level->hWnd,text,"Warning",MB_OK);
					kprintf(1,text);
				}
			}
		error = afindnext(Done,&Data);
		}

	afindclose(Done);

	chdir(odir);

	apakclose(aHandle);
	return 1;
}
Ejemplo n.º 22
0
static int InitExtraFolders(void)
{
	struct stat     stat_buffer;
	struct _finddata_t files;
	int             i, count = 0;
	long            hLong;
	char*           ext;
	char            buf[256];
	char            curdir[MAX_PATH];
	const char*     dir = GetFolderDir();

	memset(ExtraFolderData, 0, MAX_EXTRA_FOLDERS * sizeof(LPEXFOLDERDATA));

	/* NPW 9-Feb-2003 - MSVC stat() doesn't like stat() called with an empty
	 * string
	 */
	if (dir[0] == '\0')
		dir = ".";

	if (stat(dir, &stat_buffer) != 0)
    {
		_mkdir(dir);
    }

	_getcwd(curdir, MAX_PATH);

	_chdir(dir);

	hLong = _findfirst("*", &files);

	for (i = 0; i < MAX_EXTRA_FOLDERS; i++)
    {
		ExtraFolderIcons[i] = NULL;
    }

	numExtraIcons = 0;

	while (!_findnext(hLong, &files))
	{
		if ((files.attrib & _A_SUBDIR) == 0)
		{
			FILE *fp;

			fp = fopen(files.name, "r");
			if (fp != NULL)
			{
				int icon[2] = { 0, 0 };
				char *p, *name;

				while (fgets(buf, 256, fp))
				{
					if (buf[0] == '[')
					{
						p = strchr(buf, ']');
						if (p == NULL)
							continue;

						*p = '\0';
						name = &buf[1];
						if (!strcmp(name, "FOLDER_SETTINGS"))
						{
							while (fgets(buf, 256, fp))
							{
								name = strtok(buf, " =\r\n");
								if (name == NULL)
									break;

								if (!strcmp(name, "RootFolderIcon"))
								{
									name = strtok(NULL, " =\r\n");
									if (name != NULL)
										SetExtraIcons(name, &icon[0]);
								}
								if (!strcmp(name, "SubFolderIcon"))
								{
									name = strtok(NULL, " =\r\n");
									if (name != NULL)
										SetExtraIcons(name, &icon[1]);
								}
							}
							break;
						}
					}
				}
				fclose(fp);

				strcpy(buf, files.name);
				ext = strrchr(buf, '.');

				if (ext && *(ext + 1) && !_stricmp(ext + 1, "ini"))
				{
					ExtraFolderData[count] = malloc(sizeof(EXFOLDERDATA));
					if (ExtraFolderData[count]) 
					{
						*ext = '\0';

						memset(ExtraFolderData[count], 0, sizeof(EXFOLDERDATA));

						strncpy(ExtraFolderData[count]->m_szTitle, buf, 63);
						ExtraFolderData[count]->m_nFolderId   = next_folder_id++;
						ExtraFolderData[count]->m_nParent	  = -1;
						ExtraFolderData[count]->m_dwFlags	  = F_CUSTOM;
						ExtraFolderData[count]->m_nIconId	  = icon[0] ? -icon[0] : IDI_FOLDER;
						ExtraFolderData[count]->m_nSubIconId  = icon[1] ? -icon[1] : IDI_FOLDER;
						//dprintf("extra folder with icon %i, subicon %i",
						//ExtraFolderData[count]->m_nIconId,
						//ExtraFolderData[count]->m_nSubIconId);
						count++;
					}
				}
			}
		}
	}

	_chdir(curdir);
	return count;
}
Ejemplo n.º 23
0
int main(int argc, char **argv) {
		
#if defined(__APPLE__) && defined(__MACH__)
	char path[2049];
	_NSGetExecutablePath(path, 2048);

	String basePath = path;
	vector<String> cpts = basePath.split("/");
	String installPath = "";
	for(int i=0; i < cpts.size() - 2; i++) {
		installPath = installPath + cpts[i];
		installPath += String("/");
	}
#else
	char path[2049];
	TCHAR tpath[2049];
	GetModuleFileName(NULL, (LPWSTR)tpath, 2048);
	wtoc(path, tpath, 2048);
	
	String basePath = path;
	vector<String> cpts = basePath.split("\\");
	String installPath = "";
	for(int i=0; i < cpts.size() - 2; i++) {
		installPath = installPath + cpts[i];
		installPath += String("\\");
	}

#endif

	printf("Polycode build tool v0.1.1\n");

	for(int i=0; i < argc; i++) {
		String argString = String(argv[i]);
		vector<String> bits = argString.split("=");
		if(bits.size() == 2) {
			BuildArg arg;
			arg.name = bits[0];
			arg.value = bits[1];
			args.push_back(arg);
		}
		
	}
	
	if(getArg("--config") == "") {
		printf("\n\nInput config XML missing. Use --config=path to specify.\n\n");
		return 1;
	}

	
	if(getArg("--out") == "") {
		printf("\n\nOutput file not specified. Use --out=outfile.polyapp to specify.\n\n");
		return 1;		
	}

	char dirPath[4099];
#if defined(__APPLE__) && defined(__MACH__)
	_getcwd(dirPath, sizeof(dirPath));
#else	
	TCHAR tdirpath[4099];
	GetCurrentDirectory(4098, (LPWSTR)tdirpath);
	wtoc(dirPath, tdirpath, 4098);

#endif
	String currentPath = String(dirPath);

	String configPath = getArg("--config");

	String finalPath = configPath;
	if(configPath[0] != '/') {

#ifdef _WINDOWS
		finalPath = currentPath+"\\"+configPath;
#else
		finalPath = currentPath+"/"+configPath;
#endif
	}

	finalPath = finalPath.replace(":", "");
	finalPath = finalPath.replace("\\", "/");
	finalPath = finalPath.substr(1, finalPath.length() - 1);

	printf("Reading config file from %s\n", finalPath.c_str());

	Object configFile;
	if(!configFile.loadFromXML(finalPath)) {
		printf("Specified config file doesn't exist!\n");
		return 1;
	}
	printf("OK!\n");
	// start required params

	String entryPoint;
	int defaultWidth;
	int defaultHeight;
	int frameRate = 60;
	int antiAliasingLevel = 0;
	bool fullScreen = false;
	float backgroundColorR = 0.2;
	float backgroundColorG = 0.2;
	float backgroundColorB = 0.2;

	if(configFile.root["entryPoint"]) {
		printf("Entry point: %s\n", configFile.root["entryPoint"]->stringVal.c_str());
		entryPoint = configFile.root["entryPoint"]->stringVal;
	} else {
		printf("Required parameter: \"entryPoint\" is missing from config file!\n");
		return 1;		
	}

	if(configFile.root["defaultWidth"]) {
		printf("Width: %d\n", configFile.root["defaultWidth"]->intVal);
		defaultWidth = configFile.root["defaultWidth"]->intVal;
	} else {
		printf("Required parameter: \"defaultWidth\" is missing from config file!\n");
		return 1;		
	}

	if(configFile.root["defaultHeight"]) {
		printf("Height: %d\n", configFile.root["defaultHeight"]->intVal);
		defaultHeight = configFile.root["defaultHeight"]->intVal;
	} else {
		printf("Required parameter: \"defaultHeight\" is missing from config file!\n");
		return 1;		
	}

	// start optional params

	if(configFile.root["frameRate"]) {
		printf("Frame rate: %d\n", configFile.root["frameRate"]->intVal);
		frameRate = configFile.root["frameRate"]->intVal;
	}

	if(configFile.root["antiAliasingLevel"]) {
		printf("Anti-aliasing level: %d\n", configFile.root["antiAliasingLevel"]->intVal);
		antiAliasingLevel = configFile.root["antiAliasingLevel"]->intVal;
	}

	if(configFile.root["fullScreen"]) {
		fullScreen = configFile.root["fullScreen"]->boolVal;
		if(fullScreen) {
			printf("Full-screen: true\n");
		} else {
			printf("Full-screen: false\n");
		}
	}

	if(configFile.root["backgroundColor"]) {
		ObjectEntry *color = configFile.root["backgroundColor"];
		if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
			backgroundColorR = (*color)["red"]->NumberVal;
			backgroundColorG = (*color)["green"]->NumberVal;
			backgroundColorB = (*color)["blue"]->NumberVal;
			printf("Background color: %f %f %f\n", backgroundColorR, backgroundColorG, backgroundColorB);

		} else {
			printf("backgroundColor node specified, but missing all three color attributes (red,green,blue). Ignoring.\n");
		}
	}

	zipFile z = zipOpen(getArg("--out").c_str(), 0);
	

	Object runInfo;
	runInfo.root.name = "PolycodeApp";
	runInfo.root.addChild("entryPoint", entryPoint);
	runInfo.root.addChild("defaultHeight", defaultHeight);
	runInfo.root.addChild("defaultWidth", defaultWidth);
	runInfo.root.addChild("frameRate", frameRate);
	runInfo.root.addChild("antiAliasingLevel", antiAliasingLevel);
	runInfo.root.addChild("fullScreen", fullScreen);
	
	ObjectEntry *color = runInfo.root.addChild("backgroundColor");
	color->addChild("red", backgroundColorR);
	color->addChild("green", backgroundColorG);
	color->addChild("blue", backgroundColorB);

	addFileToZip(z, entryPoint, entryPoint, false);

	if(configFile.root["modules"]) {
#ifdef _WINDOWS
		String modulesPath = installPath + "Modules\\";
#else
		String modulesPath = installPath + "Modules/";
#endif

		ObjectEntry *modules = configFile.root["modules"];
		if(modules) {		
			for(int i=0; i < modules->length; i++) {
				printf("Adding module: %s\n", (*modules)[i]->stringVal.c_str());
				String modulePath = modulesPath + (*modules)[i]->stringVal;
#ifdef _WINDOWS
				String moduleAPIPath = modulePath + "\\API";
				String moduleLibPath = modulePath + "\\Lib";
				moduleAPIPath = moduleAPIPath.replace("\\", "/");
				moduleAPIPath = moduleAPIPath.substr(2, moduleAPIPath.length() - 2);	
				moduleLibPath = moduleLibPath.replace("\\", "/");
				moduleLibPath = moduleLibPath.substr(2, moduleLibPath.length() - 2);	

#else
				String moduleAPIPath = modulePath + "/API";
				String moduleLibPath = modulePath + "/Lib";
#endif
				printf("Path:%s\n", moduleAPIPath.c_str());		


				addFolderToZip(z, moduleAPIPath, "", false);
				addFolderToZip(z, moduleLibPath, "__lib", false);

				//String module = configFile.root["entryPoint"]->stringVal;
			}
			runInfo.root.addChild(configFile.root["modules"]);
		}
	}

	if(configFile.root["packedItems"]) {
		ObjectEntry *packed = configFile.root["packedItems"];
		if(packed) {
			for(int i=0; i < packed->length; i++) {
				ObjectEntry *entryPath = (*(*packed)[i])["path"];
				ObjectEntry *entryType = (*(*packed)[i])["type"];
				if(entryPath && entryType) {
					if(entryType->stringVal == "folder") {
						addFolderToZip(z, entryPath->stringVal, entryPath->stringVal, false);
					} else {
						addFileToZip(z, entryPath->stringVal, entryPath->stringVal, false);
					}
				}
			}
			runInfo.root.addChild(configFile.root["packedItems"]);
		}
	}


	runInfo.saveToXML("runinfo_tmp_zzzz.polyrun");
	addFileToZip(z, "runinfo_tmp_zzzz.polyrun", "runinfo.polyrun", true);

	//addFolderToZip(z, getArg("--project"), "");
	
	zipClose(z, "");	

	OSBasics::removeItem("runinfo_tmp_zzzz.polyrun");

	return 0;
}
Ejemplo n.º 24
0
   int main( int numLineParms , char** vtLineParms )
   {

      bool DoPassageCount      = false ;

      TAL_tpExec ErrorLevel    = TAL_ExecOK ;

      // Display test logo

         printf( "\n\nLES - Laboratorio de Engenharia de Software" ) ;
         printf( "\n   Talisman unit test, version %s, build %s (c) 2007\n" ,
                 TAL_ProductVersion , TAL_SoftwareVersion ) ;

      // Get command line parameters

         memset( BaseFolderName      , 0 , TAL_dimFileName + 1 ) ;
         memset( ScriptFileName      , 0 , TAL_dimFileName + 1 ) ;
         memset( EventLogFileName    , 0 , TAL_dimFileName + 1 ) ;
         memset( AccumulatorFileName , 0 , TAL_dimFileName + 1 ) ;

         // Retrieve all parameters

            for( int i = 1 ; i < numLineParms ; i ++ ) {

            // Handle syntactically correct parameter

               if ( ( vtLineParms[ i ][ 0 ] == '/' )
                 || ( vtLineParms[ i ][ 0 ] == '-' ))
               {

                  switch ( vtLineParms[ i ][ 1 ] ) {

                  // Handle script file parameter

                     case 's' :
                     case 'S' :
                     {

                        if ( ScriptFileName[ 0 ] == 0 )
                        {
                           if ( strlen( vtLineParms[ i ] ) < TAL_dimFileName )
                           {
                              strcpy( ScriptFileName , vtLineParms[ i ] + sizParmPrefix ) ;

                           } else
                           {
                              printf( "\n%s Test script file name is too long." ,
                                      TST_MsgPrefixError ) ;
                              strcpy( ScriptFileName , NameError ) ;
                              ErrorLevel = TAL_ExecDisaster ;
                           } /* if */

                        } else
                        {
                           printf( "\n%s Test script file name is already defined" ,
                                   TST_MsgPrefixError ) ;
                           ErrorLevel = TAL_ExecDisaster ;
                        } /* if */

                        break ;

                     } // end selection: Handle script file parameter

                  // Handle base folder parameter

                     case 'f' :
                     case 'F' :
                     {

                        if ( BaseFolderName[ 0 ] == 0 )
                        {
                           if ( strlen( vtLineParms[ i ] ) < TAL_dimFileName )
                           {
                              strcpy( BaseFolderName , vtLineParms[ i ] + sizParmPrefix ) ;

                           } else
                           {
                              printf( "\n%s Base folder name is too long." ,
                                      TST_MsgPrefixError ) ;
                              strcpy( BaseFolderName , NameError ) ;
                              ErrorLevel = TAL_ExecDisaster ;
                           } /* if */

                        } else
                        {
                           printf( "\n%s Base folder name is already defined." ,
                                   TST_MsgPrefixError ) ;
                           ErrorLevel = TAL_ExecDisaster ;
                        } /* if */

                        break ;

                     } // end selection: Handle base folder parameter

                  // Handle event log file parameter

                     case 'l' :
                     case 'L' :
                     {

                        if ( EventLogFileName[ 0 ] == 0 )
                        {
                           if ( strlen( vtLineParms[ i ] ) < TAL_dimFileName )
                           {
                              strcpy( EventLogFileName , vtLineParms[ i ] + sizParmPrefix ) ;

                           } else
                           {
                              printf( "\n%s Event log file name is too long." ,
                                      TST_MsgPrefixError ) ;
                              strcpy( ScriptFileName , NameError ) ;
                              ErrorLevel = TAL_ExecDisaster ;
                           } /* if */

                        } else
                        {
                           printf( "\n%s Event log file name is already defined." ,
                                   TST_MsgPrefixError ) ;
                           ErrorLevel = TAL_ExecDisaster ;
                        } /* if */

                        break ;

                     } // end selection: Handle event log file parameter

                  // Handle accumulator file parameter

                     case 'a' :
                     case 'A' :
                     {

                        if ( AccumulatorFileName[ 0 ] == 0 )
                        {
                           if ( strlen( vtLineParms[ i ] ) < TAL_dimFileName )
                           {
                              strcpy( AccumulatorFileName , vtLineParms[ i ] + sizParmPrefix ) ;
                           } else
                           {
                              printf( "\n%s Accumulator file name is too long." ,
                                      TST_MsgPrefixError ) ;
                              strcpy( ScriptFileName , NameError ) ;
                              ErrorLevel = TAL_ExecDisaster ;
                           } /* if */
                        } else
                        {
                           printf( "\n%s Accumulator file name is already defined." ,
                                   TST_MsgPrefixError ) ;
                           ErrorLevel = TAL_ExecDisaster ;
                        } /* if */

                        break ;

                     } // end selection: Handle accumulator file parameter

                  // Handle passage counting parameter

                     case 'c' :
                     case 'C' :
                     {

                        if ( DoPassageCount == false )
                        {
                           DoPassageCount = true ;
                        } else
                        {
                           printf( "\n%s Passage count already set." ,
                                   TST_MsgPrefixError ) ;
                           ErrorLevel = TAL_ExecDisaster ;
                        } /* if */

                        break ;

                     } // end selection: Handle passage counting parameter

                  // Handle help parameter

                     case '?' :
                     case 'h' :
                     case 'H' :
                     {

                        ErrorLevel = TAL_ExecHelp ;

                        break ;

                     } // end selection: Handle help parameter

                  // Handle unknown parameter

                     default :
                     {

                        printf( "\n%s Unknown parameter: >%s<." , vtLineParms[ i ] ,
                                TST_MsgPrefixError ) ;
                        ErrorLevel = TAL_ExecDisaster ;

                        break ;

                     } // end selection: Handle unknown parameter

                  } // end selection: Handle syntactically correct parameter

               } // end selection: Handle syntactically correct parameter

            // Handle syntactically incorrect parameter

               else
               {

                  printf( "\n%s Illegal parameter: %s" , TST_MsgPrefixError , vtLineParms[ i ] ) ;
                  ErrorLevel = TAL_ExecDisaster ;

               } // end selection: Handle syntactically incorrect parameter

            } // end repetition: Retrieve all parameters

         // Verify correctness of command line parameters

            if ( ScriptFileName[ 0 ] == 0 )
            {
               printf( "\n>>> Missing test script file name." ) ;
               ErrorLevel = TAL_ExecDisaster ;
            } /* if */

         // Handle command line parameter errors

            if ( ErrorLevel != TAL_ExecOK )
            {

               printf( "\n\n   Usage:  %s -f<base folder> -s<script file>" ,
                       vtLineParms[ 0 ] ) ;
               printf(   "\n                     -l<test log file> -a<accumulator file> -c" ) ;
               printf( "\n\n      <script file>      - name of a file containing the" ) ;
               printf(   "\n                           test script file to be used." ) ;
               printf(   "\n      <base folder>      - optional, defines the folder relative to which" ) ;
               printf(   "\n                           all files will be accessed." ) ;
               printf(   "\n      <event log file>   - optional, name of the test log file to be used." ) ;
               printf(   "\n                           If not given test logs are sent to stdout" ) ;
               printf(   "\n      <accumulator file> - optional file of the accumulated statistics" ) ;
               printf(   "\n                           relative to several executions." ) ;
               printf(   "\n      c                  - optional, activates passage counting." ) ;
               printf(   "\n-? or -h or -help        - display this help. Excecution will be cancelled." ) ;

               printf( "\n" ) ;
               printf( "\nParameters may appear in any order." ) ;
               printf( "\n" ) ;

               return ErrorLevel ;

            } // end selection: Handle command line parameter errors

      // Display test parameters

         if ( BaseFolderName[ 0 ] != 0 )
         {
            printf( "\n%s Base folder name: %s" , TST_MsgPrefixInfo , BaseFolderName ) ;
         } else
         {
            char Buffer[ TAL_dimFileName + 1 ] ;
            printf( "\n%s Base folder is: %s" , TST_MsgPrefixInfo ,
                    _getcwd( Buffer , TAL_dimFileName )) ;
         } /* if */

         printf( "\n%s Script file name: %s" , TST_MsgPrefixInfo , ScriptFileName ) ;

         if ( EventLogFileName[ 0 ] != 0 )
         {
            printf( "\n%s Event log file name: %s" , TST_MsgPrefixInfo , EventLogFileName ) ;
         } else
         {
            printf( "\n%s Event log to be directed to console." , TST_MsgPrefixInfo ) ;
         } /* if */

         if ( AccumulatorFileName[ 0 ] != 0 )
         {
            printf( "\n%s Accum  file name: %s" , TST_MsgPrefixInfo , AccumulatorFileName ) ;
         } else
         {
            printf( "\n%s Statistics will not be accumulated." , TST_MsgPrefixInfo ) ;
         } /* if */

         if ( DoPassageCount )
         {
            printf( "\n%s Count passage." , TST_MsgPrefixInfo ) ;
         } else
         {
            printf( "\n%s Do not count passages." , TST_MsgPrefixInfo ) ;
         } /* if */
         printf( "\n%s" SeparationLine "\n" , TST_MsgPrefixInfo ) ;

      // Perform the test of the chosen set

         int numFailures = 0 ;

         TST_TestGeneric * pTester = new TST_TestSpecific( ) ;

         try
         {
            numFailures = pTester->ControlTest(
                      BaseFolderName   , ScriptFileName ,
                      EventLogFileName , AccumulatorFileName , DoPassageCount  ) ;
         } // end try
         catch( ... )
         {
            numFailures ++ ;
            printf( "\n\n%s ==================================================\n" ,
                      TST_MsgPrefixError ) ;
            printf( "\n%s %-5d Generic tester returned with exception" ,
                      TST_MsgPrefixError , numFailures ) ;
         } // end try catch

         try
         {
            delete pTester ;
         } // end try
         catch( ... )
         {
            numFailures ++ ;
            printf( "\n\n%s ==================================================\n" ,
                      TST_MsgPrefixError ) ;
            printf( "\n%s %-5d Delete generic test object throwed an exception" ,
                      TST_MsgPrefixError , numFailures ) ;
         } // end try catch

      // Verify global memory leaks
      // AE: All data spaces should have been deallocated

         int SpaceCount = DSP_GetSpaceCount( ) ;

         if ( SpaceCount != 0 )
         {
            numFailures += SpaceCount ;

            printf( "\n\n%s %d Allocated data spaces remain: %d, verify memory leakage.\n" ,
                    TST_MsgPrefixError , numFailures , SpaceCount ) ;

            DSP_SetTerse( true ) ;
            DSP_ListAllDataSpaces( ) ;

         } /* if */

      // Display overall test result

         if ( numFailures > 0 )
         {
            ErrorLevel = TAL_ExecFailure ;
         } /* if */

         printf( "\n\n%s" SeparationLine , TST_MsgPrefixInfo ) ;

         if ( ErrorLevel == TAL_ExecOK )
         {
            printf( "\n\n%s TEST OK." , TST_MsgPrefixInfo ) ;

         } else if ( ErrorLevel == TAL_ExecCancel )
         {
            printf( "\n\n%s TEST was cancelled by the user." , TST_MsgPrefixInfo ) ;

         } else if ( ( numFailures > 0 )
                  || ( ErrorLevel == TAL_ExecCancel ))
         {
            printf( "\n\n%s TEST found %ld problems." , TST_MsgPrefixError ,
                    numFailures ) ;
         } else
         {
            printf( "\n\n%s TEST ended incorrectly." , TST_MsgPrefixInfo ) ;
         } /* if */

         printf( "\n\n%s" SeparationLine "\n\n" , TST_MsgPrefixInfo ) ;

         return ErrorLevel ;

   } // End of function: MAIN &Main test program
Ejemplo n.º 25
0
fs_navig_point *fsWrapGetCWD(void) {
  STR tmpcwd[FS_WRAP_MAX_PATH_LENGTH];

  _getcwd(tmpcwd, FS_WRAP_MAX_PATH_LENGTH);
  return fsWrapMakePoint(tmpcwd);
}
Ejemplo n.º 26
0
int gmx_covar(int argc,char *argv[])
{
  const char *desc[] = {
    "[TT]g_covar[tt] calculates and diagonalizes the (mass-weighted)",
    "covariance matrix.",
    "All structures are fitted to the structure in the structure file.",
    "When this is not a run input file periodicity will not be taken into",
    "account. When the fit and analysis groups are identical and the analysis",
    "is non mass-weighted, the fit will also be non mass-weighted.",
    "[PAR]",
    "The eigenvectors are written to a trajectory file ([TT]-v[tt]).",
    "When the same atoms are used for the fit and the covariance analysis,",
    "the reference structure for the fit is written first with t=-1.",
    "The average (or reference when [TT]-ref[tt] is used) structure is",
    "written with t=0, the eigenvectors",
    "are written as frames with the eigenvector number as timestamp.",
    "[PAR]",
    "The eigenvectors can be analyzed with [TT]g_anaeig[tt].",
    "[PAR]",
    "Option [TT]-ascii[tt] writes the whole covariance matrix to",
    "an ASCII file. The order of the elements is: x1x1, x1y1, x1z1, x1x2, ...",
    "[PAR]",
    "Option [TT]-xpm[tt] writes the whole covariance matrix to an [TT].xpm[tt] file.",
    "[PAR]",
    "Option [TT]-xpma[tt] writes the atomic covariance matrix to an [TT].xpm[tt] file,",
    "i.e. for each atom pair the sum of the xx, yy and zz covariances is",
    "written.",
    "[PAR]",
    "Note that the diagonalization of a matrix requires memory and time",
    "that will increase at least as fast as than the square of the number",
    "of atoms involved. It is easy to run out of memory, in which",
    "case this tool will probably exit with a 'Segmentation fault'. You",
    "should consider carefully whether a reduced set of atoms will meet",
    "your needs for lower costs."
  };
  static gmx_bool bFit=TRUE,bRef=FALSE,bM=FALSE,bPBC=TRUE;
  static int  end=-1;
  t_pargs pa[] = {
    { "-fit",  FALSE, etBOOL, {&bFit},
      "Fit to a reference structure"},
    { "-ref",  FALSE, etBOOL, {&bRef},
      "Use the deviation from the conformation in the structure file instead of from the average" },
    { "-mwa",  FALSE, etBOOL, {&bM},
      "Mass-weighted covariance analysis"},
    { "-last",  FALSE, etINT, {&end}, 
      "Last eigenvector to write away (-1 is till the last)" },
    { "-pbc",  FALSE,  etBOOL, {&bPBC},
      "Apply corrections for periodic boundary conditions" }
  };
  FILE       *out;
  t_trxstatus *status;
  t_trxstatus *trjout;
  t_topology top;
  int        ePBC;
  t_atoms    *atoms;  
  rvec       *x,*xread,*xref,*xav,*xproj;
  matrix     box,zerobox;
  real       *sqrtm,*mat,*eigval,sum,trace,inv_nframes;
  real       t,tstart,tend,**mat2;
  real       xj,*w_rls=NULL;
  real       min,max,*axis;
  int        ntopatoms,step;
  int        natoms,nat,count,nframes0,nframes,nlevels;
  gmx_large_int_t ndim,i,j,k,l;
  int        WriteXref;
  const char *fitfile,*trxfile,*ndxfile;
  const char *eigvalfile,*eigvecfile,*averfile,*logfile;
  const char *asciifile,*xpmfile,*xpmafile;
  char       str[STRLEN],*fitname,*ananame,*pcwd;
  int        d,dj,nfit;
  atom_id    *index,*ifit;
  gmx_bool       bDiffMass1,bDiffMass2;
  time_t     now;
  char       timebuf[STRLEN];
  t_rgb      rlo,rmi,rhi;
  real       *tmp;
  output_env_t oenv;
  gmx_rmpbc_t  gpbc=NULL;

  t_filenm fnm[] = { 
    { efTRX, "-f",  NULL, ffREAD }, 
    { efTPS, NULL,  NULL, ffREAD },
    { efNDX, NULL,  NULL, ffOPTRD },
    { efXVG, NULL,  "eigenval", ffWRITE },
    { efTRN, "-v",  "eigenvec", ffWRITE },
    { efSTO, "-av", "average.pdb", ffWRITE },
    { efLOG, NULL,  "covar", ffWRITE },
    { efDAT, "-ascii","covar", ffOPTWR },
    { efXPM, "-xpm","covar", ffOPTWR },
    { efXPM, "-xpma","covara", ffOPTWR }
  }; 
#define NFILE asize(fnm) 

  CopyRight(stderr,argv[0]); 
  parse_common_args(&argc,argv,PCA_CAN_TIME | PCA_TIME_UNIT | PCA_BE_NICE,
		    NFILE,fnm,asize(pa),pa,asize(desc),desc,0,NULL,&oenv); 

  clear_mat(zerobox);

  fitfile    = ftp2fn(efTPS,NFILE,fnm);
  trxfile    = ftp2fn(efTRX,NFILE,fnm);
  ndxfile    = ftp2fn_null(efNDX,NFILE,fnm);
  eigvalfile = ftp2fn(efXVG,NFILE,fnm);
  eigvecfile = ftp2fn(efTRN,NFILE,fnm);
  averfile   = ftp2fn(efSTO,NFILE,fnm);
  logfile    = ftp2fn(efLOG,NFILE,fnm);
  asciifile  = opt2fn_null("-ascii",NFILE,fnm);
  xpmfile    = opt2fn_null("-xpm",NFILE,fnm);
  xpmafile   = opt2fn_null("-xpma",NFILE,fnm);

  read_tps_conf(fitfile,str,&top,&ePBC,&xref,NULL,box,TRUE);
  atoms=&top.atoms;

  if (bFit) {
    printf("\nChoose a group for the least squares fit\n"); 
    get_index(atoms,ndxfile,1,&nfit,&ifit,&fitname);
    if (nfit < 3) 
      gmx_fatal(FARGS,"Need >= 3 points to fit!\n");
  } else
    nfit=0;
  printf("\nChoose a group for the covariance analysis\n"); 
  get_index(atoms,ndxfile,1,&natoms,&index,&ananame);

  bDiffMass1=FALSE;
  if (bFit) {
    snew(w_rls,atoms->nr);
    for(i=0; (i<nfit); i++) {
      w_rls[ifit[i]]=atoms->atom[ifit[i]].m;
      if (i)
        bDiffMass1 = bDiffMass1 || (w_rls[ifit[i]]!=w_rls[ifit[i-1]]);
    }
  }
  bDiffMass2=FALSE;
  snew(sqrtm,natoms);
  for(i=0; (i<natoms); i++)
    if (bM) {
      sqrtm[i]=sqrt(atoms->atom[index[i]].m);
      if (i)
	bDiffMass2 = bDiffMass2 || (sqrtm[i]!=sqrtm[i-1]);
    }
    else
      sqrtm[i]=1.0;
  
  if (bFit && bDiffMass1 && !bDiffMass2) {
    bDiffMass1 = natoms != nfit;
    i=0;
    for (i=0; (i<natoms) && !bDiffMass1; i++)
      bDiffMass1 = index[i] != ifit[i];
    if (!bDiffMass1) {
      fprintf(stderr,"\n"
	      "Note: the fit and analysis group are identical,\n"
	      "      while the fit is mass weighted and the analysis is not.\n"
	      "      Making the fit non mass weighted.\n\n");
      for(i=0; (i<nfit); i++)
	w_rls[ifit[i]]=1.0;
    }
  }
  
  /* Prepare reference frame */
  if (bPBC) {
    gpbc = gmx_rmpbc_init(&top.idef,ePBC,atoms->nr,box);
    gmx_rmpbc(gpbc,atoms->nr,box,xref);
  }
  if (bFit)
    reset_x(nfit,ifit,atoms->nr,NULL,xref,w_rls);

  snew(x,natoms);
  snew(xav,natoms);
  ndim=natoms*DIM;
  if (sqrt(GMX_LARGE_INT_MAX)<ndim) {
    gmx_fatal(FARGS,"Number of degrees of freedoms to large for matrix.\n");
  }
  snew(mat,ndim*ndim);

  fprintf(stderr,"Calculating the average structure ...\n");
  nframes0 = 0;
  nat=read_first_x(oenv,&status,trxfile,&t,&xread,box);
  if (nat != atoms->nr)
    fprintf(stderr,"\nWARNING: number of atoms in tpx (%d) and trajectory (%d) do not match\n",natoms,nat);
  do {
    nframes0++;
    /* calculate x: a fitted struture of the selected atoms */
    if (bPBC)
      gmx_rmpbc(gpbc,nat,box,xread);
    if (bFit) {
      reset_x(nfit,ifit,nat,NULL,xread,w_rls);
      do_fit(nat,w_rls,xref,xread);
    }
    for (i=0; i<natoms; i++)
      rvec_inc(xav[i],xread[index[i]]);
  } while (read_next_x(oenv,status,&t,nat,xread,box));
  close_trj(status);
  
  inv_nframes = 1.0/nframes0;
  for(i=0; i<natoms; i++)
    for(d=0; d<DIM; d++) {
      xav[i][d] *= inv_nframes;
      xread[index[i]][d] = xav[i][d];
    }
  write_sto_conf_indexed(opt2fn("-av",NFILE,fnm),"Average structure",
			 atoms,xread,NULL,epbcNONE,zerobox,natoms,index);
  sfree(xread);

  fprintf(stderr,"Constructing covariance matrix (%dx%d) ...\n",(int)ndim,(int)ndim);
  nframes=0;
  nat=read_first_x(oenv,&status,trxfile,&t,&xread,box);
  tstart = t;
  do {
    nframes++;
    tend = t;
    /* calculate x: a (fitted) structure of the selected atoms */
    if (bPBC)
      gmx_rmpbc(gpbc,nat,box,xread);
    if (bFit) {
      reset_x(nfit,ifit,nat,NULL,xread,w_rls);
      do_fit(nat,w_rls,xref,xread);
    }
    if (bRef)
      for (i=0; i<natoms; i++)
	rvec_sub(xread[index[i]],xref[index[i]],x[i]);
    else
      for (i=0; i<natoms; i++)
	rvec_sub(xread[index[i]],xav[i],x[i]);
    
    for (j=0; j<natoms; j++) {
      for (dj=0; dj<DIM; dj++) {
	k=ndim*(DIM*j+dj);
	xj=x[j][dj];
	for (i=j; i<natoms; i++) {
	  l=k+DIM*i;
	  for(d=0; d<DIM; d++)
	    mat[l+d] += x[i][d]*xj;
	}
      }
    }
  } while (read_next_x(oenv,status,&t,nat,xread,box) && 
	   (bRef || nframes < nframes0));
  close_trj(status);
  gmx_rmpbc_done(gpbc);

  fprintf(stderr,"Read %d frames\n",nframes);
  
  if (bRef) {
    /* copy the reference structure to the ouput array x */
    snew(xproj,natoms);
    for (i=0; i<natoms; i++)
      copy_rvec(xref[index[i]],xproj[i]);
  } else {
    xproj = xav;
  }

  /* correct the covariance matrix for the mass */
  inv_nframes = 1.0/nframes;
  for (j=0; j<natoms; j++) 
    for (dj=0; dj<DIM; dj++) 
      for (i=j; i<natoms; i++) { 
	k = ndim*(DIM*j+dj)+DIM*i;
	for (d=0; d<DIM; d++)
	  mat[k+d] = mat[k+d]*inv_nframes*sqrtm[i]*sqrtm[j];
      }

  /* symmetrize the matrix */
  for (j=0; j<ndim; j++) 
    for (i=j; i<ndim; i++)
      mat[ndim*i+j]=mat[ndim*j+i];
  
  trace=0;
  for(i=0; i<ndim; i++)
    trace+=mat[i*ndim+i];
  fprintf(stderr,"\nTrace of the covariance matrix: %g (%snm^2)\n",
	  trace,bM ? "u " : "");
  
  if (asciifile) {
    out = ffopen(asciifile,"w");
    for (j=0; j<ndim; j++) {
      for (i=0; i<ndim; i+=3)
	fprintf(out,"%g %g %g\n",
		mat[ndim*j+i],mat[ndim*j+i+1],mat[ndim*j+i+2]);
    }
    ffclose(out);
  }
  
  if (xpmfile) {
    min = 0;
    max = 0;
    snew(mat2,ndim);
    for (j=0; j<ndim; j++) {
      mat2[j] = &(mat[ndim*j]);
      for (i=0; i<=j; i++) {
	if (mat2[j][i] < min)
	  min = mat2[j][i];
	if (mat2[j][j] > max)
	  max = mat2[j][i];
      }
    }
    snew(axis,ndim);
    for(i=0; i<ndim; i++)
      axis[i] = i+1;
    rlo.r = 0; rlo.g = 0; rlo.b = 1;
    rmi.r = 1; rmi.g = 1; rmi.b = 1;
    rhi.r = 1; rhi.g = 0; rhi.b = 0;
    out = ffopen(xpmfile,"w");
    nlevels = 80;
    write_xpm3(out,0,"Covariance",bM ? "u nm^2" : "nm^2",
	       "dim","dim",ndim,ndim,axis,axis,
	       mat2,min,0.0,max,rlo,rmi,rhi,&nlevels);
    ffclose(out);
    sfree(axis);
    sfree(mat2);
  }

  if (xpmafile) {
    min = 0;
    max = 0;
    snew(mat2,ndim/DIM);
    for (i=0; i<ndim/DIM; i++)
      snew(mat2[i],ndim/DIM);
    for (j=0; j<ndim/DIM; j++) {
      for (i=0; i<=j; i++) {
	mat2[j][i] = 0;
	for(d=0; d<DIM; d++)
	  mat2[j][i] += mat[ndim*(DIM*j+d)+DIM*i+d];
	if (mat2[j][i] < min)
	  min = mat2[j][i];
	if (mat2[j][j] > max)
	  max = mat2[j][i];
	mat2[i][j] = mat2[j][i];
      }
    }
    snew(axis,ndim/DIM);
    for(i=0; i<ndim/DIM; i++)
      axis[i] = i+1;
    rlo.r = 0; rlo.g = 0; rlo.b = 1;
    rmi.r = 1; rmi.g = 1; rmi.b = 1;
    rhi.r = 1; rhi.g = 0; rhi.b = 0;
    out = ffopen(xpmafile,"w");
    nlevels = 80;
    write_xpm3(out,0,"Covariance",bM ? "u nm^2" : "nm^2",
	       "atom","atom",ndim/DIM,ndim/DIM,axis,axis,
	       mat2,min,0.0,max,rlo,rmi,rhi,&nlevels);
    ffclose(out);
    sfree(axis);
    for (i=0; i<ndim/DIM; i++)
      sfree(mat2[i]);
    sfree(mat2);
  }


  /* call diagonalization routine */
  
  fprintf(stderr,"\nDiagonalizing ...\n");
  fflush(stderr);

  snew(eigval,ndim);
  snew(tmp,ndim*ndim);
  memcpy(tmp,mat,ndim*ndim*sizeof(real));
  eigensolver(tmp,ndim,0,ndim,eigval,mat);
  sfree(tmp);
  
  /* now write the output */

  sum=0;
  for(i=0; i<ndim; i++)
    sum+=eigval[i];
  fprintf(stderr,"\nSum of the eigenvalues: %g (%snm^2)\n",
	  sum,bM ? "u " : "");
  if (fabs(trace-sum)>0.01*trace)
    fprintf(stderr,"\nWARNING: eigenvalue sum deviates from the trace of the covariance matrix\n");
  
  fprintf(stderr,"\nWriting eigenvalues to %s\n",eigvalfile);

  sprintf(str,"(%snm\\S2\\N)",bM ? "u " : "");
  out=xvgropen(eigvalfile, 
	       "Eigenvalues of the covariance matrix",
	       "Eigenvector index",str,oenv);  
  for (i=0; (i<ndim); i++)
    fprintf (out,"%10d %g\n",(int)i+1,eigval[ndim-1-i]);
  ffclose(out);  

  if (end==-1) {
    if (nframes-1 < ndim)
      end=nframes-1;
    else
      end=ndim;
  }
  if (bFit) {
    /* misuse lambda: 0/1 mass weighted analysis no/yes */
    if (nfit==natoms) {
      WriteXref = eWXR_YES;
      for(i=0; i<nfit; i++)
	copy_rvec(xref[ifit[i]],x[i]);
    } else
      WriteXref = eWXR_NO;
  } else {
    /* misuse lambda: -1 for no fit */
    WriteXref = eWXR_NOFIT;
  }

  write_eigenvectors(eigvecfile,natoms,mat,TRUE,1,end,
		     WriteXref,x,bDiffMass1,xproj,bM,eigval);

  out = ffopen(logfile,"w");

  time(&now);
  gmx_ctime_r(&now,timebuf,STRLEN);
  fprintf(out,"Covariance analysis log, written %s\n",timebuf);
    
  fprintf(out,"Program: %s\n",argv[0]);
#if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
  pcwd=_getcwd(str,STRLEN);
#else
  pcwd=getcwd(str,STRLEN);
#endif
  if(NULL==pcwd)
  {
      gmx_fatal(FARGS,"Current working directory is undefined");
  }

  fprintf(out,"Working directory: %s\n\n",str);

  fprintf(out,"Read %d frames from %s (time %g to %g %s)\n",nframes,trxfile,
	  output_env_conv_time(oenv,tstart),output_env_conv_time(oenv,tend),output_env_get_time_unit(oenv));
  if (bFit)
    fprintf(out,"Read reference structure for fit from %s\n",fitfile);
  if (ndxfile)
    fprintf(out,"Read index groups from %s\n",ndxfile);
  fprintf(out,"\n");

  fprintf(out,"Analysis group is '%s' (%d atoms)\n",ananame,natoms);
  if (bFit)
    fprintf(out,"Fit group is '%s' (%d atoms)\n",fitname,nfit);
  else
    fprintf(out,"No fit was used\n");
  fprintf(out,"Analysis is %smass weighted\n", bDiffMass2 ? "":"non-");
  if (bFit)
    fprintf(out,"Fit is %smass weighted\n", bDiffMass1 ? "":"non-");
  fprintf(out,"Diagonalized the %dx%d covariance matrix\n",(int)ndim,(int)ndim);
  fprintf(out,"Trace of the covariance matrix before diagonalizing: %g\n",
	  trace);
  fprintf(out,"Trace of the covariance matrix after diagonalizing: %g\n\n",
	  sum);

  fprintf(out,"Wrote %d eigenvalues to %s\n",(int)ndim,eigvalfile);
  if (WriteXref == eWXR_YES)
    fprintf(out,"Wrote reference structure to %s\n",eigvecfile);
  fprintf(out,"Wrote average structure to %s and %s\n",averfile,eigvecfile);
  fprintf(out,"Wrote eigenvectors %d to %d to %s\n",1,end,eigvecfile);

  ffclose(out);

  fprintf(stderr,"Wrote the log to %s\n",logfile);

  thanx(stderr);
  
  return 0;
}
Ejemplo n.º 27
0
    bool ServiceController::installService( const std::wstring& serviceName, const std::wstring& displayName, const std::wstring& serviceDesc, const std::wstring& serviceUser, const std::wstring& servicePassword, const std::string dbpath, int argc, char* argv[] ) {
        assert(argc >= 1);

        stringstream commandLine;

        if ( strchr(argv[0], ':') ) { // a crude test for fully qualified path
            commandLine << '"' << argv[0] << "\" ";
        }
        else {
            char buffer[256];
            assert( _getcwd(buffer, 256) );
            commandLine << '"' << buffer << '\\' << argv[0] << "\" ";
        }

        for ( int i = 1; i < argc; i++ ) {
            std::string arg( argv[ i ] );
            // replace install command to indicate process is being started as a service
            if ( arg == "--install" || arg == "--reinstall" ) {
                arg = "--service";
            }
            else if ( arg == "--dbpath" && i + 1 < argc ) {
                commandLine << arg << "  \"" << dbpath << "\"  ";
                i++;
                continue;
            }
            else if ( arg == "--logpath" && i + 1 < argc ) {
                commandLine << arg << "  \"" << argv[i+1] << "\"  ";
                i++;
                continue;
            }
            else if ( arg.length() > 9 && arg.substr(0, 9) == "--service" ) {
                // Strip off --service(Name|User|Password) arguments
                i++;
                continue;
            }
            commandLine << arg << "  ";
        }

        SC_HANDLE schSCManager = ::OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
        if ( schSCManager == NULL ) {
            DWORD err = ::GetLastError();
            cerr << "Error connecting to the Service Control Manager: " << GetWinErrMsg(err) << endl;
            return false;
        }

        // Make sure servise doesn't already exist.
        // TODO: Check to see if service is in "Deleting" status, suggest the user close down Services MMC snap-ins.
        SC_HANDLE schService = ::OpenService( schSCManager, serviceName.c_str(), SERVICE_ALL_ACCESS );
        if ( schService != NULL ) {
            cerr << "There is already a service named " << toUtf8String(serviceName) << ". Aborting" << endl;
            ::CloseServiceHandle( schService );
            ::CloseServiceHandle( schSCManager );
            return false;
        }
        std::basic_ostringstream< TCHAR > commandLineWide;
        commandLineWide << commandLine.str().c_str();

        cerr << "Creating service " << toUtf8String(serviceName) << "." << endl;

        // create new service
        schService = ::CreateService( schSCManager, serviceName.c_str(), displayName.c_str(),
                                      SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
                                      SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
                                      commandLineWide.str().c_str(), NULL, NULL, L"\0\0", NULL, NULL );
        if ( schService == NULL ) {
            DWORD err = ::GetLastError();
            cerr << "Error creating service: " << GetWinErrMsg(err) << endl;
            ::CloseServiceHandle( schSCManager );
            return false;
        }

        cerr << "Service creation successful." << endl;
        cerr << "Service can be started from the command line via 'net start \"" << toUtf8String(serviceName) << "\"'." << endl;

        bool serviceInstalled;

        // TODO: If neccessary grant user "Login as a Service" permission.
        if ( !serviceUser.empty() ) {
            std::wstring actualServiceUser;
            if ( serviceUser.find(L"\\") == string::npos ) {
                actualServiceUser = L".\\" + serviceUser;
            }
            else {
                actualServiceUser = serviceUser;
            }

            cerr << "Setting service login credentials. User: "******"Setting service login failed. Service has 'LocalService' permissions." << endl;
            }
        }

        // set the service description
        SERVICE_DESCRIPTION serviceDescription;
        serviceDescription.lpDescription = (LPTSTR)serviceDesc.c_str();
        serviceInstalled = ::ChangeServiceConfig2( schService, SERVICE_CONFIG_DESCRIPTION, &serviceDescription );


        if ( serviceInstalled ) {
            SC_ACTION aActions[ 3 ] = { { SC_ACTION_RESTART, 0 }, { SC_ACTION_RESTART, 0 }, { SC_ACTION_RESTART, 0 } };

            SERVICE_FAILURE_ACTIONS serviceFailure;
            ZeroMemory( &serviceFailure, sizeof( SERVICE_FAILURE_ACTIONS ) );
            serviceFailure.cActions = 3;
            serviceFailure.lpsaActions = aActions;

            // set service recovery options
            serviceInstalled = ::ChangeServiceConfig2( schService, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailure );

        }
        else {
            cerr << "Could not set service description. Check the event log for more details." << endl;
        }

        ::CloseServiceHandle( schService );
        ::CloseServiceHandle( schSCManager );

        return serviceInstalled;
    }
Ejemplo n.º 28
0
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	char cwd[ MAX_OSPATH ];
	int  startTime, endTime;

	// should never get a previous instance in Win32
	if ( hPrevInstance )
	{
		return 0;
	}

#ifdef EXCEPTION_HANDLER
	WinSetExceptionVersion( Q3_VERSION );
#endif

	g_wv.hInstance = hInstance;
	Q_strncpyz( sys_cmdline, lpCmdLine, sizeof( sys_cmdline ) );

	// done before Com/Sys_Init since we need this for error output
	Sys_CreateConsole();

	// no abort/retry/fail errors
	SetErrorMode( SEM_FAILCRITICALERRORS );

	// get the initial time base
	Sys_Milliseconds();

	//Sys_InitStreamThread();

	Com_Init( sys_cmdline );
	NET_Init();

#if !defined(DEDICATED) && !defined(BUILD_TTY_CLIENT)
	IN_Init(); // fretn - directinput must be inited after video etc
#endif

	_getcwd( cwd, sizeof( cwd ) );
	Com_Printf( "Working directory: %s\n", cwd );

	// hide the early console since we've reached the point where we
	// have a working graphics subsystems
	if ( !com_dedicated->integer && !com_viewlog->integer )
	{
		Sys_ShowConsole( 0, qfalse );
	}

	SetFocus( g_wv.hWnd );

	// main game loop
	while ( 1 )
	{
		// if not running as a game client, sleep a bit
		if ( g_wv.isMinimized || ( com_dedicated && com_dedicated->integer ) )
		{
			Sleep( 5 );
		}

		// set low precision every frame, because some system calls
		// reset it arbitrarily
//		_controlfp( _PC_24, _MCW_PC );
//    _controlfp( -1, _MCW_EM  ); // no exceptions, even if some crappy
		// syscall turns them back on!

		startTime = Sys_Milliseconds();

		// make sure mouse and joystick are only called once a frame
		IN_Frame();

//		Com_FrameExt();
		Com_Frame();

		endTime = Sys_Milliseconds();
		totalMsec += endTime - startTime;
		countMsec++;
	}

	// never gets here
}
Ejemplo n.º 29
0
extern "C" CDECL rust_str *
rust_getcwd() {
    rust_task *task = rust_get_current_task();
    LOG(task, task, "rust_getcwd()");

    char cbuf[BUF_BYTES];

#if defined(__WIN32__)
    if (!_getcwd(cbuf, sizeof(cbuf))) {
#else
        if (!getcwd(cbuf, sizeof(cbuf))) {
#endif
        task->fail();
        return NULL;
    }

    return make_str(task->kernel, cbuf, strlen(cbuf), "rust_str(getcwd)");
}

#if defined(__WIN32__)
extern "C" CDECL rust_vec_box *
rust_env_pairs() {
    rust_task *task = rust_get_current_task();
    size_t envc = 0;
    LPTCH ch = GetEnvironmentStringsA();
    LPTCH c;
    for (c = ch; *c; c += strlen(c) + 1) {
        ++envc;
    }
    c = ch;
    rust_vec_box *v = (rust_vec_box *)
        task->kernel->malloc(vec_size<rust_vec_box*>(envc),
                       "str vec interior");
    v->body.fill = v->body.alloc = sizeof(rust_vec*) * envc;
    for (size_t i = 0; i < envc; ++i) {
        size_t n = strlen(c);
        rust_str *str = make_str(task->kernel, c, n, "str");
        ((rust_str**)&v->body.data)[i] = str;
        c += n + 1;
    }
    if (ch) {
        FreeEnvironmentStrings(ch);
    }
    return v;
}
#else
extern "C" CDECL rust_vec_box *
rust_env_pairs() {
    rust_task *task = rust_get_current_task();
#ifdef __APPLE__
    char **environ = *_NSGetEnviron();
#endif
    char **e = environ;
    size_t envc = 0;
    while (*e) {
        ++envc; ++e;
    }
    return make_str_vec(task->kernel, envc, environ);
}
#endif

extern "C" CDECL void
unsupervise() {
    rust_task *task = rust_get_current_task();
    task->unsupervise();
}
Ejemplo n.º 30
0
static int RealMain( const char *pchCmdLine, HINSTANCE hInstance, int nCmdShow )
{

    if ( SteamAPI_RestartAppIfNecessary( k_uAppIdInvalid ) )
    {
        // if Steam is not running or the game wasn't started through Steam, SteamAPI_RestartAppIfNecessary starts the
        // local Steam client and also launches this game again.

        // Once you get a public Steam AppID assigned for this game, you need to replace k_uAppIdInvalid with it and
        // removed steam_appid.txt from the game depot.

        return EXIT_FAILURE;
    }


    // Init Steam CEG
    if ( !Steamworks_InitCEGLibrary() )
    {
        OutputDebugString( "Steamworks_InitCEGLibrary() failed\n" );
        Alert( "Fatal Error", "Steam must be running to play this game (InitDrmLibrary() failed).\n" );
        return EXIT_FAILURE;
    }

    // Initialize SteamAPI, if this fails we bail out since we depend on Steam for lots of stuff.
    // You don't necessarily have to though if you write your code to check whether all the Steam
    // interfaces are NULL before using them and provide alternate paths when they are unavailable.
    //
    // This will also load the in-game steam overlay dll into your process.  That dll is normally
    // injected by steam when it launches games, but by calling this you cause it to always load,
    // even when not launched via steam.
    if ( !SteamAPI_Init() )
    {
        OutputDebugString( "SteamAPI_Init() failed\n" );
        Alert( "Fatal Error", "Steam must be running to play this game (SteamAPI_Init() failed).\n" );
        return EXIT_FAILURE;
    }

    // set our debug handler
    SteamClient()->SetWarningMessageHook( &SteamAPIDebugTextHook );

    // Tell Steam where it's overlay should show notification dialogs, this can be top right, top left,
    // bottom right, bottom left. The default position is the bottom left if you don't call this.
    // Generally you should use the default and not call this as users will be most comfortable with
    // the default position.  The API is provided in case the bottom right creates a serious conflict
    // with important UI in your game.
    SteamUtils()->SetOverlayNotificationPosition( k_EPositionTopRight );

    // Ensure that the user has logged into Steam. This will always return true if the game is launched
    // from Steam, but if Steam is at the login prompt when you run your game from the debugger, it
    // will return false.
    if ( !SteamUser()->BLoggedOn() )
    {
        OutputDebugString( "Steam user is not logged in\n" );
        Alert( "Fatal Error", "Steam user must be logged in to play this game (SteamUser()->BLoggedOn() returned false).\n" );
        return EXIT_FAILURE;
    }

    // We are going to use the controller interface, initialize it, which is a seperate step as it
    // create a new thread in the game proc and we don't want to force that on games that don't
    // have native Steam controller implementations

    char rgchCWD[1024];
    _getcwd( rgchCWD, sizeof( rgchCWD ) );

    char rgchFullPath[1024];
#if defined(_WIN32)
    _snprintf( rgchFullPath, sizeof( rgchFullPath ), "%s\\%s", rgchCWD, "controller.vdf" );
#elif defined(OSX)
    // hack for now, because we do not have utility functions available for finding the resource path
    // alternatively we could disable the SteamController init on OS X
    _snprintf( rgchFullPath, sizeof( rgchFullPath ), "%s/steamworksexample.app/Contents/Resources/%s", rgchCWD, "controller.vdf" );
#else
    _snprintf( rgchFullPath, sizeof( rgchFullPath ), "%s/%s", rgchCWD, "controller.vdf" );
#endif
    if( !SteamController()->Init( rgchFullPath ) )
    {
        OutputDebugString( "SteamController()->Init() failed\n" );
        Alert( "Fatal Error", "Steam Controller Init failed. Is controller.vdf in the current working directory?\n" );
        return EXIT_FAILURE;
    }

    bool bUseVR = SteamUtils()->IsSteamRunningInVR();
    const char *pchServerAddress, *pchLobbyID;
    ParseCommandLine( pchCmdLine, &pchServerAddress, &pchLobbyID, &bUseVR );

    // do a DRM self check
    Steamworks_SelfCheck();

    // init VR before we make the window

    // Construct a new instance of the game engine
    // bugbug jmccaskey - make screen resolution dynamic, maybe take it on command line?
    IGameEngine *pGameEngine =
#if defined(_WIN32)
        new CGameEngineWin32( hInstance, nCmdShow, 1024, 768, bUseVR );
#elif defined(OSX)
        CreateGameEngineOSX();
#elif defined(SDL)
        CreateGameEngineSDL( bUseVR );
#else
#error	Need CreateGameEngine()
#endif

    // This call will block and run until the game exits
    RunGameLoop( pGameEngine, pchServerAddress, pchLobbyID );

    // Shutdown the SteamAPI
    SteamController()->Shutdown();
    SteamAPI_Shutdown();

    // Shutdown Steam CEG
    Steamworks_TermCEGLibrary();

    // exit
    return EXIT_SUCCESS;
}