Exemple #1
0
int main( int pArgc, const char** pArgs )
{

   unsigned long lIP;
   int           lIndex;
   int           lNbBanners;
   char*         lPathEnd;

   
   lPathEnd = strrchr( pArgs[0], '/' );
   if( lPathEnd != NULL )
   {
      *lPathEnd = 0;
      chdir( pArgs[0] );
   }

   lNbBanners = GetBannerCount();
   
   if( lNbBanners <= 0 )
   {
      lIndex = 0;
   }
   else
   {
      srand( time( NULL ) );
      lIndex = 1+(((unsigned)rand())%lNbBanners);
   }

   SetQueueEntry( GetIP(), lIndex );

   PrintBanner( lIndex );

   return 0;
}
Exemple #2
0
void PrintfUsage( void )
{
    char        msg_buff[MAX_MESSAGE_SIZE];
    unsigned    count;
    char        page_text[MAX_MESSAGE_SIZE];
    int         first_ln;

    count = PrintBanner();
#ifdef __OSI__
    if( _Copyright != NULL ) {
        puts( _Copyright );
        count += 1;
    }
#endif
    first_ln = MSG_USAGE_BASE;
    MsgGet( first_ln++, page_text );
    for( ; ; first_ln++ ) {
        if( ++count >= 23 ) {
            if( Wait_for_return( page_text ) ) {
                break;
            }
            count = 0;
        }
        MsgGet( first_ln, msg_buff );
        if( ( msg_buff[ 0 ] == '.' ) && ( msg_buff[ 1 ] == 0 ) )
            break;
        puts( msg_buff );
    }
}
int main( int argc, char** argv )
{
	PrintBanner();

	if ( argc > 1 )
	{
		LoadDensityMap( argv[1] );
	}

	// prepare PRNG
	gen.seed( time( NULL ) );

	std::vector<sPoint> Points = GeneratePoissonPoints( MinDistance, k, NumPoints );

	// prepare BGR image
	cv::Mat	Img(cv::Size(ImageSize,ImageSize),CV_8UC1);
	Img.setTo(0);

	for ( auto i = Points.begin(); i != Points.end(); i++ )
	{
		int x = int( i->x * ImageSize );
		int y = int( i->y * ImageSize );
		if ( g_DensityMap )
		{
			// dice
			float R = RandomFloat();
			float P = g_DensityMap[ x + y * ImageSize ];
			if ( R > P ) continue;
		}
		Img.ptr<uchar>(y)[x]	=	255;
	}
	cv::imwrite("Poisson.bmp",Img);

	return 0;
}
Exemple #4
0
void MsgPrintf( int resourceid )
{
    char        msgbuf[MAX_MESSAGE_SIZE];

    PrintBanner();
    MsgGet( resourceid, msgbuf );
    printf( "%s", msgbuf );
}
Exemple #5
0
void MsgPrintf1( int resourceid, const char *token )
{
    char        msgbuf[MAX_MESSAGE_SIZE];

    PrintBanner();
    MsgGet( resourceid, msgbuf );
    printf( msgbuf, token );
}
Exemple #6
0
int main( int argc, char* argv[] )
{
#if !ENABLE_TEST
    if ( argc <= 1 )
    {
        PrintBanner();
        return 0;
    }
#endif

    g_Config = ReadConfigFromCommandLine( argc, argv );

#if ENABLE_TEST
    if ( g_Playlist.IsEmpty() ) g_Playlist.EnqueueTrack( "test.ogg" );
    g_Config.m_Verbose = true;
#endif

    auto AudioSubsystem = CreateAudioSubsystem_OpenAL();

    AudioSubsystem->Start();

    auto Source = AudioSubsystem->CreateAudioSource();
    // allow seamless looping if there is only one track
    if ( g_Playlist.GetNumTracks() == 1 ) Source->SetLooping( g_Config.m_Loop );

    bool RequestingExit = false;

    while ( !g_Playlist.IsEmpty() && !RequestingExit )
    {
        auto FileName = g_Playlist.GetAndPopNextTrack( g_Config.m_Loop );
        auto DataBlob = ReadFileAsBlob( FileName.c_str() );
        if (!DataBlob || !DataBlob->GetDataSize()) continue;

        auto Provider = CreateWaveDataProvider( FileName.c_str(), DataBlob );
        if (!Provider) continue;

        Source->BindDataProvider( Provider );
        Source->Play();

        while ( Source->IsPlaying() && !RequestingExit )
        {
            std::this_thread::sleep_for( std::chrono::milliseconds(10) );

            if ( IsKeyPressed() ) RequestingExit = true;
        };

        Source->Stop();
    }

    Source = nullptr;

    AudioSubsystem->Stop();

    return 0;
};
Exemple #7
0
static void PrintLevelName(FILE *stream, int episode, int level)
{
    PrintBanner(stream);

    switch (discovered_gamemission)
    {

        case doom:
            fprintf(stream, "E%iM%i\n", episode + 1, level + 1);
            break;
        case doom2:
            fprintf(stream, "MAP%02i\n", level + 1);
            break;
        default:
        case none:
            fprintf(stream, "E%iM%i / MAP%02i\n", 
                    episode + 1, level + 1, level + 1);
            break;
    }

    PrintBanner(stream);
}
Exemple #8
0
/*
================
SV_Shutdown

Called when each game quits,
before Sys_Quit or Sys_Error
================
*/
void SV_Shutdown( const char *finalmsg )
{
	if ( !com_sv_running || !com_sv_running->integer )
	{
		return;
	}

	PrintBanner(_( "Server Shutdown" ))

	NET_LeaveMulticast6();

	if ( svs.clients && !com_errorEntered )
	{
		SV_FinalCommand( va( "print %s", Cmd_QuoteString( finalmsg ) ), qtrue );
	}

	SV_RemoveOperatorCommands();
	SV_MasterShutdown();
	SV_ShutdownGameProgs();

	// free current level
	SV_ClearServer();

	// free server static data
	if ( svs.clients )
	{
		int index;

		for ( index = 0; index < sv_maxclients->integer; index++ )
		{
			SV_FreeClient( &svs.clients[ index ] );
		}

		//Z_Free( svs.clients );
		free( svs.clients );  // RF, avoid trying to allocate large chunk on a fragmented zone
	}

	memset( &svs, 0, sizeof( svs ) );
	svs.serverLoad = -1;

	Cvar_Set( "sv_running", "0" );
#ifndef DEDICATED
	NET_Config( qtrue );
#endif

	Com_Printf( "---------------------------\n" );

	// disconnect any local clients
	CL_Disconnect( qfalse );
}
Exemple #9
0
void
DisplayMessage(
    const char *szFilename,
    UINT Prefix,
    UINT Message,
    va_list valist
    )
{
    const char *szFormat;

    if (FIgnoreWarning(Message)) {
        return;
    }

    if (fNeedBanner) {
        PrintBanner();
    }

    fflush(NULL);

    if (szFilename == NULL) {
        szFilename = ToolName;
    }

    if (Prefix != MSGSTR) {
        printf("%s :", szFilename);
    }

    if ((Prefix != NOTESTR) && (Prefix != MSGSTR)) {
        const char *szPrefix;

        szPrefix = GetErrorFormatString(Prefix);

        if (szPrefix) {
            printf("%s", szPrefix);
        }
    }

    if ((Message != FULLBUILD) && (Prefix != MSGSTR)) {
        printf(" LNK%04u:", GetExternalErrorCode(Message));
    }

    szFormat = GetErrorFormatString(Message);
    if (szFormat) {
        vprintf(szFormat, valist);
    }

    fputc('\n', stdout);
    fflush(stdout);
}
Exemple #10
0
/*
================
SV_Shutdown

Called when each game quits,
before Sys_Quit or Sys_Error
================
*/
void SV_Shutdown( const char *finalmsg )
{
	if ( !com_sv_running || !com_sv_running->integer )
	{
		return;
	}

	PrintBanner( "Server Shutdown" )

	NET_LeaveMulticast6();

	if ( svs.clients )
	{
		SV_FinalCommand( va( "print %s", Cmd_QuoteString( finalmsg ) ), true );
	}

	SV_RemoveOperatorCommands();
	SV_MasterShutdown();
	SV_ShutdownGameProgs();

	// free current level
	SV_ClearServer();

	// free server static data
	if ( svs.clients )
	{
		int index;

		for ( index = 0; index < sv_maxclients->integer; index++ )
		{
			SV_FreeClient( &svs.clients[ index ] );
		}

		free( svs.clients );
	}

	memset( &svs, 0, sizeof( svs ) );
	svs.serverLoad = -1;

	Cvar_Set( "sv_running", "0" );
#ifndef BUILD_SERVER
	NET_Config( true );
#endif

	Com_Printf( "---------------------------\n" );

	// disconnect any local clients
	CL_Disconnect( false );
}
Exemple #11
0
void PrintUse()
{
	// Print the use specification.
	PrintBanner();
	printf("Usage: PiPROM -r/w/e <options> <filename>\n");
	printf("\t-r\t\tRead the EEPROM chip contents to <filename>.\n");
	printf("\t-w\t\tWrite the contents of <filename> to the EEPROM chip.\n");
	printf("\t-e\t\tErases the EEPROM filling it with 00s.\n");
	printf("\tfilename\tEEPROM file to read from/write to.\n");

	printf("\nOptional:\n");
	printf("\t-a <address>\tI2C address of the EEPROM chip.\n");

	printf("\n");
}
Exemple #12
0
/***    ShowSyntax - Display command-line syntax
 *
 */
void ShowSyntax(BOOL fFull)
{
    int     i;
    int     cLines;

    // Announce ourselves
    PrintBanner();

    if (fFull) {                        // Show full help
        cLines = sizeof(apszSyntax)/sizeof(char *);
        for (i=0; i<cLines; i++) {
            printf("%s\n",apszSyntax[i]);
        }
    }
    else {                              // Just show summary line
        printf("%s\n",apszSyntax[isynSUMMARY]);
    }

    exit(0);
}
Exemple #13
0
//===========================================================================
// main
//===========================================================================
int main(int argc, char **argv)
{
	int i;

	PrintBanner();
	
	myargc = argc;
	myargv = argv;
	if(CheckOption("-f")) fullImport = true;
	
	if(argc == 1)
	{
		PrintUsage();
		return 0;
	}
	InitData();
	// Go through each command line option and process them.
	for(i = 1; i < argc; i++)
	{
		if(argv[i][0] == '-') // This is an option.
		{
			if(!stricmp(argv[i], "-i")) // Import (decompile).
			{
				if(i + 2 >= argc) 
				{
					printf("Too few parameters for import.\n");
					return 1;
				}
				Import(argv[i + 1], argv[i + 2]);
				i += 2;
			}
			continue; 
		}
		// Try to open this TX source and parse it.
		Compile(argv[i]);
	}
	WriteLumps();
	CloseData();
	return 0;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;	

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0) || ::OleInitialize(NULL) != S_OK)
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: MFC or COM initialization failed\n"));
		nRetCode = 1;
	}
	else
	{
		PrintBanner();
		ValidateIISSetup();
		ValidateIISxpressFiles();
	}

	::OleUninitialize();

	return nRetCode;
}
Exemple #15
0
static void do_init_stuff( char **cmdline )
/*****************************************/
{
    char        *env;

    if( !MsgInit() )
        exit(1);

    add_constant( "WASM=" BANSTR( _BANVER ), true );
    ForceInclude = AsmStrDup( getenv( "FORCE" ) );
    do_envvar_cmdline( "WASM" );
    parse_cmdline( cmdline );
    set_build_target();
    set_cpu_mode();
    set_fpu_mode();
    get_os_include();
    env = getenv( "INCLUDE" );
    if( env != NULL )
        AddItemToIncludePath( env, NULL );
    PrintBanner();
    open_files();
    PushLineQueue();
}
Exemple #16
0
//
// D_DoomMain
//
void D_DoomMain(void)
{
	int p;
	char file[256];
	char demolumpname[9];

	M_FindResponseFile();

	// print banner

	PrintBanner(PACKAGE_STRING);

	I_Print("Z_Init: Init zone memory allocation daemon. \n");
	Z_Init();

	iwadfile = D_FindIWAD();

	// None found?

	if (iwadfile == NULL) {
		I_Error
		    ("Game mode indeterminate.  No IWAD file was found.  Try\n"
		     "specifying one with the '-iwad' command line parameter.\n");
	}

	modifiedgame = false;

	//!
	// @vanilla
	//
	// Disable monsters.
	//

	nomonsters = M_CheckParm("-nomonsters");

	//!
	// @vanilla
	//
	// Monsters respawn after being killed.
	//

	respawnparm = M_CheckParm("-respawn");

	//!
	// @vanilla
	//
	// Monsters move faster.
	//

	fastparm = M_CheckParm("-fast");

	//! 
	// @vanilla
	//
	// Developer mode.  F1 saves a screenshot in the current working
	// directory.
	//

	devparm = M_CheckParm("-devparm");

	//!
	// @category net
	// @vanilla
	//
	// Start a deathmatch game.
	//

	if (M_CheckParm("-deathmatch"))
		deathmatch = 1;

	//!
	// @category net
	// @vanilla
	//
	// Start a deathmatch 2.0 game.  Weapons do not stay in place and
	// all items respawn after 30 seconds.
	//

	if (M_CheckParm("-altdeath"))
		deathmatch = 2;

	if (devparm)
		I_Print(D_DEVSTR);

	//!
	// @arg <x>
	// @vanilla
	//
	// Turbo mode.  The player's speed is multiplied by x%.  If unspecified,
	// x defaults to 200.  Values are rounded up to 10 and down to 400.
	//

	if ((p = M_CheckParm("-turbo"))) {
		int scale = 200;
		extern int forwardmove[2];
		extern int sidemove[2];

		if (p < myargc - 1)
			scale = atoi(myargv[p + 1]);
		if (scale < 10)
			scale = 10;
		if (scale > 400)
			scale = 400;
		/*I_Print ("turbo scale: %i%%\n",scale); */
		forwardmove[0] = forwardmove[0] * scale / 100;
		forwardmove[1] = forwardmove[1] * scale / 100;
		sidemove[0] = sidemove[0] * scale / 100;
		sidemove[1] = sidemove[1] * scale / 100;
	}
	// init subsystems
	I_Print("V_Init: allocate screens.\n");
	V_Init();

	I_Print("M_LoadDefaults: Load system defaults.\n");
	M_LoadDefaults();	// load before initing other systems

	I_Print("W_Init: Init WADfiles.\n");
	D_AddFile(iwadfile);

#ifdef FEATURE_WAD_MERGE

	// Merged PWADs are loaded first, because they are supposed to be 
	// modified IWADs.

	//!
	// @arg <files>
	// @category mod
	//
	// Simulates the behavior of deutex's -merge option, merging a PWAD
	// into the main IWAD.  Multiple files may be specified.
	//

	p = M_CheckParm("-merge");

	if (p > 0) {
		for (p = p + 1; p < myargc && myargv[p][0] != '-'; ++p) {
			char *filename;

			filename = D_TryFindWADByName(myargv[p]);

			/*I_Print(" merging %s\n", filename); */
			W_MergeFile(filename);
		}
	}
	// NWT-style merging:

	// NWT's -merge option:

	//!
	// @arg <files>
	// @category mod
	//
	// Simulates the behavior of NWT's -merge option.  Multiple files
	// may be specified.

	p = M_CheckParm("-nwtmerge");

	if (p > 0) {
		for (p = p + 1; p < myargc && myargv[p][0] != '-'; ++p) {
			char *filename;

			filename = D_TryFindWADByName(myargv[p]);

			/*I_Print(" performing NWT-style merge of %s\n", filename); */
			W_NWTDashMerge(filename);
		}
	}
	// Add flats

	//!
	// @arg <files>
	// @category mod
	//
	// Simulates the behavior of NWT's -af option, merging flats into
	// the main IWAD directory.  Multiple files may be specified.
	//

	p = M_CheckParm("-af");

	if (p > 0) {
		for (p = p + 1; p < myargc && myargv[p][0] != '-'; ++p) {
			char *filename;

			filename = D_TryFindWADByName(myargv[p]);

			/*I_Print(" merging flats from %s\n", filename); */
			W_NWTMergeFile(filename, W_NWT_MERGE_FLATS);
		}
	}
	//!
	// @arg <files>
	// @category mod
	//
	// Simulates the behavior of NWT's -as option, merging sprites
	// into the main IWAD directory.  Multiple files may be specified.
	//

	p = M_CheckParm("-as");

	if (p > 0) {
		for (p = p + 1; p < myargc && myargv[p][0] != '-'; ++p) {
			char *filename;

			filename = D_TryFindWADByName(myargv[p]);

			/*I_Print(" merging sprites from %s\n", filename); */
			W_NWTMergeFile(filename, W_NWT_MERGE_SPRITES);
		}
	}
	//!
	// @arg <files>
	// @category mod
	//
	// Equivalent to "-af <files> -as <files>".
	//

	p = M_CheckParm("-aa");

	if (p > 0) {
		for (p = p + 1; p < myargc && myargv[p][0] != '-'; ++p) {
			char *filename;

			filename = D_TryFindWADByName(myargv[p]);

			/*I_Print(" merging sprites and flats from %s\n", filename); */
			W_NWTMergeFile(filename,
				       W_NWT_MERGE_SPRITES | W_NWT_MERGE_FLATS);
		}
	}
#endif

	//!
	// @arg <files>
	// @vanilla
	//
	// Load the specified PWAD files.
	//

	p = M_CheckParm("-file");
	if (p) {
		// the parms after p are wadfile/lump names,
		// until end of parms or another - preceded parm
		modifiedgame = true;	// homebrew levels
		while (++p != myargc && myargv[p][0] != '-') {
			char *filename;

			filename = D_TryFindWADByName(myargv[p]);

			D_AddFile(filename);
		}
	}
	// add any files specified on the command line with -file wadfile
	// to the wad list
	//
	// convenience hack to allow -wart e m to add a wad file
	// prepend a tilde to the filename so wadfile will be reloadable
	/*p = M_CheckParm ("-wart");
	   if (p)
	   {
	   myargv[p][4] = 'p';     // big hack, change to -warp

	   // Map name handling.
	   switch (gamemode )
	   {
	   case shareware:
	   case retail:
	   case registered:
	   sprintf (file,"~"DEVMAPS"E%cM%c.wad",
	   myargv[p+1][0], myargv[p+2][0]);
	   I_Print("Warping to Episode %s, Map %s.\n",
	   myargv[p+1],myargv[p+2]);
	   break;

	   case commercial:
	   default:
	   p = atoi (myargv[p+1]);
	   if (p<10)
	   format_number(file,"~"DEVMAPS"cdata/map0%i.wad", p, 10);
	   else
	   format_number(file,"~"DEVMAPS"cdata/map%i.wad", p, 10);
	   break;
	   }
	   D_AddFile (file);
	   } */

	//!
	// @arg <demo>
	// @category demo
	// @vanilla
	//
	// Play back the demo named demo.lmp.
	//

	p = M_CheckParm("-playdemo");

	if (!p) {
		//!
		// @arg <demo>
		// @category demo
		// @vanilla
		//
		// Play back the demo named demo.lmp, determining the framerate
		// of the screen.
		//
		p = M_CheckParm("-timedemo");

	}

	if (p && p < myargc - 1) {
		strcpy(file, myargv[p + 1]);

		if (D_AddFile(file)) {
			strncpy(demolumpname, lumpinfo[numlumps - 1].name, 8);
			demolumpname[8] = '\0';

			/*I_Print("Playing demo %s.\n", file); */
		} else {
			// If file failed to load, still continue trying to play
			// the demo in the same way as Vanilla Doom.  This makes
			// tricks like "-playdemo demo1" possible.

			strncpy(demolumpname, myargv[p + 1], 8);
			demolumpname[8] = '\0';
		}

	}
	// Generate the WAD hash table.  Speed things up a bit.

	I_Print("W_Init: Generate Hash Table.\n");
	W_GenerateHashTable();

	D_IdentifyVersion();
	InitGameVersion();
	D_SetGameDescription();

	// Check for -file in shareware
	if (modifiedgame) {
		// These are the lumps that will be checked in IWAD,
		// if any one is not present, execution will be aborted.
		char name[23][8] = {
			"e2m1", "e2m2", "e2m3", "e2m4", "e2m5", "e2m6", "e2m7",
			"e2m8", "e2m9",
			"e3m1", "e3m3", "e3m3", "e3m4", "e3m5", "e3m6", "e3m7",
			"e3m8", "e3m9",
			"dphoof", "bfgga0", "heada1", "cybra1", "spida1d1"
		};
		int i;

		if (gamemode == shareware)
			I_Error("\nYou cannot -file with the shareware "
				"version. Register!");

		// Check for fake IWAD with right name,
		// but w/o all the lumps of the registered version. 
		if (gamemode == registered)
			for (i = 0; i < 23; i++)
				if (W_CheckNumForName(name[i]) < 0)
					I_Error
					    ("\nThis is not the registered version.");
	}
	// get skill / episode / map from parms
	startskill = sk_medium;
	startepisode = 1;
	startmap = 1;
	autostart = false;

	//!
	// @arg <skill>
	// @vanilla
	//
	// Set the game skill, 1-5 (1: easiest, 5: hardest).  A skill of
	// 0 disables all monsters.
	//

	p = M_CheckParm("-skill");

	if (p && p < myargc - 1) {
		startskill = myargv[p + 1][0] - '1';
		autostart = true;
	}
	//!
	// @arg <n>
	// @vanilla
	//
	// Start playing on episode n (1-4)
	//

	p = M_CheckParm("-episode");

	if (p && p < myargc - 1) {
		startepisode = myargv[p + 1][0] - '0';
		startmap = 1;
		autostart = true;
	}

	timelimit = 0;

	//! 
	// @arg <n>
	// @category net
	// @vanilla
	//
	// For multiplayer games: exit each level after n minutes.
	//

	p = M_CheckParm("-timer");

	if (p && p < myargc - 1 && deathmatch) {
		timelimit = atoi(myargv[p + 1]);
		/*I_Print("timer: %i\n", timelimit); */
	}
	//!
	// @category net
	// @vanilla
	//
	// Austin Virtual Gaming: end levels after 20 minutes.
	//

	p = M_CheckParm("-avg");

	if (p && p < myargc - 1 && deathmatch) {
		I_Print("Austin Virtual Gaming: Levels will end "
			"after 20 minutes\n");
		timelimit = 20;
	}
	//!
	// @arg [<x> <y> | <xy>]
	// @vanilla
	//
	// Start a game immediately, warping to ExMy (Doom 1) or MAPxy
	// (Doom 2)
	//

	p = M_CheckParm("-warp");

	if (p && p < myargc - 1) {
		if (gamemode == commercial)
			startmap = atoi(myargv[p + 1]);
		else {
			startepisode = myargv[p + 1][0] - '0';

			if (p + 2 < myargc) {
				startmap = myargv[p + 2][0] - '0';
			} else {
				startmap = 1;
			}
		}
		autostart = true;
	}
	// Check for load game parameter
	// We do this here and save the slot number, so that the network code
	// can override it or send the load slot to other players.

	//!
	// @arg <s>
	// @vanilla
	//
	// Load the game in slot s.
	//

	p = M_CheckParm("-loadgame");

	if (p && p < myargc - 1) {
		startloadgame = atoi(myargv[p + 1]);
	} else {
		// Not loading a game
		startloadgame = -1;
	}

	//!
	// @category video
	//
	// Disable vertical mouse movement.
	//

	if (M_CheckParm("-novert"))
		novert = true;

	//!
	// @category video
	//
	// Enable vertical mouse movement.
	//

	if (M_CheckParm("-nonovert"))
		novert = false;

	if (W_CheckNumForName("SS_START") >= 0
	    || W_CheckNumForName("FF_END") >= 0) {
		I_Print
		    ("===========================================================================\n");
		I_Print
		    (" WARNING: The loaded WAD file contains modified sprites or\n"
		     " floor textures.  You may want to use the '-merge' command\n"
		     " line option instead of '-file'.\n");
	}

	I_Print
	    ("===========================================================================\n");

	PrintBanner(gamedescription);

	I_Print
	    ("===========================================================================\n"
	     " " PACKAGE_NAME
	     " is free software, covered by the GNU General Public\n"
	     " License.  There is NO warranty; not even for MERCHANTABILITY or FITNESS\n"
	     " FOR A PARTICULAR PURPOSE. You are welcome to change and distribute\n"
	     " copies under certain conditions. See the source for more information.\n"
	     "===========================================================================\n");

	I_Print("M_Init: Init miscellaneous info.\n");
	M_Init();

	I_Print("R_Init: Init DOOM refresh daemon - ");
	R_Init();

	I_Print("\nP_Init: Init Playloop state.\n");
	P_Init();

	I_Print("\nG_Init: Init game state.\n");
	G_Init();

	I_Print("S_Init: Setting up sound.\n");
	S_Init(sfxVolume * 8, musicVolume * 8);

	PrintGameVersion();

	I_Print("HU_Init: Setting up heads up display.\n");
	HU_Init();

	I_Print("ST_Init: Init status bar.\n");
	ST_Init();

	// If Doom II without a MAP01 lump, this is a store demo.  
	// Moved this here so that MAP01 isn't constantly looked up
	// in the main loop.

	if (gamemode == commercial && W_CheckNumForName("map01") < 0)
		storedemo = true;

	I_Print("\nI_InitGraphics: Init graphics.\n");
	I_InitGraphics();

	//!
	// @arg <x>
	// @category demo
	// @vanilla
	//
	// Record a demo named x.lmp.
	//

	p = M_CheckParm("-record");

	if (p && p < myargc - 1) {
		G_RecordDemo(myargv[p + 1]);
		autostart = true;
	}

	p = M_CheckParm("-playdemo");
	if (p && p < myargc - 1) {
		singledemo = true;	// quit after one demo
		G_DeferedPlayDemo(demolumpname);
		D_DoomLoop();	// never returns
	}

	if (startloadgame >= 0) {
		strcpy(file, P_SaveGameFile(startloadgame));
		G_LoadGame(file);
	}

	if (gameaction != ga_loadgame) {
		if (autostart || netgame)
			G_InitNew(startskill, startepisode, startmap);
		else
			D_StartTitle();	// start up intro loop
	}

	I_Print("D_DoomLoop: GOGOGOG!\n");
	D_DoomLoop();		// never returns
}
Exemple #17
0
bool Master::Run(int /*argc*/, char** /*argv*/)
{
    char* config_file = (char*)CONFDIR "/world.conf";

    UNIXTIME = time(NULL);
    g_localTime = *localtime(&UNIXTIME);

    AscLog.InitalizeLogFiles("world");

    PrintBanner();

    LogDefault("The key combination <Ctrl-C> will safely shut down the server.");

#ifndef WIN32
    if (geteuid() == 0 || getegid() == 0)
        AscLog.ConsoleLogMajorError("You are running AscEmu as root.", "This is not needed, and may be a possible security risk.", "It is advised to hit CTRL+C now and", "start as a non-privileged user.");
#endif

    InitImplicitTargetFlags();

    ThreadPool.Startup();
    auto startTime = Util::TimeNow();

    new EventMgr;
    new World;

    if (!LoadWorldConfiguration(config_file))
    {
        return false;
    }

    sWorld.loadWorldConfigValues();

    AscLog.SetFileLoggingLevel(worldConfig.log.worldFileLogLevel);
    AscLog.SetDebugFlags(worldConfig.log.worldDebugFlags);

    OpenCheatLogFiles();

    if (!_StartDB())
    {
        Database::CleanupLibs();
        AscLog.~AscEmuLog();
        return false;
    }

    if (!_CheckDBVersion())
    {
        AscLog.~AscEmuLog();
        return false;
    }

    // Initialize Opcode Table
    WorldSession::InitPacketHandlerTable();

    new ScriptMgr;

    if (!sWorld.setInitialWorldSettings())
    {
        LOG_ERROR("SetInitialWorldSettings() failed. Something went wrong? Exiting.");
        AscLog.~AscEmuLog();
        return false;
    }

    sWorld.setWorldStartTime((uint32)UNIXTIME);

    worldRunnable = std::move(std::make_unique<WorldRunnable>());

    _HookSignals();

    ConsoleThread* console = new ConsoleThread();
    ThreadPool.ExecuteTask(console);

    StartNetworkSubsystem();

    sSocketMgr.SpawnWorkerThreads();

    sScriptMgr.LoadScripts();

    if (worldConfig.startup.enableSpellIdDump)
    {
        sScriptMgr.DumpUnimplementedSpells();
    }

    LogDetail("Server : Ready for connections. Startup time: %u ms", Util::GetTimeDifferenceToNow(startTime));

    ThreadPool.ExecuteTask(new GameEventMgr::GameEventMgrThread());

    StartRemoteConsole();

    WritePidFile();

    if (!ChannelMgr::getSingletonPtr())
        new ChannelMgr;

    channelmgr.seperatechannels = worldConfig.server.seperateChatChannels;

    if (!MailSystem::getSingletonPtr())
        new MailSystem;

    uint32_t mailFlags = 0;

    if (worldConfig.mail.isCostsForGmDisabled)
        mailFlags |= MAIL_FLAG_NO_COST_FOR_GM;

    if (worldConfig.mail.isCostsForEveryoneDisabled)
        mailFlags |= MAIL_FLAG_DISABLE_POSTAGE_COSTS;

    if (worldConfig.mail.isDelayItemsDisabled)
        mailFlags |= MAIL_FLAG_DISABLE_HOUR_DELAY_FOR_ITEMS;

    if (worldConfig.mail.isMessageExpiryDisabled)
        mailFlags |= MAIL_FLAG_NO_EXPIRY;

    if (worldConfig.mail.isInterfactionMailEnabled)
        mailFlags |= MAIL_FLAG_CAN_SEND_TO_OPPOSITE_FACTION;

    if (worldConfig.mail.isInterfactionMailForGmEnabled)
        mailFlags |= MAIL_FLAG_CAN_SEND_TO_OPPOSITE_FACTION_GM;

    sMailSystem.config_flags = mailFlags;

    //ThreadPool.Gobble();

    /* Connect to realmlist servers / logon servers */
    new LogonCommHandler();
    sLogonCommHandler.startLogonCommHandler();

    // Create listener
    ListenSocket<WorldSocket> * ls = new ListenSocket<WorldSocket>(worldConfig.listen.listenHost.c_str(), worldConfig.listen.listenPort);
    bool listnersockcreate = ls->IsOpen();
#ifdef WIN32
    if (listnersockcreate)
        ThreadPool.ExecuteTask(ls);
#endif

    ShutdownThreadPools(listnersockcreate);

    _UnhookSignals();

    worldRunnable->threadShutdown();
    worldRunnable = nullptr;

    ThreadPool.ShowStats();
    /* Shut down console system */
    console->stopThread();
    delete console;

    // begin server shutdown

    ShutdownLootSystem();

    // send a query to wake it up if its inactive
    LogNotice("Database : Clearing all pending queries...");

    // kill the database thread first so we don't lose any queries/data
    CharacterDatabase.EndThreads();
    WorldDatabase.EndThreads();

    ls->Close();

    CloseConsoleListener();
    sWorld.saveAllPlayersToDb();

    LogNotice("Network : Shutting down network subsystem.");
#ifdef WIN32
    sSocketMgr.ShutdownThreads();
#endif
    sSocketMgr.CloseAll();

    bServerShutdown = true;
    ThreadPool.Shutdown();

    delete ls;

    sWorld.logoutAllPlayers();

    delete LogonCommHandler::getSingletonPtr();

    LogNotice("AddonMgr : ~AddonMgr()");
#if VERSION_STRING != Cata
    sAddonMgr.SaveToDB();
#endif
    delete AddonMgr::getSingletonPtr();

    LogNotice("AuctionMgr : ~AuctionMgr()");
    delete AuctionMgr::getSingletonPtr();

    LogNotice("LootMgr : ~LootMgr()");
    delete LootMgr::getSingletonPtr();

    LogNotice("MailSystem : ~MailSystem()");
    delete MailSystem::getSingletonPtr();

    LogNotice("World : ~World()");
    delete World::getSingletonPtr();

    sScriptMgr.UnloadScripts();
    delete ScriptMgr::getSingletonPtr();

    LogNotice("ChatHandler : ~ChatHandler()");
    delete ChatHandler::getSingletonPtr();

    LogNotice("EventMgr : ~EventMgr()");
    delete EventMgr::getSingletonPtr();

    LogNotice("Database : Closing Connections...");
    _StopDB();

    LogNotice("Network : Deleting Network Subsystem...");
    delete SocketMgr::getSingletonPtr();
    delete SocketGarbageCollector::getSingletonPtr();

    delete GMCommand_Log;
    delete Anticheat_Log;
    delete Player_Log;

    // remove pid
    if (remove("worldserver.pid") != 0)
    {
        LOG_ERROR("Error deleting file worldserver.pid");
    }
    else
    {
        LOG_DEBUG("File worldserver.pid successfully deleted");
    }

    LogDetail("Shutdown : Shutdown complete.");
    AscLog.~AscEmuLog();

#ifdef WIN32
    WSACleanup();
#endif

    return true;
}
Exemple #18
0
int main(int argc, char **argv)
{
	int mode;
	int address;
	char *psFileName;
	FILE *file;
	char pbEEPROM[XBOX_EEPROM_SIZE];
	int status;

	// Parse the command line.
	if (argc >= 2)
	{
		// Check for the read/write argument.
		if (FindCommendLineArg(argc, argv, "-r") != 0)
			mode = MODE_READ;
		else if (FindCommendLineArg(argc, argv, "-w") != 0)
			mode = MODE_WRITE;
		else if (FindCommendLineArg(argc, argv, "-e") != 0)
			mode = MODE_ERASE;

		// Check for the address argument.
		if (FindCommendLineArg(argc, argv, "-a") != 0)
		{
			// Get the address argument value.
			const char *psAddress = FindCommndLineArgValue(argc, argv, "-a");

			// Check that the argument value is not the last argument in the command line.
			if (mode != MODE_ERASE && psAddress == argv[argc - 1])
			{
				// Invalid arguments provided.
				PrintUse();
				return 0;
			}

			// Convert the I2C address to an integer.
			address = strtol(psAddress, NULL, 16);
		}
		else
		{
			// Use the default xbox EEPROM chip address.
			address = XBOX_EEPROM_ADDRESS;
		}

		// Check if we are in erase mode or not.
		if (mode != MODE_ERASE)
		{
			// The last argument is the EEPROM file name.
			psFileName = argv[argc - 1];
		}
	}
	else
	{
		// Invalid arguments provided.
		PrintUse();
		return 0;
	}

	// Print the program banner.
	PrintBanner();

	// Try to open the EEPROM dump file that was provided.
	if (mode == MODE_READ)
		file = fopen(psFileName, "w");
	else if (mode == MODE_WRITE)
		file = fopen(psFileName, "r");

	// Check that the file handle is valid.
	if (mode != MODE_ERASE && file == NULL)
	{
		printf("Error opening file \"%s\"!\n");
		goto Cleanup;
	}

	// Initialize the broadcom processor.
    if (!bcm2835_init())
	{
		printf("Failed to initialize bcm!\n");
		return 1;
	}

	// Initialize the I2C interface.
	XboxI2C_Init();

	// Check if we are reading or writing and handle accordingly.
	if (mode == MODE_READ)
	{
		// Read the EEPROM data from the chip.
		printf("Reading EEPROM data from address 0x%02x...\n", address);
		status = XboxI2C_ReadEEPROM((char)address, pbEEPROM);
		if (status != 0)
		{
			// An error occured while reading the EEPROM chip.
			printf("Error reading EEPROM data %d!\n", status);
			goto Cleanup;
		}

		// Write the data to file.
		printf("Writing EEPROM data to file...\n");
		status = fwrite(pbEEPROM, 1, XBOX_EEPROM_SIZE, file);
		if (status != XBOX_EEPROM_SIZE)
		{
			// Error writing the EEPROM to file.
			printf("Error writing EEPROM to file!\n");
			fclose(file);
			goto Cleanup;
		}

		// Close the file.
		fclose(file);

		// Successfully dumped the EEPROM to file.
		printf("Successfully dumped EEPROM!\n");
		status = 0;
	}
	else if (mode == MODE_WRITE)
	{
		// Read the EEPROM buffer from the file.
		printf("Reading EEPROM from file...\n");
		status = fread(pbEEPROM, 1, XBOX_EEPROM_SIZE, file);
		if (status != XBOX_EEPROM_SIZE)
		{
			// Error reading the EEPROM image from file.
			printf("Error reading EEPROM from file!\n");
			goto Cleanup;
		}

		// Close the file.
		fclose(file);

		// Write the EEPROM data to the console.
		printf("Writing to EEPROM at address 0x%02x...\n", address);
		status = XboxI2C_WriteEEPROM((char)address, pbEEPROM);
		if (status != 0)
		{
			// An error occured while writing the EEPROM data to the chip.
			printf("Error writing EEPROM data %d!\n", status);
			goto Cleanup;
		}

		// Successfully wrote the EEPROM.
		printf("Successfully wrote EEPROM!\n");
		status = 0;
	}
	else if (mode == MODE_ERASE)
	{
		// Initialize the EEPROM data to all 00s.
		memset(pbEEPROM, 0, XBOX_EEPROM_SIZE);

		// Write the EEPROM data to the console.
		printf("Writing to EEPROM at address 0x%02x...\n", address);
		status = XboxI2C_WriteEEPROM((char)address, pbEEPROM);
		if (status != 0)
		{
			// An error occured while writing the EEPROM data to the chip.
			printf("Error writing EEPROM data %d!\n", status);
			goto Cleanup;
		}

		// Successfully erased the EEPROM.
		printf("Successfully erased EEPROM!\n");
		status = 0;
	}

Cleanup:
	// Cleanup the I2C interface.
	XboxI2C_Cleanup();

	return status;
}
Exemple #19
0
int main(int argc, char **argv)
{
	char *wadfile;
	char *prefix = "";
	FILE *file;
	wadinfo_t hdr;
	lumpinfo_t info;
	fname_t *it;
	int c;
	char lumpbase[4];
	int direc_size, direc_offset;

	PrintBanner();
	if (argc < 2 || argc > 3)
	{
		PrintUsage();
		return 0;
	}
	wadfile = argv[1];
	if (argc > 2) prefix = argv[2];

    srand((unsigned int)time(0));
	rand();
	rand();

	// First compile the list of all file names.
	InitList();
	printf("Collecting files...\n");
	CollectFiles("");	
	printf("Creating WAD file %s...\n", wadfile);
	if ((file = fopen(wadfile, "wb")) == NULL)
	{
		printf("Couldn't open %s.\n", wadfile);
		perror("Error");
		goto stop_now;
	}

	// The header.
	hdr.identification[0] = 'P';
	hdr.identification[1] = 'W';
	hdr.identification[2] = 'A';
	hdr.identification[3] = 'D';
	hdr.numlumps = CountList() + 1;
	hdr.infotableofs = 0; // We've no idea yet.
	fwrite(&hdr, sizeof(hdr), 1, file);

	// Write all the files.
	sprintf(lumpbase, "%c%c", 'A' + rand() % 26, 'A' + rand() % 26);
	for (it = root.next, c = 0; it != &root; it = it->next, c++)
	{
		it->offset = ftell(file);
		if (!CopyToStream(file, it)) 
		{
			perror(it->path);
			goto stop_now;
		}
		printf("%s\n", it->path);
		sprintf(it->lump, "__%s%04X", lumpbase, c);			
	}

	// Write DD_DIREC. 
	direc_offset = ftell(file);
	for (it = root.next; it != &root; it = it->next)
		fprintf(file, "%s %s%s\n", it->lump, prefix, it->path);
	direc_size = ftell(file) - direc_offset;
	
	// Time to write the info table.
	hdr.infotableofs = ftell(file);
	for (it = root.next, c = 0; it != &root; it = it->next, c++)
	{
		memset(&info, 0, sizeof(info));
		info.filepos = it->offset;
		info.size = it->size;
		memcpy(info.name, it->lump, 8);
		fwrite(&info, sizeof(info), 1, file);
	}
	// Finally DD_DIREC's entry.
	info.filepos = direc_offset;
	info.size = direc_size;
	strncpy(info.name, "DD_DIREC", 8);
	fwrite(&info, sizeof(info), 1, file);

	// Rewrite the header.
	rewind(file);
	fwrite(&hdr, sizeof(hdr), 1, file);
	
	// We're done!
	fclose(file);
stop_now:
	DestroyList();
	return 0;
}
Exemple #20
0
int Initialize (int argc, char *argv[])
{
/*---*/PrintLog ("Initializing data\n");
gameData.time.xGameTotal = 0;
signal (SIGABRT, D2SignalHandler);
signal (SIGFPE, D2SignalHandler);
signal (SIGILL, D2SignalHandler);
signal (SIGINT, D2SignalHandler);
signal (SIGSEGV, D2SignalHandler);
signal (SIGTERM, D2SignalHandler);
#ifdef _WIN32
SDL_SetSpecialKeyHandling (0);
#endif
hogFileManager.Init ("", "");
InitGameStates ();
gameData.Init ();
InitExtraGameInfo ();
InitNetworkData ();
InitGameOptions (0);
InitArgs (argc, argv);
GetAppFolders ();
if (FindArg ("-debug-printlog") || FindArg ("-printlog")) {
	   char fnErr [FILENAME_LEN];
#ifdef __unix__
	sprintf (fnErr, "%s/d2x.log", getenv ("HOME"));
	fErr = fopen (fnErr, "wt");
#else
	sprintf (fnErr, "%s/d2x.log", gameFolders.szGameDir);
	fErr = fopen (fnErr, "wt");
#endif
	}
PrintLog ("%s\n", DESCENT_VERSION);
InitArgs (argc, argv);
GetAppFolders ();
#ifdef D2X_MEM_HANDLER
MemInit ();
#endif
error_init (NULL, NULL);
*szAutoHogFile =
*szAutoMission = '\0';
EvalArgs ();
InitGameOptions (1);
DefaultAllSettings ();
gameOpts->render.nMathFormat = gameOpts->render.nDefMathFormat;
/*---*/PrintLog ("Loading text resources\n");
/*---*/PrintLog ("Loading main hog file\n");
if (!(hogFileManager.Init ("descent2.hog", gameFolders.szDataDir) || 
	  (gameStates.app.bDemoData = hogFileManager.Init ("d2demo.hog", gameFolders.szDataDir)))) {
	/*---*/PrintLog ("Descent 2 data not found\n");
	Error (TXT_NO_HOG2);
	}
LoadGameTexts ();
/*---*/PrintLog ("Reading configuration file\n");
ReadConfigFile ();
if (!InitGraphics ())
	return 1;
console.Setup (SMALL_FONT, &screen, CON_NUM_LINES, 0, 0, screen.Width (), screen.Height () / 2);
if (gameStates.app.bProgressBars && gameOpts->menus.nStyle)
	InitializeGauge ();
else {
	CMenu m (1);
	int key = 0;
	m.AddGauge ("", -1, 1000); // dummy for InitializePoll()
	messageBox.Show (TXT_INITIALIZING);
	for (loadOp = 0; loadOp < InitGaugeSize (); )
		InitializePoll (m, key, 0, 0);
	}
messageBox.Clear ();
PrintBanner ();
if (!gameStates.app.bAutoRunMission) {
	/*---*/PrintLog ("Showing title screens\n");
	if (!ShowTitleScreens ())
		ShowLoadingScreen ();
	}
if (FindArg ("-norun"))
	return 0;
/*---*/PrintLog ("Loading hires models\n");
LoadHiresModels (0);
LoadModelData ();
ogl.InitShaders (); //required for some menus to show all possible choices
return 0;
}
/**********************************************************************
 *  main()
 *
 **********************************************************************/
int main(int argc, char **argv) {
  const char* lang = "eng";
  const char* image = NULL;
  const char* outputbase = NULL;
  const char* datapath = NULL;
  bool list_langs = false;
  bool print_parameters = false;
  GenericVector<STRING> vars_vec, vars_values;
  int arg_i = 1;
  tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO;

  ParseArgs(argc, argv,
          &lang, &image, &outputbase, &datapath,
          &list_langs, &print_parameters,
          &vars_vec, &vars_values, &arg_i, &pagesegmode);

  bool banner = false;
  if (outputbase != NULL && strcmp(outputbase, "-") &&
      strcmp(outputbase, "stdout")) {
    banner = true;
  }

  PERF_COUNT_START("Tesseract:main")
  tesseract::TessBaseAPI api;

  api.SetOutputName(outputbase);

  int init_failed = api.Init(datapath, lang, tesseract::OEM_DEFAULT,
                &(argv[arg_i]), argc - arg_i, &vars_vec, &vars_values, false);
  if (init_failed) {
    fprintf(stderr, "Could not initialize tesseract.\n");
    exit(1);
  }

  SetVariablesFromCLArgs(&api, argc, argv);

  if (list_langs) {
     PrintLangsList(&api);
     exit(0);
  }

  if (print_parameters) {
     FILE* fout = stdout;
     fprintf(stdout, "Tesseract parameters:\n");
     api.PrintVariables(fout);
     api.End();
     exit(0);
  }

  FixPageSegMode(&api, pagesegmode);

  if (pagesegmode == tesseract::PSM_AUTO_ONLY) {
    int ret_val = 0;

    Pix* pixs = pixRead(image);
    if (!pixs) {
      fprintf(stderr, "Cannot open input file: %s\n", image);
      exit(2);
    }

    api.SetImage(pixs);

    tesseract::Orientation orientation;
    tesseract::WritingDirection direction;
    tesseract::TextlineOrder order;
    float deskew_angle;

    tesseract::PageIterator* it =  api.AnalyseLayout();
    if (it) {
      it->Orientation(&orientation, &direction, &order, &deskew_angle);
      tprintf("Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n" \
             "Deskew angle: %.4f\n",
              orientation, direction, order, deskew_angle);
    } else {
      ret_val = 1;
    }

    delete it;

    pixDestroy(&pixs);
    exit(ret_val);
  }

  // set in_training_mode to true when using one of these configs:
  // ambigs.train, box.train, box.train.stderr, linebox, rebox
  bool b = false;
  bool in_training_mode =
        (api.GetBoolVariable("tessedit_ambigs_training", &b) && b) ||
        (api.GetBoolVariable("tessedit_resegment_from_boxes", &b) && b) ||
        (api.GetBoolVariable("tessedit_make_boxes_from_boxes", &b) && b);

  tesseract::PointerVector<tesseract::TessResultRenderer> renderers;



  if (in_training_mode) {
    renderers.push_back(NULL);
  } else {
    PreloadRenderers(&api, &renderers, pagesegmode, outputbase);
  }

  if (!renderers.empty()) {
    if (banner) PrintBanner();
    bool succeed = api.ProcessPages(image, NULL, 0, renderers[0]);
    if (!succeed) {
      fprintf(stderr, "Error during processing.\n");
      exit(1);
    }
  }

  PERF_COUNT_END
  return 0;                      // Normal exit
}
Exemple #22
0
int main(int argc, char** argv) {
  const char* lang = "eng";
  const char* image = NULL;
  const char* outputbase = NULL;
  const char* datapath = NULL;
  bool list_langs = false;
  bool print_parameters = false;
  int arg_i = 1;
  tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO;
  tesseract::OcrEngineMode enginemode = tesseract::OEM_DEFAULT;
  /* main() calls functions like ParseArgs which call exit().
   * This results in memory leaks if vars_vec and vars_values are
   * declared as auto variables (destructor is not called then). */
  static GenericVector<STRING> vars_vec;
  static GenericVector<STRING> vars_values;

#if !defined(DEBUG)
  // Disable debugging and informational messages from Leptonica.
  setMsgSeverity(L_SEVERITY_WARNING);
#endif

#if defined(HAVE_TIFFIO_H) && defined(_WIN32)
  /* Show libtiff warnings on console (not in GUI). */
  TIFFSetWarningHandler(Win32WarningHandler);
#endif /* HAVE_TIFFIO_H &&  _WIN32 */

  ParseArgs(argc, argv, &lang, &image, &outputbase, &datapath, &list_langs,
            &print_parameters, &vars_vec, &vars_values, &arg_i, &pagesegmode,
            &enginemode);

  bool banner = false;
  if (outputbase != NULL && strcmp(outputbase, "-") &&
      strcmp(outputbase, "stdout")) {
    banner = true;
  }

  PERF_COUNT_START("Tesseract:main")
  tesseract::TessBaseAPI api;

  api.SetOutputName(outputbase);

  int init_failed = api.Init(datapath, lang, enginemode, &(argv[arg_i]),
                             argc - arg_i, &vars_vec, &vars_values, false);
  if (init_failed) {
    fprintf(stderr, "Could not initialize tesseract.\n");
    exit(1);
  }

  SetVariablesFromCLArgs(&api, argc, argv);

  if (list_langs) {
    PrintLangsList(&api);
    exit(0);
  }

  if (print_parameters) {
     FILE* fout = stdout;
     fprintf(stdout, "Tesseract parameters:\n");
     api.PrintVariables(fout);
     api.End();
     exit(0);
  }

  FixPageSegMode(&api, pagesegmode);

  if (pagesegmode == tesseract::PSM_AUTO_ONLY) {
    int ret_val = 0;

    Pix* pixs = pixRead(image);
    if (!pixs) {
      fprintf(stderr, "Cannot open input file: %s\n", image);
      exit(2);
    }

    api.SetImage(pixs);

    tesseract::Orientation orientation;
    tesseract::WritingDirection direction;
    tesseract::TextlineOrder order;
    float deskew_angle;

    tesseract::PageIterator* it = api.AnalyseLayout();
    if (it) {
      it->Orientation(&orientation, &direction, &order, &deskew_angle);
      tprintf(
          "Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n"
          "Deskew angle: %.4f\n",
          orientation, direction, order, deskew_angle);
    } else {
      ret_val = 1;
    }

    delete it;

    pixDestroy(&pixs);
    exit(ret_val);
  }

  // set in_training_mode to true when using one of these configs:
  // ambigs.train, box.train, box.train.stderr, linebox, rebox
  bool b = false;
  bool in_training_mode =
      (api.GetBoolVariable("tessedit_ambigs_training", &b) && b) ||
      (api.GetBoolVariable("tessedit_resegment_from_boxes", &b) && b) ||
      (api.GetBoolVariable("tessedit_make_boxes_from_boxes", &b) && b);

  tesseract::PointerVector<tesseract::TessResultRenderer> renderers;

  if (in_training_mode) {
    renderers.push_back(NULL);
  } else {
    PreloadRenderers(&api, &renderers, pagesegmode, outputbase);
  }

  if (!renderers.empty()) {
    if (banner) PrintBanner();
    bool succeed = api.ProcessPages(image, NULL, 0, renderers[0]);
    if (!succeed) {
      fprintf(stderr, "Error during processing.\n");
      exit(1);
    }
  }

  PERF_COUNT_END
  return 0;                      // Normal exit
}
Exemple #23
0
//
// D_DoomMain
//
void D_DoomMain (void)
{
    int             p;
    char            file[256];
    char            demolumpname[9];

    M_FindResponseFile ();

    // Undocumented "search for IWADs" parameter used by the setup
    // tool.

    if (M_CheckParm("-findiwads") > 0)
    {
        D_FindInstalledIWADs();
    }

    // print banner

    PrintBanner(PACKAGE_STRING);

    DEH_printf("Z_Init: Init zone memory allocation daemon. \n");
    Z_Init ();

#ifdef FEATURE_MULTIPLAYER
    //!
    // @category net
    //
    // Start a dedicated server, routing packets but not participating
    // in the game itself.
    //

    if (M_CheckParm("-dedicated") > 0)
    {
        printf("Dedicated server mode.\n");
        NET_DedicatedServer();

        // Never returns
    }

    //!
    // @category net
    //
    // Query the Internet master server for a global list of active
    // servers.
    //

    if (M_CheckParm("-search"))
    {
        printf("\nSearching for servers on Internet ...\n");
        p = NET_MasterQuery(NET_QueryPrintCallback, NULL);
        printf("\n%i server(s) found.\n", p);
        exit(0);
    }

    //!
    // @arg <address>
    // @category net
    //
    // Query the status of the server running on the given IP
    // address.
    //

    p = M_CheckParmWithArgs("-query", 1);

    if (p)
    {
        NET_QueryAddress(myargv[p+1]);
        exit(0);
    }

    //!
    // @category net
    //
    // Search the local LAN for running servers.
    //

    if (M_CheckParm("-localsearch"))
    {
        printf("\nSearching for servers on local LAN ...\n");
        p = NET_LANQuery(NET_QueryPrintCallback, NULL);
        printf("\n%i server(s) found.\n", p);
        exit(0);
    }

#endif
            
#ifdef FEATURE_DEHACKED
    printf("DEH_Init: Init Dehacked support.\n");
    DEH_Init();
#endif

    iwadfile = D_FindIWAD();
// *** PID BEGIN ***
    psdoom1wad = D_FindWADByName("psdoom1.wad");
    psdoom2wad = D_FindWADByName("psdoom2.wad");
// *** PID END ***

    // None found?

    if (iwadfile == NULL)
    {
        I_Error("Game mode indeterminate.  No IWAD file was found.  Try\n"
                "specifying one with the '-iwad' command line parameter.\n");
    }

    modifiedgame = false;

    //!
    // @vanilla
    //
    // Disable monsters.
    //
	
    nomonsters = M_CheckParm ("-nomonsters");

// This keeps a 'no monsters' that is persistant across new games
// and level warps.
    if ( (nomonstersperiod = M_CheckParm("-nomonsters.") ) ) {
       nomonsters = true;
    }

// This makes items respawn as in -altdeath (ie. no dropped items,
// no invis, no invun)
    respawnitems = M_CheckParm("-respawnitems");

    //!
    // @vanilla
    //
    // Monsters respawn after being killed.
    //

    respawnparm = M_CheckParm ("-respawn");

    //!
    // @vanilla
    //
    // Monsters move faster.
    //

    fastparm = M_CheckParm ("-fast");

    //! 
    // @vanilla
    //
    // Developer mode.  F1 saves a screenshot in the current working
    // directory.
    //

    devparm = M_CheckParm ("-devparm");

    //!
    // @category net
    // @vanilla
    //
    // Start a deathmatch game.
    //

    if (M_CheckParm ("-deathmatch"))
	deathmatch = 1;

    //!
    // @category net
    // @vanilla
    //
    // Start a deathmatch 2.0 game.  Weapons do not stay in place and
    // all items respawn after 30 seconds.
    //

    if (M_CheckParm ("-altdeath"))
	deathmatch = 2;

    if (devparm)
	DEH_printf(D_DEVSTR);
    
    // find which dir to use for config files

    M_SetConfigDir();
    
    //!
    // @arg <x>
    // @vanilla
    //
    // Turbo mode.  The player's speed is multiplied by x%.  If unspecified,
    // x defaults to 200.  Values are rounded up to 10 and down to 400.
    //

    if ( (p=M_CheckParm ("-turbo")) )
    {
	int     scale = 200;
	extern int forwardmove[2];
	extern int sidemove[2];
	
	if (p<myargc-1)
	    scale = atoi (myargv[p+1]);
	if (scale < 10)
	    scale = 10;
	if (scale > 400)
	    scale = 400;
        DEH_printf("turbo scale: %i%%\n", scale);
	forwardmove[0] = forwardmove[0]*scale/100;
	forwardmove[1] = forwardmove[1]*scale/100;
	sidemove[0] = sidemove[0]*scale/100;
	sidemove[1] = sidemove[1]*scale/100;
    }
    
    // init subsystems
    DEH_printf("V_Init: allocate screens.\n");
    V_Init ();

    DEH_printf("M_LoadDefaults: Load system defaults.\n");
    M_ApplyPlatformDefaults();
    M_LoadDefaults ();              // load before initing other systems

    DEH_printf("W_Init: Init WADfiles.\n");
    D_AddFile(iwadfile);
   
// *** PID BEGIN ***
// If the command-line flag to suppress auto-loading of custom
// ps management levels is *not* there, load the appropriate level.
    p = M_CheckParm ("-nopslev");
    if (p)
    {
// Add psdoom1.wad if this is registered (Doom 1) or retail (Ultimite Doom).
// If we loaded it, set the flag to true so we can place the monsters in the
// correct positions.
		if ( gamemode == registered || gamemode == retail ){
			D_AddFile(iwadfile);
			ps_level_loaded = true;
		}
// Add psdoom2.wad if this is commercial (Doom 2) and not an add-on pack.
// If we loaded it, set the flag to true so we can place the monsters in the
// correct positions.
		if ( gamemode == commercial && gamemission == doom2 ) {
			D_AddFile(iwadfile);
			ps_level_loaded = true;
		}
    }
// *** PID END ***
 

#ifdef FEATURE_WAD_MERGE

    // Merged PWADs are loaded first, because they are supposed to be 
    // modified IWADs.

    //!
    // @arg <files>
    // @category mod
    //
    // Simulates the behavior of deutex's -merge option, merging a PWAD
    // into the main IWAD.  Multiple files may be specified.
    //

    p = M_CheckParmWithArgs("-merge", 1);

    if (p > 0)
    {
        for (p = p + 1; p<myargc && myargv[p][0] != '-'; ++p)
        {
            char *filename;

            filename = D_TryFindWADByName(myargv[p]);

            printf(" merging %s\n", filename);
            W_MergeFile(filename);
        }
    }

    // NWT-style merging:

    // NWT's -merge option:

    //!
    // @arg <files>
    // @category mod
    //
    // Simulates the behavior of NWT's -merge option.  Multiple files
    // may be specified.

    p = M_CheckParmWithArgs("-nwtmerge", 1);

    if (p > 0)
    {
        for (p = p + 1; p<myargc && myargv[p][0] != '-'; ++p)
        {
            char *filename;

            filename = D_TryFindWADByName(myargv[p]);

            printf(" performing NWT-style merge of %s\n", filename);
            W_NWTDashMerge(filename);
        }
    }
    
    // Add flats

    //!
    // @arg <files>
    // @category mod
    //
    // Simulates the behavior of NWT's -af option, merging flats into
    // the main IWAD directory.  Multiple files may be specified.
    //

    p = M_CheckParmWithArgs("-af", 1);

    if (p > 0)
    {
        for (p = p + 1; p<myargc && myargv[p][0] != '-'; ++p)
        {
            char *filename;

            filename = D_TryFindWADByName(myargv[p]);

            printf(" merging flats from %s\n", filename);
            W_NWTMergeFile(filename, W_NWT_MERGE_FLATS);
        }
    }

    //!
    // @arg <files>
    // @category mod
    //
    // Simulates the behavior of NWT's -as option, merging sprites
    // into the main IWAD directory.  Multiple files may be specified.
    //

    p = M_CheckParmWithArgs("-as", 1);

    if (p > 0)
    {
        for (p = p + 1; p<myargc && myargv[p][0] != '-'; ++p)
        {
            char *filename;

            filename = D_TryFindWADByName(myargv[p]);

            printf(" merging sprites from %s\n", filename);
            W_NWTMergeFile(filename, W_NWT_MERGE_SPRITES);
        }
    }

    //!
    // @arg <files>
    // @category mod
    //
    // Equivalent to "-af <files> -as <files>".
    //

    p = M_CheckParmWithArgs("-aa", 1);

    if (p > 0)
    {
        for (p = p + 1; p<myargc && myargv[p][0] != '-'; ++p)
        {
            char *filename;

            filename = D_TryFindWADByName(myargv[p]);

            printf(" merging sprites and flats from %s\n", filename);
            W_NWTMergeFile(filename, W_NWT_MERGE_SPRITES | W_NWT_MERGE_FLATS);
        }
    }

#endif

    //!
    // @arg <files>
    // @vanilla
    //
    // Load the specified PWAD files.
    //

    p = M_CheckParmWithArgs("-file", 1);
    if (p)
    {
	// the parms after p are wadfile/lump names,
	// until end of parms or another - preceded parm
	modifiedgame = true;            // homebrew levels
	while (++p != myargc && myargv[p][0] != '-')
        {
            char *filename;

            filename = D_TryFindWADByName(myargv[p]);

	    D_AddFile(filename);
        }
    }

    // Debug:
//    W_PrintDirectory();

    //!
    // @arg <demo>
    // @category demo
    // @vanilla
    //
    // Play back the demo named demo.lmp.
    //

    p = M_CheckParmWithArgs ("-playdemo", 1);

    if (!p)
    {
        //!
        // @arg <demo>
        // @category demo
        // @vanilla
        //
        // Play back the demo named demo.lmp, determining the framerate
        // of the screen.
        //
	p = M_CheckParmWithArgs("-timedemo", 1);

    }

    if (p)
    {
        if (!strcasecmp(myargv[p+1] + strlen(myargv[p+1]) - 4, ".lmp"))
        {
            strcpy(file, myargv[p + 1]);
        }
        else
        {
	    sprintf (file,"%s.lmp", myargv[p+1]);
        }

	if (D_AddFile (file))
        {
            strncpy(demolumpname, lumpinfo[numlumps - 1].name, 8);
            demolumpname[8] = '\0';

            printf("Playing demo %s.\n", file);
        }
        else
        {
            // If file failed to load, still continue trying to play
            // the demo in the same way as Vanilla Doom.  This makes
            // tricks like "-playdemo demo1" possible.

            strncpy(demolumpname, myargv[p + 1], 8);
            demolumpname[8] = '\0';
        }

    }

    // Generate the WAD hash table.  Speed things up a bit.

    W_GenerateHashTable();
    
    D_IdentifyVersion();
    InitGameVersion();
    LoadChexDeh();
    LoadHacxDeh();
    D_SetGameDescription();
    D_SetSaveGameDir();

    // Check for -file in shareware
    if (modifiedgame)
    {
	// These are the lumps that will be checked in IWAD,
	// if any one is not present, execution will be aborted.
	char name[23][8]=
	{
	    "e2m1","e2m2","e2m3","e2m4","e2m5","e2m6","e2m7","e2m8","e2m9",
	    "e3m1","e3m3","e3m3","e3m4","e3m5","e3m6","e3m7","e3m8","e3m9",
	    "dphoof","bfgga0","heada1","cybra1","spida1d1"
	};
	int i;
	
	if ( gamemode == shareware)
	    I_Error(DEH_String("\nYou cannot -file with the shareware "
			       "version. Register!"));

	// Check for fake IWAD with right name,
	// but w/o all the lumps of the registered version. 
	if (gamemode == registered)
	    for (i = 0;i < 23; i++)
		if (W_CheckNumForName(name[i])<0)
		    I_Error(DEH_String("\nThis is not the registered version."));
    }
    
    // get skill / episode / map from parms
    startskill = sk_medium;
    startepisode = 1;
    startmap = 1;
    autostart = false;

    //!
    // @arg <skill>
    // @vanilla
    //
    // Set the game skill, 1-5 (1: easiest, 5: hardest).  A skill of
    // 0 disables all monsters.
    //

    p = M_CheckParmWithArgs("-skill", 1);

    if (p)
    {
	startskill = myargv[p+1][0]-'1';
	autostart = true;
    }

    //!
    // @arg <n>
    // @vanilla
    //
    // Start playing on episode n (1-4)
    //

    p = M_CheckParmWithArgs("-episode", 1);

    if (p)
    {
	startepisode = myargv[p+1][0]-'0';
	startmap = 1;
	autostart = true;
    }
	
    timelimit = 0;

    //! 
    // @arg <n>
    // @category net
    // @vanilla
    //
    // For multiplayer games: exit each level after n minutes.
    //

    p = M_CheckParmWithArgs("-timer", 1);

    if (p)
    {
	timelimit = atoi(myargv[p+1]);
    }

    //!
    // @category net
    // @vanilla
    //
    // Austin Virtual Gaming: end levels after 20 minutes.
    //

    p = M_CheckParm ("-avg");

    if (p)
    {
	timelimit = 20;
    }

    //!
    // @arg [<x> <y> | <xy>]
    // @vanilla
    //
    // Start a game immediately, warping to ExMy (Doom 1) or MAPxy
    // (Doom 2)
    //

    p = M_CheckParmWithArgs("-warp", 1);

    if (p)
    {
        if (gamemode == commercial)
            startmap = atoi (myargv[p+1]);
        else
        {
            startepisode = myargv[p+1][0]-'0';

            if (p + 2 < myargc)
            {
                startmap = myargv[p+2][0]-'0';
            }
            else
            {
                startmap = 1;
            }
        }
        autostart = true;
    }

    // Undocumented:
    // Invoked by setup to test the controls.

    p = M_CheckParm("-testcontrols");

    if (p > 0)
    {
        startepisode = 1;
        startmap = 1;
        autostart = true;
        testcontrols = true;
    }

    // Check for load game parameter
    // We do this here and save the slot number, so that the network code
    // can override it or send the load slot to other players.

    //!
    // @arg <s>
    // @vanilla
    //
    // Load the game in slot s.
    //

    p = M_CheckParmWithArgs("-loadgame", 1);
    
    if (p)
    {
        startloadgame = atoi(myargv[p+1]);
    }
    else
    {
        // Not loading a game
        startloadgame = -1;
    }

    //!
    // @category video
    //
    // Disable vertical mouse movement.
    //

    if (M_CheckParm("-novert"))
        novert = true;

    //!
    // @category video
    //
    // Enable vertical mouse movement.
    //

    if (M_CheckParm("-nonovert"))
        novert = false;

    if (W_CheckNumForName("SS_START") >= 0
     || W_CheckNumForName("FF_END") >= 0)
    {
        printf ("===========================================================================\n");
        printf(" WARNING: The loaded WAD file contains modified sprites or\n"
               " floor textures.  You may want to use the '-merge' command\n"
               " line option instead of '-file'.\n");
    }
    
    printf ("===========================================================================\n");

    PrintBanner(gamedescription);

    
    printf (
	    "===========================================================================\n"
	    " " PACKAGE_NAME " is free software, covered by the GNU General Public\n"
            " License.  There is NO warranty; not even for MERCHANTABILITY or FITNESS\n"
            " FOR A PARTICULAR PURPOSE. You are welcome to change and distribute\n"
            " copies under certain conditions. See the source for more information.\n"

	    "===========================================================================\n"
	);

    PrintDehackedBanners();

    DEH_printf("M_Init: Init miscellaneous info.\n");
    M_Init ();

    DEH_printf("R_Init: Init DOOM refresh daemon - ");
    R_Init ();

    DEH_printf("\nP_Init: Init Playloop state.\n");
    P_Init ();

    DEH_printf("I_Init: Setting up machine state.\n");
    I_Init ();

#ifdef FEATURE_MULTIPLAYER
    printf ("NET_Init: Init network subsystem.\n");
    NET_Init ();
#endif

    DEH_printf("S_Init: Setting up sound.\n");
    S_Init (sfxVolume * 8, musicVolume * 8);

    DEH_printf("D_CheckNetGame: Checking network game status.\n");
    D_CheckNetGame ();

    PrintGameVersion();

    DEH_printf("HU_Init: Setting up heads up display.\n");
    HU_Init ();

    DEH_printf("ST_Init: Init status bar.\n");
    ST_Init ();

    // If Doom II without a MAP01 lump, this is a store demo.  
    // Moved this here so that MAP01 isn't constantly looked up
    // in the main loop.

    if (gamemode == commercial && W_CheckNumForName("map01") < 0)
        storedemo = true;

    //!
    // @arg <x>
    // @category demo
    // @vanilla
    //
    // Record a demo named x.lmp.
    //

    p = M_CheckParmWithArgs("-record", 1);

    if (p)
    {
	G_RecordDemo (myargv[p+1]);
	autostart = true;
    }

    p = M_CheckParmWithArgs("-playdemo", 1);
    if (p)
    {
	singledemo = true;              // quit after one demo
	G_DeferedPlayDemo (demolumpname);
	D_DoomLoop ();  // never returns
    }
	
    p = M_CheckParmWithArgs("-timedemo", 1);
    if (p)
    {
	G_TimeDemo (demolumpname);
	D_DoomLoop ();  // never returns
    }
	
    if (startloadgame >= 0)
    {
        strcpy(file, P_SaveGameFile(startloadgame));
	G_LoadGame (file);
    }
	
    if (gameaction != ga_loadgame )
    {
	if (autostart || netgame)
	    G_InitNew (startskill, startepisode, startmap);
	else
	    D_StartTitle ();                // start up intro loop
    }

    D_DoomLoop ();  // never returns
}
Exemple #24
0
BOOL RecursiveIsMember(IADsGroup * pADsGroup,LPWSTR pwszMemberGUID,LPWSTR pwszMemberPath, 
                                             BOOL bVerbose, LPOLESTR  pwszUser, LPOLESTR pwszPassword)
{
    HRESULT         hr                = S_OK;     // COM Result Code
    IADsMembers *   pADsMembers       = NULL;     // Ptr to Members of the IADsGroup
    BOOL            fContinue         = TRUE;     // Looping Variable
    IEnumVARIANT *  pEnumVariant      = NULL;     // Ptr to the Enum variant
    IUnknown *      pUnknown          = NULL;     // IUnknown for getting the ENUM initially
    VARIANT         VariantArray[FETCH_NUM];      // Variant array for temp holding returned data
    ULONG           ulElementsFetched = NULL;     // Number of elements retrieved
    BSTR            bsGroupPath       = NULL;
    BOOL            bRet              = FALSE;

    if(!pADsGroup || !pwszMemberGUID || !pwszMemberPath)
    {
        return FALSE;
    }
 
    // Get the path of the object passed in
    hr = pADsGroup->get_ADsPath(&bsGroupPath);
 
    if (!SUCCEEDED(hr))
        return hr;
 
    if (bVerbose)
    {
        WCHAR pwszOutput[2048];
        wsprintf(pwszOutput,L"Checking the Group:\n\n%s\n\n for the member:\n\n%s\n\n",bsGroupPath,pwszMemberPath);
        PrintBanner(pwszOutput);
    }
 
    // Get an interface pointer to the IADsCollection of members
    hr = pADsGroup->Members(&pADsMembers);
 
    if (SUCCEEDED(hr))
    {
        // Query the IADsCollection of members for a new ENUM Interface
        // Be aware that the enum comes back as an IUnknown *
        hr = pADsMembers->get__NewEnum(&pUnknown);
 
        if (SUCCEEDED(hr))
        {
            // QI the IUnknown * for an IEnumVARIANT interface
            hr = pUnknown->QueryInterface(IID_IEnumVARIANT, (void **)&pEnumVariant);
 
            if (SUCCEEDED(hr))
            {
                // While have not hit errors or end of data....
                while (fContinue) 
                {
                   ulElementsFetched = 0;
                    // Get a "batch" number of group members-number of rows specified by FETCH_NUM
                    hr = ADsEnumerateNext(pEnumVariant, FETCH_NUM, VariantArray, &ulElementsFetched);
 
                    if (ulElementsFetched )
                    {
                        // Loop through the current batch-printing the path for each member.
                        for (ULONG i = 0; i < ulElementsFetched; i++ ) 
                        {
                            IDispatch * pDispatch         = NULL; // ptr for holding dispath of element
                            BSTR        bstrCurrentPath   = NULL; // Holds path of object
                            BSTR        bstrGuidCurrent   = NULL; // Holds path of object
                            IDirectoryObject * pIDOCurrent = NULL;// Holds the current object          
 
                            // Get the dispatch ptr for the variant
                            pDispatch = VariantArray[i].pdispVal;
//                            assert(HAS_BIT_STYLE(VariantArray[i].vt,VT_DISPATCH));
 
                            // Get the IADs interface for the "member" of this group
                            hr = pDispatch->QueryInterface(IID_IDirectoryObject,
                                                           (VOID **) &pIDOCurrent ) ;
 
                            if (SUCCEEDED(hr))
                            {
                                // Get the GUID for the current object
                                hr = GetObjectGuid(pIDOCurrent,bstrGuidCurrent);
 
                                if (FAILED(hr))
                                    return hr;
 
                                IADs * pIADsCurrent = NULL;
 
                                // Retrieve the IADs Interface for the current object
                                hr = pIDOCurrent->QueryInterface(IID_IADs,(void**)&pIADsCurrent);
                                if (FAILED(hr))
                                    return hr;
 
                                // Get the ADsPath property for this member
                                hr = pIADsCurrent->get_ADsPath(&bstrCurrentPath);
 
                                if (SUCCEEDED(hr))
                                {
                                    if (bVerbose)
                                        wprintf(L"Comparing:\n\n%s\nWITH:\n%s\n\n",bstrGuidCurrent,pwszMemberGUID);
                                    
                                    // Verify that the member of this group is Equal to passed.
                                    if (_wcsicmp(bstrGuidCurrent,pwszMemberGUID)==0)
                                    {
                                        if (bVerbose)
                                            wprintf(L"!!!!!Object:\n\n%s\n\nIs a member of\n\n%s\n\n",pwszMemberPath,bstrGuidCurrent);   
 
                                        bRet = TRUE;
                                        break;
                                    }
                                    else // Otherwise, bind to this and see if it is a group.
                                    {    // If is it a group then the QI to IADsGroup succeeds
                                        
                                        IADsGroup * pIADsGroupAsMember = NULL;
                                        
                                        if (pwszUser)
                                            hr = ADsOpenObject( bstrCurrentPath,
                                                                pwszUser, 
                                                                pwszPassword, 
                                                                ADS_SECURE_AUTHENTICATION,
                                                                IID_IADsGroup, 
                                                                (void**) &pIADsGroupAsMember);
                                        else
                                            hr = ADsGetObject( bstrCurrentPath, IID_IADsGroup,(void **)&pIADsGroupAsMember);
 
                                        // If bind was completed, then this is a group.
                                        if (SUCCEEDED(hr))
                                        {
                                            // Recursively call this group to verify this group.
                                            BOOL bRetRecurse;
                                            bRetRecurse = RecursiveIsMember(pIADsGroupAsMember,pwszMemberGUID,pwszMemberPath,bVerbose,pwszUser ,pwszPassword );
                                            
                                            if (bRetRecurse)
                                            {
                                                bRet = TRUE;
                                                break;
                                            }
                                            pIADsGroupAsMember->Release();
                                            pIADsGroupAsMember = NULL;
                                        }
                                    }
                                    SysFreeString(bstrCurrentPath);
                                    bstrCurrentPath = NULL;
 
                                    SysFreeString(bstrGuidCurrent);
                                    bstrGuidCurrent = NULL;
                                }
                                // Release
                                pIDOCurrent->Release();
                                pIDOCurrent = NULL;
                                if (pIADsCurrent)
                                {
                                    pIADsCurrent->Release();
                                    pIADsCurrent = NULL;
                                }
                            }
                         }
                        // Clear the variant array.
                        memset(VariantArray, 0, sizeof(VARIANT)*FETCH_NUM);
                    }
                    else
                        fContinue = FALSE;
                }
                pEnumVariant->Release();
                pEnumVariant = NULL;
            }
            pUnknown->Release();
            pUnknown = NULL;
        }
        pADsMembers ->Release();
        pADsMembers  = NULL;
    }
 
    // Free the group path if retrieved.
    if (bsGroupPath)
    {
        SysFreeString(bsGroupPath);
        bsGroupPath = NULL;
    }
    return bRet;
}
Exemple #25
0
//
// Function	: _tmain
// Role		: Entry point to application
// Notes	: 
//
int _tmain(int argc, _TCHAR* argv[])
{
	
	int	chOpt;
	int	intOptHelp=0, intOptPrintNetDevs=0, intOptInDir=0, intOptOutDir=0, intOptNet=0;
	int	intOptTempDir=0, intOptConfig=0;

	// Extract all the options
	while ((chOpt = getopt(argc, argv, _T("c:f:n:i:o:t:l:v:dhp"))) != EOF) 
	switch(chOpt)
	{
		case _T('f'): // PCAP filter
			break;
		case _T('d'): // Debugging Mode
			bDebug=true;
			break;
		case _T('v'): // Verbose Mode
			bVerbose=true;
			intVerboseLvl=_wtol(optarg);
			break;
		case _T('l'): // Log File
			bLog=true;
			strLogFile=optarg;
			break;
		case _T('i'): // In directory
			intOptInDir=1;
			strInDir=optarg;
			break;
		case _T('o'): // Out directory
			intOptOutDir=1;
			strOutDir=optarg;
			break;
		case _T('n'): // Network device to sniff
			intOptNet=1;
			intNetDevice=_wtol(optarg);
			break;
		case _T('t'): // Temp directory
			intOptTempDir=1;
			strTempDir=optarg;
			break;
		case _T('c'): // Config files
			intOptConfig=1;
			strConfFile=optarg;
			break;
		case _T('h'): // Help
			intOptHelp=1;
			break;
		case _T('p'): // Print network devices
			intOptPrintNetDevs=1;
			break;
		default:
			fwprintf(stderr,L"[!] No handler - %c\n", chOpt);
			break;
	}

	// Print the banner
	PrintBanner();

	// Just print and exit
	if(intOptPrintNetDevs) PrintNetworkDeviceList();

	// Input validation
	if((!intOptInDir || !intOptOutDir || !intOptTempDir || !intOptNet) && !intOptConfig) {
		if(!intOptInDir) fprintf(stderr,"[!] Need to specify the input directory OR configuration file\n");
		if(!intOptOutDir) fprintf(stderr,"[!] Need to specify the output directory OR configuration file\n");
		if(!intOptTempDir) fprintf(stderr,"[!] Need to specify the temporary directory OR configuration file\n");
		if(!intOptNet) fprintf(stderr,"[!] Need to specify the network interface to use OR configuration file\n");
		fprintf(stderr,"\n");
		PrintHelp(argv[0]);
	}

	// Print help if required
	if(intOptHelp) PrintHelp(argv[0]);

	

	// Print some flag status
	if(!bDebug) fwprintf(stdout,L"[i] Debugging: Off\n"); 
	else fwprintf(stdout,L"[i] Debugging: On\n");
	if(!bVerbose) fwprintf(stdout,L"[i] Verbose: Off\n"); 
	else fwprintf(stdout,L"[i] Verbose: On (Level %u)\n",intVerboseLvl);
	if(intOptInDir)   fwprintf(stdout,L"[i] Input Directory : %s\n",strInDir);
    if(intOptOutDir)  fwprintf(stdout,L"[i] Output Directory: %s\n",strOutDir);
	if(intOptTempDir) fwprintf(stdout,L"[i] Temporary Directory: %s\n",strTempDir);

	// Get the required privs
	if(SetPrivilege(GetCurrentProcess(),L"SeLoadDriverPrivilege")){
		fwprintf(stdout,L"[*] Privilege obtained - SeLoadDriverPrivilege\n");
	} else{
		fwprintf(stderr,L"[!] Failed to obtain privilege - SeLoadDriverPrivilege\n");
		return 1;
	}

	// Get some Windows privs - needs to be run as administrator / 
	// be granted these as required
	if(SetPrivilege(GetCurrentProcess(),L"SeDebugPrivilege")){
		fwprintf(stdout,L"[*] Privilege obtained - SeDebugPrivilege\n");
	} else{
		fwprintf(stderr,L"[!] Failed to obtain privilege - SeDebugPrivilege\n");
		return 1;
	}

	// Open the log file if required
	if(bVerbose && intVerboseLvl >= 5) fwprintf(stdout,L"[i] Log file chosen %s..\n",strLogFile);
    if(bLog && strLogFile!=NULL){
		if(OpenLog(strLogFile)){
			fwprintf(stdout,L"[*] Log file opened\n");
		} else {
			fwprintf(stderr,L"[!] Failed to open log file '%s' - !\n",strLogFile);
			return 1;
		}
	}


	// Call the main engine (vrrrrm!!)
	if(WhiteboxEngine()!=0){
		wbprintf(1,"[!] Engine suffered an unrecoverable error!\n");
		return 1;
	} else {
		wbprintf(0,"[!] Engine exited cleanly..\n");
	}

	//Close the log file if required
	if(bLog && fileLog!=NULL){
		if(CloseLog()){
			fwprintf(stdout,L"[*] Log file closed\n");
		} else {
			fwprintf(stderr,L"[!] Failed to close log file '%s' - !\n",strLogFile);
		}
	}

		
	return 0;
}
Exemple #26
0
/*
================
SV_SpawnServer

Change the server to a new map, taking all connected
clients along with it.
This is NOT called for map_restart
================
*/
void SV_SpawnServer( const char *server )
{
	int        i;
	bool   isBot;

	// shut down the existing game if it is running
	SV_ShutdownGameProgs();

	PrintBanner( "Server Initialization" )
	Com_Printf( "Server: %s\n", server );

	// clear the whole hunk because we're (re)loading the server
	Hunk_Clear();

	// if not running a dedicated server CL_MapLoading will connect the client to the server
	// also print some status stuff
	CL_MapLoading();

	// clear collision map data
	CM_ClearMap();

	// wipe the entire per-level structure
	SV_ClearServer();

	// allocate empty config strings
	for ( i = 0; i < MAX_CONFIGSTRINGS; i++ )
	{
		sv.configstrings[ i ] = CopyString( "" );
		sv.configstringsmodified[ i ] = false;
	}

	// init client structures and svs.numSnapshotEntities
	if ( !Cvar_VariableValue( "sv_running" ) )
	{
		SV_Startup();
	}
	else
	{
		// check for maxclients change
		if ( sv_maxclients->modified )
		{
			SV_ChangeMaxClients();
		}
	}

	// allocate the snapshot entities on the hunk
	svs.snapshotEntities = ( entityState_t * ) Hunk_Alloc( sizeof( entityState_t ) * svs.numSnapshotEntities, h_high );
	svs.nextSnapshotEntities = 0;

	// toggle the server bit so clients can detect that a
	// server has changed
	svs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT;

	// set sv_nextmap to the same map, but it may be overridden
	// by the game startup or another console command
	Cvar_Set( "sv_nextmap", "map_restart 0" );

	// make sure we are not paused
	Cvar_Set( "cl_paused", "0" );

	// get a new checksum feed and restart the file system
	srand( Sys_Milliseconds() );
	sv.checksumFeed = ( ( rand() << 16 ) ^ rand() ) ^ Sys_Milliseconds();

	FS::PakPath::ClearPaks();
	FS_LoadBasePak();
	if (!FS_LoadPak(va("map-%s", server)))
		Com_Error(ERR_DROP, "Could not load map pak\n");

	CM_LoadMap(server);

	// set serverinfo visible name
	Cvar_Set( "mapname", server );

	// serverid should be different each time
	sv.serverId = com_frameTime;
	sv.restartedServerId = sv.serverId;
	Cvar_Set( "sv_serverid", va( "%i", sv.serverId ) );

	// media configstring setting should be done during
	// the loading stage, so connected clients don't have
	// to load during actual gameplay
	sv.state = SS_LOADING;

	// load and spawn all other entities
	SV_InitGameProgs();

	// run a few frames to allow everything to settle
	for ( i = 0; i < GAME_INIT_FRAMES; i++ )
	{
		gvm.GameRunFrame( sv.time );
		svs.time += FRAMETIME;
		sv.time += FRAMETIME;
	}

	// create a baseline for more efficient communications
	SV_CreateBaseline();

	for ( i = 0; i < sv_maxclients->integer; i++ )
	{
		// send the new gamestate to all connected clients
		if ( svs.clients[ i ].state >= CS_CONNECTED )
		{
			bool denied;
			char reason[ MAX_STRING_CHARS ];

			isBot = SV_IsBot(&svs.clients[i]);

			// connect the client again
			denied = gvm.GameClientConnect( reason, sizeof( reason ), i, false, isBot );   // firstTime = false

			if ( denied )
			{
				// this generally shouldn't happen, because the client
				// was connected before the level change
				SV_DropClient( &svs.clients[ i ], reason );
			}
			else
			{
				if ( !isBot )
				{
					// when we get the next packet from a connected client,
					// the new gamestate will be sent
					svs.clients[ i ].state = CS_CONNECTED;
				}
				else
				{
					client_t       *client;
					sharedEntity_t *ent;

					client = &svs.clients[ i ];
					client->state = CS_ACTIVE;
					ent = SV_GentityNum( i );
					ent->s.number = i;
					client->gentity = ent;

					client->deltaMessage = -1;
					client->nextSnapshotTime = svs.time; // generate a snapshot immediately

					gvm.GameClientBegin( i );
				}
			}
		}
	}

	// run another frame to allow things to look at all the players
	gvm.GameRunFrame( sv.time );
	svs.time += FRAMETIME;
	sv.time += FRAMETIME;

	// the server sends these to the clients so they can figure
	// out which pk3s should be auto-downloaded

	Cvar_Set( "sv_paks", FS_LoadedPaks() );

	// save systeminfo and serverinfo strings
	cvar_modifiedFlags &= ~CVAR_SYSTEMINFO;
	SV_SetConfigstring( CS_SYSTEMINFO, Cvar_InfoString( CVAR_SYSTEMINFO, true ) );

	SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO, false ) );
	cvar_modifiedFlags &= ~CVAR_SERVERINFO;

	// any media configstring setting now should issue a warning
	// and any configstring changes should be reliably transmitted
	// to all clients
	sv.state = SS_GAME;

	// send a heartbeat now so the master will get up to date info
	SV_Heartbeat_f();

	Hunk_SetMark();

	SV_UpdateConfigStrings();

	SV_AddOperatorCommands();

	Com_Printf( "-----------------------------------\n" );
}
Exemple #27
0
// Main Initialization
int wmain (int argc, wchar_t **argv)
{
    vector<wstring>       Drives;
    vector<Defragment *> Defrags;
    DefragType           DefragMode = DefragInvalid;

    PrintBanner ();

    // Parse command line arguments
    bool ValidCmdLine = false;
    for (int c = 0; c < argc; c++)
    {
        if (wcslen(argv[c]) == 2  &&  argv[c][1] == L':')
        {
            Drives.push_back (wcsupr(argv[c]));
        }
        else
        if (argv[c][0] == L'-'  ||  argv[c][0] == L'/'  &&  wcslen(argv[c]) == 2)
        {
            switch (tolower(argv[c][1]))
            {
                case L'?' :
                case L'h' :
                    FraggerHelp ();
                    return (0);

                case L'f' :
                    if (DefragMode != DefragInvalid)
                    {
                        ValidCmdLine = false;
                        break;
                    }
                    DefragMode = DefragFast;
                    ValidCmdLine = true;
                    break;

                case L'e' :
                    if (DefragMode != DefragInvalid)
                    {
                        ValidCmdLine = false;
                        break;
                    }
                    DefragMode = DefragExtensive;
                    ValidCmdLine = true;
                    break;

            }
        }
    }

    if (DefragMode == DefragInvalid)
        ValidCmdLine = false;

    if (!ValidCmdLine)
    {
        wprintf (L"Invalid command-line options. Use '%s -?' for help.\n", argv[0]);
        return (0);
    }

    // Check OS requirements
    if (!CheckWinVer())
    {
        wprintf (L"Fatal Error: This program requires Windows 2000.\n");
        return (0);
    }

	for (size_t d = 0; d < Drives.size (); d++)
    {
        HANDLE TossMe;
        Defrags.push_back (StartDefragThread (Drives[d], DefragMode, TossMe));
    }

    for (size_t d = 0; d < Drives.size () - 1; d++)
        wprintf (L"\n ");

    bool Continue = true;
    HANDLE Screen;

    Screen = GetStdHandle (STD_OUTPUT_HANDLE);
    while (Continue)
    {
        Sleep (25);

        // Get current screen coords
        CONSOLE_SCREEN_BUFFER_INFO ScreenInfo;

        GetConsoleScreenBufferInfo (Screen, &ScreenInfo);

        // Now set back to the beginning
        ScreenInfo.dwCursorPosition.X = 0;
        ScreenInfo.dwCursorPosition.Y -= Drives.size();
        SetConsoleCursorPosition (Screen, ScreenInfo.dwCursorPosition);

        for (size_t d = 0; d < Drives.size (); d++)
        {
            wprintf (L"\n%6.2f%% %-70s", Defrags[d]->GetStatusPercent(), Defrags[d]->GetStatusString().c_str());
        }

        // Determine if we should keep going
        Continue = false;
        for (size_t d = 0; d < Drives.size (); d++)
        {
            if (!Defrags[d]->IsDoneYet()  &&  !Defrags[d]->HasError())
                Continue = true;
        }
    }

#if 0
    // Loop through the drives list
    for (int d = 0; d < Drives.size(); d++)
    {
        DriveVolume *Drive;

        Drive = new DriveVolume;

        // First thing: build a file list.
        wprintf (L"Opening volume %s ...", Drives[d].c_str());
        if (!Drive->Open (Drives[d]))
        {
            wprintf (L"FAILED\n\n");
            delete Drive;
            continue;
        }
        wprintf (L"\n");

        wprintf (L"    Getting drive bitmap ...");
        if (!Drive->GetBitmap ())
        {
            wprintf (L"FAILED\n\n");
            delete Drive;
            continue;
        }
        wprintf (L"\n");

        wprintf (L"    Obtaining drive geometry ...");
        if (!Drive->ObtainInfo ())
        {
            wprintf (L"FAILED\n\n");
            delete Drive;
            continue;
        }
        wprintf (L"\n");

        wprintf (L"    Building file database for drive %s ...", Drives[d].c_str());
        if (!Drive->BuildFileList ())
        {
            wprintf (L"FAILED\n\n");
            delete Drive;
            continue;
        }
        wprintf (L"\n");

        wprintf (L"    %u files\n", Drive->GetDBFileCount ());

        // Analyze only?
        if (DefragMode == DefragAnalyze)
        {
            uint64 UsedBytes  = 0;  // total bytes used, with cluster size considerations
            uint64 TotalBytes = 0;  // total bytes used
            uint64 SlackBytes = 0;  // wasted space due to slack
            uint32 Fragged    = 0;  // fragmented files

            wprintf (L"    Analyzing ...");
            if (VerboseMode)
                wprintf (L"\n");

            for (int i = 0; i < Drive->GetDBFileCount(); i++)
            {
                uint64 Used;
                uint64 Slack;
                FileInfo Info;

                Info = Drive->GetDBFile (i);

                // Compute total used disk space
                Used = ((Info.Size + Drive->GetClusterSize() - 1) / Drive->GetClusterSize()) * Drive->GetClusterSize();
                Slack = Used - Info.Size;

                UsedBytes += Used;
                SlackBytes += Slack;
                TotalBytes += Info.Size;

                if (VerboseMode)
                {
                    wprintf (L"    %s%s, ", Drive->GetDBDir (Info.DirIndice).c_str(), Info.Name.c_str());

                    if (Info.Attributes.AccessDenied)
                        wprintf (L"access was denied\n");
                    else
                    {
                        if (Info.Attributes.Unmovable == 1)
                            wprintf (L"unmovable, ");

                        wprintf (L"%I64u bytes, %I64u bytes on disk, %I64u bytes slack, %u fragments\n",
                            Info.Size, Used, Slack, Info.Fragments.size());
                    }
                }

                if (Info.Fragments.size() > 1)
                    Fragged++;
            }

            if (!VerboseMode)
                wprintf (L"\n");

            // TODO: Make it not look like ass
            wprintf (L"\n");
            wprintf (L"    Overall Analysis\n");
            wprintf (L"    ----------------\n");
            wprintf (L"    %u clusters\n", Drive->GetClusterCount ());
            wprintf (L"    %u bytes per cluster\n", Drive->GetClusterSize());
            wprintf (L"    %I64u total bytes on drive\n", (uint64)Drive->GetClusterCount() * (uint64)Drive->GetClusterSize());
            wprintf (L"\n");
            wprintf (L"    %u files\n", Drive->GetDBFileCount ());
            wprintf (L"    %u contiguous files\n", Drive->GetDBFileCount () - Fragged);
            wprintf (L"    %u fragmented files\n", Fragged);
            wprintf (L"\n");
            wprintf (L"    %I64u bytes\n", TotalBytes);
            wprintf (L"    %I64u bytes on disk\n", UsedBytes);
            wprintf (L"    %I64u bytes slack\n", SlackBytes);
        }

        // Fast defragment!
        if (DefragMode == DefragFast  ||  DefragMode == DefragExtensive)
        {
            uint32 i;
            uint64 FirstFreeLCN;
            wchar_t PrintName[80];
            int Width = 66;

            if (DefragMode == DefragFast)
                wprintf (L"    Performing fast file defragmentation ...\n");
            else
            if (DefragMode == DefragExtensive)
                wprintf (L"    Performing extensive file defragmentation\n");

            // Find first free LCN for speedier searches ...
            Drive->FindFreeRange (0, 1, FirstFreeLCN);

            for (i = 0; i < Drive->GetDBFileCount(); i++)
            {
                FileInfo Info;
                bool Result;
                uint64 TargetLCN;

                wprintf (L"\r");

                Info = Drive->GetDBFile (i);

                FitName (PrintName, Drive->GetDBDir (Info.DirIndice).c_str(), Info.Name.c_str(), Width);
                wprintf (L"    %6.2f%% %-66s", (float)i / (float)Drive->GetDBFileCount() * 100.0f, PrintName);

                // Can't defrag 0 byte files :)
                if (Info.Fragments.size() == 0)
                    continue;

                // If doing fast defrag, skip non-fragmented files
                if (Info.Fragments.size() == 1  &&  DefragMode == DefragFast)
                    continue;

                // Find a place that can fit the file
                Result = Drive->FindFreeRange (FirstFreeLCN, Info.Clusters, TargetLCN);

                // If we're doing an extensive defrag and the file is already defragmented
                // and if its new location would be after its current location, don't
                // move it.
                if (DefragMode == DefragExtensive  &&  Info.Fragments.size() == 1)
                {
                    if (TargetLCN > Info.Fragments[0].StartLCN)
                        continue;
                }

                // Otherwise, defrag0rize it!
                if (Result)
                {
                    bool Success = false;

                    if (Drive->MoveFileDumb (i, TargetLCN))
                        Success = true;
                    else
                    {   // hmm, look for another area to move it to
                        Result = Drive->FindFreeRange (TargetLCN + 1, Info.Clusters, TargetLCN);
                        if (Result)
                        {
                            if (Drive->MoveFileDumb (i, TargetLCN))
                                Success = true;
                            else
                            {   // Try updating the drive bitmap
                                if (Drive->GetBitmap ())
                                {
                                    Result = Drive->FindFreeRange (0, Info.Clusters, TargetLCN);
                                    if (Result)
                                    {
                                        if (Drive->MoveFileDumb (i, TargetLCN))
                                            Success = true;
                                    }
                                }
                            }
                        }
                    }

                    if (!Success)
                        wprintf (L"\n        -> failed\n");

                    Drive->FindFreeRange (0, 1, FirstFreeLCN);
                }
            }

            wprintf (L"\n");
        }
        wprintf (L"Closing volume %s ...", Drives[d].c_str());
        delete Drive;
        wprintf (L"\n");
    }
#endif

    return (0);
}
Exemple #28
0
void
StartOS (AppModeType mode)
{
  /* Set application mode */
  sdvos_appmode = mode;

  /*
   * Initialize the MCU we are using. This involves low
   * level initialization which usually at least include
   * a stack switch after disabling interrupts globally for
   * initialization. It is OK because StartOS will never
   * return and we already processed the parameter.
   * Procedures after this call will be carried out in
   * SDVOS kernel context.
   *
   * McuInit can either be a C function, assembly function
   * or a macro on different platforms.
   */
  McuInit ();

  /*
   * Board specific initialization. Might include clock
   * configuration, flash setup, etc.
   */
  BoardInit ();

  /* Initialize Interrupt Handling */
  InterruptInit ();

  /* Initialize all the drivers configured */
  DriversInit ();

  /* Activate auto start tasks */
  TaskAutoStart (sdvos_appmode);

  /* Initialize Alarm/Counter */
  AlarmInit ();

#ifdef USE_SCHEDTBL
  /*
   * Initialize schedule table. This is mostly schedule
   * table auto start. And it has to be done after task
   * and alarm auto start. [SWS_Os_00510]
   */
  ScheduleTableInit ();
#endif

  /*
   * StartupHook is called by the OS at the end of the
   * initialization and before the scheduler is running.
   */
  STARTUPHOOK ();

#ifdef DEBUG_SDVOS_VERBOSE
  IntegrityCheck ();
#endif

#ifdef PRINT_BANNER
  PrintBanner ();
#endif

  DEBUG_PRINTF ("Starting SDVOS in mode %d...\n", sdvos_appmode);

  /* Switch to the first user task */
  JumpNext ();

  /* Should never reach here */
  return;
}