Beispiel #1
0
void MakeRtnData(void * pConn,long reqno, unsigned long funcid, long errcode,const char * errInfo , const char * retbuf, long len,bool islast)
{
	tagTradeErrorInfo *pErrInfo = new tagTradeErrorInfo();
	pErrInfo->ErrorID = 0;
	void * datahandle = NULL;
	int iRowCount = 0;
	if (errcode >= 0)
	{
		datahandle = YTData_NewData();
		YTData_ConvertData(datahandle, retbuf, len);
		iRowCount = YTData_GetRowCount(datahandle);
		if (iRowCount > 0)
		{
			YTData_GotoBeginRow(datahandle);
			pErrInfo->ErrorID = YTData_GetFieldInt(datahandle,"retcode");
			if (pErrInfo->ErrorID < 0)
			{
				YTData_GetFieldString(datahandle,"comment",pErrInfo->ErrorMsg,sizeof(pErrInfo->ErrorMsg));
			}
		}
	}
	else
	{
		pErrInfo->ErrorID = errcode;
		strcpy_s(pErrInfo->ErrorMsg, sizeof(pErrInfo->ErrorMsg), errInfo);
	}

	int i = 0;
	switch(funcid)
	{
	case LOGIN:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsLogin(NULL,pErrInfo);
			
		}
		else  //正常返回
		{
			tagTradeAnsLogin* pPara = new tagTradeAnsLogin();
			pPara->UserID = YTData_GetFieldInt(datahandle,"userid");
			pPara->UserType = YTData_GetFieldInt(datahandle,"usertype");
			iUserID = pPara->UserID;

			//登陆成功之后,初始化连接池。连接池开始有maxconn/2 个连接
      void* conn = pConn;  
      EnterCriticalSection(&secLock); 
      //for(int k=0;k<imaxConnects/2;k++)  
      //{ 
      //  conn = YTConn_NewConn(ptrConfig);
      //  if (YTConn_Connect(conn) >=0)
      //  {
      //    connLists.push_back(conn);
      //    iCurConnects++;
      //  }
      //}  
      connLists.push_back(conn);
      iCurConnects++;
      LeaveCriticalSection(&secLock);  
      if(iCurConnects >= imaxConnects/2){ 
			  pFuncList->Func_TradeAnsLogin(pPara,pErrInfo);
      }
			delete pPara;			
		}
		break;
	case QURELATED:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuRelated(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuRelated* pPara = new tagTradeAnsQuRelated[iRowCount];
			for (i=0;i<iRowCount;i++)
			{
				pPara[i].UserID = YTData_GetFieldInt(datahandle,"userid");
				YTData_GetFieldString(datahandle,"user",pPara[i].User,sizeof(pPara[i].User));
				pPara[i].AccID = YTData_GetFieldInt(datahandle,"accountid");
				YTData_GetFieldString(datahandle,"accountalias",pPara[i].AccountName,sizeof(pPara[i].AccountName));
				pPara[i].CounterID = YTData_GetFieldInt(datahandle,"counterid");
				pPara[i].UsableMoney = YTData_GetFieldDouble(datahandle,"usablemoney");
			}
			pFuncList->Func_TradeAnsQuRelated(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case QUMONEY:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuMoney(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuMoney* pPara = new tagTradeAnsQuMoney[iRowCount];
			for (i=0;i<iRowCount;i++)
			{
				pPara[i].UsableMoney = YTData_GetFieldDouble(datahandle,"usablemoney");
			}
			pFuncList->Func_TradeAnsQuMoney(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case QUAMOUNT:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuAmount(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuAmount* pPara = new tagTradeAnsQuAmount[iRowCount];
			for (i=0;i<iRowCount;i++)
			{

				pPara[i].AccID = YTData_GetFieldInt(datahandle,"accountid");
				YTData_GetFieldString(datahandle,"accountalias",pPara[i].AccountName,sizeof(pPara[i].AccountName));
				pPara[i].Amount = YTData_GetFieldInt(datahandle,"stockamount");
				YTData_GetFieldString(datahandle,"symbol",pPara[i].InstrumentID,sizeof(pPara[i].InstrumentID));
				YTData_GetFieldString(datahandle,"exchange",pPara[i].ExchangeID,sizeof(pPara[i].ExchangeID));
				YTData_GetFieldString(datahandle,"cname",pPara[i].InstrumentName,sizeof(pPara[i].InstrumentName));
			}
			pFuncList->Func_TradeAnsQuAmount(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case QUUNFINISHENTRUST:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuUnFinishEntrust(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuUnFinishEntrust* pPara = new tagTradeAnsQuUnFinishEntrust[iRowCount];
			for (i=0;i<iRowCount;i++)
			{
				pPara[i].UserID = YTData_GetFieldInt(datahandle,"userid");
				YTData_GetFieldString(datahandle,"user",pPara[i].User,sizeof(pPara[i].User));
				pPara[i].AccID = YTData_GetFieldInt(datahandle,"accountid");
				YTData_GetFieldString(datahandle,"accountalias",pPara[i].AccountName,sizeof(pPara[i].AccountName));
				pPara[i].CounterID = YTData_GetFieldInt(datahandle,"counterid");
				YTData_GetFieldString(datahandle,"symbol",pPara[i].InstrumentID,sizeof(pPara[i].InstrumentID));
				YTData_GetFieldString(datahandle,"exchange",pPara[i].ExchangeID,sizeof(pPara[i].ExchangeID));
				YTData_GetFieldString(datahandle,"cname",pPara[i].InstrumentName,sizeof(pPara[i].InstrumentName));
				pPara[i].EntrustDate = YTData_GetFieldInt(datahandle,"entrustdate");
				pPara[i].EntrustTime = YTData_GetFieldInt(datahandle,"entrusttime");
				pPara[i].EntrustType = YTData_GetFieldChar(datahandle,"entrusttype");
				pPara[i].EntrustStatus = YTData_GetFieldChar(datahandle,"entruststatus");
				YTData_GetFieldString(datahandle,"entrustno",pPara[i].EntrustNo,sizeof(pPara[i].EntrustNo));
				pPara[i].EntrustPrice = YTData_GetFieldDouble(datahandle,"entrustprice");
				pPara[i].EntrustAmount = YTData_GetFieldInt(datahandle,"entrustamount");
				pPara[i].BargAmount = YTData_GetFieldInt(datahandle,"stockturnover");
				pPara[i].LastUpdateTime = YTData_GetFieldInt(datahandle,"lasttime");
			}
			pFuncList->Func_TradeAnsQuUnFinishEntrust(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case QULOG:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuLog(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuLog* pPara = new tagTradeAnsQuLog[iRowCount];
			for (i=0;i<iRowCount;i++)
			{
				pPara[i].UserID = YTData_GetFieldInt(datahandle,"userid");
				YTData_GetFieldString(datahandle,"user",pPara[i].User,sizeof(pPara[i].User));
				pPara[i].AccID = YTData_GetFieldInt(datahandle,"accountid");
				YTData_GetFieldString(datahandle,"accountalias",pPara[i].AccountName,sizeof(pPara[i].AccountName));
				YTData_GetFieldString(datahandle,"symbol",pPara[i].InstrumentID,sizeof(pPara[i].InstrumentID));
				YTData_GetFieldString(datahandle,"cname",pPara[i].InstrumentName,sizeof(pPara[i].InstrumentName));
				pPara[i].EntrustDate = YTData_GetFieldInt(datahandle,"entrustdate");
				pPara[i].EntrustTime = YTData_GetFieldInt(datahandle,"entrusttime");
				pPara[i].EntrustStatus = YTData_GetFieldChar(datahandle,"entruststatus");
				YTData_GetFieldString(datahandle,"entrustno",pPara[i].EntrustNo,sizeof(pPara[i].EntrustNo));
				YTData_GetFieldString(datahandle,"event",pPara[i].LogDetail,sizeof(pPara[i].LogDetail));
				pPara[i].Index = YTData_GetFieldInt(datahandle,"qryindex");
			}
			pFuncList->Func_TradeAnsQuLog(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case QUPOSITION:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuPosition(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuPosition* pPara = new tagTradeAnsQuPosition[iRowCount];
			for (i=0;i<iRowCount;i++)
			{
				if (i==0)
				{
					pPara[i].TotalMarketValue = YTData_GetFieldDouble(datahandle,"totalmarketvalue");
					pPara[i].FloatProfitorLoss = YTData_GetFieldDouble(datahandle,"floatprofitorloss");
					pPara[i].AchieveFpl = YTData_GetFieldDouble(datahandle,"achievefpl");
				}
				YTData_GetFieldString(datahandle,"user",pPara[i].User,sizeof(pPara[i].User));
				YTData_GetFieldString(datahandle,"accountalias",pPara[i].AccountName,sizeof(pPara[i].AccountName));
				YTData_GetFieldString(datahandle,"symbol",pPara[i].InstrumentID,sizeof(pPara[i].InstrumentID));
				YTData_GetFieldString(datahandle,"cname",pPara[i].InstrumentName,sizeof(pPara[i].InstrumentName));
				YTData_GetFieldString(datahandle,"exchange",pPara[i].ExchangeID,sizeof(pPara[i].ExchangeID));
				pPara[i].Amount = YTData_GetFieldInt(datahandle,"stockamount");
				pPara[i].Side = YTData_GetFieldInt(datahandle,"side");
				pPara[i].CurrentFloatProfit = YTData_GetFieldDouble(datahandle,"currentfloatprofit");
				pPara[i].AveragePrice = YTData_GetFieldDouble(datahandle,"averageprice");
			}
			pFuncList->Func_TradeAnsQuPosition(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case QUBARGAIN:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuBargain(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuBargain* pPara = new tagTradeAnsQuBargain[iRowCount];
			for (i=0;i<iRowCount;i++)
			{
				pPara[i].UserID = YTData_GetFieldInt(datahandle,"userid");
				YTData_GetFieldString(datahandle,"user",pPara[i].User,sizeof(pPara[i].User));
				pPara[i].AccID = YTData_GetFieldInt(datahandle,"accountid");
				YTData_GetFieldString(datahandle,"accountalias",pPara[i].AccountName,sizeof(pPara[i].AccountName));
				YTData_GetFieldString(datahandle,"symbol",pPara[i].InstrumentID,sizeof(pPara[i].InstrumentID));
				YTData_GetFieldString(datahandle,"cname",pPara[i].InstrumentName,sizeof(pPara[i].InstrumentName));
				pPara[i].EntrustType = YTData_GetFieldChar(datahandle,"entrusttype");
				pPara[i].EntrustTime = YTData_GetFieldInt(datahandle,"entrusttime");
				YTData_GetFieldString(datahandle,"entrustno",pPara[i].EntrustNo,sizeof(pPara[i].EntrustNo));
				pPara[i].BargAmount = YTData_GetFieldInt(datahandle,"stockturnover");
				pPara[i].BargPrice = YTData_GetFieldDouble(datahandle,"bargainprice");
				pPara[i].EntrustFee = YTData_GetFieldChar(datahandle,"entrustfee");
			}
			pFuncList->Func_TradeAnsQuBargain(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case QUCOLLECTBARGAIN:
		if (errcode < 0 || pErrInfo->ErrorID < 0)  
		{
			pFuncList->Func_TradeAnsQuCollectBargain(NULL,0,pErrInfo,reqno,islast);

		}
		else  //正常返回
		{
			iRowCount = YTData_GetRowCount(datahandle); 
			tagTradeAnsQuCollectBargain* pPara = new tagTradeAnsQuCollectBargain[iRowCount];
			for (i=0;i<iRowCount;i++)
			{
				if (i == 0)
				{
					pPara[i].AchieveFpl = YTData_GetFieldDouble(datahandle,"achievefpl");
					pPara[i].TotalTradeMoney = YTData_GetFieldDouble(datahandle,"totaltrademoney");
				}
				pPara[i].UserID = YTData_GetFieldInt(datahandle,"userid");
				YTData_GetFieldString(datahandle,"accountalias",pPara[i].AccountName,sizeof(pPara[i].AccountName));
				YTData_GetFieldString(datahandle,"symbol",pPara[i].InstrumentID,sizeof(pPara[i].InstrumentID));
				YTData_GetFieldString(datahandle,"cname",pPara[i].InstrumentName,sizeof(pPara[i].InstrumentName));
				pPara[i].BargAmount = YTData_GetFieldInt(datahandle,"stockturnover");
				pPara[i].EntrustCount = YTData_GetFieldInt(datahandle,"entrustcount");
				pPara[i].BargMoney = YTData_GetFieldDouble(datahandle,"priceturnover");
				pPara[i].Profits = YTData_GetFieldDouble(datahandle,"profits");
				pPara[i].EntrustFee = YTData_GetFieldChar(datahandle,"entrustfee");
			}
			pFuncList->Func_TradeAnsQuCollectBargain(pPara,iRowCount,pErrInfo,reqno,islast);
			delete []pPara;
		}
		break;
	case ENTRUST:
		pFuncList->Func_TradeAnsEntrust(pErrInfo,reqno);
		break;
	case DISENTRUST:
		pFuncList->Func_TradeAnsDisEntrust(pErrInfo,reqno);
		break;
	case  DISLASTENTRUST:
		pFuncList->Func_TradeAnsDisLastEntrust(pErrInfo,reqno);
		break;
	case DISALLENTRUST:
		pFuncList->Func_TradeAnsDisAllEntrust(pErrInfo,reqno);
		break;
	default:
		break;
	}

	YTData_DeleteData(datahandle);
	delete pErrInfo;
}
// CConnect
STDMETHODIMP CConnect::OnConnection(IDispatch *pApplication, AddInDesignerObjects::ext_ConnectMode /*ConnectMode*/, IDispatch *pAddInInst, SAFEARRAY ** /*custom*/)
{
	char BERTXLL[32] = "";
	
	char RBin[MAX_PATH];
	char Home[MAX_PATH];

	char Install[MAX_PATH];
	char XLLPath[MAX_PATH];

	if (!CRegistryUtils::GetRegExpandString(HKEY_CURRENT_USER, RBin, MAX_PATH - 1, REGISTRY_KEY, REGISTRY_VALUE_R_HOME, true))
		ExpandEnvironmentStringsA(DEFAULT_R_HOME, RBin, MAX_PATH - 1);

	if (!CRegistryUtils::GetRegExpandString(HKEY_CURRENT_USER, Home, MAX_PATH - 1, REGISTRY_KEY, REGISTRY_VALUE_R_USER, true))
		ExpandEnvironmentStringsA(DEFAULT_R_USER, Home, MAX_PATH - 1);

	if (!CRegistryUtils::GetRegString(HKEY_CURRENT_USER, Install, MAX_PATH - 1, REGISTRY_KEY, REGISTRY_VALUE_INSTALL_DIR))
		sprintf_s(Install, MAX_PATH, "");

	int len = strlen(RBin);
	if (len > 0)
	{
		if (RBin[len - 1] != '\\') strcat_s(RBin, MAX_PATH - 1, "\\");
	}

	// DERP

#ifdef _WIN64
	strcat_s(RBin, MAX_PATH, "bin\\x64;");
#else
	strcat_s(RBin, MAX_PATH, "bin\\i386;");
#endif

	// set path

	int elen = ::GetEnvironmentVariableA("PATH", 0, 0);
	int blen = strlen(RBin);

	char *buffer = new char[blen + elen + 1];
	strcpy_s(buffer, blen + elen + 1, RBin);
	if (elen > 0)
	{
		::GetEnvironmentVariableA("PATH", &(buffer[blen]), elen);
	}

	::SetEnvironmentVariableA("PATH", buffer);
	::SetEnvironmentVariableA("HOME", Home);

	delete[] buffer;

	// load xll

#ifdef _DEBUG 
#ifdef _WIN64
	sprintf_s(BERTXLL, 32, "BERT64D.xll");
#else
	sprintf_s(BERTXLL, 32, "BERT32D.xll");
#endif
#else
#ifdef _WIN64
	sprintf_s(BERTXLL, 32, "BERT64.xll");
#else
	sprintf_s(BERTXLL, 32, "BERT32.xll");
#endif
#endif

	pApplication->QueryInterface(__uuidof(IDispatch), (LPVOID*)&m_pApplication);
	pAddInInst->QueryInterface(__uuidof(IDispatch), (LPVOID*)&m_pAddInInstance);

	::PathAddBackslashA(Install);
	::PathCombineA(XLLPath, Install, BERTXLL);

	CComQIPtr<Excel::_Application> app = m_pApplication;
	if (app){

		int rslt = SetCOMPtrs((void*)m_pApplication.p, (void*)this);
		if (!rslt){
			ATLTRACE("Already registered\n");
		}
		else if (rslt && strlen(XLLPath))
		{
			_bstr_t bstrPath(XLLPath);
			VARIANT_BOOL vb = VARIANT_FALSE;
			HRESULT hr = app->RegisterXLL(bstrPath, 1033, &vb);
			if (SUCCEEDED(hr)){
				if (vb) {
					SetCOMPtrs((void*)m_pApplication.p, (void*)this);
					// ATLTRACE("Loaded xll OK");
				}
				else {
					// ATLTRACE("Succeeded but load returned false\n");
				}
			}
			else {
				// ATLTRACE("Failed with 0x%x\n", hr);
			}
		}
	}

	return S_OK;
}
Beispiel #3
0
int main(int argc, char** argv) {
    char *outfile = 0;
    int from_stdin = 0;
    bool generate_source_map = false;
    struct Sass_Options* options = sass_make_options();
    sass_option_set_output_style(options, SASS_STYLE_NESTED);
    char *include_paths = NULL;
    sass_option_set_precision(options, 5);

    int c, i;
    int long_index = 0;
    static struct option long_options[] =
    {
        { "stdin",              no_argument,       0, 's' },
        { "load-path",          required_argument, 0, 'I' },
        { "style",              required_argument, 0, 't' },
        { "line-numbers",       no_argument,       0, 'l' },
        { "line-comments",      no_argument,       0, 'l' },
        { "sourcemap",          no_argument,       0, 'm' },
        { "omit-map-comment",   no_argument,       0, 'M' },
        { "precision",          required_argument, 0, 'p' },
        { "version",            no_argument,       0, 'v' },
        { "help",               no_argument,       0, 'h' },
        { NULL,                 0,                 NULL, 0}
    };
    while ((c = getopt_long(argc, argv, "vhslmMt:I:", long_options, &long_index)) != -1) {
        switch (c) {
        case 's':
            from_stdin = 1;
            break;
        case 'I':
            if (!include_paths) {
#ifdef _MSC_VER
                include_paths = _strdup(optarg);
#else 
				include_paths = strdup(optarg);
#endif
			} else {
                char *old_paths = include_paths;
				size_t len = strlen(old_paths) + 1 + strlen(optarg) + 1;
                include_paths = malloc(len);
#ifdef _MSC_VER
				assert(include_paths != 0);
                sprintf_s(include_paths, len, "%s%c%s", old_paths, PATH_SEP, optarg);
#else
				sprintf(include_paths, "%s%c%s", old_paths, PATH_SEP, optarg);
#endif
				free(old_paths);
            }
            break;
        case 't':
            for(i = 0; i < NUM_STYLE_OPTION_STRINGS; ++i) {
                if(strcmp(optarg, style_option_strings[i].style_string) == 0) {
                    sass_option_set_output_style(options, style_option_strings[i].output_style);
                    break;
                }
            }
            if(i == NUM_STYLE_OPTION_STRINGS) {
                fprintf(stderr, "Invalid argument for -t flag: '%s'. Allowed arguments are:", optarg);
                for(i = 0; i < NUM_STYLE_OPTION_STRINGS; ++i) {
                    fprintf(stderr, " %s", style_option_strings[i].style_string);
                }
                fprintf(stderr, "\n");
                invalid_usage(argv[0]);
            }
            break;
        case 'l':
            sass_option_set_source_comments(options, true);
            break;
        case 'm':
            generate_source_map = true;
            break;
        case 'M':
            sass_option_set_omit_source_map_url(options, true);
            break;
        case 'p':
            sass_option_set_precision(options, atoi(optarg)); // TODO: make this more robust
            if (sass_option_get_precision(options) < 0) sass_option_set_precision(options, 5);
            break;
        case 'v':
            print_version(argv[0]);
            return 0;
        case 'h':
            print_usage(argv[0]);
            return 0;
        case '?':
            /* Unrecognized flag or missing an expected value */
            /* getopt should produce it's own error message for this case */
            invalid_usage(argv[0]);
        default:
            fprintf(stderr, "Unknown error while processing arguments\n");
            return 2;
        }
    }

    sass_option_set_include_path(options, include_paths ? include_paths : "");

    if(optind < argc - 2) {
        fprintf(stderr, "Error: Too many arguments.\n");
        invalid_usage(argv[0]);
    }

    int result;
    if(optind < argc && strcmp(argv[optind], "-") != 0 && !from_stdin) {
        if (optind + 1 < argc) {
            outfile = argv[optind + 1];
        }
        if (generate_source_map && outfile) {
            const char* extension = ".map";
			size_t len = strlen(outfile) + strlen(extension) + 1;
            char* source_map_file  = calloc(len, sizeof(char));
#ifdef _MSC_VER
            strcpy_s(source_map_file, (len*sizeof(char)), outfile);
            strcat_s(source_map_file, (len*sizeof(char)), extension);
#else
			strcpy(source_map_file, outfile);
			strcat(source_map_file, extension);
#endif
            sass_option_set_source_map_file(options, source_map_file);
        }
        result = compile_file(options, argv[optind], outfile);
    } else {
        if (optind < argc) {
            outfile = argv[optind];
        }
        result = compile_stdin(options, outfile);
    }

    free(include_paths);

    return result;
}
Beispiel #4
0
int verbTOC::DoWork(const char *nameOfInput)
{
    LogVerbose("Indexing from '%s' into '%s.mct'", nameOfInput, nameOfInput);

    MethodContextIterator mci;
    if (!mci.Initialize(nameOfInput))
        return -1;

    int savedCount = 0;

    TOCElementNode *head = nullptr;
    TOCElementNode *curElem = nullptr;

    while (mci.MoveNext())
    {
        MethodContext* mc = mci.Current();

        TOCElementNode *nxt = new TOCElementNode(mci.MethodContextNumber(), mci.CurrentPos());
        mc->dumpMethodMD5HashToBuffer(nxt->tocElement.Hash, MD5_HASH_BUFFER_SIZE);

        if (curElem != nullptr)
        {
            curElem->Next = nxt;
        }
        else
        {
            head = nxt;
        }
        curElem = nxt;
        savedCount++;
    }

    size_t maxLen = strlen(nameOfInput) + 5;
    char *nameOfOutput = (char*)_alloca(maxLen);
    strcpy_s(nameOfOutput, maxLen, nameOfInput);
    strcat_s(nameOfOutput, maxLen, ".mct");
    HANDLE hFileOut = CreateFileA(nameOfOutput, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFileOut == INVALID_HANDLE_VALUE)
    {
        LogError("Failed to open input 1 '%s'. GetLastError()=%u", nameOfOutput, GetLastError());
        return -1;
    }

    DWORD written;
    // Write out the signature "INDX" and then the element count
    LARGE_INTEGER token;
    token.u.LowPart = *(const int*)"INDX"; // cuz Type Safety is for languages that have good IO facilities
    token.u.HighPart = savedCount;
    if (!WriteFile(hFileOut, &token, sizeof(token), &written, nullptr) || written != sizeof(token))
    {
        LogError("Failed to write index header. GetLastError()=%u", GetLastError());
    }

    // Now just dump sizeof(TOCElement) byte chunks into the file.
    // I could probably do this more efficiently, but I don't think it matters
    DWORD chunkSize = sizeof(TOCElement);
    for (curElem = head; curElem != nullptr; curElem = curElem->Next)
    {
        if (!WriteFile(hFileOut, &curElem->tocElement, chunkSize, &written, nullptr) || written != chunkSize)
        {
            LogError("Failed to write index element '%d'. GetLastError()=%u", curElem->tocElement.Number, GetLastError());
            return -1;
        }
    }
    // Now write out a final "INDX" to flag the end of the file...
    if (!WriteFile(hFileOut, &token.u.LowPart, sizeof(token.u.LowPart), &written, nullptr) || (written != sizeof(token.u.LowPart)))
    {
        LogError("Failed to write index terminal. GetLastError()=%u", GetLastError());
    }

    LogInfo("Loaded %d, added %d to Table of Contents", mci.MethodContextNumber(), savedCount);

    if (CloseHandle(hFileOut) == 0)
    {
        LogError("CloseHandle failed. GetLastError()=%u", GetLastError());
        return -1;
    }

    if (!mci.Destroy())
        return -1;

    return 0;
}
/**
 * @brief Load an animation.  This stores the compressed data, which instances of the animation can reference.  
 * Must be free'ed later with anim_free().
 * 
 * @param real_filename Filename of animation
 * @param cf_dir_type 
 * @param file_mapped Whether to use memory-mapped file or not.
 * 
 * @details Memory-mapped files will page in the animation from disk as it is needed, but performance is not as good.
 * @return Pointer to anim that is loaded if sucess, NULL if failure.
 */
anim *anim_load(const char *real_filename, int cf_dir_type, int file_mapped)
{
	anim			*ptr;
	CFILE			*fp;
	int			count,idx;
	char name[_MAX_PATH];

	Assert( real_filename != NULL );

	strcpy_s( name, real_filename );
	char *p = strchr( name, '.' );
	if ( p ) {
		*p = 0;
	}
	strcat_s( name, ".ani" );

	ptr = first_anim;
	while (ptr) {
		if (!stricmp(name, ptr->name))
			break;

		ptr = ptr->next;
	}

	if (!ptr) {
		fp = cfopen(name, "rb", CFILE_NORMAL, cf_dir_type);
		if ( !fp )
			return NULL;

		ptr = (anim *) vm_malloc(sizeof(anim));
		Assert(ptr);

		ptr->flags = 0;
		ptr->next = first_anim;
		first_anim = ptr;
		Assert(strlen(name) < _MAX_PATH - 1);
		strcpy_s(ptr->name, name);
		ptr->instance_count = 0;
		ptr->width = 0;
		ptr->height = 0;
		ptr->total_frames = 0;
		ptr->keys = NULL;
		ptr->ref_count=0;

		anim_read_header(ptr, fp);

		if (ptr->width < 0 || ptr->height < 0) {
			Error(LOCATION, "Ani file %s has a faulty header and cannot be loaded.", name);
		}

		if(ptr->num_keys > 0){
			ptr->keys = (key_frame*)vm_malloc(sizeof(key_frame) * ptr->num_keys);
			Assert(ptr->keys != NULL);
		} 			

		// store how long the anim should take on playback (in seconds)
		ptr->time = i2fl(ptr->total_frames)/ptr->fps;

		for(idx=0;idx<ptr->num_keys;idx++){
			ptr->keys[idx].frame_num = 0;
			cfread(&ptr->keys[idx].frame_num, 2, 1, fp);
			cfread(&ptr->keys[idx].offset, 4, 1, fp);
			ptr->keys[idx].frame_num = INTEL_INT( ptr->keys[idx].frame_num ); //-V570
			ptr->keys[idx].offset = INTEL_INT( ptr->keys[idx].offset ); //-V570
		}

		cfread(&count, 4, 1, fp);	// size of compressed data
		count = INTEL_INT( count );

		ptr->cfile_ptr = NULL;

		if ( file_mapped == PAGE_FROM_MEM) {
			// Try mapping the file to memory 
			ptr->flags |= ANF_MEM_MAPPED;
			ptr->cfile_ptr = cfopen(name, "rb", CFILE_MEMORY_MAPPED, cf_dir_type);
		}

		// couldn't memory-map file... must be in a packfile, so stream manually
		if ( file_mapped == PAGE_FROM_MEM && !ptr->cfile_ptr ) {
			ptr->flags &= ~ANF_MEM_MAPPED;
			ptr->flags |= ANF_STREAMED;
			ptr->cfile_ptr = cfopen(name, "rb", CFILE_NORMAL, cf_dir_type);
		}

		ptr->cache = NULL;

		// If it opened properly as mem-mapped (or streamed)
		if (ptr->cfile_ptr != NULL)	{
			// VERY IMPORTANT STEP
			// Set the data pointer to the compressed data (which is not at the start of the
			// file).  Use ftell() to find out how far we've already parsed into the file
			//
			int offset;
			offset = cftell(fp);
			ptr->file_offset = offset;
			if ( ptr->flags & ANF_STREAMED ) {
				ptr->data = NULL;
				ptr->cache_file_offset = ptr->file_offset;
				ptr->cache = (ubyte*)vm_malloc(ANI_STREAM_CACHE_SIZE+2);
				Assert(ptr->cache);
				cfseek(ptr->cfile_ptr, offset, CF_SEEK_SET);
				cfread(ptr->cache, ANI_STREAM_CACHE_SIZE, 1, ptr->cfile_ptr);
			} else {
				ptr->data = (ubyte*)cf_returndata(ptr->cfile_ptr) + offset;
			}
		} else {
			// Not a memory mapped file (or streamed)
			ptr->flags &= ~ANF_MEM_MAPPED;
			ptr->flags &= ~ANF_STREAMED;
			ptr->data = (ubyte *) vm_malloc(count);
			ptr->file_offset = -1;
			cfread(ptr->data, count, 1, fp);
		}

		cfclose(fp);

		// store screen signature, so we can tell if palette changes
		ptr->screen_sig = gr_screen.signature;

		anim_set_palette(ptr);
	}

	ptr->ref_count++;
	return ptr;
}
Beispiel #6
0
/*++
Function:
  SearchPathA

See MSDN doc.

PAL-specific notes :
-lpPath must be non-NULL; path delimiters are platform-dependent (':' for Unix)
-lpFileName must be non-NULL, may be an absolute path
-lpExtension must be NULL
-lpFilePart (if non-NULL) doesn't need to be used (but we do)
--*/
DWORD
PALAPI
SearchPathA(
    IN LPCSTR lpPath,
    IN LPCSTR lpFileName,
    IN LPCSTR lpExtension,
    IN DWORD nBufferLength,
    OUT LPSTR lpBuffer,
    OUT LPSTR *lpFilePart
    )
{
    DWORD nRet = 0;
    CHAR FullPath[MAX_PATH];
    CHAR CanonicalFullPath[MAX_PATH];
    LPCSTR pPathStart;
    LPCSTR pPathEnd;
    size_t PathLength;
    size_t FileNameLength;
    DWORD dw;

    PERF_ENTRY(SearchPathA);
    ENTRY("SearchPathA(lpPath=%p (%s), lpFileName=%p (%s), lpExtension=%p, "
          "nBufferLength=%u, lpBuffer=%p, lpFilePart=%p)\n",
      lpPath,
      lpPath, lpFileName, lpFileName, lpExtension, nBufferLength, lpBuffer, 
          lpFilePart);

    /* validate parameters */
    
    if(NULL == lpPath)
    {
        ASSERT("lpPath may not be NULL\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }
    if(NULL == lpFileName)
    {
        ASSERT("lpFileName may not be NULL\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }
    if(NULL != lpExtension)
    {
        ASSERT("lpExtension must be NULL, is %p instead\n", lpExtension);
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    FileNameLength = strlen(lpFileName);

    /* special case : if file name contains absolute path, don't search the 
       provided path */
    if('\\' == lpFileName[0] || '/' == lpFileName[0])
    {
        if(FileNameLength >= MAX_PATH)
        {
            WARN("absolute file name <%s> is too long\n", lpFileName);
            SetLastError(ERROR_INVALID_PARAMETER);
            goto done;
        }
        /* Canonicalize the path to deal with back-to-back '/', etc. */
        dw = GetFullPathNameA(lpFileName, MAX_PATH, CanonicalFullPath, NULL);
        if (dw == 0 || dw >= MAX_PATH) 
        {
            WARN("couldn't canonicalize path <%s>, error is %#x. failing.\n",
                 FullPath, GetLastError());
            SetLastError(ERROR_INVALID_PARAMETER);
            goto done;
        }

        /* see if the file exists */
        if(0 == access(CanonicalFullPath, F_OK))
        {
            /* found it */
            nRet = dw;
        }
    }
    else
    {
        LPCSTR pNextPath;
        
        pNextPath = lpPath;
    
        while (*pNextPath) 
        {
            pPathStart = pNextPath;
            
            /* get a pointer to the end of the first path in pPathStart */
            pPathEnd = strchr(pPathStart, ':');
            if (!pPathEnd)
            {
                pPathEnd = pPathStart + strlen(pPathStart);
                /* we want to break out of the loop after this pass, so let
                   *pNextPath be '\0' */
                pNextPath = pPathEnd;
            }
            else
            {
                /* point to the next component in the path string */
                pNextPath = pPathEnd+1;
            }
    
            PathLength = pPathEnd-pPathStart;
    
            if (PathLength+FileNameLength+1 >= MAX_PATH) 
            {
                /* The path+'/'+file length is too long.  Skip it. */
                WARN("path component %.*s is too long, skipping it\n", 
                     (int)PathLength, pPathStart);
                continue;
            }
            else if(0 == PathLength)
            {
                /* empty component : there were 2 consecutive ':' */
                continue;
            }
    
            /* Construct a pathname by concatenating one path from lpPath, '/' 
               and lpFileName */
            memcpy(FullPath, pPathStart, PathLength);
            FullPath[PathLength] = '/';
            if (strcpy_s(&FullPath[PathLength+1], MAX_PATH-PathLength, lpFileName) != SAFECRT_SUCCESS)
            {
                ERROR("strcpy_s failed!\n");
                SetLastError( ERROR_FILENAME_EXCED_RANGE );
                nRet = 0;
                goto done;
            }

            /* Canonicalize the path to deal with back-to-back '/', etc. */
            dw = GetFullPathNameA(FullPath, MAX_PATH,
                                  CanonicalFullPath, NULL);
            if (dw == 0 || dw >= MAX_PATH) 
            {
                /* Call failed - possibly low memory.  Skip the path */
                WARN("couldn't canonicalize path <%s>, error is %#x. "
                     "skipping it\n", FullPath, GetLastError());
                continue;
            }
    
            /* see if the file exists */
            if(0 == access(CanonicalFullPath, F_OK))
            {
                /* found it */
                nRet = dw;
                break;
            }
        }
    }

    if (nRet == 0) 
    {
       /* file not found anywhere; say so. in Windows, this always seems to say
          FILE_NOT_FOUND, even if path doesn't exist */
       SetLastError(ERROR_FILE_NOT_FOUND);
    }
    else
    {
        if (nRet < nBufferLength) 
        {
            if(NULL == lpBuffer)
            {
                /* Windows merily crashes here, but let's not */
                ERROR("caller told us buffer size was %d, but buffer is NULL\n",
                      nBufferLength);
                SetLastError(ERROR_INVALID_PARAMETER);
                nRet = 0;
                goto done;
            }
            
            if (strcpy_s(lpBuffer, nBufferLength, CanonicalFullPath) != SAFECRT_SUCCESS)
            {
                ERROR("strcpy_s failed!\n");
                SetLastError( ERROR_FILENAME_EXCED_RANGE );
                nRet = 0;
                goto done;
            }

            if(NULL != lpFilePart)
            {
                *lpFilePart = strrchr(lpBuffer,'/');
                if(NULL == *lpFilePart)
                {
                    ASSERT("no '/' in full path!\n");
                }
                else
                {
                    /* point to character after last '/' */
                    (*lpFilePart)++;
                }
            }
        }
        else
        {
            /* if buffer is too small, report required length, including 
               terminating null */
            nRet++;
        }
    }
done:
    LOGEXIT("SearchPathA returns DWORD %u\n", nRet);
    PERF_EXIT(SearchPathA);
    return nRet;
}
Beispiel #7
0
/*++
Function:
  GetFullPathNameA

See MSDN doc.
--*/
DWORD
PALAPI
GetFullPathNameA(
     IN LPCSTR lpFileName,
     IN DWORD nBufferLength,
     OUT LPSTR lpBuffer,
     OUT LPSTR *lpFilePart)
{
    DWORD  nReqPathLen, nRet = 0;
    LPSTR lpUnixPath = NULL;
    BOOL fullPath = FALSE;

    PERF_ENTRY(GetFullPathNameA);
    ENTRY("GetFullPathNameA(lpFileName=%p (%s), nBufferLength=%u, lpBuffer=%p, "
          "lpFilePart=%p)\n",
          lpFileName?lpFileName:"NULL",
          lpFileName?lpFileName:"NULL", nBufferLength, lpBuffer, lpFilePart);

    if(NULL == lpFileName)
    {
        WARN("lpFileName is NULL\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    /* find out if lpFileName is a partial or full path */
    if ('\\' == *lpFileName || '/' == *lpFileName)
    {
        fullPath = TRUE;
    }

    if(fullPath)
    {
        lpUnixPath = PAL__strdup( lpFileName );
        if(NULL == lpUnixPath)
        {
            ERROR("strdup() failed; error is %d (%s)\n",
                  errno, strerror(errno));
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto done;
        }
    }   
    else
    {
        size_t max_len;

        /* allocate memory for full non-canonical path */
        max_len = strlen(lpFileName)+1; /* 1 for the slash to append */
        max_len += MAX_LONGPATH + 1; 
        lpUnixPath = (LPSTR)PAL_malloc(max_len);
        if(NULL == lpUnixPath)
        {
            ERROR("PAL_malloc() failed; error is %d (%s)\n",
                  errno, strerror(errno));
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto done;
        }
        
        /* build full path */
        if(!GetCurrentDirectoryA(MAX_LONGPATH + 1, lpUnixPath))
        {
            /* no reason for this to fail now... */
            ASSERT("GetCurrentDirectoryA() failed! lasterror is %#xd\n",
                   GetLastError());
            SetLastError(ERROR_INTERNAL_ERROR);
            goto done;
        }
        
        if (strcat_s(lpUnixPath, max_len, "/") != SAFECRT_SUCCESS)
        {
            ERROR("strcat_s failed!\n");
            SetLastError(ERROR_FILENAME_EXCED_RANGE);
            goto done;
        }

        if (strcat_s(lpUnixPath, max_len, lpFileName) != SAFECRT_SUCCESS)
        {
            ERROR("strcat_s failed!\n");
            SetLastError(ERROR_FILENAME_EXCED_RANGE);
            goto done;
        }
    }

    /* do conversion to Unix path */
    FILEDosToUnixPathA( lpUnixPath );
 
    /* now we can canonicalize this */
    FILECanonicalizePath(lpUnixPath);

    /* at last, we can figure out how long this path is */
    nReqPathLen = strlen(lpUnixPath)+1;

    if(nBufferLength < nReqPathLen)
    {
        TRACE("reporting insufficient buffer : minimum is %d, caller "
              "provided %d\n", nReqPathLen, nBufferLength);
        nRet = nReqPathLen;
        goto done;
    }

    nRet = nReqPathLen-1;
    strcpy_s(lpBuffer, nBufferLength, lpUnixPath);

    /* locate the filename component if caller cares */
    if(lpFilePart)
    {
        *lpFilePart = strrchr(lpBuffer, '/');

        if (*lpFilePart == NULL)
        {
            ASSERT("Not able to find '/' in the full path.\n");
            SetLastError( ERROR_INTERNAL_ERROR );
            nRet = 0;
            goto done;
        }
        else 
        {
            (*lpFilePart)++; 
        }
    }

done:
    PAL_free (lpUnixPath);
    LOGEXIT("GetFullPathNameA returns DWORD %u\n", nRet);
    PERF_EXIT(GetFullPathNameA);
    return nRet;
}
Beispiel #8
0
BOOL CDBConnect::init()
{
	strcpy_s(m_szConnStr, g_pCfg->GetDBConnStr().GetBuffer());
	strcpy_s(m_szUser, g_pCfg->GetDBUser().GetBuffer());
	strcpy_s(m_szPwd, g_pCfg->GetDBPwd());

	try
	{
		//没有配置oracle客户端情况下ado连接字符串
		//CString  m_sConn="Provider=OraOLEDB.Oracle.1;Password=platform1234;Persist Security Info=True;User ID=platform;Data Source=\"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 服务器地址)(PORT = 1521)) )(CONNECT_DATA = (SID = 数据库实例名)))\"";
		
		//配置好了oracle客户端 情况下ado连接字符串
		CString m_sConn;
		m_sConn.Format("Provider=OraOLEDB.Oracle.1;Persist Security Info=True;server=serveraddress;Data Source=%s;User ID=%s;Password=%s",
			m_szConnStr, m_szUser, m_szPwd);
		
		m_pConnection->Open((_bstr_t)m_sConn,"","",adConnectUnspecified);
		
		//下面是查询数据的例子
		CString strSql = "update authentication set auth_info = '2EXR8U3TUWYUOWF167PT4W46I4R550H1' where user_code = 9999";
		//CString strSql = "select authentication.auth_info from authentication where authentication.user_code = 9999";
		BSTR bstrSQL = strSql.AllocSysString();

		_variant_t RecordsAffected; //VARIANT数据类型

		m_pConnection->BeginTrans();
		m_pConnection->Execute(bstrSQL,&RecordsAffected,adCmdText);
		m_pConnection->CommitTrans();

		strSql="select * from  customers where cust_code = 10007887";
		bstrSQL = strSql.AllocSysString();
		m_pRecordset->Open(bstrSQL, (IDispatch*)m_pConnection, adOpenDynamic, adLockOptimistic, adCmdText); 
		
		_variant_t TheValue; //VARIANT数据类型
		char szTmp[100] = {0};

		while(!m_pRecordset->adoEOF)
		{				
			TheValue = m_pRecordset->GetCollect("CUST_CODE");
			if(TheValue.vt!=VT_NULL)
			{				
				strncpy_s(szTmp, (char*)_bstr_t(TheValue), 100);
			}
			m_pRecordset->MoveNext();
		}

		m_pRecordset->Close();
	}
	catch (_com_error e)//异常处理
	{
		CString strMsg;
		strMsg.Format(_T("错误描述:%s\n错误消息%s"),
		(LPCTSTR)e.Description(),
		(LPCTSTR)e.ErrorMessage());

		return FALSE;
	}

	g_pLog->WriteRunLog(SYS_MODE, LOG_DEBUG, "初始化DBConn成功! ConnStr:%s, User:%s, Pwd:%s", m_szConnStr, m_szUser, m_szPwd);
	return TRUE;
}
Beispiel #9
0
void    scr_label( void )
{
    condcode        cc;
    getnum_block    gn;
    labelcb     *   lb;
    char            linestr[MAX_L_AS_STR];

    scan_start += 2;                    // over dots

    while( *scan_start == ' ' ) {       // may be ...LABEL or ...      LABEL
        scan_start++;                   // over blanks
    }
    if( *scan_start == '\0'  ) {        // no label?
        scan_err = true;
        err_count++;
        g_err( err_missing_name, "" );
        if( input_cbs->fmflags & II_macro ) {
            ultoa( input_cbs->s.m->lineno, linestr, 10 );
            g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
        } else {
            ultoa( input_cbs->s.f->lineno, linestr, 10 );
            g_info( inf_file_line, linestr, input_cbs->s.f->filename );
        }
        show_include_stack();
        return;
    } else {

        gn.argstart      = scan_start;
        gn.argstop       = scan_stop;
        gn.ignore_blanks = 0;

        cc = getnum( &gn );             // try numeric expression evaluation
        if( cc == pos ) {               // numeric linenumber

            scan_start = gn.argstart;   // start for next token

            // check if lineno from label matches actual lineno

            if( input_cbs->fmflags & II_macro ) {
                if( gn.result != input_cbs->s.m->lineno ) {
                    scan_err = true;
                    err_count++;
                    g_err( err_label_line, gn.resultstr );
                    ultoa( input_cbs->s.m->lineno, linestr, 10 );
                    g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                    show_include_stack();
                    return;
                }
            } else {
                if( gn.result != input_cbs->s.f->lineno ) {
                    scan_err = true;
                    err_count++;
                    g_err( err_label_line, gn.resultstr );
                    ultoa( input_cbs->s.f->lineno, linestr, 10 );
                    g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                    show_include_stack();
                    return;
                }
            }

            if( input_cbs->fmflags & II_macro ) {
                  // numeric macro label no need to store
            } else {
                wng_count++;
                g_warn( wng_label_num );
                ultoa( input_cbs->s.f->lineno, linestr, 10 );
                g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                show_include_stack();
            }

        } else {                        // no numeric label
            cc = getarg();
            if( cc == pos ) {           // label name specefied
                char    *   p;
                char    *   pt;
                int         len;

                p   = tok_start;
                pt  = token_buf;
                len = 0;
                while( len < arg_flen ) {   // copy to buffer
                    *pt++ = *p++;
                    len++;
                }
                *pt = '\0';
                if( len >  MAC_NAME_LENGTH ) {
                    err_count++;
                    g_err( err_sym_long, token_buf );
                    ultoa( input_cbs->s.f->lineno, linestr, 10 );
                    g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                    show_include_stack();
                    token_buf[MAC_NAME_LENGTH] = '\0';
                }

                if( input_cbs->fmflags & II_macro ) {

                    cc = test_duplicate( token_buf, input_cbs->s.m->lineno );
                    if( cc == pos ) {   // ok name and lineno match
                        // nothing to do
                    } else {
                        if( cc == neg ) {   // name with different lineno
                            scan_err = true;
                            err_count++;
                            g_err( err_label_dup, token_buf );
                            ultoa( input_cbs->s.m->lineno, linestr, 10 );
                            g_info( inf_mac_line, linestr,
                                     input_cbs->s.m->mac->name );
                            show_include_stack();
                            return;
                        } else {        // new label
                            lb              = mem_alloc( sizeof( labelcb ) );
                            lb->prev        = input_cbs->s.m->mac->label_cb;
                            input_cbs->s.m->mac->label_cb = lb;
                            lb->pos         = 0;
                            lb->lineno      = input_cbs->s.m->lineno;
                            strcpy_s( lb->label_name, sizeof( lb->label_name ),
                                      token_buf );
                        }
                    }
                } else {
                    cc = test_duplicate( token_buf, input_cbs->s.f->lineno );
                    if( cc == pos ) {   // ok name and lineno match
                        // nothing to do
                    } else {
                        if( cc == neg ) {   // name with different lineno
                            scan_err = true;
                            err_count++;
                            g_err( err_label_dup, token_buf );
                            ultoa( input_cbs->s.f->lineno, linestr, 10 );
                            g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                            show_include_stack();
                            return;
                        } else {        // new label

                            lb              = mem_alloc( sizeof( labelcb ) );
                            lb->prev        = input_cbs->s.f->label_cb;
                            input_cbs->s.f->label_cb = lb;
                            lb->pos         = input_cbs->s.f->pos;
                            lb->lineno      = input_cbs->s.f->lineno;
                            strcpy_s( lb->label_name, sizeof( lb->label_name ),
                                      token_buf );
                        }
                    }
                }
            } else {
                scan_err = true;
                err_count++;
                g_err( err_missing_name, "" );
                if( input_cbs->fmflags & II_macro ) {
                    ultoa( input_cbs->s.m->lineno, linestr, 10 );
                    g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                } else {
                    ultoa( input_cbs->s.f->lineno, linestr, 10 );
                    g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                }
                show_include_stack();
                return;
            }
        }

        if( *scan_start == ' ' ) {
            scan_start++;               // skip one blank

            if( *scan_start ) {         // rest of line is not empty
                split_input( buff2, scan_start, false );// split and process next
            }
        }
        scan_restart = scan_stop + 1;
        return;
    }
}
Beispiel #10
0
void ConsoleCommand()
{
	char command[127];
	char args[4][127];
	int tmp;
	FILE *file_exist;

	Help();

	while(true)
	{
	 printf("> ");
	 gets_s(command);
	 sscanf(command, "%s %s", args[0], args[1]);
	 if(!strcmp(args[0], "load"))
	 {
	  printf("COMMAND LOADING [%s]\n", args[1]);
	  for(int i = 0; i < MAX_SCRIPT_RUN; i++)
	  {
		if(LS[i].active == false)
		{
		 strncpy_s(PATH_FILE_TMP_FILE, PATH_FILE, index_file+1);
		 PATH_FILE_TMP_FILE[index_file+1] = '\0';
      
		 strcat_s(PATH_FILE_TMP_FILE,  args[1]);
		 strcpy_s(LS[i].FileScrips, PATH_FILE_TMP_FILE);

		 if(file_exist = fopen(LS[i].FileScrips, "r"))
		 {
		  loadscript(L, LS[i].FileScrips);
		  LS[i].active = true;
		  scrips_load++;

		  printf("SCRIPT_ID [%d]\n", i);
		  printf("[%d] Script Loaded\n", scrips_load);

		  fclose(file_exist);
		 }
		 else
		 {
		  printf("ERROR: file no found\n");
		  LS[i].FileScrips[0] = NULL;
		 }
		 break;
		}
	  }
	 }

	 if(!strcmp(args[0], "stop"))
	 {
	  tmp = atol(args[1]);
	  if(LS[tmp].FileScrips[0] != NULL)
	  {
	   LS[tmp].active = false;
	   printf("STOP SUCESSFULLY\n");
	  }
	  else
	   printf("STOP FAILED\n");
	 }

	 if(!strcmp(args[0], "start"))
	 {
	  tmp = atol(args[1]);
	  if(LS[tmp].FileScrips[0] != NULL)
	  {
	   LS[tmp].active = true;
	   printf("START SUCESSFULLY\n");
	  }
	  else
	   printf("START FAILED\n");
	 }

	 if(!strcmp(args[0], "exit"))
	  exit(1);

	 args[0][0] = NULL;
	 args[1][0] = NULL;
	 args[2][0] = NULL;
	 args[3][0] = NULL;
	}
}
/*
* ディスプレイ関数
*/
static void display(void)
{
	const static GLfloat white[] = { 1.0, 1.0, 1.0, 1.0 };    /* ���̐F */
	const static GLfloat lightpos[] = { 12.0, 16.0, 20.0, 1.0 }; /* �����̈ʒu */

	/* ���ʃN���A */
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	t = dt * tn;

	/* ���f���r���[�ϊ��s���̏����� */
	glLoadIdentity();

	if (batted) gluLookAt(px, py, pz, px, py - 2, pz - 15, 0, 0.8, 0.4);
	else gluLookAt(0, 0, 0, cam_x, cam_y, cam_z, 0, 1, 0);
	
	glLightfv(GL_LIGHT0, GL_POSITION, lightpos);

	/* 回転 */
	glRotated(cam_x_angle, 1.0, 0.0, 0.0);
	glRotated(cam_y_angle, 0.0, 1.0, 0.0);

		

	/* �����̈ʒu���ݒ� */
	
	/* カメラの位置 */
	glTranslated(cam_x, cam_y, cam_z);

	zone(); // ストライクゾーンの描画	
	myGround(0.0); // 大地の描画

	base(); //ホームベースの描画
	line(); //塁線の描画
	scoreboard(0, -60, 15.0, 3.5, 1.25);
	//scoreboard(1, -60, 1.7, 1.5, 3.0);
	//scoreboard(2, -60, 1.1, 0.56, 3.75);

	//myBox(15, 13, 5, 0, 1, -80);
	//glPushMatrix();
	//glRotated(10, 1.0, 0.0, 0.0);
	//myPalse(0.0, 5.0, -10.0, 10.0, 8.0, 90);
	//glPopMatrix();

	tn++;

	/* ピッチャーの描画 */
	pitcher(QX, QY - 0.9, QZ);

	if (batted){ // 打球の軌道計算
		px = mx + vx * (t - 2.0);
		py = my + 0.5 * G * (t - 2.0) * (t - 2.0) + vy * (t - 2.0);
		pz = 16.0 + 6.5 + 0.5 * az * (t - 2.0) * (t - 2.0) + vz * (t - 2.0);

		/*px = px_achieve + vx * t;
		py = py_achieve + 0.5 * G * t * t + vy * t;
		pz = 18.0 + 0.5 * az * t * t + vz * t;*/
	} else { // 投球の軌道計算
		px = vx * (t - 2.0) + QX;
		py = 0.5 * G * (t - 2.0) * (t - 2.0) + vy * (t - 2.0) + QY;
		pz = 0.5 * az * (t - 2.0) * (t - 2.0) + vz * (t - 2.0) + QZ;

	}

	/* 着弾点の x, y座標を計算 */
	if (pz < 18.0){
		t_achieve = (-vz + sqrt(vz * vz + 2 * az * 18.0)) / az;
		px_achieve = vx * t_achieve + QX;
		py_achieve = 0.5 * G * t_achieve * t_achieve + vy * t_achieve + QY;
	}

	//printf("t = %f\n", t);
	//printf("(px, py, pz) = (%f, %f, %f)\n", px, py, pz);
	//printf("(vx, vy, vz) = (%f, %f, %f)\n", vx, vy, vz);
	/* 床との衝突 */
	if (py < R){
		py = R;
		vy *= -A;
	}
	/* スライダー */
	if (species == 1 && pz > 12 && pz < 18) {
		vx += 0.002 * pow(t, 4);
	}
	/* カーブ */
	if (species == 2 && pz > 12 && pz < 18) {
		vx += 0.001 * pow(t, 4);
		vy -= 0.002 * pow(t, 4);
	}
	/* スプリット */
	if (species == 3 && pz > 12 && pz < 18) {
		vy -= 0.002 * pow(t, 4);
	}
	/* シンカー */
	if (species == 4 && pz > 12 && pz < 18) {
		vx -= 0.001 * pow(t, 4);
		vy -= 0.002 * pow(t, 4);
	}
	/* シュート */
	if (species == 5 && pz > 12 && pz < 18) {
		vx -= 0.002 * pow(t, 4);
	}
	/* ライジングキャノン */
	if (species == 6 && pz > 12 && pz < 18){
		vy += 0.0015 * pow(t, 4);
	}
	/* Wボール */
	if (species == 7 && pz > 6 && pz < 9){
		vy -= 0.04 * pow(t, 4);
	}
	else if (species == 7 && pz > 9 && pz < 12){
		vy += 0.09 * pow(t, 4);
	}
	else if (species == 7 && pz > 12 && pz < 15){
		vy -= 0.07 * pow(t, 4);
	}
	else if (species == 7 && pz > 15 && pz < 18){
		vy += 0.04 * pow(t, 4);
	}

	char species_name[][15] = { "STRAIGHT", "SLIDER", "CURVE", "SFF", "SINKER", "SHOOT", "RISING_CANON", "W_BALL" };
	/* 球速の表示 */
	char str[100], vz_s[4] = { '\0' }, pz_s[4];
	if (t > t_achieve - 0.01 && t < t_achieve + 0.01){
		vz_achieve = vz;
	}
	if (t > t_achieve + 1.8){
		sprintf_s(vz_s, "%3d", (int)(vz_achieve * 2.7));
		strcpy_s(str, "Speed: ");
		strcat_s(str, vz_s);
		strcat_s(str, "km/h");
		//strcat_s(str, species[key]);
		if ((fabs(px_achieve) < 0.3 && py_achieve > 1.0 && py_achieve < 1.7) || (swinged == 1 && hitted == 0)) {
			strcpy_s(judge, " Judge: STRIKE! Count: S| ");
		}
		else if (vz < 0){
			strcpy_s(judge, " Judge: HIT! Count: S| ");
		}
		else if (!(fabs(px_achieve) < 0.3 && py_achieve > 1.0 && py_achieve < 1.7)) {
			strcpy_s(judge, " Judge: BALL. Count: S| ");
		}
		for (int i = 0; i < s_count; i++)strcat_s(judge, "*");
		strcat_s(judge, " B| ");
		for (int i = 0; i < b_count; i++)strcat_s(judge, "*");
		if (out == 1)strcat_s(judge, " BATTER OUT!");
		else if (four == 1)strcat_s(judge, " FOUR BALL!");
		//else if (az < 0) strcat_s(judge, " HIT!");
		strcat_s(str, judge);
		strcat_s(str, " Species: ");
		strcat_s(str, species_name[species]);
		if (batted == 1){
			fd = hypot(px, -pz + 18.0);
			sprintf_s(pz_s, "%3d", (int)(fd));
			strcat_s(str, " Frying Distance: ");
			strcat_s(str, pz_s);
			strcat_s(str, "m");
		}
		DrawString(str, 500, 200, 100, 10);
	}

	/* 着弾点を表示 */
	if (pitched){
		GLfloat white[] = { 1.f, 1.f, 1.f };
		if (t > 1.0 && t < 2.0){
			glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
			PrintCircle(2.0 - 1.0 * t + R, 100, px_achieve, py_achieve, 18.0); //円を描画 (半径, 分割数, X座標, Y座標, Z座標)
		}
		else if (t > 2.0){
			glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
			PrintCircle(R, 100, px_achieve, py_achieve, 18.0);
		}
		if (t < 2.0){
			arm_angle = 50 * t * t;
		}
		else if (t > 1.8 && t < 2.17){
			arm_angle += 2.0 * t * t;
		}
	}

	if (swinged){
		bat_angle += VS;
	}
	if (bat_angle > 300){
		bat_angle = 300;
	}
	/* 衝突時の処理 */
	if (hitted){
		bat_angle_hitted = bat_angle + 400 * (2 * t_achieve - 2 * swinged_time + 2.15); // ボールと衝突時のバットの角度を計算
		//th = 10 * PI / 180;
		th = (2 * (bat_angle_hitted - 180) - phi) * PI / 180; /* 打球のY-Z平面となす角度の計算 */
		//r = (200 * (py_achieve - my + 0.1) / 0.125) * PI / 180; /* 打球とX-Z平面となす角度の計算 */
		r = 195 * PI / 180;

		v = -0.3500 / (fabs(mx - px_achieve) + fabs(my - py_achieve)) * 0.5 * 4;

		px = px_achieve;
		py = py_achieve;
		pz = 18.0;
		az = -0.1;

		vx = v * sin(th) * cos(r);
		vy = v * sin(r);
		vz = v * cos(th) * cos(r);

		hitted = 0;
		printf("th = %f\n dt = %f\n",th,t_achieve - swinged_time + 2.0);
	}

	if (t > 2.0 && pitched){
		glPushMatrix();
		glTranslated(px, py, pz);
		glMaterialfv(GL_FRONT, GL_DIFFUSE, white);
		glutSolidSphere(R, 16, 8);
		glPopMatrix();
	}

	/* バッターの描画 */
	batter(mx - 1.2, my - 0.6, 18.0);

	/* バット */
	glPushMatrix();
	glTranslated(mx - 1.2, my, 18.0);
	glRotated(bat_angle, 0.0, 1.0, 0.0);
	glTranslated(-0.8, 0, 0);
	
	glEnable(GL_NORMALIZE);
	GLfloat bat_color[] = { 0.9, 0.7, 0.3, 1.0 };
	glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, bat_color);
	glScalef(1.f, 0.07f, 0.05f);
	displaySphere(0.5f, 0.8f, 0.8f, 0.8f, 0.2f, 0.2f, 0.2f, 10.f);
	glDisable(GL_NORMALIZE);
	glPopMatrix();

	/* ミートカーソルの表示 */

	GLfloat yellow[] = { 1.f, 1.f, 0.f, 1.f };
	glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, yellow);
	PrintEllipse(R + 0.1, 100, mx, my, mz);

	glutSwapBuffers();
}
Beispiel #12
0
void D3DClass::GetVideoCardInfo(char* cardName, int& memory) //returns the name and the memory of the videocard by reference
{
	strcpy_s(cardName, 128, m_videoCardDescription);
	memory = m_videoCardMemory;
	return;
}
Beispiel #13
0
char *GetDirectoryFile(char *filename) {
	static char path[320];
	strcpy_s(path, dlldir);
	strcat_s(path, filename);
	return path;
}
Beispiel #14
0
static GHTTPBool ptaFilePlanetCompletedCallback
(
	GHTTPRequest request,
	GHTTPResult result,
	char * buffer,
	GHTTPByteCount bufferLen,
	void * param
)
{
	ptaFilePlanetInfoData * data = (ptaFilePlanetInfoData *)param;
	int len;
	char description[256];
	char size[64];
	char * mirrorNames[MAX_MIRRORS];
	char * mirrorURLs[MAX_MIRRORS];
	int i;
	char * str;

	// check if the backend is available
	if(__GSIACResult != GSIACAvailable)
		return GHTTPFalse;

	GSI_UNUSED(request);
	GSI_UNUSED(bufferLen);

	// Check for success.
	/////////////////////
	if(result != GHTTPSuccess)
		return ptaFilePlanetInfoFailed(data);

	// Get the description.
	///////////////////////
	len = ptaFillLine(buffer);
	if(len == EOF)
		return ptaFilePlanetInfoFailed(data);
	buffer += len;
	strncpy(description, Line, sizeof(description));
	description[sizeof(description) - 1] = '\0';

	// Get the size.
	////////////////
	len = ptaFillLine(buffer);
	if(len == EOF)
		return ptaFilePlanetInfoFailed(data);
	buffer += len;
	strncpy(size, Line, sizeof(size));
	size[sizeof(size) - 1] = '\0';

	// Get the mirrors.
	///////////////////
	for(i = 0 ; (i < MAX_MIRRORS) && ((len = ptaFillLine(buffer)) != EOF) ; )
	{
		// Adjust the buffer.
		/////////////////////
		buffer += len;

		// Find the tab.
		////////////////
		str = strchr(Line, '\t');
		if(!str)
			continue;

		// Copy off the name.
		/////////////////////
		len = (str - Line);
		mirrorNames[i] = (char *)gsimalloc((unsigned int)len + 1);
		if(!mirrorNames[i])
			break;
		memcpy(mirrorNames[i], Line, (unsigned int)len);
		mirrorNames[i][len] = '\0';

		// Copy off the URL.
		////////////////////
		str++;
		len = (int)strlen(str);
		mirrorURLs[i] = (char *)gsimalloc((unsigned int)len + 1);
		if(!mirrorURLs[i])
		{
			gsifree(mirrorNames[i]);
			break;
		}
		strcpy_s(mirrorURLs[i], sizeof(mirrorURLs)-i, str);

		// One more mirror.
		///////////////////
		i++;
	}

	// Call the callback.
	/////////////////////
	ptaCallFilePlanetInfoCallback(data, PTTrue, description, size, i, mirrorNames, mirrorURLs);

	return GHTTPTrue;
}
int main (int argc, char *argv[])
{
  char buf[MAX_PATH*sizeof(WCHAR) + sizeof(REPARSE_DATA_BUFFER)]={'\0'};
  char* dest_path=NULL;
  char* src_path=NULL;
  char* src_link=NULL;
  char* src_vol=NULL;
  char* dest_vol=NULL;
  HANDLE dir=NULL;
  REPARSE_DATA_BUFFER* reparse = (REPARSE_DATA_BUFFER*) buf;
  int path_len=0, data_len=0;
  DWORD ioctl_return = 0xdeadbeef;

  // To allow this to be used as a drop-in replacement for the posix ln command,
  // allow (and ignore) extra flags.
  if (argc != 3 && (argc !=4 || *argv[1] != '-')) {
    fputs("Usage: create-ntfs-junction <destination dir> <source dir>\n", stderr);
    return -1;
  }

  src_path = argv[argc-2];
  path_len = strlen(src_path);
  if (src_path[path_len-1] == '\\')
    src_path[path_len-1] = '\0';

  dest_path = argv[argc-1];
  path_len = strlen(dest_path);
  if (dest_path[path_len-1] == '\\')
    dest_path[path_len-1] = '\0';

  if (GetFileAttributes(src_path) == INVALID_FILE_ATTRIBUTES) {
    fprintf(stderr, "%s: No such animal.\n", src_path);
    return -1;
  }

  if (!GetVolumePathName(src_path, buf, MAX_PATH)) {
    fprintf(stderr, "Couldn't get volume name for '%s'.\n", src_path);
    return -1;
  }
  src_vol = _strdup(buf);

  if (!GetVolumePathName(dest_path, buf, MAX_PATH)) {
    fprintf(stderr, "Couldn't get volume name for '%s'.\n", dest_path);
    return -1;
  }
  dest_vol = _strdup(buf);

  if (strcmp(src_vol, dest_vol)) {
    fprintf(stderr, "Cannot create junction point across volume boundary.\n");
    fprintf(stderr, "  (from volume '%s' to volume '%s')\n", src_vol, dest_vol);
    return -1;
  }

  // End of input sanity checks; file system modifications may now occur.

  if (GetFileAttributes(dest_path) == INVALID_FILE_ATTRIBUTES) {
    if (!CreateDirectory(dest_path, NULL)) {
      switch(GetLastError()) {
        case ERROR_ALREADY_EXISTS:
          fprintf(stderr, "Can't create directory %s because it already exists "
                  "(this should never happen).\n", dest_path);
          return -1;
          break;
        case ERROR_PATH_NOT_FOUND:
          fprintf(stderr, "Can't create directory %s because some part of the "
                  "intermediate path doesn't exist.", dest_path);
          return -1;
          break;
        default:
          fprintf(stderr, "Unknown error occurred while trying to create "
                  "directory %s.", dest_path);
          return -1;
          break;
      }
    }
  }

  dir = CreateFile(dest_path,
                   GENERIC_WRITE,
                   0,
                   NULL,
                   OPEN_EXISTING,
                   FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
                   NULL);

  strcpy_s(buf, 5, "\\??\\");
  GetFullPathName(src_path, MAX_PATH, buf+4, NULL);
  src_link = _strdup(buf);

  memset(buf, 0, sizeof(buf));
  path_len = MultiByteToWideChar(CP_ACP,
                                 0,
                                 src_link,
                                 -1,
                                 reparse->MountPointReparseBuffer.PathBuffer,
                                 MAX_PATH*sizeof(WCHAR));

  reparse->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
  reparse->ReparseDataLength = (path_len+2)*sizeof(WCHAR) + 6;
  reparse->MountPointReparseBuffer.SubstituteNameLength =
      (path_len-1) * sizeof(WCHAR);
  reparse->MountPointReparseBuffer.PrintNameOffset =
      path_len * sizeof(WCHAR);
  data_len = reparse->ReparseDataLength + 8;

  if (!DeviceIoControl(dir,
                       FSCTL_SET_REPARSE_POINT,
                       &buf,
                       data_len,
                       NULL,
                       0,
                       &ioctl_return,
                       NULL)) {
    fprintf(stderr, "Junction point creation failed (ioctl_return=0x%x) (%d)\n",
            ioctl_return, GetLastError());
    return 1;
  }

  return 0;
}
Beispiel #16
0
void D3DClass::GetVideoCardInfo(char* cardName, int& memory)
{
	strcpy_s(cardName, 128, m_videoCardDescription);
	memory = m_videoCardMemory;
	return;
}
// loads nframes bitmaps, starting at index start_frame.
// anything < start_frame will not be loaded.
// this keeps the loading code from trying to load bitmaps which don't exist
// and taking an unnecessary disk hit.		
int UI_GADGET::set_bmaps(char *ani_fname, int nframes, int start_frame)
{
	int first_frame, i;	
	char full_name[MAX_FILENAME_LEN] = "";
	char tmp[33];
	int idx, s_idx;	
	int num_digits;
	int its_all_good = 0;
	
	// clear out all frames
	for(idx=0; idx<MAX_BMAPS_PER_GADGET; idx++){
		bmap_ids[idx] = -1;
	}
	
	// load all the bitmaps
	bm_filename = ani_fname;

	Assertion(nframes < MAX_BMAPS_PER_GADGET, "Too many frames specified (%d), must be less than MAX_BMAPS_PER_GADGET", nframes);
	m_num_frames = nframes;
	for(idx=start_frame; idx<nframes; idx++){
		// clear the string
		strcpy_s(full_name, "");

		// get the # of digits for this index
		num_digits = (idx < 10) ? 1 : (idx < 100) ? 2 : (idx < 1000) ? 3 : 4;

		// build the actual filename
		strcpy_s(full_name, ani_fname);
		for(s_idx=0; s_idx<(4-num_digits); s_idx++){
			strcat_s(full_name, NOX("0"));
		}
		sprintf(tmp, "%d", idx);
		strcat_s(full_name, tmp);

		// try and load the bitmap				
		bmap_ids[idx] = bm_load(full_name);	
		if(bmap_ids[idx] != -1){		
			
			its_all_good = 1;
		} 
	}

	// done
	if(its_all_good){
		uses_bmaps = 1;		
		return 0;
	}

	// no go, so try and load as an ani. try and load as an .ani	
	first_frame = bm_load_animation(ani_fname, &m_num_frames);	
	if((first_frame >= 0) && (m_num_frames <= MAX_BMAPS_PER_GADGET)){					
		// seems pretty stupid that we didn't just use a variable for the first frame and access all
		// other frames offset from it instead of accessing this bmap_ids[] array, but probably too
		// much trouble to go through and change this anymore.  How sad..
		for ( i=0; i<m_num_frames; i++ ) {
			bmap_ids[i] = first_frame + i;
		}	
	}	

	// flag that this control is using bitmaps for art	
	uses_bmaps = 1;
	return 0;
}
// initialize all popup details (graphics, etc)
void multi_pinfo_popup_init(net_player *np)
{
	int idx;
	
	// no errors to start with
	Multi_pinfo_popup_error = 0;

	// shouldn't be done
	Multi_pinfo_popup_done = 0;

	// store the background as it currently is
	Multi_pinfo_screen_save = gr_save_screen();
	if(Multi_pinfo_screen_save == -1){
		Multi_pinfo_popup_error = 1;
		return;
	}

	// create the interface window
	Multi_pinfo_window.create(0,0,gr_screen.max_w_unscaled,gr_screen.max_h_unscaled,0);
	Multi_pinfo_window.set_mask_bmap(Multi_pinfo_bitmap_mask[gr_screen.res]);

	// load the background bitmap
	Multi_pinfo_bitmap = bm_load(Multi_pinfo_bitmap_name[gr_screen.res]);
	if(Multi_pinfo_bitmap < 0){
		Multi_pinfo_popup_error = 1;
		return;	
	}

	// backup hardware textures setting and bash to max
	Multi_pinfo_hardware_texture_backup = Detail.hardware_textures;
	Detail.hardware_textures = MAX_DETAIL_LEVEL;

	// zero bitmap info
	Mp_pilot.bitmap = -1;
	strcpy_s(Mp_pilot.filename, "");
	Mp_squad.bitmap = -1;
	strcpy_s(Mp_squad.filename, "");

	// set the player status
	multi_pinfo_reset_player(np);	
	
	// create the interface buttons
	for(idx=0;idx<MULTI_PINFO_NUM_BUTTONS;idx++){
		// create the object
		Multi_pinfo_buttons[gr_screen.res][idx].button.create(&Multi_pinfo_window, "", Multi_pinfo_buttons[gr_screen.res][idx].x, Multi_pinfo_buttons[gr_screen.res][idx].y, 1, 1, 0, 1);

		// set the sound to play when highlighted
		Multi_pinfo_buttons[gr_screen.res][idx].button.set_highlight_action(common_play_highlight_sound);

		// set the ani for the button
		Multi_pinfo_buttons[gr_screen.res][idx].button.set_bmaps(Multi_pinfo_buttons[gr_screen.res][idx].filename);

		// set the hotspot
		Multi_pinfo_buttons[gr_screen.res][idx].button.link_hotspot(Multi_pinfo_buttons[gr_screen.res][idx].hotspot);
	}			

	// add xstrs
	for(idx=0; idx<MULTI_PINFO_NUM_TEXT; idx++){
		Multi_pinfo_window.add_XSTR(&Multi_pinfo_text[gr_screen.res][idx]);
	}

	// initialize strings	
	Multi_pinfo_stats_labels[0] = vm_strdup(XSTR("Rank", 1007));
	Multi_pinfo_stats_labels[1] = vm_strdup(XSTR("Missions Flown", 1008));
	Multi_pinfo_stats_labels[2] = vm_strdup(XSTR("Flight Time", 1009));
	Multi_pinfo_stats_labels[3] = vm_strdup(XSTR("Last Flown",1010));
	Multi_pinfo_stats_labels[4] = vm_strdup(XSTR("Total Kills", 115));
	Multi_pinfo_stats_labels[5] = vm_strdup(XSTR("Primary Shots Fired", 1012));
	Multi_pinfo_stats_labels[6] = vm_strdup(XSTR("Primary Hit %", 1013));
	Multi_pinfo_stats_labels[7] = vm_strdup(XSTR("Secondary Shots Fired",	1014));
	Multi_pinfo_stats_labels[8] = vm_strdup(XSTR("Secondary Hit %", 1015));				
}
Beispiel #19
0
/*++
Function:
  GetTempPathA

See MSDN.

Notes:
    On Windows, the temp path is determined by the following steps:
    1. The value of the "TMP" environment variable, or if it doesn't exist,
    2. The value of the "TEMP" environment variable, or if it doesn't exist,
    3. The Windows directory.

    On Unix, we follow in spirit:
    1. The value of the "TMPDIR" environment variable, or if it doesn't exist,
    2. The /tmp directory.
    This is the same approach employed by mktemp.

--*/
DWORD
PALAPI
GetTempPathA(
	     IN DWORD nBufferLength,
	     OUT LPSTR lpBuffer)
{
    DWORD dwPathLen = 0;

    PERF_ENTRY(GetTempPathA);
    ENTRY("GetTempPathA(nBufferLength=%u, lpBuffer=%p)\n",
          nBufferLength, lpBuffer);

    if ( !lpBuffer )
    {
        ERROR( "lpBuffer was not a valid pointer.\n" )
        SetLastError( ERROR_INVALID_PARAMETER );
        LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen);
        PERF_EXIT(GetTempPathA);
        return 0;
    }

    /* Try the TMPDIR environment variable. This is the same env var checked by mktemp. */
    dwPathLen = GetEnvironmentVariableA("TMPDIR", lpBuffer, nBufferLength);
    if (dwPathLen > 0)
    {
        /* The env var existed. dwPathLen will be the length without null termination 
         * if the entire value was successfully retrieved, or it'll be the length
         * required to store the value with null termination.
         */
        if (dwPathLen < nBufferLength)
        {
            /* The environment variable fit in the buffer. Make sure it ends with '/'. */
            if (lpBuffer[dwPathLen - 1] != '/')
            {
                /* If adding the slash would still fit in our provided buffer, do it.  Otherwise, 
                 * let the caller know how much space would be needed.
                 */
                if (dwPathLen + 2 <= nBufferLength)
                {
                    lpBuffer[dwPathLen++] = '/';
                    lpBuffer[dwPathLen] = '\0';
                }
                else
                {
                    dwPathLen += 2;
                }
            }
        }
        else /* dwPathLen >= nBufferLength */
        {
            /* The value is too long for the supplied buffer.  dwPathLen will now be the
             * length required to hold the value, but we don't know whether that value
             * is going to be '/' terminated.  Since we'll need enough space for the '/', and since
             * a caller would assume that the dwPathLen we return will be sufficient, 
             * we make sure to account for it in dwPathLen even if that means we end up saying
             * one more byte of space is needed than actually is.
             */
            dwPathLen++;
        }
    }
    else /* env var not found or was empty */
    {
        /* no luck, use /tmp/ */
        const char *defaultDir = "/tmp/";
        int defaultDirLen = strlen(defaultDir);
        if (defaultDirLen < nBufferLength)
        {
            dwPathLen = defaultDirLen;
            strcpy_s(lpBuffer, nBufferLength, defaultDir);
        }
        else
        {
            /* get the required length */
            dwPathLen = defaultDirLen + 1;
        }
    }

    if ( dwPathLen >= nBufferLength )
    {
        ERROR("Buffer is too small, need space for %d characters including null termination\n", dwPathLen);
        SetLastError( ERROR_INSUFFICIENT_BUFFER );
    }

    LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen);
    PERF_EXIT(GetTempPathA);
    return dwPathLen;
}
//회원 삭제
void deleteMember(int num, int index)
{
	MemberInfo save[100];
	int i, j;
	char inputDeletetext[6];
	char deleteText[6];

	//파일 포인터 선언
	FILE *fp;

	//파일 열기,에러 체크
	if ((fp = _fsopen("memberInfo.txt", "r", _SH_DENYNO)) == NULL)
	{
		puts("memberInfo.txt 열기 샐패");
		return;
	}
	//용도에 맞게 쓰기
	fread(&save, sizeof(MemberInfo), index, fp);
	//파일 닫기
	fclose(fp);

	printf("정말 삭제 하시려면 아래의 문구를 정확히 입력 하세요\n");
	srand((unsigned int)time(0));
	for (j = 0; j < 5; j++)
	{
		deleteText[j] = (rand() % 26) + 65;
	}
	for (j = 0; j < 5; j++)
	{
		printf("%c", deleteText[j]);
	}
	puts("");
	printf("입력 : ");
	
	inputString(inputDeletetext);
	
	for (i = 0; i < 2; i++)
	{
		if ((strlen(inputDeletetext) != 5))
		{
			system("cls");
			printf("5개의 문자를 입력 하세요\n");

			srand((unsigned int)time(0));
			for (j = 0; j < 5; j++)
			{
				deleteText[j] = (rand() % 26) + 65;
			}
			for (j = 0; j < 5; j++)
			{
				printf("%c", deleteText[j]);
			}
			puts("");

			printf("입력 : ");
			inputString(inputDeletetext);			
		}

		else if (strlen(inputDeletetext) == 5 && (strncmp(inputDeletetext, deleteText, 5) != 0))
		{
			system("cls");
			printf("입력하신 문자가 정확하지 않습니다 다시 입력해 주세요\n");

			srand((unsigned int)time(0));
			for (j = 0; j < 5; j++)
			{
				deleteText[j] = (rand() % 26) + 65;
			}
			for (j = 0; j < 5; j++)
			{
				printf("%c", deleteText[j]);
			}
			puts("");

			printf("입력 : "); 
			inputString(inputDeletetext);
			
		}
		else if ((strlen(inputDeletetext) == 5) && (strncmp(inputDeletetext, deleteText, 5) == 0))
		{
			if (save[num - 1].bookList[0] != 0)
			{
				printf("빌린 책이 있는 회원 정보는 삭제 하실수 없습니다.");
				return;
			}
			else
			{
				save[num - 1].id = 0;
				strcpy_s(save[num - 1].name, MAX_LENGTH, "delete");
				strcpy_s(save[num - 1].email, MAX_LENGTH, "delete");
				strcpy_s(save[num - 1].address, MAX_LENGTH, "delete");
				strcpy_s(save[num - 1].signNumber, MAX_LENGTH, "delete");
				strcpy_s(save[num - 1].phoneNumber, MAX_LENGTH, "delete");
				//strcpy_s(save[num].bookList, MAXBOOK, 0);
				save[num - 1].bookList[0] = 0;
				printf("%d번 회원의 정보 삭제가 완료 되었습니다.", num);
				Sleep(1000);
				system("cls");
			}
		}
	}
	//회원정보 저장
	//파일 열기,에러 체크
	if ((fp = _fsopen("memberInfo.txt", "w", _SH_DENYNO)) == NULL)
	{
		puts("memberInfo.txt 열기 샐패");
		return;
	}
	//용도에 맞게 쓰기
	fwrite(&save, sizeof(MemberInfo), index, fp);
	//파일 닫기
	fclose(fp);
}
Beispiel #21
0
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
IMGCODECPLUGIN_EncodeImage( void* pluginData      ,
                            void* codecData       ,
                            const char* codecType ,
                            TImage* inputImage    ,
                            TIOAccess* output     )
{
    UInt32 i = 0;
    UInt32 n = 0;
    TImageInfo* imageInfo = NULL;
    char codecTypeExt[ 256 ];

    /* generate an image ID and make that ID the ID of the current image */
    ilBindImage( ilGenImage() );

    /* Only 1 layer is supported atm */
    ilActiveLayer( 0 );

    imageInfo = &inputImage->imageInfo;
    for ( i=0; i<imageInfo->nrOfFramesInImage; ++i )
    {
        TImageFrameInfo* imageFrameInfo = &inputImage->frames[ i ].frameInfo;
        
        /* activate the frame */
        ilActiveImage( i );        

        for ( n=0; n<imageFrameInfo->nrOfMipmapLevels; ++n )
        {
            /* create a shortcut */
            TImageMipMapLevelInfo* mipInfo = &inputImage->frames[ i ].mipmapLevel[ n ].mipLevelInfo;
            void* imageBuffer = inputImage->frames[ i ].mipmapLevel[ n ].pixelData;

            /* activate the mip-map */
            ilActiveMipmap( n );
            
            /* hand the data over to DevIL */
            if ( IL_TRUE != ilTexImage( (ILuint)mipInfo->frameWidth                                                   ,
                                        (ILuint)mipInfo->frameHeight                                                  ,
                                        (ILuint)1                                                                     ,
                                        (ILubyte) GetChannelCountForFormat( mipInfo->pixelStorageFormat )             ,
                                        (ILenum)ConvertGUCEFPixelFormatToILPixelFormat( mipInfo->pixelStorageFormat ) ,
                                        (ILenum)ConvertGUCEFTypeToILType( mipInfo->pixelComponentDataType )           ,
                                        (void*)imageBuffer                                                            ) )
            {
                /* Failed to transfer the data over to DevIL */
                return 0;
            }
                        
        }
    }
    
    /* Make sure we prefix a dot before the codecType */    
    strcpy_s( codecTypeExt+1, 255, codecType );
    codecTypeExt[ 0 ] = '.';

    /* now we can perform the actual save */
    currentResource = output;
    if ( IL_TRUE == ilSaveF( ilTypeFromExt( codecTypeExt ), output ) )
    {
        currentResource = NULL;
        return 1;
    }
    
    currentResource = NULL;
    return 0;
}
Beispiel #22
0
void credits_init()
{
	int i;
	credits_screen_buttons *b;

	// pre-initialize
	Credits_num_images = DEFAULT_NUM_IMAGES;
	Credits_artwork_index = -1;

	// this is moved up here so we can override it if desired
	strcpy_s(Credits_music_name, "Cinema");

	// parse credits early so as to set up any overrides (for music and such)
	Credits_parsed = false;
	credits_parse();

	// we could conceivably have specified a number of images but not an index,
	// so if that's the case, set the value here
	if (Credits_artwork_index < 0) {
		Credits_artwork_index = rand() % Credits_num_images;
	}

	int credits_spooled_music_index = event_music_get_spooled_music_index(Credits_music_name);	
	if(credits_spooled_music_index != -1){
		char *credits_wavfile_name = Spooled_music[credits_spooled_music_index].filename;		
		if(credits_wavfile_name != NULL){
			credits_load_music(credits_wavfile_name);
		}
	}

	// Use this id to trigger the start of music playing on the briefing screen
	Credits_music_begin_timestamp = timestamp(Credits_music_delay);

	Credits_frametime = 0;
	Credits_last_time = timer_get_milliseconds();
	
	if (!Credits_parsed)
	{
		Credit_text_parts.push_back(SCP_string("No credits available.\n"));
	}
	else
	{
		switch (SCP_credits_position)
		{
			case START:
				Credit_text_parts.insert(Credit_text_parts.begin(), fs2_open_credit_text);
				break;

			case END:
				Credit_text_parts.push_back(fs2_open_credit_text);
				break;

			default:
				Error(LOCATION, "Unimplemented credits position %d. Get a coder!", (int) SCP_credits_position);
				break;
		}
	}

	int ch;
	SCP_vector<SCP_string>::iterator iter;

	for (iter = Credit_text_parts.begin(); iter != Credit_text_parts.end(); ++iter)
	{
		for (SCP_string::iterator ii = iter->begin(); ii != iter->end(); ++ii)
		{
			ch = *ii;
			switch (ch)
			{
				case -4:
					ch = 129;
					break;

				case -28:
					ch = 132;
					break;

				case -10:
					ch = 148;
					break;

				case -23:
					ch = 130;
					break;

				case -30:
					ch = 131;
					break;

				case -25:
					ch = 135;
					break;

				case -21:
					ch = 137;
					break;

				case -24:
					ch = 138;
					break;

				case -17:
					ch = 139;
					break;

				case -18:
					ch = 140;
					break;

				case -60:
					ch = 142;
					break;

				case -55:
					ch = 144;
					break;

				case -12:
					ch = 147;
					break;

				case -14:
					ch = 149;
					break;

				case -5:
					ch = 150;
					break;

				case -7:
					ch = 151;
					break;

				case -42:
					ch = 153;
					break;

				case -36:
					ch = 154;
					break;

				case -31:
					ch = 160;
					break;

				case -19:
					ch = 161;
					break;

				case -13:
					ch = 162;
					break;

				case -6:
					ch = 163;
					break;

				case -32:
					ch = 133;
					break;

				case -22:
					ch = 136;
					break;

				case -20:
					ch = 141;
					break;
			}

			*ii = (char) ch;
		}
	}

	int temp_h;
	int h = 0;

	for (iter = Credit_text_parts.begin(); iter != Credit_text_parts.end(); ++iter)
	{
		gr_get_string_size(NULL, &temp_h, iter->c_str(), (int)iter->length());

		h = h + temp_h;
	}

	Credit_start_pos = i2fl(Credits_text_coords[gr_screen.res][CREDITS_H_COORD]);
	Credit_stop_pos = -i2fl(h);
	Credit_position = Credit_start_pos;

	Ui_window.create(0, 0, gr_screen.max_w_unscaled, gr_screen.max_h_unscaled, 0);
	Ui_window.set_mask_bmap(Credits_bitmap_mask_fname[gr_screen.res]);
	common_set_interface_palette("InterfacePalette");  // set the interface palette

	for (i=0; i<NUM_BUTTONS; i++) {
		b = &Buttons[i][gr_screen.res];

		b->button.create(&Ui_window, "", b->x, b->y, 60, 30, (i < 2), 1);
		// set up callback for when a mouse first goes over a button
		b->button.set_highlight_action(common_play_highlight_sound);
		b->button.set_bmaps(b->filename);
		b->button.link_hotspot(b->hotspot);
	}

	// add some text
	Ui_window.add_XSTR("Technical Database", 1055, Buttons[TECH_DATABASE_BUTTON][gr_screen.res].xt,  Buttons[TECH_DATABASE_BUTTON][gr_screen.res].yt, &Buttons[TECH_DATABASE_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Mission Simulator", 1056, Buttons[SIMULATOR_BUTTON][gr_screen.res].xt,  Buttons[SIMULATOR_BUTTON][gr_screen.res].yt, &Buttons[SIMULATOR_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Cutscenes", 1057, Buttons[CUTSCENES_BUTTON][gr_screen.res].xt,  Buttons[CUTSCENES_BUTTON][gr_screen.res].yt, &Buttons[CUTSCENES_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Credits", 1058, Buttons[CREDITS_BUTTON][gr_screen.res].xt,  Buttons[CREDITS_BUTTON][gr_screen.res].yt, &Buttons[CREDITS_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Exit", 1420, Buttons[EXIT_BUTTON][gr_screen.res].xt,  Buttons[EXIT_BUTTON][gr_screen.res].yt, &Buttons[EXIT_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_PINK);

	if (Player->flags & PLAYER_FLAGS_IS_MULTI) {
		Buttons[SIMULATOR_BUTTON][gr_screen.res].button.disable();
		Buttons[CUTSCENES_BUTTON][gr_screen.res].button.disable();
	}

	Buttons[EXIT_BUTTON][gr_screen.res].button.set_hotkey(KEY_CTRLED | KEY_ENTER);

	Background_bitmap = bm_load(Credits_bitmap_fname[gr_screen.res]);

	Credits_bmps.resize(Credits_num_images);
	for (i=0; i<Credits_num_images; i++) {
		Credits_bmps[i] = -1;
	}
}
Beispiel #23
0
double CScript::LocalVar(const char* CmdStr, char* retStr)
{
    // 取第一个参数: 变量名字符串, 该脚本系统仅支持数组下标为$var变量,不支持[]嵌套
    // 如 $Var[$Var1],#strVar[$Var1];
    char* firstVarName = (char*)CmdStr;

    // 先循环到第一个参数处
    long cmdStrLen = strlen(CmdStr);
    long tCurPos = 0;
    while(*firstVarName != '(' && tCurPos < cmdStrLen && *firstVarName != '\0')
    {
        tCurPos++;
        firstVarName++;
    }

    if(*firstVarName == '(') // 跳过'('
        firstVarName++;

    if(firstVarName)
    {
        char MainVarName[1024];  // 变量
        char InnVarName[1024];   // 下标变量

        // 分解字符串第一个参数及下标
        long tempPos = 0;
        char* tMainPtr = MainVarName;
        char* tInnPtr = InnVarName;
        CheckParamStringForArray(firstVarName, cmdStrLen-tCurPos, &tMainPtr, 1024, &tInnPtr, 1024, tempPos);

        // 读取字符串值
        if(MainVarName[0] == '#') // 字符串
        {
            char* strValue = NULL;
            strValue = GetStringParam(CmdStr, 1);

            if(m_pVariableList && strValue)
            {
                if(InnVarName[0] == '\0') // 不是数组变量
                {
                    if(strValue[0] != '#') // 第二个参数不是变量
                        m_pVariableList->AddVar(MainVarName, strValue);
                    else
                    {
                        char* str2ndValue = (char*)m_pVariableList->GetVarValue(strValue);
                        if(str2ndValue)
                            m_pVariableList->AddVar(MainVarName, str2ndValue);
                    }
                }
                else// 是数组变量
                {
                    int lArray = 0;
                    if(InnVarName[0] == '$') // 下标是普通变量而非数组变量
                    {
                        lArray = GetScriptVarValue((CMoveShape*)p_SrcShape, InnVarName, 0);
                    }
                    else if(InnVarName[0] != '$' && InnVarName[0] != '#') // 下标是常量
                    {
                        lArray = atoi(InnVarName);
                    }

                    // 去掉'[' ']'
                    for(int i=0; i < lArray; i++)
                    {
                        char tNum[32];
                        char name[1024];
                        strcpy_s(name, 1024, MainVarName);
                        itoa(i, tNum, 10);
                        strcat(name, tNum);
                        m_pVariableList->AddVar(name, strValue);
                    }
                }
            }

            M_FREE( strValue, sizeof(char)*MAX_VAR_LEN );
        }
        else if(MainVarName[0] == '$') // 第一个参数是数字变量
        {
            double value = GetIntParam(CmdStr, 1);

            if(m_pVariableList && (value != ERROR_CODE) )
            {
                if(InnVarName[0] == '\0') // 不是数组变量
                {
                    m_pVariableList->AddVar(MainVarName, value);
                }
                else // 是数组变量
                {
                    int lArray = 0;
                    if(InnVarName[0] == '$') // 下标是普通变量
                    {
                        lArray = GetScriptVarValue((CMoveShape*)p_SrcShape, InnVarName, 0);

                    }
                    else if(InnVarName[0] != '$' && InnVarName[0] != '#') // 下标是常量
                    {
                        lArray = atoi(InnVarName);
                    }

                    // 去掉'[' ']'
                    m_pVariableList->AddVar(MainVarName, lArray, value);
                }
            }
        }

        else if(MainVarName[0] == '@') // 定义GUID
        {
            double value = GetIntParam(CmdStr, 1);

            if(m_pVariableList && (value != ERROR_CODE) )
            {
                if(InnVarName[0] == '\0') // 不是数组变量
                {
                    m_pVariableList->AddGuid(MainVarName, NULL_GUID);
                }
                else // 是数组变量
                {
                    int lArray = 0;
                    if(InnVarName[0] == '$') // 下标是普通变量
                    {
                        lArray = GetScriptVarValue((CMoveShape*)p_SrcShape, InnVarName, 0);
                    }
                    else if(InnVarName[0] != '$' && InnVarName[0] != '#') // 下标是常量
                    {
                        lArray = atoi(InnVarName);
                    }

                    // 去掉'[' ']'
                    for(int i=0; i < lArray; i++)
                    {
                        char tNum[32];
                        char name[1024];
                        strcpy_s(name, 1024, MainVarName);
                        itoa(i, tNum, 10);
                        strcat(name, tNum);
                        m_pVariableList->AddGuid(name, NULL_GUID);
                    }
                }
            }
        }

        //	SAFE_DELETE_ARRAY(firstVarName);
    }
    return 1;
}
Beispiel #24
0
//ユーザーIDを格納
void User::SetUserId(const char *userId) {
	strcpy_s(this->userId, sizeof(this->userId), userId);
}
mfxStatus ParseInputString(msdk_char* strInput[], mfxU8 nArgNum, sInputParams* pParams)
{
    if (1 == nArgNum)
    {
        PrintHelp(strInput[0], NULL);
        return MFX_ERR_UNSUPPORTED;
    }

    MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR);

    // set default implementation
    pParams->bUseHWLib = true;
    pParams->bUseFullColorRange = false;
#if defined(LIBVA_SUPPORT)
    pParams->libvaBackend = MFX_LIBVA_DRM;
#endif

    for (mfxU8 i = 1; i < nArgNum; i++)
    {
        if (MSDK_CHAR('-') != strInput[i][0])
        {
            mfxStatus sts = StrFormatToCodecFormatFourCC(strInput[i], pParams->videoType);
            if (sts != MFX_ERR_NONE)
            {
                PrintHelp(strInput[0], MSDK_STRING("Unknown codec"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (!IsDecodeCodecSupported(pParams->videoType))
            {
                PrintHelp(strInput[0], MSDK_STRING("Unsupported codec"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (pParams->videoType == CODEC_MVC)
            {
                pParams->videoType = MFX_CODEC_AVC;
                pParams->bIsMVC = true;
            }
            continue;
        }

        if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-sw")))
        {
            pParams->bUseHWLib = false;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-hw")))
        {
            pParams->bUseHWLib = true;
        }
#if D3D_SURFACES_SUPPORT
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-d3d")))
        {
            pParams->memType = D3D9_MEMORY;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-d3d11")))
        {
            pParams->memType = D3D11_MEMORY;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-r")))
        {
            pParams->mode = MODE_RENDERING;
            // use d3d9 rendering by default
            if (SYSTEM_MEMORY == pParams->memType)
                pParams->memType = D3D9_MEMORY;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-wall")))
        {
            if(i + 6 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -wall key"));
                return MFX_ERR_UNSUPPORTED;
            }
            // use d3d9 rendering by default
            if (SYSTEM_MEMORY == pParams->memType)
                pParams->memType = D3D9_MEMORY;

            pParams->mode = MODE_RENDERING;

            msdk_opt_read(strInput[++i], pParams->nWallW);
            msdk_opt_read(strInput[++i], pParams->nWallH);
            msdk_opt_read(strInput[++i], pParams->nWallCell);
            msdk_opt_read(strInput[++i], pParams->nWallMonitor);

            mfxU32 nTitle;
            msdk_opt_read(strInput[++i], nTitle);

            pParams->bWallNoTitle = 0 == nTitle;

            msdk_opt_read(strInput[++i], pParams->nWallTimeout);
        }
#endif
#if defined(LIBVA_SUPPORT)
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-vaapi")))
        {
            pParams->memType = D3D9_MEMORY;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-r")))
        {
            pParams->memType = D3D9_MEMORY;
            pParams->mode = MODE_RENDERING;
            pParams->libvaBackend = MFX_LIBVA_X11;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-rwld")))
        {
            pParams->memType = D3D9_MEMORY;
            pParams->mode = MODE_RENDERING;
            pParams->libvaBackend = MFX_LIBVA_WAYLAND;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-perf")))
        {
            pParams->bPerfMode = true;
        }
        else if (0 == msdk_strncmp(strInput[i], MSDK_STRING("-rdrm"), 5))
        {
            pParams->memType = D3D9_MEMORY;
            pParams->mode = MODE_RENDERING;
            pParams->libvaBackend = MFX_LIBVA_DRM_MODESET;
            if (strInput[i][5]) {
                if (strInput[i][5] != '-') {
                    PrintHelp(strInput[0], MSDK_STRING("unsupported monitor type"));
                    return MFX_ERR_UNSUPPORTED;
                }
                pParams->monitorType = getMonitorType(&strInput[i][6]);
                if (pParams->monitorType >= MFX_MONITOR_MAXNUMBER) {
                    PrintHelp(strInput[0], MSDK_STRING("unsupported monitor type"));
                    return MFX_ERR_UNSUPPORTED;
                }
            } else {
                pParams->monitorType = MFX_MONITOR_AUTO; // that's case of "-rdrm" pure option
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-window")))
        {
            if(i +4 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -window key"));
                return MFX_ERR_UNSUPPORTED;
            }
            msdk_opt_read(strInput[++i], pParams->nRenderWinX);
            msdk_opt_read(strInput[++i], pParams->nRenderWinY);
            msdk_opt_read(strInput[++i], pParams->Width);
            msdk_opt_read(strInput[++i], pParams->Height);

            if (0 == pParams->Width)
                pParams->Width = 320;
            if (0 == pParams->Height)
                pParams->Height = 240;

            pParams->bRenderWin = true;
        }
#endif
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-low_latency")))
        {
            switch (pParams->videoType)
            {
                case MFX_CODEC_HEVC:
                case MFX_CODEC_AVC:
                case MFX_CODEC_JPEG:
                {
                    pParams->bLowLat = true;
                    if (!pParams->bIsMVC)
                        break;
                }
                default:
                {
                     PrintHelp(strInput[0], MSDK_STRING("-low_latency mode is suppoted only for H.264 and JPEG codecs"));
                     return MFX_ERR_UNSUPPORTED;
                }
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-jpeg_rotate")))
        {
            if(MFX_CODEC_JPEG != pParams->videoType)
                return MFX_ERR_UNSUPPORTED;

            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -jpeg_rotate key"));
                return MFX_ERR_UNSUPPORTED;
            }

            msdk_opt_read(strInput[++i], pParams->nRotation);
            if((pParams->nRotation != 90)&&(pParams->nRotation != 180)&&(pParams->nRotation != 270))
            {
                PrintHelp(strInput[0], MSDK_STRING("-jpeg_rotate is supported only for 90, 180 and 270 angles"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-calc_latency")))
        {
            switch (pParams->videoType)
            {
                case MFX_CODEC_HEVC:
                case MFX_CODEC_AVC:
                case MFX_CODEC_JPEG:
                {
                    pParams->bCalLat = true;
                    if (!pParams->bIsMVC)
                        break;
                }
                default:
                {
                     PrintHelp(strInput[0], MSDK_STRING("-calc_latency mode is suppoted only for H.264 and JPEG codecs"));
                     return MFX_ERR_UNSUPPORTED;
                }
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-async")))
        {
            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -async key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nAsyncDepth))
            {
                PrintHelp(strInput[0], MSDK_STRING("async is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-di")))
        {
            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -di key"));
                return MFX_ERR_UNSUPPORTED;
            }
            msdk_char diMode[4] = {};
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], diMode))
            {
                PrintHelp(strInput[0], MSDK_STRING("deinterlace value is not set"));
                return MFX_ERR_UNSUPPORTED;
            }

            if (0 == msdk_strcmp(diMode, MSDK_CHAR("bob")))
            {
                pParams->eDeinterlace = MFX_DEINTERLACING_BOB;
            }
            else if (0 == msdk_strcmp(diMode, MSDK_CHAR("adi")))
            {
                pParams->eDeinterlace = MFX_DEINTERLACING_ADVANCED;
            }
            else
            {
                PrintHelp(strInput[0], MSDK_STRING("deinterlace value is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-gpucopy::on")))
        {
            pParams->gpuCopy = MFX_GPUCOPY_ON;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-gpucopy::off")))
        {
            pParams->gpuCopy = MFX_GPUCOPY_OFF;
        }
#if !defined(_WIN32) && !defined(_WIN64)
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-threads_num")))
        {
            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -threads_num key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nThreadsNum))
            {
                PrintHelp(strInput[0], MSDK_STRING("threads_num is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-threads_schedtype")))
        {
            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -threads_schedtype key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_thread_get_schedtype(strInput[++i], pParams->SchedulingType))
            {
                PrintHelp(strInput[0], MSDK_STRING("threads_schedtype is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-threads_priority")))
        {
            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -threads_priority key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->Priority))
            {
                PrintHelp(strInput[0], MSDK_STRING("threads_priority is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
#endif // #if !defined(_WIN32) && !defined(_WIN64)
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-f")))
        {
            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -f key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nMaxFPS))
            {
                PrintHelp(strInput[0], MSDK_STRING("rendering frame rate is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-scr:w")))
        {
            if (i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -scr:w key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->scrWidth))
            {
                PrintHelp(strInput[0], MSDK_STRING("screen width rate is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-scr:h")))
        {
            if (i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -scr:h key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->scrHeight))
            {
                PrintHelp(strInput[0], MSDK_STRING("screen height is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-w")))
        {
            if (i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -w key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->Width))
            {
                PrintHelp(strInput[0], MSDK_STRING("width is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-h")))
        {
            if (i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -h key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->Height))
            {
                PrintHelp(strInput[0], MSDK_STRING("height is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-n")))
        {
            if(i + 1 >= nArgNum)
            {
                PrintHelp(strInput[0], MSDK_STRING("Not enough parameters for -n key"));
                return MFX_ERR_UNSUPPORTED;
            }
            if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nFrames))
            {
                PrintHelp(strInput[0], MSDK_STRING("rendering frame rate is invalid"));
                return MFX_ERR_UNSUPPORTED;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-jpeg_rgb")))
        {
            if(MFX_CODEC_JPEG == pParams->videoType)
            {
               pParams->chromaType = MFX_JPEG_COLORFORMAT_RGB;
            }
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-i420")))
        {
            pParams->fourcc = MFX_FOURCC_NV12;
            pParams->outI420 = true;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-nv12")))
        {
            pParams->fourcc = MFX_FOURCC_NV12;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-rgb4")))
        {
            pParams->fourcc = MFX_FOURCC_RGB4;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-rgb4_fcr")))
        {
            pParams->fourcc = MFX_FOURCC_RGB4;
            pParams->bUseFullColorRange = true;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-p010")))
        {
            pParams->fourcc = MFX_FOURCC_P010;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-a2rgb10")))
        {
            pParams->fourcc = MFX_FOURCC_A2RGB10;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-path")))
        {
            i++;
#if defined(_WIN32) || defined(_WIN64)
            msdk_char wchar[MSDK_MAX_FILENAME_LEN];
            msdk_opt_read(strInput[i], wchar);
            std::wstring wstr(wchar);
            std::string str(wstr.begin(), wstr.end());

            strcpy_s(pParams->pluginParams.strPluginPath, str.c_str());
#else
            msdk_opt_read(strInput[i], pParams->pluginParams.strPluginPath);
#endif
            pParams->pluginParams.type = MFX_PLUGINLOAD_TYPE_FILE;
        }
        else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-i:null")))
        {
            ;
        }
        else // 1-character options
        {
            switch (strInput[i][1])
            {
            case MSDK_CHAR('p'):
                if (++i < nArgNum) {
                   if (MFX_ERR_NONE == ConvertStringToGuid(strInput[i], pParams->pluginParams.pluginGuid))
                    {
                        pParams->pluginParams.type = MFX_PLUGINLOAD_TYPE_GUID;
                    }
                    else
                    {
                        PrintHelp(strInput[0], MSDK_STRING("Unknown options"));
                    }
                 }
                else {
                    msdk_printf(MSDK_STRING("error: option '-p' expects an argument\n"));
                }
                break;
            case MSDK_CHAR('i'):
                if (++i < nArgNum) {
                    msdk_opt_read(strInput[i], pParams->strSrcFile);
                }
                else {
                    msdk_printf(MSDK_STRING("error: option '-i' expects an argument\n"));
                }
                break;
            case MSDK_CHAR('o'):
                if (++i < nArgNum) {
                    pParams->mode = MODE_FILE_DUMP;
                    msdk_opt_read(strInput[i], pParams->strDstFile);
                }
                else {
                    msdk_printf(MSDK_STRING("error: option '-o' expects an argument\n"));
                }
                break;
            case MSDK_CHAR('?'):
                PrintHelp(strInput[0], NULL);
                return MFX_ERR_UNSUPPORTED;
            default:
                {
                    std::basic_stringstream<msdk_char> stream;
                    stream << MSDK_STRING("Unknown option: ") << strInput[i];
                    PrintHelp(strInput[0], stream.str().c_str());
                    return MFX_ERR_UNSUPPORTED;
                }
            }
        }
    }

    if (0 == msdk_strlen(pParams->strSrcFile) && MFX_CODEC_CAPTURE != pParams->videoType)
    {
        msdk_printf(MSDK_STRING("error: source file name not found"));
        return MFX_ERR_UNSUPPORTED;
    }

    if (MFX_CODEC_CAPTURE == pParams->videoType)
    {
        if (!pParams->scrWidth || !pParams->scrHeight)
        {
            msdk_printf(MSDK_STRING("error: for screen capture, width and height must be specified manually (-scr:w and -scr:h)"));
            return MFX_ERR_UNSUPPORTED;
        }
    }
    else if (pParams->scrWidth || pParams->scrHeight)
    {
        msdk_printf(MSDK_STRING("error: width and height parameters are supported only by screen capture decoder"));
        return MFX_ERR_UNSUPPORTED;
    }

    if ((pParams->mode == MODE_FILE_DUMP) && (0 == msdk_strlen(pParams->strDstFile)))
    {
        msdk_printf(MSDK_STRING("error: destination file name not found"));
        return MFX_ERR_UNSUPPORTED;
    }

    if (MFX_CODEC_MPEG2   != pParams->videoType &&
        MFX_CODEC_AVC     != pParams->videoType &&
        MFX_CODEC_HEVC    != pParams->videoType &&
        MFX_CODEC_VC1     != pParams->videoType &&
        MFX_CODEC_JPEG    != pParams->videoType &&
        MFX_CODEC_CAPTURE != pParams->videoType &&
        CODEC_VP8         != pParams->videoType)
    {
        PrintHelp(strInput[0], MSDK_STRING("Unknown codec"));
        return MFX_ERR_UNSUPPORTED;
    }

    if (pParams->nAsyncDepth == 0)
    {
        pParams->nAsyncDepth = 4; //set by default;
    }

    return MFX_ERR_NONE;
}
Beispiel #26
0
/******************************************************************************
 * openlog
 *
 * Open connection to system logger.
 */
ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
openlog( char* ident, int option, int facility )
{
    BOOL failed = FALSE;
    SOCKADDR_IN sa_local;
    DWORD n;
    int size;

    if ( !initialized )
        return;

    EnterCriticalSection(&cs_syslog);

    if( syslog_opened )
        goto done;

    failed = TRUE;

    syslog_facility = facility? facility : LOG_USER;

    if( option & LOG_PID )
        sprintf_s( syslog_procid_str, sizeof(syslog_procid_str), "[%lu]", GetCurrentProcessId() );
    else
        syslog_procid_str[0] = '\0';

    /* FIXME: handle other options */

    n = sizeof(local_hostname);
    if( !GetComputerName( local_hostname, &n ) )
        goto done;

    syslog_socket = INVALID_SOCKET;

    init_logger_addr();

    for( n = 0;; n++ )
    {
        syslog_socket = socket( AF_INET, SOCK_DGRAM, 0 );
        if( INVALID_SOCKET == syslog_socket )
            goto done;

        memset( &sa_local, 0, sizeof(SOCKADDR_IN) );
        sa_local.sin_family = AF_INET;
        if( bind( syslog_socket, (SOCKADDR*) &sa_local, sizeof(SOCKADDR_IN) ) == 0 )
            break;
        rk_closesocket( syslog_socket );
        syslog_socket = INVALID_SOCKET;
        if( n == 100 )
            goto done;
        Sleep(0);
    }

    /* get size of datagramm */
    size = sizeof(datagramm_size);
    if( getsockopt( syslog_socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char*) &datagramm_size, &size ) )
        goto done;
    if( datagramm_size - strlen(local_hostname) - (ident? strlen(ident) : 0) < 64 )
        goto done;
    if( datagramm_size > SYSLOG_DGRAM_SIZE )
        datagramm_size = SYSLOG_DGRAM_SIZE;

    if (ident)
        strcpy_s(syslog_ident, sizeof(syslog_ident), ident);

    syslog_facility = (facility ? facility : LOG_USER);
    failed = FALSE;

 done:
    if( failed ) {
        if( syslog_socket != INVALID_SOCKET )
            rk_closesocket( syslog_socket );
    }
    syslog_opened = !failed;

    LeaveCriticalSection(&cs_syslog);
}
Beispiel #27
0
	Word CText::GetWord(const char* szText, bool bSpace, slong slCounter)
	{
		Word ret;
		int len = strlen(szText);
		if (len == 0)//Quick escape
			return ret;

		if (bSpace)
		{
			//Get Spaces
			char delim[256];
			for (ulong i = 0; i < 256; i++)
				delim[i] = char(i);
			delim[0] = delim[' '] = 1;

			char* wordPtr = new char[len + 1];
			strcpy_s(wordPtr, len + 1, szText);
			char* context = nullptr;

			char* tok = strtok_s(wordPtr, delim, &context);

			for (int i = 0; i <= slCounter; i++)
			{
				if (tok == NULL)
				{
					ret.text = "";
					ret.pixWidth = 0;
					break;
				}
				ret.text = tok;
				ret.pixWidth = this->GetWordPixelLength(ret.text.c_str());
				tok = strtok_s(NULL, delim, &context);
			}

			/*while (tok != nullptr && count <= slCounter )
			{
				ret.text = tok;
				ret.pixWidth = this->GetWordPixelLength(ret.text.c_str());
				tok = strtok_s(NULL, delim, &context);
				count++;
			}*/
			delete[] wordPtr;
		}
		else
		{
			char* wordPtr = new char[len + 1];
			strcpy_s(wordPtr, len + 1, szText);
			char delim[] = " ";
			char* context = nullptr;

			char* tok = strtok_s(wordPtr, delim, &context);
			for (int i = 0; i <= slCounter; i++)
			{
				if (tok == NULL)
				{
					ret.text = "";
					ret.pixWidth = 0;
					break;
				}
				ret.text = tok;
				ret.pixWidth = this->GetWordPixelLength(ret.text.c_str());
				tok = strtok_s(NULL, delim, &context);
			}
			delete[] wordPtr;
		}

		return ret;
	}
Beispiel #28
0
//Called after StarCraft is completely loaded
extern "C" __declspec(dllexport) bool ApplyPatch(HANDLE hProcess, DWORD dwProcessID)
{
	wchar_t msgtemp[255];
	wchar_t dll[MAX_PATH];

	GetFullPathNameW(WDETECTOR, MAX_PATH, dll, NULL);

	wLog(LOG_INFO, L"~Logging started~");

	//Get SeDebugPrivilege
	if (SetDebugPrivilege(TRUE) == true)
	{
		wLog(LOG_INFO, L"Obtained SeDebugPrivilege");
	}
	else
	{
		wLog(LOG_ERROR, L"Unable to obtain SeDebugPrivilege");
		return false;
	}

	//Inject wDetector.w
	if (CreateRemoteThreadInject(dwProcessID, dll) == true)
	{
		swprintf_s(msgtemp, sizeof(msgtemp), L"Injected %ls into %d", dll, dwProcessID);
		wLog(LOG_INFO, msgtemp);
	}
	else
	{
		swprintf_s(msgtemp, sizeof(msgtemp), L"Could not inject %ls into %d", dll, dwProcessID);
		wLog(LOG_ERROR, msgtemp);
		return false;
	}

	//Kill wLauncher.exe
	std::thread wLauncher(KillProc, processInfo.hProcess);

	//Wait for wDetector.w
	std::this_thread::sleep_for(std::chrono::milliseconds(250));

	//Get base address of wDetector.w module
	uint32_t wDetectorBaseAddress = 0;
	if (FindModuleBaseAddress(WDETECTOR, wDetectorBaseAddress) == true)
	{
		swprintf_s(msgtemp, sizeof(msgtemp), L"wDetector's base address is %d", wDetectorBaseAddress);
		wLog(LOG_INFO, msgtemp);
	}
	else
	{
		wLog(LOG_ERROR, L"Could not get wDetector's base address!");
		return false;
	}
	
	//Wait for wLauncher to be killed
	wLauncher.join();
	
	//Patch wDetector
	int8_t activate = { 0x12 };
	WriteProcessMemory(hProcess, (LPVOID)(wDetectorBaseAddress + (uint32_t)0x5AD94), &activate, sizeof(activate), NULL);
	wLog(LOG_INFO, L"wDetector activated!");

	std::array<uint32_t, 17> offset = {
		0x429E4,	//Refresh game message
		0x43CB4,	//toggle automatic refresh - enable
		0x43CAC,	//toggle automatic refresh - disable
		0x41B8C,	//ago
		0x41B84,	//min
		0x41B88,	//sec
		0x41AB0,
		0x418D3,	//mission briefing
		0x43DB3,	//time off
		0x43DA3,	//time on
		0x43CBD,	//toggle automatic refresh
		0x4297D,	//Automatic game refresh disable -msg after 3 mins
		0x4299F,	//3 minutes passed) -msg after 3 mins
		0x429C7,	//F5 - seconds until refreshing.
		0x41C0B,	//English
		0x42755,	//"Conflict" (no null terminator)
		0x444CC		//"has banned you. (Host hack)"
	};

	std::array<std::string, 17> vals = {
		"Refreshing", //<wDetector 3.35 - Refreshing>
		"enabled", //toggle automatic refresh
		"disable", //toggle automatic refresh
		"ago",
		"min",
		"sec",
		" min %u sec",
		"Players Ready", //mission briefing
		"Time off",
		"Time on",
		"Automatic refresh %s", //toggle automatic refresh
		"Automatic game refresh disable", //msg after 3 mins
		"3 minutes passed)", //msg after 3 mins
		" seconds until refreshing.", //F5
		"English",
/*16*/	"Conflict",
		"has banned you. (Host hack)"
	};

	std::array<char, 17> terminator = {
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
		0x00,
/*16*/	0x20,
		0x00
	};

	{
		char buff[50] = "";
		int a = 0;
		for (std::size_t i{ 0 }; i < offset.size(); ++i)
		{
			if (terminator.at(i) == 0x00)
			{
				a = 1;
			}
			else
			{
				vals.at(i) += terminator.at(i); //append to end of C++ string
				a = 0; //don't leave room for null terminator
			}
			strcpy_s(buff, sizeof(buff), vals.at(i).c_str());
			//vals.size() does not have a null terminator
			WriteProcessMemory(hProcess, (LPVOID)(wDetectorBaseAddress + offset.at(i)), buff, vals.at(i).size() + a, NULL);
		}
	}

	wLog(LOG_INFO, L"wDetector translated");

	return true;
}
Beispiel #29
0
void SetRootPath(LPCSTR path)
{
   strcpy_s(s_rootPath, 256, path);
}
Beispiel #30
0
DWORD PE::AddSection(LPBYTE pBuffer,DWORD dwSize,PCHAR pszSectionName)
{
	//修改文件头中的区段数量
	m_pNt->FileHeader.NumberOfSections++;
	//增加区段表项
	memset(m_pLastSection,0,sizeof(IMAGE_SECTION_HEADER));
	//写入区段名
	strcpy_s((char*)m_pLastSection->Name,IMAGE_SIZEOF_SHORT_NAME,pszSectionName);
	//区段虚拟大小
	DWORD dwVirtualSize=0;
	//区段文件大小
	DWORD dwSizeOfRawData=0;
	//把文件加载到内存所需要的大小  
	DWORD dwSizeOfImage=m_pNt->OptionalHeader.SizeOfImage;
	//取余 查看内存是否对齐 
	if (dwSizeOfImage%m_dwMemAlign)
	{
		// 取商再原来基础上+1  比如说dwSizeOfImage=1726 对齐粒度m_dwMemAlign=200 
		//此时dwSizeOfImage=1800
		dwSizeOfImage=(dwSizeOfImage/m_dwMemAlign+1)*m_dwMemAlign;
	}
	else
	{
		dwSizeOfImage=(dwSizeOfImage/m_dwMemAlign)*m_dwMemAlign;
	}

	//区段对齐后的RVA(dwSize) /内存对齐粒度 m_dwMemAlign
	if (dwSize%m_dwMemAlign)
	{
		dwVirtualSize=(dwSize/m_dwMemAlign+1)*m_dwMemAlign;
	}
	else
	{
		dwVirtualSize=(dwSize/m_dwMemAlign)*m_dwMemAlign;
	}

	//区段对齐后的RVA(dwSize) /文件对齐粒度 m_dwMemAlign
	if (dwSize%m_dwFileAlign)
	{
		dwSizeOfRawData=(dwSize/m_dwFileAlign+1)*m_dwFileAlign;
	}
	else
	{
		dwSizeOfRawData=(dwSize/m_dwFileAlign)*m_dwFileAlign;
	}

	//获取到新的相对虚拟地址 RVA
	m_pLastSection->VirtualAddress=(m_pLastSection[-1].VirtualAddress+(dwSize/m_dwMemAlign)*m_dwMemAlign);
	//区段在文件中的偏移
	m_pLastSection->PointerToRawData=m_dwFileSize;
	//区段在文件中大小
	m_pLastSection->SizeOfRawData=dwSizeOfRawData;
	//区段在内存中大小
	m_pLastSection->Misc.VirtualSize=dwVirtualSize;
	//区段属性
	m_pLastSection->Characteristics=0Xe0000040;

	//增加 文件大小 创建文件 添加代码段 确定入口点
	m_pNt->OptionalHeader.SizeOfImage=dwSizeOfImage+dwVirtualSize;
	m_pNt->OptionalHeader.AddressOfEntryPoint=m_dwNewOEP+m_pLastSection->VirtualAddress;

	//生成输出文件路径
	CString strPath=m_objFIle.GetFilePath();
	TCHAR SzOutPath[MAX_PATH]={0};
	//获取文件后缀名
	LPWSTR strSuffix=PathFindExtension(strPath);
	//目标文件路径到SzOutPath
	wcsncpy_s(SzOutPath,MAX_PATH,strPath,wcslen(strPath));

	//移除后缀名
	PathRemoveExtension(SzOutPath);
	// 在路径最后附加“_1”
	wcscat_s(SzOutPath,MAX_PATH,L"_1");
	// 在路径最后附加刚刚保存的后缀名
	wcscat_s(SzOutPath, MAX_PATH, strSuffix);                           

	//创建文件
	CFile objFile(SzOutPath,CFile::modeCreate|CFile::modeReadWrite);
	objFile.Write(m_pFileBase,(DWORD)m_objFIle.GetLength());
	//移到文件尾
	objFile.SeekToEnd();
	//将pBuffer 按照大小dwSize 写入文件
	objFile.Write(pBuffer,dwSize);
	//返回操作完成后的最后一个区段的相对虚拟地址 RAV
	return m_pLastSection->VirtualAddress;

}