예제 #1
0
ITDrawModelWidget::ITDrawModelWidget(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	initWidget();
	readIniFile();
}
예제 #2
0
void MainWindow::slotFileOpt()
{
int ret,cnt,i;

  if(opt.arg_debug) printf("slotFileOpt\n");
  DlgOpt *dlg = new DlgOpt(this);
  dlg->setWindowTitle("pvbrowser options");
  dlg->setFilename(inifile());
  if(opt.arg_debug) printf("slotFileOpt before dlg->exec()\n");
  ret = dlg->exec();
  if(opt.arg_debug) printf("slotFileOpt after dlg->exec() ret=%d\n", ret);
  if(ret == QDialog::Accepted)
  {
    cnt = urlComboBox->count();
    for(i=0; i<cnt; i++)
    {
      urlComboBox->removeItem(0);
    }
    readIniFile();
    for(i=0; i<MAX_TABS; i++)
    {
      pvbtab[i].interpreter.temp = opt.temp;
    }
    readHosts();
  }
  delete dlg;
}
예제 #3
0
void setDefaultEval() {

    setBasicValues();
    setSquaresNearKing();
    setPcsq();
    readIniFile();
    correctValues();
}
예제 #4
0
int main(int argc, const char * argv[])
{
    struct TDCMopts opts;
    readIniFile(&opts, argv);
#ifdef mydebugtest
    //strcpy(opts.indir, "/Users/rorden/desktop/sliceOrder/dicom2/Philips_PARREC_Rotation/NoRotation/DBIEX_4_1.PAR");
     strcpy(opts.indir, "/Users/rorden/desktop/sliceOrder/dicom2/test");
#else
    printf("Chris Rorden's dcm2niiX version %s\n",kDCMvers);
    if (argc < 2) {
        showHelp(argv, opts);
        return 0;
    }
    strcpy(opts.indir,argv[argc-1]);
    strcpy(opts.outdir,opts.indir);
    int i = 1;
    int lastCommandArg = -1;
    while (i < (argc)) { //-1 as final parameter is DICOM directory
        if ((strlen(argv[i]) > 1) && (argv[i][0] == '-')) { //command
            if (argv[i][1] == 'h')
                showHelp(argv, opts);
            else if ((argv[i][1] == 'z') && ((i+1) < argc)) {
                i++;
                if ((argv[i][0] == 'i') || (argv[i][0] == 'I') ) {
                    opts.isGz = true; //force use of internal compression instead of pigz
                	strcpy(opts.pigzname,"");
                } else if ((argv[i][0] == 'n') || (argv[i][0] == 'N')  || (argv[i][0] == '0'))
                    opts.isGz = false;
                else
                    opts.isGz = true;
            } else if ((argv[i][1] == 'f') && ((i+1) < argc)) {
                i++;
                strcpy(opts.filename,argv[i]);
            } else if ((argv[i][1] == 'o') && ((i+1) < argc)) {
                i++;
                strcpy(opts.outdir,argv[i]);
            }
            lastCommandArg = i;
            
        } //if parameter is a command
        i ++; //read next parameter
    } //while parameters to read
    //printf("%d %d",argc,lastCommandArg);
    if (argc == (lastCommandArg+1))  { //+1 as array indexed from 0
        //the user did not provide an input filename, report filename structure
        char niiFilename[1024];
        strcpy(opts.outdir,"");//no input supplied
        nii_createDummyFilename(niiFilename, opts);
        printf("%s\n",niiFilename);
        return EXIT_SUCCESS;
    }
#endif
    clock_t start = clock();
    nii_loadDir(&opts);
    printf ("Conversion required %f seconds.\n",((float)(clock()-start))/CLOCKS_PER_SEC);
    saveIniFile(opts);
    return EXIT_SUCCESS;
}
예제 #5
0
파일: main.cpp 프로젝트: pvbrowser/pvb
int main(int argc, char *argv[])
{
    setlocale(LC_NUMERIC, "C");
    getargs(argc,argv);
    setDefaultOptions();
    readIniFile();

    Q_INIT_RESOURCE(pvdevelop);

    QApplication app(argc, argv);
    setlocale(LC_NUMERIC, "C");
    perhapsDoAction();
    QIcon appIcon(":/images/app.png");
    app.setWindowIcon(appIcon);
    MainWindow mainWin;
    mainWin.showMaximized();
    if(opt_develop.murx) QDir::setCurrent("/home/lehrig/temp/murx");
    return app.exec();
}
예제 #6
0
MainWindow::MainWindow()
{
  const char *cptr;
  int i;

#ifdef BROWSERPLUGIN
  pvbinit();
#endif

  isReconnect = 0;
#ifndef NO_WEBKIT  
  textbrowser = NULL;
#endif  
  tabToolBar  = NULL;
  maxfd = currentTab = numTabs = 0;
  for(i=0; i<MAX_TABS; i++)
  {
    pvbtab[i].s          = -1;        // socket
    pvbtab[i].in_use     = 0;         // tab is currently not used
    pvbtab[i].w          = 1280;      // default width
    pvbtab[i].h          = 1024;      // default height
    pvbtab[i].pvsVersion = 0x0040600; // last version of pvserver that does not send version
    pvbtab[i].rootWidget = NULL;
    pvbtab[i].hasLayout  = 0;
    for(int ii=0; ii<MAX_DOCK_WIDGETS; ii++) 
    {
      pvbtab[i].dock[ii] = NULL;
    }  
  }

  cptr = readIniFile();
  if(cptr != NULL)
  {
    QMessageBox::warning(NULL,"MainWindow","readIniFile ERROR: terminating ...");
    printf("readIniFile ERROR=%s\n",cptr);
    exit(-1);
  }
  if(opt.appfontsize > 0) // intoduced june 2012 for android application font setting
  {
    //QFont f = qApp->font();
    //f.setPointSize(opt.appfontsize);
    //qApp->setFont(f);
    QFont f = QApplication::font();
    f.setPointSize(opt.appfontsize);
    QApplication::setFont(f);
  }

  createActions();
  createToolBars();
  createMenus();
  createStatusBar();
  if(opt.menubar   == 0) menuBar()->hide();
  if(opt.toolbar   == 0) fileToolBar->hide();
  if(opt.statusbar == 0) statusBar()->hide();
  tcp_init();

  setCurrentFile("");
  readHosts();

  semaphore.release();
  mythread.pv = this;
  // slow_start_on_windows mythread.start();
  // there is a problem within the firefox plugin on windows
  // we do not get enough CPU time there
  // no problem on linux
  // we get more CPU time if we continiously move the mouse over the widget
  // problem not solved jet
#ifdef BROWSERPLUGIN
  mythread.start(QThread::HighestPriority); // this does not help also
#endif

  // setup watchdog
  timer = new QTimer();
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()));
  // moved timer start to end of this method  because show may need longer on mobile devices  timer->start(1000*10);

  if(opt.arg_host[0] != '\0') url = opt.arg_host;
  else                        url = opt.initialhost;
  add_host(url.toUtf8());

  if(opt.arg_x != -1 && opt.arg_y != -1 && opt.arg_w != -1 && opt.arg_h != -1)
  {
    setGeometry(opt.arg_x,opt.arg_y, opt.arg_w,opt.arg_h);
  }
  else if(opt.fullscreen)
  {
    showFullScreen();
  }
  else if(opt.maximized)
  {
    showMaximized();
  }
  else
  {
    resize(800,600);
  }

  if(opt.cursor_shape >= 0)
  {
    QApplication::restoreOverrideCursor();
    QApplication::setOverrideCursor(QCursor((Qt::CursorShape) opt.cursor_shape));
  }  

// delay textbrowser for speedup starting on windows  
// loading the help file is damn slow on windows
// thus we delay this operation until help is really needed
//QMessageBox::information(this,"pvbrowser","step begin",1);
//  textbrowser = new dlgTextBrowser;
//QMessageBox::information(this,"pvbrowser","step end",1);
  setFocus(Qt::MouseFocusReason);
#ifdef BROWSERPLUGIN
  QApplication::setActiveWindow(this); // now we will get keyboard events
#endif
  busyWidget = new QPushButton(this);
  busyWidget->setIcon(QIcon(":images/app.png"));
  busyWidgetTimer = new QTimer(this);
  busyWidgetTimer->setSingleShot(true);
  connect(busyWidgetTimer,SIGNAL(timeout()),this,SLOT(slotBusyWidgetTimeout()));
  timer->start(1000*10);
}
예제 #7
0
int main( int argc, _TCHAR* argv[] )
{
    _TCHAR*  errorMsg;
    _TCHAR*  program;
    _TCHAR*  iniFile;
    _TCHAR*  ch;
    _TCHAR** configArgv = NULL;
    int 	 configArgc = 0;
    int      exitCode = 0;
    int      ret = 0;
    void *	 handle = 0;
    RunMethod 		runMethod;
    SetInitialArgs  setArgs;

    setlocale(LC_ALL, "");

    initialArgc = argc;
    initialArgv = malloc((argc + 1) * sizeof(_TCHAR*));
    memcpy(initialArgv, argv, (argc + 1) * sizeof(_TCHAR*));

    /*
     * Strip off any extroneous <CR> from the last argument. If a shell script
     * on Linux is created in DOS format (lines end with <CR><LF>), the C-shell
     * does not strip off the <CR> and hence the argument is bogus and may
     * not be recognized by the launcher or eclipse itself.
     */
    ch = _tcschr( argv[ argc - 1 ], _T_ECLIPSE('\r') );
    if (ch != NULL)
    {
        *ch = _T_ECLIPSE('\0');
    }

    /* Determine the full pathname of this program. */
    program = findProgram(argv);

    /* Parse configuration file arguments */
    iniFile = checkForIni(argc, argv);
    if (iniFile != NULL)
        ret = readConfigFile(iniFile, &configArgc, &configArgv);
    else
        ret = readIniFile(program, &configArgc, &configArgv);
    if (ret == 0)
    {
        parseArgs (&configArgc, configArgv);
    }

    /* Parse command line arguments           */
    /* Overrides configuration file arguments */
    parseArgs( &argc, argv );

    /* Special case - user arguments specified in the config file
     * are appended to the user arguments passed from the command line.
     */
    if (configArgc > 0)
    {
        createUserArgs(configArgc, configArgv, &argc, &argv);
    }

    /* Initialize official program name */
    officialName = name != NULL ? _tcsdup( name ) : getDefaultOfficialName(program);

    /* Find the directory where the Eclipse program is installed. */
    programDir = getProgramDir(program);

    /* Find the eclipse library */
    eclipseLibrary = findLibrary(eclipseLibrary, program);

    if(eclipseLibrary != NULL)
        handle = loadLibrary(eclipseLibrary);
    if(handle == NULL) {
        errorMsg = malloc( (_tcslen(libraryMsg) + _tcslen(officialName) + 10) * sizeof(_TCHAR) );
        _stprintf( errorMsg, libraryMsg, officialName );
        if (!suppressErrors)
            displayMessage( officialName, errorMsg );
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, errorMsg);
        free( errorMsg );
        exit( 1 );
    }

    setArgs = (SetInitialArgs)findSymbol(handle, SET_INITIAL_ARGS);
    if(setArgs != NULL)
        setArgs(initialArgc, initialArgv, eclipseLibrary);
    else {
        if(!suppressErrors)
            displayMessage(officialName, entryMsg);
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, entryMsg);
        exit(1);
    }

    runMethod = (RunMethod)findSymbol(handle, RUN_METHOD);
    if(runMethod != NULL)
        exitCode = runMethod(argc, argv, userVMarg);
    else {
        if(!suppressErrors)
            displayMessage(officialName, entryMsg);
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, entryMsg);
        exit(1);
    }
    unloadLibrary(handle);

    free( eclipseLibrary );
    free( programDir );
    free( program );
    free( officialName );

    return exitCode;
}
예제 #8
0
int main()
{
	readIniFile();

	IPC_initKeyboard();

	if(drvFlg)
	{
		for (int i = 0; i < driveCnt; i++)
		{
			printf("Data of drive %s will be DESTROYED!!! Continue ?\n", driveName[i]);
			IPC_getch();
		}
	}
	else
	{
		for (int i = 0; i < driveCnt; i++)
		{
			printf("File name is %s\n", fileName[i]);
		}
	}

	LARGE_INTEGER Frequency;
	IPC_TIMEVAL StartPerformCount;
	IPC_TIMEVAL StopPerformCount;
	//IPC_TIMEVAL StartCount;
	//IPC_TIMEVAL StopCount;

	int bHighRes = QueryPerformanceFrequency (&Frequency);

	void* pBuffer[4];
	for (int i = 0; i < driveCnt; i++)
	{
		pBuffer[i] = IPC_virtAlloc(bBufSize);
		if (!pBuffer[i])
		{
			printf("VirtualAlloc() is error!!!\n");
			IPC_getch();
			return -1; // error
		}
	}

	double* pTimes = NULL;
	if(bufStat)
		pTimes = new double[bufCnt];

	IPC_handle hfile[4];

	if(drvFlg)
	{
		for (int i = 0; i < driveCnt; i++)
		{
			hfile[i] = IPC_openFileEx(driveName[i], IPC_OPEN_FILE | IPC_FILE_WRONLY, 0);
		}
	}
	else
	{
		for (int i = 0; i < driveCnt; i++)
		{
			//hfile = IPC_openFile(fileName, IPC_CREATE_FILE | IPC_FILE_WRONLY, FILE_ATTRIBUTE_NORMAL);
			hfile[i] = IPC_openFileEx(fileName[i], IPC_CREATE_FILE | IPC_FILE_WRONLY, IPC_FILE_NOBUFFER);
		}
	}
	for (int i = 0; i < driveCnt; i++)
		if (hfile[i] == INVALID_HANDLE_VALUE)
		{
			printf("CreateFile() is error!!!\n");
			IPC_getch();
			return -1;
		}

	//ULONG nNumberOfWriteBytes;
	
	//double ms_time;
	//IPC_getTime(&StartPerformCount);

	//for(int i = 0; i < bufCnt; i++)
	//{
	//	IPC_getTime(&StartCount);
	//	for (int i = 0; i < driveCnt; i++)
	//	{
	//		IPC_writeFile(hfile[i], pBuffer[i], bBufSize);
	//	}

	//	IPC_getTime(&StopCount);
	//	ms_time = IPC_getDiffTime(&StartCount, &StopCount);
	//	if(bufStat)
	//		pTimes[i] = ms_time;
	//	if(ms_time > max_time)
	//		max_time = ms_time;
	//	printf("Buffer number is %d\r", i);
	//}
	//IPC_getTime(&StopPerformCount);

	IPC_handle hThread[4];
	THREAD_PARAM thread_par[4];

	IPC_getTime(&StartPerformCount);

	for (int i = 0; i < driveCnt; i++)
	{
		thread_par[i].file_handle = hfile[i];
		thread_par[i].idx = i;
		thread_par[i].pBufData = pBuffer[i];
		hThread[i] = IPC_createThread(("WriteFileThread"), &FileWritingThread, &thread_par[i]);

	}
	// Wait until threads terminates
	for (int i = 0; i < driveCnt; i++)
	{
		IPC_waitThread(hThread[i], INFINITE);// Wait until threads terminates
		IPC_deleteThread(hThread[i]);
	}

	IPC_getTime(&StopPerformCount);

	double msTime = IPC_getDiffTime(&StartPerformCount, &StopPerformCount);
	printf("Hard drive(s) write speed is %f(%f) Mbytes/sec\n", ((double)bBufSize * bufCnt / msTime) / 1000.,
									((double)bBufSize * bufCnt * driveCnt / msTime)/1000.);

	printf("Min write (one buffer) speed is %f Mbytes/sec\n", ((double)bBufSize / max_time)/1000.);

	for (int i = 0; i < driveCnt; i++)
	{
		IPC_closeFile(hfile[i]);
		IPC_virtFree(pBuffer[i]);
	}

	if (bufStat)
	{
		//wr_time(pTimes);
		delete[] pTimes;
	}

	IPC_getch();
	IPC_cleanupKeyboard();
	return 0;
}
예제 #9
0
int main(int argc, char *argv[])
{
    int i;

    signal(SIGINT, SIG_IGN);
    setbuf(stdin, NULL);

    // windows only:
    SYSTEM_INFO sysinfo;

    std::cout << KENNY_PROG_VERSION << std::endl;
#ifdef KENNY_DEBUG_PERFT
    std::cout << "KENNY_DEBUG_PERFT defined" << std::endl;
#endif
#ifdef KENNY_DEBUG_MOVES
    std::cout << "KENNY_DEBUG_MOVES defined" << std::endl;
#endif
#ifdef KENNY_VERBOSE_EVAL
    std::cout << "KENNY_VERBOSE_EVAL defined" << std::endl;
#endif
#ifdef KENNY_DEBUG_EVAL
    std::cout << "KENNY_DEBUG_EVAL defined" << std::endl;
#endif
#ifdef KENNY_VERBOSE_SEE
    std::cout << "KENNY_VERBOSE_SEE defined" << std::endl;
#endif
#ifdef KENNY_DEBUG_WINBOARD
    std::cout << "KENNY_DEBUG_WINBOARD defined" << std::endl;
#endif
#ifdef KENNY_CUSTOM_VALUES
    std::cout << "KENNY_CUSTOM_VALUES defined" << std::endl;
#endif
#ifdef KENNY_CUSTOM_POSVALS
    std::cout << "KENNY_CUSTOM_VALUES defined" << std::endl;
#endif
#ifdef KENNY_CUSTOM_PSTABLES
    std::cout << "KENNY_CUSTOM_PSTABLES defined" << std::endl;
#endif
#ifdef KENNY_CUSTOM_ENDGAME
    std::cout << "KENNY_CUSTOM_ENDGAME defined" << std::endl;
#endif

    dataInit();
    board.init();

    // windows only:
    GetSystemInfo(&sysinfo);
    if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
        std::cout << "Version: X86, ";
    else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
        std::cout << "Version: IA64, ";
    else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
        std::cout << "Version: X64, ";
    std::cout << sysinfo.dwNumberOfProcessors << " CPU's (1 CPU used)" << std::endl;
    std::cout << "Search structure = " << sizeof(board)/1024 << "kB" << std::endl;

    // read the initialization file:
    strcpy(PATHNAME, argv[0]);
    strcpy(INIFILE, "KENNYx.ini");  // default name
    // check command-line to see if we need to use another ini-file:
    // usage: "KENNYx.exe i=somefile.ini"
    for (i = 1; i < argc; i++)
    {
        if (!strncmp(argv[i], "i=", 2)) sscanf_s(argv[i]+2,"%s", INIFILE);
    }
    readIniFile();

    std::cout <<  "'help' displays a list of commands" << std::endl;
    commands();

    return 0;
}
예제 #10
0
// ----------------------------------------------------------------------------
//
void DMXStudio::runStudio()
{
    CoInitializeEx( NULL, COINIT_MULTITHREADED );

    srand( (unsigned)time( NULL ) );

    DMXHttpServer server;

    try {
        openStudioLogFile();

        log_status( "DMX Studio v0.8.0 [%s]", __DATE__ );

        readIniFile();

        // Read fixture definitions
        FixtureDefinition::readFixtureDefinitions();

        // Load all available audio capture devices
        AudioInputStream::collectAudioCaptureDevices();

        // Start event bus
        m_event_bus.startThread();
        m_event_bus.addListener( this );

        // Enumerate the IP addresses
        showIpAddress();

        // Create and connect to the music player if available
        if ( m_config.isMusicPlayerEnabled() )
            createMusicPlayer( m_config.getMusicUsername(), m_config.getMusicPlayer() );
        
        // Start the request server
        if ( isHttpEnabled() )
            server.start();

        // Load the default venue
        if ( !DMXStudio::loadVenueFromFile( getDefaultVenueFilename() ) ) {
			log_status( "Cannot open default venue '%s'", getDefaultVenueFilename() );
            m_venue = new Venue();
        }

        // Start the console UI
        DMXTextUI ui;
        ui.run();
    }
    catch ( StudioException& ex ) {
        log( ex );
        getchar();
    }
    catch ( std::exception& ex ) {
        log( ex );
        getchar();
    }

    if ( isHttpEnabled() )
        server.stop();

    if ( m_venue )
        delete m_venue;

    m_event_bus.stopThread();

    if ( hasMusicPlayer() ) {
        getMusicPlayer()->unregisterEventListener( this );

        if ( getMusicPlayer()->isLoaded() )
            getMusicPlayer()->disconnect( );
    }

    closeStudioLogFile();

    //writeIniFile();

    CoUninitialize();
}
예제 #11
0
void commands()
{

// ================================================================
// commands is used to read console input and execute the commands
// It also serves as winboard driver. 
// The code is based on H.G. Muller's model WinBoard protocol driver:
// http://www.open-aurec.com/wbforum/viewtopic.php?f=24&t=51739
// =================================================================

	int i, j, number;
	int fenhalfmoveclock;
	int fenfullmovenumber;
	char fen[100];
	char fencolor[1];      
	char fencastling[4];
	char fenenpassant[2];
	char sanMove[12];
	char command[80];
	char userinput[80];
	U64 msStart,msStop, perftcount;
	Timer timer;
	Move move, dummy;

	// =================================================================
	// infinite loop:
	// =================================================================

	while (1) 
	{ 

		fflush(stdout);                 

		// =================================================================
		// think & move
		// =================================================================

		if (XB_MODE)
		{
			if (XB_COMPUTER_SIDE == board.nextMove) 
			{
				#ifdef KENNY_DEBUG_WINBOARD
					std::cout << "#-KENNY : start think" << std::endl;
				#endif
				move = board.think();
				#ifdef KENNY_DEBUG_WINBOARD
					std::cout << "#-KENNY : exit think" << std::endl;
					std::cout << "#<KENNY : move " << SQUARENAME[move.getFrom()] << SQUARENAME[move.getTosq()]  << std::endl;
				#endif
				if (move.moveInt) 
				{
					printf("move "); printf("%s",SQUARENAME[move.getFrom()]); printf("%s",SQUARENAME[move.getTosq()]); 
					if (move.isPromotion()) printf("%s",PIECECHARS[move.getProm()]);
					printf("\n");
					makeMove(move);
					board.endOfGame++;
					board.endOfSearch = board.endOfGame;
				}
			}
			fflush(stdout); 

			// =================================================================
			// ponder
			// =================================================================

			if (XB_COMPUTER_SIDE != XB_NONE && XB_COMPUTER_SIDE != XB_ANALYZE && XB_PONDER && board.endOfGame)
			{
				XB_NO_TIME_LIMIT = true;
				#ifdef KENNY_DEBUG_WINBOARD
					std::cout << "#-KENNY : start ponder" << std::endl;
				#endif
				move = board.think();
				#ifdef KENNY_DEBUG_WINBOARD
					std::cout << "#-KENNY : exit ponder" << std::endl;
				#endif
				XB_NO_TIME_LIMIT = false;
			} 

			// =================================================================
			// analyze
			// =================================================================

			if (XB_COMPUTER_SIDE == XB_ANALYZE)
			{
				XB_NO_TIME_LIMIT = true;
				#ifdef KENNY_DEBUG_WINBOARD
					std::cout << "#-KENNY : start analyze" << std::endl;
				#endif
				move = board.think();
				#ifdef KENNY_DEBUG_WINBOARD
					std::cout << "#-KENNY : exit analyze" << std::endl;
				#endif
				XB_NO_TIME_LIMIT = false;
			} 
		}

noPonder:

		// =================================================================
		// display the command prompt
		// =================================================================

		if (!XB_MODE)
		{
			if (board.nextMove == WHITE_MOVE) std::cout << "wt> ";
			else std::cout << "bl> ";
			fflush(stdout);
		}

		// =================================================================
		// read input, but only after attending a pending command received during 
		// search/ponder/analyze:
		// =================================================================

		if (!XB_DO_PENDING)
		{
			#ifdef KENNY_DEBUG_WINBOARD
				if (XB_MODE)
					std::cout << "#-KENNY : COMPUTER_SIDE=" << (int)XB_COMPUTER_SIDE << " PONDER=" << XB_PONDER << " nextMove=" << (int)board.nextMove << std::endl;
			#endif

			for (CMD_BUFF_COUNT = 0; (CMD_BUFF[CMD_BUFF_COUNT] = getchar()) != '\n'; CMD_BUFF_COUNT++);
			CMD_BUFF[CMD_BUFF_COUNT+1] = '\0';

			#ifdef KENNY_DEBUG_WINBOARD
				if (XB_MODE) std::cout << "#>KENNY : " << CMD_BUFF << std::endl;
			#endif
		}
		#ifdef KENNY_DEBUG_WINBOARD
			else
			{
				if (XB_MODE) std::cout << "#>KENNY : " << CMD_BUFF << " (from peek)" << std::endl;
			}
		#endif
		XB_DO_PENDING = false;
	
		// =================================================================
		// ignore empty lines
		// =================================================================

		if (!CMD_BUFF_COUNT) continue; 

		// =================================================================
		// extract the first word
		// =================================================================

		sscanf(CMD_BUFF, "%s", command);

		// =================================================================
		// help, h or ?: show this help - list of CONSOLE-ONLY COMMANDS
		// =================================================================
		if ((!XB_MODE) && ((!strcmp(command, "help")) || (!strcmp(command, "h")) || (!strcmp(command, "?"))))
		{ 
			std::cout << std::endl << "help:" << std::endl;
			std::cout << "black               : BLACK to move" << std::endl;
			std::cout << "cc                  : play computer-to-computer " << std::endl;
			std::cout << "d                   : display board " << std::endl;
			std::cout << "eval                : show static evaluation of this position" << std::endl;
			std::cout << "exit                : exit program " << std::endl;
			std::cout << "game                : show game moves " << std::endl;
			std::cout << "go                  : computer next move " << std::endl;
			std::cout << "help, h, or ?       : show this help " << std::endl;
			std::cout << "info                : display variables (for testing purposes)" << std::endl;
			std::cout << "ini                 : read the initialization file" << std::endl;
			std::cout << "memory n            : max memory to use (in MB)" << std::endl;
			std::cout << "move e2e4, or h7h8q : enter a move (use this format)" << std::endl;
			std::cout << "moves               : show all legal moves" << std::endl;
			std::cout << "new                 : start new game" << std::endl;
			std::cout << "perft n             : calculate raw number of nodes from here, depth n " << std::endl;
			#ifdef KENNY_VERBOSE_SEE
				std::cout << "qsearch             : shows sorted capture movelist" << std::endl;
			#endif
			std::cout << "quit                : exit program " << std::endl;
			std::cout << "r                   : rotate board " << std::endl;
			std::cout << "readfen filename n  : reads #-th FEN position from filename" << std::endl;
			std::cout << "sd n                : set the search depth to n" << std::endl;
			std::cout << "setup               : setup board... " << std::endl;
			std::cout << "test filename       : starts search on all FEN position in 'filename'" << std::endl;
			std::cout << "                      using current time & search depth parameters" << std::endl;
			std::cout << "                      output is written in test.log" << std::endl;
			std::cout << "time s              : time per move in seconds" << std::endl;
			std::cout << "undo                : take back last move" << std::endl;
			std::cout << "white               : WHITE to move" << std::endl;
			std::cout << std::endl;
			continue; 
		}

		// =================================================================
		// accepted: in reply to the "feature" command
		// =================================================================

		if (XB_MODE && !strcmp(command, "accepted")) continue; 

		// =================================================================
		// analyze: enter analyze mode
		// =================================================================

		if (XB_MODE && !strcmp(command, "analyze")) 
		{ 
			XB_COMPUTER_SIDE = XB_ANALYZE;			
			continue; 
		}

		// =================================================================
		// black: BLACK to move
		// =================================================================

		if (!XB_MODE && !strcmp(command, "black") && board.nextMove == WHITE_MOVE)
		{ 
			board.hashkey ^= KEY.side;
			board.endOfSearch = 0; 
			board.endOfGame = 0;
			board.nextMove = BLACK_MOVE;
			continue; 
		}

		// =================================================================
		// bk: show book moves from this position, if any
		// =================================================================

		if (XB_MODE && !strcmp(command, "bk")) continue; 

		// =================================================================
		// cc: play computer-to-computer
		// =================================================================

		if (!XB_MODE && !strcmp(command, "cc"))    
		{ 
			while (!_kbhit() && !board.isEndOfgame(i, dummy))
			{
				move = board.think();
				if (move.moveInt) 
				{
					makeMove(move);
					board.endOfGame++;
					board.endOfSearch = board.endOfGame;
					board.display();
				}
			}
			continue; 
		}

		// =================================================================
		// computer: the opponent is also a computer chess engine
		// =================================================================

		if (XB_MODE && !strcmp(command, "computer")) continue; 

		// =================================================================
		// cores n: informs the engine on how many CPU cores it is allowed to use maximally
		// =================================================================

		if (XB_MODE && !strcmp(command, "cores")) continue; 

		// =================================================================
		// d: display board
		// =================================================================

		if (!XB_MODE && !strcmp(command, "d"))
		{
			board.display();
			continue; 
		}

		// =================================================================
		// easy: turn off pondering
		// =================================================================

		if (XB_MODE && !strcmp(command, "easy"))    
		{ 
			XB_PONDER = false;
			continue; 
		}

		// =================================================================
		// egtpath type path: informs the engine in which directory it can find end-game tables
		// =================================================================

		if (XB_MODE && !strcmp(command, "egtpath")) continue; 

		// =================================================================
		// eval: show static evaluation of this position
		// =================================================================

		if (!XB_MODE && !strcmp(command, "eval"))    
		{ 
			number = board.eval();
			std::cout << "eval score = " << number << std::endl;
			#ifdef KENNY_DEBUG_EVAL
				board.mirror();
				board.display();
				i = board.eval();
				std::cout << "eval score = " << i << std::endl;
				board.mirror();
				if (number != i) std::cout << "evaluation is not symmetrical! " << number << std::endl;
				else std::cout << "evaluation is symmetrical" << std::endl;
			#endif
			continue; 
		}

		// =================================================================
		// exit: leave analyze mode / exit program (if not in WB)
		// =================================================================

		if (!strcmp(command, "exit"))    
		{ 
			if (XB_MODE)
			{
				XB_COMPUTER_SIDE = XB_NONE;			
				continue; 
			}
			else break;
		}

		// =================================================================
		// force: Set the engine to play neither color
		// =================================================================

		if (XB_MODE && !strcmp(command, "force"))   
		{ 
			XB_COMPUTER_SIDE = XB_NONE;
			continue; 
		}

		// =================================================================
		// game: show game moves
		// =================================================================

		if (!XB_MODE && !strcmp(command, "game"))   
		{ 
			if (board.endOfGame)
			{
				// make a temporary copy of board.gameLine[];
				number = board.endOfGame;
				GameLineRecord *tmp = new GameLineRecord[number];
				memcpy(tmp, board.gameLine, number * sizeof(GameLineRecord));

				// unmake all moves:
				for (i = number-1 ; i >= 0 ; i--) 
				{ 
					unmakeMove(tmp[i].move);
					board.endOfSearch = --board.endOfGame;
				}

				// redo all moves:
				j = board.nextMove;
				for (i = 0 ; i < number; i++)
				{
					// move numbering:
					if (!((i+j+2)%2)) std::cout << (i+2*j+2)/2 << ". ";
					else if (!i) std::cout << "1. ... ";

					// construct the move string
					toSan(tmp[i].move, sanMove);
					std::cout << sanMove; 

					// output CRLF, or space:
					if (!((i+j+1)%2)) std::cout << std::endl;
					else std::cout << " ";

					// make the move:
					makeMove(tmp[i].move);
					board.endOfSearch = ++board.endOfGame;
				}
				std::cout << std::endl;

				// delete the temporary copy:
				delete[] tmp;
			} 
			else
			{
				std::cout << "there are no game moves" << std::endl;        
			}
			continue; 
		}

		// =================================================================
		// go: leave force mode and set the engine to play the color that is on move
		// =================================================================

		if (!strcmp(command, "go"))      
		{
			if (XB_MODE)
			{
				XB_COMPUTER_SIDE = board.nextMove;  
				continue; 
			}
			else
			{
				if (!board.isEndOfgame(i, dummy))
				{
					move = board.think();
					if (move.moveInt) 
					{
						makeMove(move);
						board.endOfGame++;
						board.endOfSearch = board.endOfGame;
					}
					board.display();
					board.isEndOfgame(i, dummy);
					CMD_BUFF_COUNT = '\0';
				}
				else
				{
					board.display();
					CMD_BUFF_COUNT = '\0';
				}
			}
			continue;
		}

		// =================================================================
		// hard: turn on pondering
		// =================================================================

		if (XB_MODE && !strcmp(command, "hard"))    
		{ 
			XB_PONDER = true;  
			continue; 
		}

		// =================================================================
		// hint: respond with "Hint: xxx", where xxx is a suggested move
		// =================================================================

		if (XB_MODE && !strcmp(command, "hint")) 
		{
				continue; 
		}

		// =================================================================
		// ics hostname: the engine is playing on an Internet Chess Server (ICS) with the given hostname
		// =================================================================

		if (XB_MODE && !strcmp(command, "ics"))     { continue; }

		// =================================================================
		// info: display variables (for testing purposes)
		// =================================================================

		if (!XB_MODE && !strcmp(command, "info"))    
		{ 
			info();
			continue; 
		}

		// =================================================================
		// ini: read the initialization file
		// =================================================================

		if (!XB_MODE && !strcmp(command, "ini"))    
		{ 
			readIniFile();
			continue; 
		}

		// =================================================================
		// level mps base inc: set time controls
		// =================================================================

		if (XB_MODE && !strcmp(command, "level"))   
		{
			sscanf(CMD_BUFF, "level %d %d %d", &XB_MPS, &XB_MIN, &XB_INC) == 3 ||  
			sscanf(CMD_BUFF, "level %d %d:%d %d", &XB_MPS, &XB_MIN, &XB_SEC, &XB_INC);
			XB_INC *= 1000;
			continue;
		}

		// =================================================================
		// memory n: informs the engine on how much memory it is allowed to use maximally, in MB
		// =================================================================

		if (XB_MODE && !strcmp(command, "memory")) continue; 

		// =================================================================
		// moves: show all legal moves
		// =================================================================

		if (!XB_MODE && !strcmp(command, "moves"))    
		{ 
			board.moveBufLen[0] = 0;
			board.moveBufLen[1] = movegen(board.moveBufLen[0]);
			std::cout << std::endl << "moves from this position:" << std::endl;
			number = 0;
			for (i = board.moveBufLen[0]; i < board.moveBufLen[1]; i++)
			{
				makeMove(board.moveBuffer[i]);
				if (isOtherKingAttacked())
				{
					unmakeMove(board.moveBuffer[i]);
				}
				else
				{
					unmakeMove(board.moveBuffer[i]);
					toSan(board.moveBuffer[i], sanMove);
					std::cout << ++number << ". " << sanMove << std::endl;
				}
			}
			continue; 
		}

		// =================================================================
		// move: enter a move (use this format: move e2e4, or h7h8q)
		// =================================================================

		if (!XB_MODE && !strcmp(command, ""))    
		{
			sscanf(CMD_BUFF,"%s",userinput);
			// generate the pseudo-legal move list
			board.moveBufLen[0] = 0;
			board.moveBufLen[1] = movegen(board.moveBufLen[0]);
 
			if (isValidTextMove(userinput, move))        // check to see if the user move is also found in the pseudo-legal move list
			{
				makeMove(move);
 
				if (isOtherKingAttacked())              // post-move check to see if we are leaving our king in check
				{
					unmakeMove(move);
					std::cout << "    invalid move, leaving king in check: " << userinput << std::endl;
				}
				else
				{
					board.endOfGame++;
					board.endOfSearch = board.endOfGame;
					board.display();
				}
			}
			else
			{
				std::cout << "    move is invalid or not recognized: " << userinput << std::endl;
			}
			continue; 
		}

		// =================================================================
		// name <something>: informs the engine of its opponent's name
		// =================================================================

		if (XB_MODE && !strcmp(command, "name")) continue; 

		// =================================================================
		// new: reset the board to the standard chess starting position
		// =================================================================

		if (!strcmp(command, "new"))     
		{
			board.init(); 
			if (XB_MODE) 
			{
				XB_COMPUTER_SIDE = BLACK_MOVE;
				board.searchDepth = MAX_PLY;
			}
			continue; 
		}

		// =================================================================
		// nopost: turn off thinking/pondering output
		// =================================================================

		if (XB_MODE && !strcmp(command, "nopost"))  
		{ 
			XB_POST = false;
			continue; 
		}

		// =================================================================
		// otim n: set a clock that belongs to the opponent, in centiseconds
		// =================================================================
		if (XB_MODE && !strcmp(command, "otim"))    
		{ 
			// do not start pondering after receiving time commands, as a move will follow immediately
			sscanf(CMD_BUFF, "otim %d", &XB_OTIM);
			XB_OTIM *= 10;  // convert to miliseconds;
			goto noPonder; 
		} 

		// =================================================================
		// option name[=value]: setting of an engine-define option
		// =================================================================
		if (XB_MODE && !strcmp(command, "option"))  continue;

		// =================================================================
		// perft: calculate raw number of nodes from here, depth n 
		// =================================================================
		if (!XB_MODE && !strcmp(command, "perft"))  
		{ 
			sscanf(CMD_BUFF,"perft %d", &number);
			std::cout << "    starting perft " << number << "..." << std::endl;
			timer.init();
			board.moveBufLen[0] = 0;
 
			#ifdef KENNY_DEBUG_PERFT
				ICAPT = 0;
				IEP = 0;
				IPROM = 0;
				ICASTLOO = 0;
				ICASTLOOO = 0;
				ICHECK = 0;
			#endif
 
			msStart = timer.getms();
			perftcount = perft(0, number);
			msStop = timer.getms();
 
			std::cout << "nodes        = " << perftcount << ", " << msStop - msStart << " ms, ";
			if ((msStop - msStart) > 0)
			std::cout << (perftcount/(msStop - msStart)) << " knods/s";
			std::cout << std::endl;
			CMD_BUFF_COUNT = '\0';
 
			#ifdef KENNY_DEBUG_PERFT
				std::cout << "captures     = " << ICAPT << std::endl;
				std::cout << "en-passant   = " << IEP << std::endl;
				std::cout << "castlings    = " << ICASTLOO + ICASTLOOO << std::endl;
				std::cout << "promotions   = " << IPROM << std::endl;
				std::cout << "checks       = " << ICHECK << std::endl;
			#endif
			continue; 
		}

		// =================================================================
		// ping n: reply by sending the string pong n
		// =================================================================

		if (XB_MODE && !strcmp(command, "ping"))    
		{ 
			sscanf(CMD_BUFF,"ping %d", &number);
			std::cout << "pong " << number << std::endl; 
			continue; 
		}

		// =================================================================
		// post: turn on thinking/pondering output
		// =================================================================

		if (XB_MODE && !strcmp(command, "post"))    
		{ 
			XB_POST = true; 
			continue; 
		}

		// =================================================================
		// protover n: protocol version
		// =================================================================

		if (XB_MODE && !strcmp(command, "protover")) 
		{
			std::cout << "feature ping=1" << std::endl;
			std::cout << "feature setboard=1" << std::endl;
			std::cout << "feature colors=0" << std::endl;
			std::cout << "feature usermove=1" << std::endl;
			std::cout << "feature memory=1" << std::endl;
			std::cout << "feature debug=1" << std::endl;
			std::cout << "feature done=1" << std::endl;

			continue;
		}

		#ifdef KENNY_VERBOSE_SEE
		// =================================================================
		// qsearch: shows sorted capture movelist
		// =================================================================
				if (!XB_MODE && !strcmp(command, "qsearch"))  
				{ 
					board.moveBufLen[0] = 0;
					board.moveBufLen[1] = captgen(board.moveBufLen[0]);
					std::cout << std::endl << "sorted capturing moves from this position:" << std::endl;
					std::cout << std::endl << "        score:" << std::endl;
					number = 0;
					for (i = board.moveBufLen[0]; i < board.moveBufLen[1]; i++)
					{
						makeMove(board.moveBuffer[i]);
						if (isOtherKingAttacked())
						{
							unmakeMove(board.moveBuffer[i]);
						}
						else
						{
							unmakeMove(board.moveBuffer[i]);
							std::cout << ++number << ". "; 
							displayMove(board.moveBuffer[i]);
							std::cout << "   " << board.moveBuffer[i + OFFSET].moveInt << std::endl;
						}
					}
					continue; 
				}
		#endif

		// =================================================================
		// quit: exit program
		// =================================================================

		if (!strcmp(command, "quit")) break; 

		// =================================================================
		// r: rotate board
		// =================================================================

		if (!XB_MODE && !strcmp(command, "r"))  
		{ 
			board.viewRotated = !board.viewRotated;
			continue; 
		}

		// =================================================================
		// random: ignored
		// =================================================================

		if (XB_MODE && !strcmp(command, "random")) continue;

		// =================================================================
		// rating: ICS opponent's rating
		// =================================================================

		if (XB_MODE && !strcmp(command, "rating")) continue;

		// =================================================================
		// readfen filename n: reads #-th FEN position from filename
		// =================================================================

		if (!XB_MODE && !strcmp(command, "readfen"))  
		{ 
			sscanf(CMD_BUFF,"readfen %s %d", userinput, &number);
			board.init();
			readFen(userinput, number);
			board.display();
			continue; 
		}

		// =================================================================
		// rejected: feature is rejected
		// =================================================================

		if (XB_MODE && !strcmp(command, "rejected")) continue;

		// =================================================================
		// remove: undo the last two moves (one for each player) and continue playing the same color.
		// =================================================================

		if (XB_MODE && !strcmp(command, "remove"))  
		{ 
			if (board.endOfGame)
			{
				unmakeMove(board.gameLine[--board.endOfGame].move);
				board.endOfSearch = board.endOfGame;
			}
			if (board.endOfGame)
			{
				unmakeMove(board.gameLine[--board.endOfGame].move);
				board.endOfSearch = board.endOfGame;
			}
			continue; 
		}

		// =================================================================
		// result string {comment}: end the each game, e.g.: result 1-0 {White mates}
		// =================================================================

		if (XB_MODE && !strcmp(command, "result"))  
		{ 
			XB_COMPUTER_SIDE = XB_NONE;
			continue; 
		}

		// =================================================================
		// sd n: set the search depth to n
		// =================================================================

		if (!strcmp(command, "sd"))      
		{ 
			sscanf(CMD_BUFF,"sd %d", &board.searchDepth);
			if (board.searchDepth < 1) board.searchDepth = 1;
			if (board.searchDepth > MAX_PLY) board.searchDepth = MAX_PLY;
			std::cout << "KENNY> search depth " << board.searchDepth << std::endl;
			continue; 
		}

		// =================================================================
		// setboard fen: set up the board/position 
		// =================================================================

		if (XB_MODE && !strcmp(command, "setboard"))
		{ 
			XB_COMPUTER_SIDE = XB_NONE;
			sscanf(CMD_BUFF, "setboard %s %s %s %s %d %d", fen, fencolor, fencastling, fenenpassant, &fenhalfmoveclock, &fenfullmovenumber);
			setupFen(fen, fencolor, fencastling, fenenpassant, fenhalfmoveclock, fenfullmovenumber);
			continue; 
		}

		// =================================================================
		// setup: setup board... 
		// =================================================================

		if (!XB_MODE && !strcmp(command, "setup"))
		{ 
			setup();
			continue; 
		}

		// =================================================================
		// stopfrac (0-100%): undocumented command to interactively change this 
		// parameter (e.g. for running testsuites), default value is 60
		// Don't start a new iteration if STOPFRAC fraction of the max search time 
		// has passed
		// =================================================================

		if (!XB_MODE && !strcmp(command, "stopfrac"))      
		{ 
			number = (int)(STOPFRAC * 100);
			sscanf(CMD_BUFF, "stopfrac %d", &number);
			if (number < 1) number = 1;
			if (number > 100) number = 100;
			STOPFRAC = (float)(number/100.0);
			std::cout << "KENNY> stopfrac " << 100*STOPFRAC << std::endl;
			continue; 
		}

		// =================================================================
		// st time: set time controls
		// =================================================================

		if (XB_MODE && !strcmp(command, "st"))      
		{ 
			sscanf(CMD_BUFF, "st %d", &board.maxTime);
			board.maxTime *= board.maxTime;  // convert to ms
			continue; 
		}

		// =================================================================
		// test filename: starts search on all FEN position in 'filename
		// =================================================================

		if (!XB_MODE && !strcmp(command, "test"))      
		{ 
			sscanf(CMD_BUFF,"test %s", userinput);
			board.init();
			test(userinput);
			continue; 
		}

		// =================================================================
		// time: set a clock that belongs to the engine
		// =================================================================

		if (!strcmp(command, "time"))    
		{ 
			number = (int)board.maxTime / 1000;
			sscanf(CMD_BUFF,"time %d", &number);
			if (number < 1) number = 1;
			if (!XB_MODE) std::cout << "KENNY> search time " << number << " seconds" << std::endl;
			if (XB_MODE)
			{
				XB_CTIM = number * 10;
				board.maxTime = number * 10; // conversion to ms
			}
			else
			{
				board.maxTime = number * 1000; // conversion to ms
			}
			goto noPonder; 
		}

		// =================================================================
		// undo: take back last move
		// =================================================================

		if (!strcmp(command, "undo"))    
		{ 
			if (board.endOfGame)
			{
				unmakeMove(board.gameLine[--board.endOfGame].move);
				board.endOfSearch = board.endOfGame;
				if (!XB_MODE) board.display();
			}
			else if (!XB_MODE) std::cout << "already at start of game" << std::endl;
			continue; 
		}

		// =================================================================
		// usermove move: do a move
		// =================================================================

		if (XB_MODE && !strcmp(command, "usermove"))
		{
			sscanf(CMD_BUFF,"usermove %s",userinput);

			// generate the pseudo-legal move list
			board.moveBufLen[0] = 0;
			board.moveBufLen[1] = movegen(board.moveBufLen[0]);
 
			if (isValidTextMove(userinput, move))        // check to see if the user move is also found in the pseudo-legal move list
			{
				makeMove(move);
				if (isOtherKingAttacked())              // post-move check to see if we are leaving our king in check
				{
					#ifdef KENNY_DEBUG_WINBOARD
						std::cout << "#-KENNY : usermove illegal" << std::endl;
					#endif
					unmakeMove(move);
				}
				else
				{
					#ifdef KENNY_DEBUG_WINBOARD
						std::cout << "#-KENNY : usermove " << userinput << " made" << std::endl;
					#endif
					board.endOfGame++;
					board.endOfSearch = board.endOfGame;
				}
			}
			else
			{
				#ifdef KENNY_DEBUG_WINBOARD
						std::cout << "#-KENNY : usermove illegal" << std::endl;
				#endif
			} 
			continue;
		}

		// =================================================================
		// variant: the game is not standard chess
		// =================================================================

		if(XB_MODE && !strcmp(command, "variant")) continue; 

		// =================================================================
		// white: WHITE to move
		// =================================================================

		if (!XB_MODE && !strcmp(command, "white") && board.nextMove == BLACK_MOVE)    
		{ 
			board.hashkey ^= KEY.side;
			board.endOfSearch = 0; 
			board.endOfGame = 0;
			board.nextMove = WHITE_MOVE;
			continue; 
		}

		// =================================================================
		// xboard: put the engine into "xboard mode", stop all unsolicited output
		// =================================================================

		if (!XB_MODE && !strcmp(command, "xboard"))  
		{ 
			#ifdef KENNY_DEBUG_WINBOARD
				if (XB_MODE) std::cout << "#>KENNY : xboard" << std::endl;
			#endif

			std::cout << std::endl;
			XB_COMPUTER_SIDE = XB_NONE;
			XB_MODE = true;
			XB_POST = false;
			board.init();
			continue; 
		}

		// =================================================================
		// unknown command: 
		// =================================================================

		printf("Error: unknown command: %s\n", command);
		#ifdef KENNY_DEBUG_WINBOARD
			if (XB_MODE) std::cout << "#<KENNY : Error: unknown command: " << command << std::endl;
		#endif
	}
}
예제 #12
0
bool initSludge (char * filename) {
	int a = 0;
	mouseCursorAnim = makeNullAnim ();

	FILE * fp = openAndVerify (filename, 'G', 'E', ERROR_BAD_HEADER, gameVersion);
	if (! fp) return false;

	if (fgetc (fp)) {
		numBIFNames = get2bytes (fp);
		allBIFNames = new char * [numBIFNames];
		if (! checkNew (allBIFNames)) return false;

		for (int fn = 0; fn < numBIFNames; fn ++) {
			allBIFNames[fn] = readString (fp);
		}
		numUserFunc = get2bytes (fp);
		allUserFunc = new char * [numUserFunc];
		if (! checkNew (allUserFunc)) return false;

		for (int fn = 0; fn < numUserFunc; fn ++) {
			allUserFunc[fn] = readString (fp);
		}
		if (gameVersion >= VERSION(1,3)) {
			numResourceNames = get2bytes (fp);
			allResourceNames = new char * [numResourceNames];
			if (! checkNew (allResourceNames)) return false;

			for (int fn = 0; fn < numResourceNames; fn ++) {
				allResourceNames[fn] = readString (fp);
			}
		}
	}
	winWidth = get2bytes (fp);
	winHeight = get2bytes (fp);
	specialSettings = fgetc (fp);

	desiredfps = 1000/fgetc (fp);

	delete[] readString (fp); // Unused - was used for registration purposes.

	size_t bytes_read = fread (& fileTime, sizeof (FILETIME), 1, fp);
	if (bytes_read != sizeof (FILETIME) && ferror (fp)) {
		debugOut("Reading error in initSludge.\n");
	}

	char * dataFol = (gameVersion >= VERSION(1,3)) ? readString(fp) : joinStrings ("", "");

	gameSettings.numLanguages = (gameVersion >= VERSION(1,3)) ? (fgetc (fp)) : 0;
	makeLanguageTable (fp);

	if (gameVersion >= VERSION(1,6))
	{
		fgetc(fp);
		// aaLoad
		fgetc (fp);
		getFloat (fp);
		getFloat (fp);
	}

	char * checker = readString (fp);

	if (strcmp (checker, "okSoFar")) return fatal (ERROR_BAD_HEADER, filename);
	delete checker;
	checker = NULL;

    unsigned char customIconLogo = fgetc (fp);

	if (customIconLogo & 1) {
		// There is an icon - read it!
		int n;

		long file_pointer = ftell (fp);

		png_structp png_ptr;
		png_infop info_ptr, end_info;

		int fileIsPNG = true;

		// Is this a PNG file?

		char tmp[10];
		bytes_read = fread(tmp, 1, 8, fp);
		if (bytes_read != 8 && ferror (fp)) {
			debugOut("Reading error in initSludge.\n");
		}
		if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
			// No, it's old-school HSI
			fileIsPNG = false;
			fseek(fp, file_pointer, SEEK_SET);

			iconW = get2bytes (fp);
			iconH = get2bytes (fp);
		} else {
			// Read the PNG header

			png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
			if (!png_ptr) {
				return false;
			}

			info_ptr = png_create_info_struct(png_ptr);
			if (!info_ptr) {
				png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
				return false;
			}

			end_info = png_create_info_struct(png_ptr);
			if (!end_info) {
				png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
				return false;
			}
			png_init_io(png_ptr, fp);		// Tell libpng which file to read
			png_set_sig_bytes(png_ptr, 8);	// 8 bytes already read

			png_read_info(png_ptr, info_ptr);

			png_uint_32 width, height;
			int bit_depth, color_type, interlace_type, compression_type, filter_method;
			png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);

			iconW = width;
			iconH = height;

			if (bit_depth < 8) png_set_packing(png_ptr);
			png_set_expand(png_ptr);
			if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
			if (bit_depth == 16) png_set_strip_16(png_ptr);

			png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);

			png_read_update_info(png_ptr, info_ptr);
			png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);

		}

        gameIcon = new unsigned char [iconW*iconH*4];
        if (! gameIcon) return fatal ("Can't reserve memory for game icon.");

        int32_t transCol = 63519;
        Uint8 *p = (Uint8 *) gameIcon;

        if (fileIsPNG) {
            unsigned char * row_pointers[iconH];
            for (int i = 0; i<iconH; i++)
                row_pointers[i] = p + 4*i*iconW;

            png_read_image(png_ptr, (png_byte **) row_pointers);
            png_read_end(png_ptr, NULL);
            png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
        } else {

            for (int t2 = 0; t2 < iconH; t2 ++) {
                int t1 = 0;
                while (t1 < iconW) {
                    unsigned short c = (unsigned short) get2bytes (fp);
                    if (c & 32) {
                        n = fgetc (fp) + 1;
                        c -= 32;
                    } else {
                        n = 1;
                    }
                    while (n --) {
                       *p++ = (Uint8) redValue(c);
                        *p++ = (Uint8) greenValue(c);
                        *p++ = (Uint8) blueValue(c);
                        *p++ = (Uint8) (c == transCol) ? 0 : 255;

                        t1++;
                    }
                }
            }
        }
	}

	if (customIconLogo & 2) {
		// There is an logo - read it!
		int n;

		long file_pointer = ftell (fp);

		png_structp png_ptr;
		png_infop info_ptr, end_info;

		int fileIsPNG = true;

		// Is this a PNG file?

		char tmp[10];
		bytes_read = fread(tmp, 1, 8, fp);
		if (bytes_read != 8 && ferror (fp)) {
			debugOut("Reading error in initSludge.\n");
		}
		if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
			// No, it's old-school HSI
			fileIsPNG = false;
			fseek(fp, file_pointer, SEEK_SET);

			logoW = get2bytes (fp);
			logoH = get2bytes (fp);
		} else {
			// Read the PNG header

			png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
			if (!png_ptr) {
				return false;
			}

			info_ptr = png_create_info_struct(png_ptr);
			if (!info_ptr) {
				png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
				return false;
			}

			end_info = png_create_info_struct(png_ptr);
			if (!end_info) {
				png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
				return false;
			}
			png_init_io(png_ptr, fp);		// Tell libpng which file to read
			png_set_sig_bytes(png_ptr, 8);	// 8 bytes already read

			png_read_info(png_ptr, info_ptr);

			png_uint_32 width, height;
			int bit_depth, color_type, interlace_type, compression_type, filter_method;
			png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);

			logoW = width;
			logoH = height;

			if (bit_depth < 8) png_set_packing(png_ptr);
			png_set_expand(png_ptr);
			if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
			if (bit_depth == 16) png_set_strip_16(png_ptr);
#ifdef WIN32
            // Windows wants a BGR bitmap
            if (color_type == PNG_COLOR_TYPE_RGB ||
                color_type == PNG_COLOR_TYPE_RGB_ALPHA)
                    png_set_bgr(png_ptr);
#endif

			png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);

			png_read_update_info(png_ptr, info_ptr);
			png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);

		}

        if ((logoW != 310) || (logoH != 88)) return fatal ("Game logo have wrong dimensions. (Should be 310x88)");

        gameLogo = new unsigned char [logoW*logoH*4];
        if (! gameLogo) return fatal ("Can't reserve memory for game logo.");

        // int32_t transCol = 63519;
        Uint8 *p = (Uint8 *) gameLogo;

        if (fileIsPNG) {
            unsigned char * row_pointers[logoH];
            for (int i = 0; i<logoH; i++)
                row_pointers[i] = p + 4*i*logoW;

            png_read_image(png_ptr, (png_byte **) row_pointers);
            png_read_end(png_ptr, NULL);
            png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
        } else {

            for (int t2 = 0; t2 < logoH; t2 ++) {
                int t1 = 0;
                while (t1 < logoW) {
                    unsigned short c = (unsigned short) get2bytes (fp);
                    if (c & 32) {
                        n = fgetc (fp) + 1;
                        c -= 32;
                    } else {
                        n = 1;
                    }
                    while (n --) {
#ifdef WIN32
                        // Windows wants a BGR bitmap
                       *p++ = (Uint8) blueValue(c);
                        *p++ = (Uint8) greenValue(c);
                        *p++ = (Uint8) redValue(c);
#else
                       *p++ = (Uint8) redValue(c);
                        *p++ = (Uint8) greenValue(c);
                        *p++ = (Uint8) blueValue(c);
#endif
                        *p++ = (Uint8) /*(c == transCol) ? 0 :*/ 255;

                        t1++;
                    }
                }
            }
        }
	}

 	numGlobals = get2bytes (fp);

	globalVars = new variable[numGlobals];
	if (! checkNew (globalVars)) return false;
	for (a = 0; a < numGlobals; a ++) initVarNew (globalVars[a]);

	// Get the original (untranslated) name of the game and convert it to Unicode.
	// We use this to find saved preferences and saved games.
	setFileIndices (fp, gameSettings.numLanguages, 0);
	char * gameNameOrig = getNumberedString(1);

	char * gameName = encodeFilename (gameNameOrig);

	delete gameNameOrig;

	changeToUserDir ();

#ifdef _WIN32
	mkdir (gameName);
#else
	mkdir (gameName, 0000777);
#endif

	if (chdir (gameName)) return fatal ("This game's preference folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", gameName);

	delete [] gameName;
	
	// Get user settings
	readIniFile (filename);

	// There's no startup window on Linux and respecting this 
	// option from the ini file would disable commandline options.
#if defined __unix__ && !(defined __APPLE__)
		if (! showSetupWindow()) return 0;
		saveIniFile (filename);
#else
	if (! gameSettings.noStartWindow) {
		if (! showSetupWindow()) return 0;
		saveIniFile (filename);
	}
#endif

	// Now set file indices properly to the chosen language.
	languageNum = getLanguageForFileB ();
	if (languageNum < 0) return fatal ("Can't find the translation data specified!");
	setFileIndices (NULL, gameSettings.numLanguages, languageNum);

	if (dataFol[0]) {
		char *dataFolder = encodeFilename(dataFol);
#ifdef _WIN32
		mkdir (dataFolder);
#else
		mkdir (dataFolder, 0000777);
#endif

		if (chdir (dataFolder)) return fatal ("This game's data folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", dataFolder);

		delete dataFolder;
	}

 	positionStatus (10, winHeight - 15);

	return true;
}
예제 #13
0
SludgeProjectManager::SludgeProjectManager()
 : SludgeApplication(joinTwoStrings(DATADIR, "ProjectManager.glade"), "ProjIcon", "projectmanager")
{
	if (!initSuccess) return;

	numResources = 0;
	resourceList[0] = NULL;
	fileList[0] = NULL;

	filesListStore = NULL;
	resourcesListStore = NULL;
	errorsListStore = NULL;
	filesSelection = NULL;

	notebook = GTK_NOTEBOOK (gtk_builder_get_object(theXml, "notebook"));
	saveItem = GTK_WIDGET (gtk_builder_get_object(theXml, "save"));
	saveAsItem = GTK_WIDGET (gtk_builder_get_object(theXml, "save_as"));
	projectPropertiesItem = GTK_WIDGET (gtk_builder_get_object(theXml, "project_properties"));
	projectCompileItem = GTK_WIDGET (gtk_builder_get_object(theXml, "project_compile"));
	projectRunGameItem = GTK_WIDGET (gtk_builder_get_object(theXml, "project_run_game"));
	addFileButton = GTK_WIDGET (gtk_builder_get_object(theXml, "add_file"));
	removeFileButton = GTK_WIDGET (gtk_builder_get_object(theXml, "remove_file"));

	compilerDialog = GTK_DIALOG (gtk_builder_get_object(theXml, "compiler_dialog"));
	compProgress1 = GTK_PROGRESS_BAR (gtk_builder_get_object(theXml, "progressbar1"));
	compProgress2 = GTK_PROGRESS_BAR (gtk_builder_get_object(theXml, "progressbar2"));
	compTask = GTK_LABEL (gtk_builder_get_object(theXml, "comp_task"));
	compFile = GTK_LABEL (gtk_builder_get_object(theXml, "comp_file"));
	compItem = GTK_LABEL (gtk_builder_get_object(theXml, "comp_item"));
	compFuncs = GTK_LABEL (gtk_builder_get_object(theXml, "comp_funcs"));
	compObjs = GTK_LABEL (gtk_builder_get_object(theXml, "comp_objs"));
	compGlobs = GTK_LABEL (gtk_builder_get_object(theXml, "comp_globs"));
	compStrings = GTK_LABEL (gtk_builder_get_object(theXml, "comp_strings"));
	compResources = GTK_LABEL (gtk_builder_get_object(theXml, "comp_resources"));
	runGameButton = GTK_WIDGET (gtk_builder_get_object(theXml, "comp_gamebutton"));
	closeCompilerButton = GTK_WIDGET (gtk_builder_get_object(theXml, "comp_okbutton"));

	projectSettingsDialog = GTK_DIALOG (gtk_builder_get_object(theXml, "project_settings_dialog"));
	prefName = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_name"));
	prefQuit = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_quit"));
	prefSave = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_save"));
	prefLanguage = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_language"));
	prefFilename = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_filename"));
	prefIcon = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_icon"));
	prefLogo = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_logo"));
	prefWidth = GTK_SPIN_BUTTON (gtk_builder_get_object(theXml, "pref_width"));
	prefHeight = GTK_SPIN_BUTTON (gtk_builder_get_object(theXml, "pref_height"));
	prefSpeed = GTK_SPIN_BUTTON (gtk_builder_get_object(theXml, "pref_speed"));
	prefSilent = GTK_TOGGLE_BUTTON (gtk_builder_get_object(theXml, "pref_silent"));

	preferenceDialog = GTK_DIALOG (gtk_builder_get_object(theXml, "preferences_dialog"));
	prefKeepImages = GTK_TOGGLE_BUTTON (gtk_builder_get_object(theXml, "pref_keep_images"));
	prefWriteStrings = GTK_TOGGLE_BUTTON (gtk_builder_get_object(theXml, "pref_write_strings"));
	prefVerbose = GTK_TOGGLE_BUTTON (gtk_builder_get_object(theXml, "pref_verbose"));
	prefEditor = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_editor"));
	prefImageViewer = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_image_viewer"));
	prefAudioPlayer = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_audio_player"));
	prefModPlayer = GTK_ENTRY (gtk_builder_get_object(theXml, "pref_mod_player"));

	compilerInfoQueue = NULL;

	if (!getcwd(workingDir, 998))
		fprintf(stderr, "Couldn't get current working directory.");

	readIniFile();

    init(TRUE);

	setupButtons();
}
예제 #14
0
void UpdateApplication::downloadFinished()
// ----------------------------------------------------------------------------
//    Process downloaded data reply
// ----------------------------------------------------------------------------
{
    if (state == NetworkErrorCheck || state == NetworkErrorDownload)
    {
        QString details = reply->errorString();
        reply->abort();
        progress->close();

        if (state == NetworkErrorDownload || show)
        {
            QString msg = tr("<h3>Network error</h3>");
            QString info = tr("<p>Impossible to obtain update information.</p>"
                              "<p>Please make sure that you are connected to "
                              "the Internet and try again.</p>");
            QMessageBox box(TaoApp->windowWidget());
            setBoxMinimumWidth(box, 400);
            box.setIconPixmap(connectionErrorIcon);
            box.setWindowTitle(dialogTitle);
            box.setText(msg);
            box.setInformativeText(info);
            box.setDetailedText(details);
            box.setStandardButtons(QMessageBox::Ok);
            box.exec();
        }

        return;
    }

    if (code != 200)
        return;

    bool updateAvailable = false;
    qint64 pid = 0;
    QString name;
    switch (state)
    {
    case WaitingForUpdate:

        // Save and process the update information we have just received

        progress->hide();

        XL_ASSERT(!file);
        pid = QCoreApplication::applicationPid();
        name = QString("tao_update.%1").arg(pid);
        file = new QFile(QDir::temp().filePath(name));
        if (!file->open(QIODevice::WriteOnly | QIODevice::Truncate))
        {
            IFTRACE(update)
            debug() << "Failed to open: " << +file->fileName() << "\n";
            delete file;
            file = NULL;
            return;
        }
        file->write(reply->readAll());
        file->close();

        reply->deleteLater();
        reply = NULL;

        readIniFile();

        file->remove();
        delete file;
        file = NULL;

        setLastChecked(QDateTime::currentDateTime());

        // Propose to update if current version is older than the remote one
        updateAvailable = (version < remoteVersion) && !url.isEmpty();
        IFTRACE(update)
        debug() << "Update available: " << updateAvailable
                << " (local " << version << " remote " << remoteVersion
                << ")\n";
        if (updateAvailable)
        {
            bool ok = false;
            double min = QSettings().value("AppUpdatePromptMinVersion", -1.0)
                         .toDouble(&ok);
            if (!ok)
                min = -1.0;

            if (show || remoteVersion > min)
            {
                if (remoteVersion > min)
                {
                    // Remember that user was prompted to download  this
                    // version. He/she will not be prompted again on application
                    // startup, unless a newer version exists.
                    QSettings().setValue("AppUpdatePromptMinVersion",
                                         remoteVersion);
                    IFTRACE2(update, settings)
                    debug() << "Saving AppUpdatePromptMinVersion="
                            << remoteVersion << "\n";
                }

                // Show update dialog
                QString msg = tr("<h3>Update available</h3>");
                QString info = tr("<p>%1 version %2 is available."
                                  " Do you want to download it now?</p>")
                               .arg(appName()).arg(remoteVer());
                QMessageBox box(TaoApp->windowWidget());
                setBoxMinimumWidth(box, 400);
                box.setIconPixmap(downloadIcon);
                box.setWindowTitle(dialogTitle);
                box.setText(msg);
                box.setInformativeText(info);
                if (!description.isEmpty())
                    box.setDetailedText(description);
                box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
                if (box.exec() == QMessageBox::Yes)
                {
                    startDownload();
                    break;
                }
            }
            else
            {
                IFTRACE(update)
                debug() << "Update available dialog not shown due to "
                        "AppUpdatePromptMinVersion=" << min << "\n";
            }
        }
        else
        {
            if (show)
                showNoUpdateAvailable();
        }

        progress->close();
        break;

    case Downloading:

        IFTRACE(update)
        debug() << "Download finished\n";

        progress->hide();
        state = Downloaded;
        if (file)
            saveDownloadedData();

        break;

    default:
        break;
    }
}